From cfdcef7a7fe85627a0ca5affb03a7071f02758f9 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Wed, 16 Sep 2026 14:58:38 -0600 Subject: [PATCH 01/35] feat: implement blob storage functionality with BlobName, BlobPolicy, BlobRead, BlobRef, and BlobWrite classes --- src/AgentCore.Application/Blobs/BlobName.cs | 39 ++++++++ src/AgentCore.Application/Blobs/BlobPolicy.cs | 62 +++++++++++++ src/AgentCore.Application/Blobs/BlobRead.cs | 14 +++ src/AgentCore.Application/Blobs/BlobRef.cs | 12 +++ src/AgentCore.Application/Blobs/BlobWrite.cs | 14 +++ src/AgentCore.Application/Ports/IBlobStore.cs | 27 ++++++ .../Ports/IBlobStoreAdapter.cs | 18 ++++ .../PublicAPI.Unshipped.txt | 72 +++++++++++++++ .../Blobs/.editorconfig | 5 + .../Blobs/BlobNameTests.cs | 64 +++++++++++++ .../Blobs/BlobPolicyTests.cs | 92 +++++++++++++++++++ 11 files changed, 419 insertions(+) create mode 100644 src/AgentCore.Application/Blobs/BlobName.cs create mode 100644 src/AgentCore.Application/Blobs/BlobPolicy.cs create mode 100644 src/AgentCore.Application/Blobs/BlobRead.cs create mode 100644 src/AgentCore.Application/Blobs/BlobRef.cs create mode 100644 src/AgentCore.Application/Blobs/BlobWrite.cs create mode 100644 src/AgentCore.Application/Ports/IBlobStore.cs create mode 100644 src/AgentCore.Application/Ports/IBlobStoreAdapter.cs create mode 100644 tests/AgentCore.Application.Tests/Blobs/.editorconfig create mode 100644 tests/AgentCore.Application.Tests/Blobs/BlobNameTests.cs create mode 100644 tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs diff --git a/src/AgentCore.Application/Blobs/BlobName.cs b/src/AgentCore.Application/Blobs/BlobName.cs new file mode 100644 index 00000000..a3a958b3 --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobName.cs @@ -0,0 +1,39 @@ +using System.Text; + +namespace AgentCore.Application.Blobs; + +/// +/// The one shape a blob name may take. A name is a key, never a path. +/// +public static class BlobName +{ + /// The longest name, in UTF-8 bytes, that every backing store accepts. + public const int MaxBytes = 255; + + /// Says whether a name is safe to use as a key. + /// What the model or the caller wrote. + /// when the name is not empty, holds no path separator, no .., + /// no control character, and fits in . + public static bool IsSafe(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + { + return false; + } + + if (name.Contains("..", StringComparison.Ordinal)) + { + return false; + } + + foreach (var c in name) + { + if (c is '/' or '\\' || char.IsControl(c)) + { + return false; + } + } + + return Encoding.UTF8.GetByteCount(name) <= MaxBytes; + } +} diff --git a/src/AgentCore.Application/Blobs/BlobPolicy.cs b/src/AgentCore.Application/Blobs/BlobPolicy.cs new file mode 100644 index 00000000..8545eb6f --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobPolicy.cs @@ -0,0 +1,62 @@ +namespace AgentCore.Application.Blobs; + +/// +/// What a captured sandbox file must satisfy before it is stored. +/// +public sealed class BlobPolicy +{ + /// The cap a sandbox file must fit under. 10 MB. + public const long DefaultMaxBytes = 10L * 1024 * 1024; + + /// The extensions stored by default: png, pdf, csv. + public static readonly IReadOnlySet DefaultExtensions = + new HashSet(StringComparer.OrdinalIgnoreCase) { "png", "pdf", "csv" }; + + /// The policy the harness uses when the document names none. + public static BlobPolicy Default { get; } = new(DefaultMaxBytes, DefaultExtensions); + + /// Makes a policy. + /// The largest file stored. Must be positive. + /// Extensions stored, without the dot. Case does not matter. + public BlobPolicy(long maxBytes, IEnumerable allowedExtensions) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxBytes); + ArgumentNullException.ThrowIfNull(allowedExtensions); + + MaxBytes = maxBytes; + AllowedExtensions = new HashSet(allowedExtensions, StringComparer.OrdinalIgnoreCase); + } + + /// Gets the largest file stored, in bytes. + public long MaxBytes { get; } + + /// Gets the extensions stored, without the dot. + public IReadOnlySet AllowedExtensions { get; } + + /// Says why a file is refused, or that it is not. + /// The file's name, already normalised by . + /// The file's size in bytes. + /// A short reason fit for a log line, or when the file may be stored. + public string? WhyRefused(string name, long length) + { + ArgumentNullException.ThrowIfNull(name); + + if (length < 0 || length > MaxBytes) + { + return $"size {length} is outside 0..{MaxBytes} bytes"; + } + + var dot = name.LastIndexOf('.'); + + if (dot < 0 || dot == name.Length - 1) + { + return "no extension"; + } + + var extension = name[(dot + 1)..]; + + return AllowedExtensions.Contains(extension) + ? null + : $"extension '{extension}' is not allowed"; + } +} diff --git a/src/AgentCore.Application/Blobs/BlobRead.cs b/src/AgentCore.Application/Blobs/BlobRead.cs new file mode 100644 index 00000000..5b5741f1 --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobRead.cs @@ -0,0 +1,14 @@ +namespace AgentCore.Application.Blobs; + +/// One stored blob, opened for reading. Dispose it to release the stream. +/// The IANA media type, such as image/png. +/// How many bytes holds. +/// The bytes, positioned at the start. +public sealed record BlobRead( + string MediaType, + long Length, + Stream Content) : IAsyncDisposable +{ + /// + public ValueTask DisposeAsync() => Content.DisposeAsync(); +} diff --git a/src/AgentCore.Application/Blobs/BlobRef.cs b/src/AgentCore.Application/Blobs/BlobRef.cs new file mode 100644 index 00000000..e6a114ab --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobRef.cs @@ -0,0 +1,12 @@ +namespace AgentCore.Application.Blobs; + +/// One stored blob, apart from its bytes. +/// Who wrote it. +/// The name it is stored under. +/// The IANA media type, such as image/png. +/// How many bytes it holds. +public sealed record BlobRef( + string OwnerId, + string Name, + string MediaType, + long Length); diff --git a/src/AgentCore.Application/Blobs/BlobWrite.cs b/src/AgentCore.Application/Blobs/BlobWrite.cs new file mode 100644 index 00000000..3f3436a8 --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobWrite.cs @@ -0,0 +1,14 @@ +namespace AgentCore.Application.Blobs; + +/// One blob to store. +/// Who writes it. The call id today. +/// The name it is stored under. Must pass . +/// The IANA media type, such as image/png. +/// The bytes. Read once, from its current position. The caller disposes it. +/// How many bytes holds. +public sealed record BlobWrite( + string OwnerId, + string Name, + string MediaType, + Stream Content, + long Length); diff --git a/src/AgentCore.Application/Ports/IBlobStore.cs b/src/AgentCore.Application/Ports/IBlobStore.cs new file mode 100644 index 00000000..e6201fb8 --- /dev/null +++ b/src/AgentCore.Application/Ports/IBlobStore.cs @@ -0,0 +1,27 @@ +using AgentCore.Application.Blobs; + +namespace AgentCore.Application.Ports; + +/// +/// Durable bytes an owner wrote, keyed by owner and name. +/// +public interface IBlobStore +{ + /// Writes one blob. The same owner and name replaces the earlier blob. + /// What to store. The stream is read once, from its current position. + /// Cancels the write. + /// What was stored. + ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default); + + /// Opens one blob for reading. + /// Who wrote it. + /// The name it was written under. + /// Cancels the open. + /// The blob, or when no such blob exists. The caller disposes it. + ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default); + + /// Deletes every blob an owner wrote. Nothing to delete is not an error. + /// Whose blobs to delete. + /// Cancels the delete. + ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs b/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs new file mode 100644 index 00000000..8cf10de0 --- /dev/null +++ b/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs @@ -0,0 +1,18 @@ +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Ports; + +/// +/// Opens the blob store behind one providers.blobs value. +/// +public interface IBlobStoreAdapter : IVendorAdapter +{ + /// Opens the store this vendor writes to, and hands it over. + /// The providers.blobs block, whose kind named this adapter. + /// The chain a credential resolves through, or . + /// Cancels the open. + ValueTask OpenAsync( + VendorProviderConfiguration entry, + ISecretResolverPort? secrets, + CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 1aa679d1..174a2e90 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2102,3 +2102,75 @@ virtual AgentCore.Application.Calls.CallInput.PrintMembers(System.Text.StringBui virtual AgentCore.Application.Tools.Binding.ToolBinding.Invoke(System.Text.Json.Nodes.JsonObject! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask ~override AgentCore.Application.Providers.VendorSeam.Equals(object obj) -> bool ~override AgentCore.Application.Providers.VendorSeam.ToString() -> string +AgentCore.Application.Blobs.BlobName +AgentCore.Application.Blobs.BlobPolicy +AgentCore.Application.Blobs.BlobPolicy.AllowedExtensions.get -> System.Collections.Generic.IReadOnlySet! +AgentCore.Application.Blobs.BlobPolicy.BlobPolicy(long maxBytes, System.Collections.Generic.IEnumerable! allowedExtensions) -> void +AgentCore.Application.Blobs.BlobPolicy.MaxBytes.get -> long +AgentCore.Application.Blobs.BlobPolicy.WhyRefused(string! name, long length) -> string? +AgentCore.Application.Blobs.BlobRead +AgentCore.Application.Blobs.BlobRead.$() -> AgentCore.Application.Blobs.BlobRead! +AgentCore.Application.Blobs.BlobRead.BlobRead(string! MediaType, long Length, System.IO.Stream! Content) -> void +AgentCore.Application.Blobs.BlobRead.Content.get -> System.IO.Stream! +AgentCore.Application.Blobs.BlobRead.Content.init -> void +AgentCore.Application.Blobs.BlobRead.Deconstruct(out string! MediaType, out long Length, out System.IO.Stream! Content) -> void +AgentCore.Application.Blobs.BlobRead.DisposeAsync() -> System.Threading.Tasks.ValueTask +AgentCore.Application.Blobs.BlobRead.Equals(AgentCore.Application.Blobs.BlobRead? other) -> bool +AgentCore.Application.Blobs.BlobRead.Length.get -> long +AgentCore.Application.Blobs.BlobRead.Length.init -> void +AgentCore.Application.Blobs.BlobRead.MediaType.get -> string! +AgentCore.Application.Blobs.BlobRead.MediaType.init -> void +AgentCore.Application.Blobs.BlobRef +AgentCore.Application.Blobs.BlobRef.$() -> AgentCore.Application.Blobs.BlobRef! +AgentCore.Application.Blobs.BlobRef.BlobRef(string! OwnerId, string! Name, string! MediaType, long Length) -> void +AgentCore.Application.Blobs.BlobRef.Deconstruct(out string! OwnerId, out string! Name, out string! MediaType, out long Length) -> void +AgentCore.Application.Blobs.BlobRef.Equals(AgentCore.Application.Blobs.BlobRef? other) -> bool +AgentCore.Application.Blobs.BlobRef.Length.get -> long +AgentCore.Application.Blobs.BlobRef.Length.init -> void +AgentCore.Application.Blobs.BlobRef.MediaType.get -> string! +AgentCore.Application.Blobs.BlobRef.MediaType.init -> void +AgentCore.Application.Blobs.BlobRef.Name.get -> string! +AgentCore.Application.Blobs.BlobRef.Name.init -> void +AgentCore.Application.Blobs.BlobRef.OwnerId.get -> string! +AgentCore.Application.Blobs.BlobRef.OwnerId.init -> void +AgentCore.Application.Blobs.BlobWrite +AgentCore.Application.Blobs.BlobWrite.$() -> AgentCore.Application.Blobs.BlobWrite! +AgentCore.Application.Blobs.BlobWrite.BlobWrite(string! OwnerId, string! Name, string! MediaType, System.IO.Stream! Content, long Length) -> void +AgentCore.Application.Blobs.BlobWrite.Content.get -> System.IO.Stream! +AgentCore.Application.Blobs.BlobWrite.Content.init -> void +AgentCore.Application.Blobs.BlobWrite.Deconstruct(out string! OwnerId, out string! Name, out string! MediaType, out System.IO.Stream! Content, out long Length) -> void +AgentCore.Application.Blobs.BlobWrite.Equals(AgentCore.Application.Blobs.BlobWrite? other) -> bool +AgentCore.Application.Blobs.BlobWrite.Length.get -> long +AgentCore.Application.Blobs.BlobWrite.Length.init -> void +AgentCore.Application.Blobs.BlobWrite.MediaType.get -> string! +AgentCore.Application.Blobs.BlobWrite.MediaType.init -> void +AgentCore.Application.Blobs.BlobWrite.Name.get -> string! +AgentCore.Application.Blobs.BlobWrite.Name.init -> void +AgentCore.Application.Blobs.BlobWrite.OwnerId.get -> string! +AgentCore.Application.Blobs.BlobWrite.OwnerId.init -> void +AgentCore.Application.Ports.IBlobStore +AgentCore.Application.Ports.IBlobStoreAdapter +AgentCore.Application.Ports.IBlobStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IBlobStore.DeleteByOwnerAsync(string! ownerId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IBlobStore.OpenReadAsync(string! ownerId, string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IBlobStore.PutAsync(AgentCore.Application.Blobs.BlobWrite! write, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +const AgentCore.Application.Blobs.BlobName.MaxBytes = 255 -> int +const AgentCore.Application.Blobs.BlobPolicy.DefaultMaxBytes = 10485760 -> long +override AgentCore.Application.Blobs.BlobRead.Equals(object? obj) -> bool +override AgentCore.Application.Blobs.BlobRead.GetHashCode() -> int +override AgentCore.Application.Blobs.BlobRead.ToString() -> string! +override AgentCore.Application.Blobs.BlobRef.Equals(object? obj) -> bool +override AgentCore.Application.Blobs.BlobRef.GetHashCode() -> int +override AgentCore.Application.Blobs.BlobRef.ToString() -> string! +override AgentCore.Application.Blobs.BlobWrite.Equals(object? obj) -> bool +override AgentCore.Application.Blobs.BlobWrite.GetHashCode() -> int +override AgentCore.Application.Blobs.BlobWrite.ToString() -> string! +static AgentCore.Application.Blobs.BlobPolicy.Default.get -> AgentCore.Application.Blobs.BlobPolicy! +static AgentCore.Application.Blobs.BlobRead.operator ==(AgentCore.Application.Blobs.BlobRead? left, AgentCore.Application.Blobs.BlobRead? right) -> bool +static AgentCore.Application.Blobs.BlobRead.operator !=(AgentCore.Application.Blobs.BlobRead? left, AgentCore.Application.Blobs.BlobRead? right) -> bool +static AgentCore.Application.Blobs.BlobRef.operator ==(AgentCore.Application.Blobs.BlobRef? left, AgentCore.Application.Blobs.BlobRef? right) -> bool +static AgentCore.Application.Blobs.BlobRef.operator !=(AgentCore.Application.Blobs.BlobRef? left, AgentCore.Application.Blobs.BlobRef? right) -> bool +static AgentCore.Application.Blobs.BlobWrite.operator ==(AgentCore.Application.Blobs.BlobWrite? left, AgentCore.Application.Blobs.BlobWrite? right) -> bool +static AgentCore.Application.Blobs.BlobWrite.operator !=(AgentCore.Application.Blobs.BlobWrite? left, AgentCore.Application.Blobs.BlobWrite? right) -> bool +static readonly AgentCore.Application.Blobs.BlobPolicy.DefaultExtensions -> System.Collections.Generic.IReadOnlySet! +static AgentCore.Application.Blobs.BlobName.IsSafe(string? name) -> bool diff --git a/tests/AgentCore.Application.Tests/Blobs/.editorconfig b/tests/AgentCore.Application.Tests/Blobs/.editorconfig new file mode 100644 index 00000000..3d6eebe7 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Blobs/.editorconfig @@ -0,0 +1,5 @@ +[*.cs] + +# CA1707: "Remove the underscores from member name". A test name reads Subject_Behaviour, and the +# underscore is what separates the two halves. +dotnet_diagnostic.CA1707.severity = none diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobNameTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobNameTests.cs new file mode 100644 index 00000000..850940cd --- /dev/null +++ b/tests/AgentCore.Application.Tests/Blobs/BlobNameTests.cs @@ -0,0 +1,64 @@ +using AgentCore.Application.Blobs; +using Xunit; + +namespace AgentCore.Application.Tests.Blobs; + +/// The name a blob is keyed by. A key, never a path. +public sealed class BlobNameTests +{ + [Theory] + [InlineData("chart.png")] + [InlineData("sales report.pdf")] + [InlineData("q3-données.csv")] + public void IsSafe_PlainName_Accepts(string name) + { + Assert.True(BlobName.IsSafe(name)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("../etc/passwd")] + [InlineData("..")] + [InlineData("a/b.png")] + [InlineData("a\\b.png")] + [InlineData("/chart.png")] + [InlineData("chart\0.png")] + [InlineData("chart\n.png")] + [InlineData("chart..png")] + public void IsSafe_PathOrControlChars_Refuses(string? name) + { + Assert.False(BlobName.IsSafe(name)); + } + + [Fact] + public void IsSafe_Over255Utf8Bytes_Refuses() + { + // Arrange: 252 ASCII bytes + ".png" = 256 bytes. + var name = new string('a', 252) + ".png"; + + // Act & Assert + Assert.False(BlobName.IsSafe(name)); + } + + [Fact] + public void IsSafe_Exactly255Utf8Bytes_Accepts() + { + // Arrange + var name = new string('a', 251) + ".png"; + + // Act & Assert + Assert.True(BlobName.IsSafe(name)); + } + + [Fact] + public void IsSafe_MultiByteCharsCountAsBytesNotChars() + { + // Arrange: "é" is 2 UTF-8 bytes, so 126 of them + ".png" = 256 bytes in 130 chars. + var name = new string('é', 126) + ".png"; + + // Act & Assert + Assert.False(BlobName.IsSafe(name)); + } +} diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs new file mode 100644 index 00000000..8dbcda5c --- /dev/null +++ b/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs @@ -0,0 +1,92 @@ +using AgentCore.Application.Blobs; +using Xunit; + +namespace AgentCore.Application.Tests.Blobs; + +/// The cap and the allowlist a captured file must pass. +public sealed class BlobPolicyTests +{ + [Theory] + [InlineData("chart.png", 15_769)] + [InlineData("report.PDF", 1)] + [InlineData("rows.csv", 0)] + [InlineData("big.png", 10L * 1024 * 1024)] + public void WhyRefused_AllowedExtensionUnderCap_ReturnsNull(string name, long length) + { + // Act + var reason = BlobPolicy.Default.WhyRefused(name, length); + + // Assert + Assert.Null(reason); + } + + [Fact] + public void WhyRefused_OneByteOverCap_NamesTheSize() + { + // Act + var reason = BlobPolicy.Default.WhyRefused("chart.png", 10L * 1024 * 1024 + 1); + + // Assert + Assert.NotNull(reason); + Assert.Contains("10485760", reason, StringComparison.Ordinal); + } + + [Theory] + [InlineData("page.html")] + [InlineData("logo.svg")] + [InlineData("run.exe")] + [InlineData("chart.png.js")] + public void WhyRefused_ExtensionOffTheList_NamesTheExtension(string name) + { + // Act + var reason = BlobPolicy.Default.WhyRefused(name, 10); + + // Assert + Assert.NotNull(reason); + Assert.Contains("not allowed", reason, StringComparison.Ordinal); + } + + [Theory] + [InlineData("README")] + [InlineData("chart.")] + public void WhyRefused_NoExtension_Refuses(string name) + { + // Act + var reason = BlobPolicy.Default.WhyRefused(name, 10); + + // Assert + Assert.Equal("no extension", reason); + } + + [Fact] + public void WhyRefused_NegativeLength_Refuses() + { + // Act + var reason = BlobPolicy.Default.WhyRefused("chart.png", -1); + + // Assert + Assert.NotNull(reason); + } + + [Fact] + public void Constructor_CustomList_MatchesWithoutRegardToCase() + { + // Arrange + var policy = new BlobPolicy(100, ["JPG"]); + + // Act + var accepted = policy.WhyRefused("photo.jpg", 50); + var refused = policy.WhyRefused("chart.png", 50); + + // Assert + Assert.Null(accepted); + Assert.NotNull(refused); + } + + [Fact] + public void Constructor_ZeroCap_Throws() + { + // Act & Assert + Assert.Throws(() => new BlobPolicy(0, ["png"])); + } +} From 0a3b6bccad9dffeb7ff205c8b241535e5be8f19b Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Wed, 16 Sep 2026 15:14:40 -0600 Subject: [PATCH 02/35] feat: implement S3 blob storage adapter and related functionality --- .../Schema/BlobProviderConfiguration.cs | 25 +++ .../Ports/IBlobStoreAdapter.cs | 2 +- .../PublicAPI.Unshipped.txt | 25 ++- .../Secrets/KnownSecrets.cs | 19 +++ .../Blobs/S3/S3BlobStore.cs | 148 ++++++++++++++++++ .../Blobs/S3/S3BlobStoreAdapter.cs | 83 ++++++++++ .../ObjectStore/BackblazeB2/.gitkeep | 0 .../PublicAPI.Unshipped.txt | 12 ++ .../Blobs/S3/S3BlobStoreAdapterTests.cs | 32 ++++ .../Blobs/S3/S3BlobStoreTests.cs | 132 ++++++++++++++++ .../Blobs/S3/S3Bucket.cs | 28 ++++ .../Blobs/S3/S3FactAttribute.cs | 21 +++ 12 files changed, 525 insertions(+), 2 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Schema/BlobProviderConfiguration.cs create mode 100644 src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs create mode 100644 src/AgentCore.Infrastructure/Blobs/S3/S3BlobStoreAdapter.cs delete mode 100644 src/AgentCore.Infrastructure/ObjectStore/BackblazeB2/.gitkeep create mode 100644 tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreAdapterTests.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3Bucket.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3FactAttribute.cs diff --git a/src/AgentCore.Application/Configuration/Schema/BlobProviderConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/BlobProviderConfiguration.cs new file mode 100644 index 00000000..b44e9845 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Schema/BlobProviderConfiguration.cs @@ -0,0 +1,25 @@ +namespace AgentCore.Application.Configuration.Schema; + +/// +/// The blob provider: the store that keeps what a vendor's sandbox produced, and where it is. +/// +public sealed record BlobProviderConfiguration +{ + /// Gets the vendor, such as s3. + public required string Kind { get; init; } + + /// + /// Gets the service URL. + /// when the vendor needs none. + /// + public string? Endpoint { get; init; } + + /// Gets the bucket every blob is written into, or when the vendor needs none. + public string? Bucket { get; init; } + + /// + /// Gets the region the request signature names, or to read it off the + /// endpoint host. + /// + public string? Region { get; init; } +} diff --git a/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs b/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs index 8cf10de0..de98c69f 100644 --- a/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs +++ b/src/AgentCore.Application/Ports/IBlobStoreAdapter.cs @@ -12,7 +12,7 @@ public interface IBlobStoreAdapter : IVendorAdapter /// The chain a credential resolves through, or . /// Cancels the open. ValueTask OpenAsync( - VendorProviderConfiguration entry, + BlobProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default); } diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 174a2e90..16158966 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2150,7 +2150,7 @@ AgentCore.Application.Blobs.BlobWrite.OwnerId.get -> string! AgentCore.Application.Blobs.BlobWrite.OwnerId.init -> void AgentCore.Application.Ports.IBlobStore AgentCore.Application.Ports.IBlobStoreAdapter -AgentCore.Application.Ports.IBlobStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IBlobStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.BlobProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Ports.IBlobStore.DeleteByOwnerAsync(string! ownerId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Ports.IBlobStore.OpenReadAsync(string! ownerId, string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Ports.IBlobStore.PutAsync(AgentCore.Application.Blobs.BlobWrite! write, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask @@ -2174,3 +2174,26 @@ static AgentCore.Application.Blobs.BlobWrite.operator ==(AgentCore.Application.B static AgentCore.Application.Blobs.BlobWrite.operator !=(AgentCore.Application.Blobs.BlobWrite? left, AgentCore.Application.Blobs.BlobWrite? right) -> bool static readonly AgentCore.Application.Blobs.BlobPolicy.DefaultExtensions -> System.Collections.Generic.IReadOnlySet! static AgentCore.Application.Blobs.BlobName.IsSafe(string? name) -> bool +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.$() -> AgentCore.Application.Configuration.Schema.BlobProviderConfiguration! +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.BlobProviderConfiguration() -> void +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Bucket.get -> string? +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Bucket.init -> void +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Endpoint.get -> string? +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Endpoint.init -> void +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Equals(AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Kind.get -> string! +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Kind.init -> void +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Region.get -> string? +AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Region.init -> void +const AgentCore.Application.Secrets.KnownSecrets.S3AccessKeyIdName = "s3-access-key-id" -> string! +const AgentCore.Application.Secrets.KnownSecrets.S3AccessKeyIdVariable = "AWS_ACCESS_KEY_ID" -> string! +const AgentCore.Application.Secrets.KnownSecrets.S3SecretAccessKeyName = "s3-secret-access-key" -> string! +const AgentCore.Application.Secrets.KnownSecrets.S3SecretAccessKeyVariable = "AWS_SECRET_ACCESS_KEY" -> string! +override AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.ToString() -> string! +static AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.operator ==(AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? left, AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? left, AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? right) -> bool +static readonly AgentCore.Application.Secrets.KnownSecrets.S3AccessKeyId -> AgentCore.Application.Secrets.SecretName! +static readonly AgentCore.Application.Secrets.KnownSecrets.S3SecretAccessKey -> AgentCore.Application.Secrets.SecretName! diff --git a/src/AgentCore.Application/Secrets/KnownSecrets.cs b/src/AgentCore.Application/Secrets/KnownSecrets.cs index b0cd1001..e3dcba63 100644 --- a/src/AgentCore.Application/Secrets/KnownSecrets.cs +++ b/src/AgentCore.Application/Secrets/KnownSecrets.cs @@ -35,6 +35,18 @@ public static class KnownSecrets /// The environment variable the PostgreSQL connection string is read from. public const string PostgresConnectionStringVariable = "POSTGRES_CONNECTION_STRING"; + /// The ${secret:name} name the S3 access key id resolves under. + public const string S3AccessKeyIdName = "s3-access-key-id"; + + /// The standard AWS environment variable, read when the chain holds no name. + public const string S3AccessKeyIdVariable = "AWS_ACCESS_KEY_ID"; + + /// The ${secret:name} name the S3 secret access key resolves under. + public const string S3SecretAccessKeyName = "s3-secret-access-key"; + + /// The standard AWS environment variable, read when the chain holds no name. + public const string S3SecretAccessKeyVariable = "AWS_SECRET_ACCESS_KEY"; + /// The one OpenAI credential, which chat, embedding, and moderation all read. public static readonly SecretName OpenAi = new(OpenAiApiKeyName, OpenAiApiKeyVariable); @@ -52,4 +64,11 @@ public static class KnownSecrets /// The Grafana Cloud token, which is the password half of the OTLP basic credential. public static readonly SecretName GrafanaCloudApiToken = new(GrafanaCloudApiTokenName, GrafanaCloudApiTokenVariable); + + /// The key id half of the S3 credential. Backblaze B2 calls it the keyID. + public static readonly SecretName S3AccessKeyId = new(S3AccessKeyIdName, S3AccessKeyIdVariable); + + /// The secret half of the S3 credential. Backblaze B2 calls it the applicationKey. + public static readonly SecretName S3SecretAccessKey = + new(S3SecretAccessKeyName, S3SecretAccessKeyVariable); } diff --git a/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs new file mode 100644 index 00000000..16f66107 --- /dev/null +++ b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs @@ -0,0 +1,148 @@ +using System.Net; +using AgentCore.Application.Blobs; +using AgentCore.Application.Ports; +using Amazon.S3; +using Amazon.S3.Model; + +namespace AgentCore.Infrastructure.Blobs.S3; + +/// +/// on any S3-compatible bucket: Backblaze B2 today, Tigris or AWS tomorrow. +/// +public sealed class S3BlobStore : IBlobStore, IDisposable +{ + /// The most keys one DeleteObjects call accepts. + private const int DeleteBatchSize = 1000; + + private readonly IAmazonS3 _client; + + private readonly string _bucket; + + /// Wraps an S3 client the store then owns. + /// The client. Disposed with the store. + /// The bucket every blob is written into. + public S3BlobStore(IAmazonS3 client, string bucket) + { + ArgumentNullException.ThrowIfNull(client); + ArgumentException.ThrowIfNullOrWhiteSpace(bucket); + + _client = client; + _bucket = bucket; + } + + /// + public async ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(write); + ArgumentNullException.ThrowIfNull(write.Content); + + var key = KeyOf(write.OwnerId, write.Name); + + PutObjectRequest request = new() + { + BucketName = _bucket, + Key = key, + InputStream = write.Content, + ContentType = write.MediaType, + AutoCloseStream = false, + AutoResetStreamPosition = false, + }; + + request.Headers.ContentLength = write.Length; + + await _client.PutObjectAsync(request, cancellationToken).ConfigureAwait(false); + + return new BlobRef(write.OwnerId, write.Name, write.MediaType, write.Length); + } + + /// + public async ValueTask OpenReadAsync( + string ownerId, + string name, + CancellationToken cancellationToken = default) + { + var key = KeyOf(ownerId, name); + + GetObjectResponse response; + + try + { + response = await _client.GetObjectAsync(_bucket, key, cancellationToken).ConfigureAwait(false); + } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + + return new BlobRead(response.Headers.ContentType, response.ContentLength, response.ResponseStream); + } + + /// + public async ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) + { + var prefix = OwnerPrefix(ownerId); + + ListObjectsV2Request list = new() { BucketName = _bucket, Prefix = prefix }; + + List batch = new(DeleteBatchSize); + + do + { + var page = await _client.ListObjectsV2Async(list, cancellationToken).ConfigureAwait(false); + + foreach (var found in page.S3Objects ?? []) + { + batch.Add(new KeyVersion { Key = found.Key }); + + if (batch.Count == DeleteBatchSize) + { + await DeleteBatchAsync(batch, cancellationToken).ConfigureAwait(false); + } + } + + list.ContinuationToken = page.NextContinuationToken; + } + while (list.ContinuationToken is not null); + + await DeleteBatchAsync(batch, cancellationToken).ConfigureAwait(false); + } + + /// + public void Dispose() => _client.Dispose(); + + private async ValueTask DeleteBatchAsync(List batch, CancellationToken cancellationToken) + { + if (batch.Count == 0) + { + return; + } + + DeleteObjectsRequest request = new() { BucketName = _bucket, Objects = [.. batch] }; + + await _client.DeleteObjectsAsync(request, cancellationToken).ConfigureAwait(false); + + batch.Clear(); + } + + private static string KeyOf(string ownerId, string name) + { + if (!BlobName.IsSafe(name)) + { + throw new ArgumentException("A blob name must pass BlobName.IsSafe.", nameof(name)); + } + + return OwnerPrefix(ownerId) + name; + } + + private static string OwnerPrefix(string ownerId) + { + ArgumentException.ThrowIfNullOrWhiteSpace(ownerId); + + if (ownerId.Contains('/', StringComparison.Ordinal)) + { + throw new ArgumentException("An owner id may not hold a slash.", nameof(ownerId)); + } + + return ownerId + "/"; + } +} diff --git a/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStoreAdapter.cs b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStoreAdapter.cs new file mode 100644 index 00000000..8ae554bf --- /dev/null +++ b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStoreAdapter.cs @@ -0,0 +1,83 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using AgentCore.Application.Secrets; +using Amazon.Runtime; +using Amazon.S3; + +namespace AgentCore.Infrastructure.Blobs.S3; + +/// +/// The s3 blob vendor behind . +/// +public sealed class S3BlobStoreAdapter : IBlobStoreAdapter +{ + /// The one kind value this adapter serves. + public const string ProviderKind = "s3"; + + /// The region signed when the document names none and the host does not say. + public const string DefaultRegion = "us-east-1"; + + /// + public string Kind => ProviderKind; + + /// + public async ValueTask OpenAsync( + BlobProviderConfiguration entry, + ISecretResolverPort? secrets, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(entry); + + if (entry.Endpoint is not { Length: > 0 } endpoint) + { + throw Fail("/providers/blobs/endpoint", "providers.blobs: { kind: s3 } names no endpoint. Write the service URL, such as https://s3.us-west-004.backblazeb2.com."); + } + + if (entry.Bucket is not { Length: > 0 } bucket) + { + throw Fail("/providers/blobs/bucket", "providers.blobs: { kind: s3 } names no bucket. Write the bucket every blob is written into."); + } + + const string because = "A sandbox file under providers.blobs is written to an S3 bucket."; + + var keyId = await secrets.RequireAsync(KnownSecrets.S3AccessKeyId, because, cancellationToken).ConfigureAwait(false); + var secret = await secrets.RequireAsync(KnownSecrets.S3SecretAccessKey, because, cancellationToken).ConfigureAwait(false); + + AmazonS3Config config = new() + { + ServiceURL = endpoint, + AuthenticationRegion = entry.Region ?? RegionOf(endpoint), + ForcePathStyle = true, + RequestChecksumCalculation = RequestChecksumCalculation.WHEN_REQUIRED, + ResponseChecksumValidation = ResponseChecksumValidation.WHEN_REQUIRED, + }; + + return new S3BlobStore(new AmazonS3Client(new BasicAWSCredentials(keyId, secret), config), bucket); + } + + /// Reads the region off a host shaped s3.{region}.{rest}, as B2's are. + /// The service URL. + /// The region label, or when the host is not shaped that way. + internal static string RegionOf(string endpoint) + { + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri)) + { + return DefaultRegion; + } + + var labels = uri.Host.Split('.'); + + return labels.Length >= 3 && labels[0].Equals("s3", StringComparison.OrdinalIgnoreCase) + ? labels[1] + : DefaultRegion; + } + + private static ConfigurationLoadException Fail(string pointer, string message) + => new(new ConfigurationError + { + Pointer = pointer, + Message = message, + Check = ConfigurationCheck.ReferenceResolution, + }); +} diff --git a/src/AgentCore.Infrastructure/ObjectStore/BackblazeB2/.gitkeep b/src/AgentCore.Infrastructure/ObjectStore/BackblazeB2/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt index d4521433..a981fd1e 100644 --- a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt @@ -87,3 +87,15 @@ static AgentCore.Infrastructure.Secrets.EnvironmentSecretResolver.ToVariableName static readonly AgentCore.Infrastructure.Evaluation.OpenAiModeration.OpenAiModerationEvaluator.ApiEndpoint -> System.Uri! static readonly AgentCore.Infrastructure.Evaluation.OpenAiModeration.OpenAiModerationEvaluator.Categories -> System.Collections.Generic.IReadOnlyList! static readonly AgentCore.Infrastructure.Evaluation.OpenAiModeration.OpenAiModerationEvaluator.ModerationDeadline -> System.TimeSpan +AgentCore.Infrastructure.Blobs.S3.S3BlobStore +AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter +AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.Kind.get -> string! +AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.BlobProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.S3BlobStoreAdapter() -> void +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.DeleteByOwnerAsync(string! ownerId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.Dispose() -> void +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.OpenReadAsync(string! ownerId, string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.PutAsync(AgentCore.Application.Blobs.BlobWrite! write, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.S3BlobStore(Amazon.S3.IAmazonS3! client, string! bucket) -> void +const AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.DefaultRegion = "us-east-1" -> string! +const AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.ProviderKind = "s3" -> string! diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreAdapterTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreAdapterTests.cs new file mode 100644 index 00000000..8e60a649 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreAdapterTests.cs @@ -0,0 +1,32 @@ +using AgentCore.Infrastructure.Blobs.S3; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Blobs.S3; + +/// The s3 vendor's reading of a Backblaze-shaped endpoint. +public sealed class S3BlobStoreAdapterTests +{ + [Theory] + [InlineData("https://s3.us-west-004.backblazeb2.com", "us-west-004")] + [InlineData("https://s3.eu-central-003.backblazeb2.com", "eu-central-003")] + [InlineData("https://S3.us-east-005.backblazeb2.com/", "us-east-005")] + public void RegionOf_BackblazeHost_ReadsTheLabelAfterS3(string endpoint, string expected) + { + Assert.Equal(expected, S3BlobStoreAdapter.RegionOf(endpoint)); + } + + [Theory] + [InlineData("https://fly.storage.tigris.dev")] + [InlineData("http://localhost:9000")] + [InlineData("not a url")] + public void RegionOf_OtherHost_FallsBackToTheDefault(string endpoint) + { + Assert.Equal(S3BlobStoreAdapter.DefaultRegion, S3BlobStoreAdapter.RegionOf(endpoint)); + } + + [Fact] + public void Kind_IsS3() + { + Assert.Equal("s3", new S3BlobStoreAdapter().Kind); + } +} diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs new file mode 100644 index 00000000..edb66975 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs @@ -0,0 +1,132 @@ +using System.Text; +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using AgentCore.Infrastructure.Blobs.S3; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Blobs.S3; + +/// Put, read, replace and sweep, against a real bucket. +public sealed class S3BlobStoreTests : IAsyncLifetime +{ + private readonly string _owner = "test-" + Guid.NewGuid().ToString("N"); + + private IBlobStore? _store; + + private IBlobStore Store => _store ?? throw new InvalidOperationException("Not opened."); + + /// + public async ValueTask InitializeAsync() + { + if (!S3Bucket.IsConfigured) + { + return; + } + + BlobProviderConfiguration entry = new() + { + Kind = S3BlobStoreAdapter.ProviderKind, + Endpoint = S3Bucket.Endpoint, + Bucket = S3Bucket.Bucket, + }; + + _store = await new S3BlobStoreAdapter().OpenAsync(entry, secrets: null, TestContext.Current.CancellationToken); + } + + /// + public async ValueTask DisposeAsync() + { + if (_store is null) + { + return; + } + + await _store.DeleteByOwnerAsync(_owner, CancellationToken.None); + (_store as IDisposable)?.Dispose(); + } + + [S3Fact] + public async Task PutAsync_ThenOpenReadAsync_ReturnsTheSameBytesAndMediaType() + { + // Arrange + var bytes = Encoding.UTF8.GetBytes("a,b\n1,2\n"); + var token = TestContext.Current.CancellationToken; + + // Act + var put = await Store.PutAsync(new BlobWrite(_owner, "rows.csv", "text/csv", new MemoryStream(bytes), bytes.Length), token); + await using var read = await Store.OpenReadAsync(_owner, "rows.csv", token); + + // Assert + Assert.Equal(new BlobRef(_owner, "rows.csv", "text/csv", bytes.Length), put); + Assert.NotNull(read); + Assert.Equal("text/csv", read.MediaType); + Assert.Equal(bytes.Length, read.Length); + using MemoryStream copy = new(); + await read.Content.CopyToAsync(copy, token); + Assert.Equal(bytes, copy.ToArray()); + } + + [S3Fact] + public async Task PutAsync_SameNameTwice_SecondReplacesFirst() + { + // Arrange + var token = TestContext.Current.CancellationToken; + var first = Encoding.UTF8.GetBytes("first"); + var second = Encoding.UTF8.GetBytes("second, longer"); + + // Act + await Store.PutAsync(new BlobWrite(_owner, "chart.png", "image/png", new MemoryStream(first), first.Length), token); + await Store.PutAsync(new BlobWrite(_owner, "chart.png", "image/png", new MemoryStream(second), second.Length), token); + await using var read = await Store.OpenReadAsync(_owner, "chart.png", token); + + // Assert + Assert.NotNull(read); + Assert.Equal(second.Length, read.Length); + } + + [S3Fact] + public async Task OpenReadAsync_UnknownName_ReturnsNull() + { + // Act + var read = await Store.OpenReadAsync(_owner, "missing.pdf", TestContext.Current.CancellationToken); + + // Assert + Assert.Null(read); + } + + [S3Fact] + public async Task DeleteByOwnerAsync_RemovesEveryBlobOfThatOwnerOnly() + { + // Arrange + var token = TestContext.Current.CancellationToken; + var other = _owner + "-other"; + var bytes = new byte[] { 1, 2, 3 }; + + await Store.PutAsync(new BlobWrite(_owner, "a.png", "image/png", new MemoryStream(bytes), bytes.Length), token); + await Store.PutAsync(new BlobWrite(_owner, "b.pdf", "application/pdf", new MemoryStream(bytes), bytes.Length), token); + await Store.PutAsync(new BlobWrite(other, "a.png", "image/png", new MemoryStream(bytes), bytes.Length), token); + + try + { + // Act + await Store.DeleteByOwnerAsync(_owner, token); + + // Assert + Assert.Null(await Store.OpenReadAsync(_owner, "a.png", token)); + Assert.Null(await Store.OpenReadAsync(_owner, "b.pdf", token)); + await using var kept = await Store.OpenReadAsync(other, "a.png", token); + Assert.NotNull(kept); + } + finally + { + await Store.DeleteByOwnerAsync(other, CancellationToken.None); + } + } + + [S3Fact] + public async Task DeleteByOwnerAsync_NothingStored_DoesNotThrow() + { + await Store.DeleteByOwnerAsync(_owner, TestContext.Current.CancellationToken); + } +} diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3Bucket.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3Bucket.cs new file mode 100644 index 00000000..a44fd2d6 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3Bucket.cs @@ -0,0 +1,28 @@ +namespace AgentCore.Infrastructure.Tests.Blobs.S3; + +/// The S3-compatible bucket the integration tests write into, if the environment names one. +/// +/// AGENTCORE_TEST_S3_ENDPOINT and AGENTCORE_TEST_S3_BUCKET name it. The credential is +/// read the way the adapter reads it: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. +/// +public static class S3Bucket +{ + private const string EndpointVariable = "AGENTCORE_TEST_S3_ENDPOINT"; + + private const string BucketVariable = "AGENTCORE_TEST_S3_BUCKET"; + + /// Why a test skipped, when it did. + public const string SkipReason = "Set AGENTCORE_TEST_S3_ENDPOINT and AGENTCORE_TEST_S3_BUCKET to run."; + + /// The service URL, or null when the environment names none. + public static string? Endpoint => Read(EndpointVariable); + + /// The bucket, or null when the environment names none. + public static string? Bucket => Read(BucketVariable); + + /// Whether a bucket was named. + public static bool IsConfigured => Endpoint is not null && Bucket is not null; + + private static string? Read(string variable) => + Environment.GetEnvironmentVariable(variable) is { Length: > 0 } value ? value : null; +} diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3FactAttribute.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3FactAttribute.cs new file mode 100644 index 00000000..4fe1ac1b --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3FactAttribute.cs @@ -0,0 +1,21 @@ +using System.Runtime.CompilerServices; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Blobs.S3; + +/// A test that needs a live S3-compatible bucket, and skips itself when none is named. +public sealed class S3FactAttribute : FactAttribute +{ + /// Creates the attribute. + /// Supplied by the compiler. + /// Supplied by the compiler. + public S3FactAttribute( + [CallerFilePath] string? sourceFilePath = null, + [CallerLineNumber] int sourceLineNumber = -1) + : base(sourceFilePath, sourceLineNumber) + { + Skip = S3Bucket.SkipReason; + SkipUnless = nameof(S3Bucket.IsConfigured); + SkipType = typeof(S3Bucket); + } +} From 3d2e12c8f9801bca7ba7ffd0557a74fd9221c341 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Wed, 16 Sep 2026 15:28:22 -0600 Subject: [PATCH 03/35] feat: add blob store functionality with BlobStoreFactory, configuration, and tests --- .../Blobs/BlobStoreFactory.cs | 45 +++++++ .../Compilation/AgentCompilationContext.cs | 7 + .../Schema/ProvidersConfiguration.cs | 5 + .../Schema/agentcore-v1.schema.json | 32 +++++ .../PublicAPI.Unshipped.txt | 6 + .../DependencyInjection/AgentCoreBoot.cs | 10 ++ .../DependencyInjection/AgentCoreOptions.cs | 13 ++ .../AgentCoreServiceCollectionExtensions.cs | 1 + .../Startup/BlobStartup.cs | 24 ++++ .../Startup/CompilationStartup.cs | 3 + .../PublicAPI.Unshipped.txt | 1 + .../AgentCoreHostBuilderExtensions.cs | 4 + .../Blobs/BlobStoreFactoryTests.cs | 125 ++++++++++++++++++ 13 files changed, 276 insertions(+) create mode 100644 src/AgentCore.Application/Blobs/BlobStoreFactory.cs create mode 100644 src/AgentCore.AspNetCore/DependencyInjection/Startup/BlobStartup.cs create mode 100644 tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs diff --git a/src/AgentCore.Application/Blobs/BlobStoreFactory.cs b/src/AgentCore.Application/Blobs/BlobStoreFactory.cs new file mode 100644 index 00000000..8d870b4e --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobStoreFactory.cs @@ -0,0 +1,45 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using AgentCore.Application.Providers; + +namespace AgentCore.Application.Blobs; + +/// +/// Opens the blob store the document names, from the adapters the host registered. +/// +public static class BlobStoreFactory +{ + /// What this seam calls itself, so the shared selector writes its failures. + private static readonly VendorSeam Seam = + new("providers.blobs", "/providers/blobs/kind", "options.UseBlobStores(...)", "stores"); + + /// Opens the store providers.blobs names, or nothing. + /// The loaded document. + /// The chain a credential resolves through, or . + /// The vendors this host supports. + /// Cancels the open. + /// The store, or when the document names none. + /// The configuration or the adapters are . + /// + /// The document names a kind no adapter serves, or a kind two adapters answer to. + /// + public static async ValueTask OpenAsync( + AgentCoreConfiguration configuration, + ISecretResolverPort? secrets, + IReadOnlyList adapters, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(adapters); + + if (configuration.Providers?.Blobs is not { } entry) + { + return null; + } + + var adapter = VendorAdapterSelector.Select(entry.Kind, adapters, Seam); + + return await adapter.OpenAsync(entry, secrets, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs index ac91f2f5..075197f0 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs @@ -53,6 +53,13 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// public IKnowledgeRetrievalPort? Knowledge { get; init; } + /// + /// Gets or sets the store a sandbox file is kept in after the run, or + /// when the document names no providers.blobs. With it null, a code.execute agent + /// captures nothing. + /// + public IBlobStore? Blobs { get; init; } + /// /// Gets or sets the skills every agent's skills: list is drawn from, or /// when the host bound no skills folder. diff --git a/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs index a07f9b67..16d7d55a 100644 --- a/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs @@ -368,4 +368,9 @@ public sealed record ProvidersConfiguration /// Gets the call store provider, or for the in-process default. public VendorProviderConfiguration? Calls { get; init; } + + /// + /// Gets the blob store provider, or when a sandbox file is never kept. + /// + public BlobProviderConfiguration? Blobs { get; init; } } diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index 00f85e2f..4f4c0625 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -1205,6 +1205,38 @@ "calls": { "$ref": "#/$defs/vendorProvider", "description": "Where a call is kept: its row, and the words of it. A document that names none uses the in-process memory store, which is not durable and holds no retention window." + }, + "blobs": { + "$ref": "#/$defs/blobProvider", + "description": "Where a file the vendor's sandbox wrote is kept after the run, such as s3. A document that names none keeps no sandbox file." + } + } + }, + "blobProvider": { + "type": "object", + "required": [ + "kind" + ], + "additionalProperties": false, + "properties": { + "kind": { + "type": "string", + "minLength": 1 + }, + "endpoint": { + "type": "string", + "minLength": 1, + "description": "The service URL, such as https://s3.us-west-004.backblazeb2.com." + }, + "bucket": { + "type": "string", + "minLength": 1, + "description": "The bucket every blob is written into." + }, + "region": { + "type": "string", + "minLength": 1, + "description": "The region the request signature names. Omit it to read the region off the endpoint host." } } }, diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 16158966..7b2710da 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2197,3 +2197,9 @@ static AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.oper static AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? left, AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? right) -> bool static readonly AgentCore.Application.Secrets.KnownSecrets.S3AccessKeyId -> AgentCore.Application.Secrets.SecretName! static readonly AgentCore.Application.Secrets.KnownSecrets.S3SecretAccessKey -> AgentCore.Application.Secrets.SecretName! +AgentCore.Application.Blobs.BlobStoreFactory +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Blobs.get -> AgentCore.Application.Ports.IBlobStore? +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Blobs.init -> void +AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Blobs.get -> AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? +AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Blobs.init -> void +static AgentCore.Application.Blobs.BlobStoreFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index 1f189c51..b96e80dd 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -92,6 +92,9 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers, /// Gets the knowledge base, or when no agent reads one. internal IKnowledgeRetrievalPort? Knowledge => Started.Knowledge; + /// Gets the blob store, or when the document names none. + internal IBlobStore? Blobs => Started.Blobs; + /// Gets what each entry's call route runs, keyed by entry name, or when no call routes here. internal IReadOnlyDictionary? CallHandlers => Started.CallHandlers; @@ -217,6 +220,10 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) .OpenAsync(configuration, _options, _loggers, cancellationToken) .ConfigureAwait(false)); + var blobs = Track(await BlobStartup + .OpenAsync(configuration, _options, cancellationToken) + .ConfigureAwait(false)); + var evaluators = await EvaluationStartup .CreateRegistryAsync(configuration, _options, cancellationToken) .ConfigureAwait(false); @@ -227,6 +234,7 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) chatClients, tools.Registry, calls, + blobs, evaluators, knowledge, skills, @@ -247,6 +255,7 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) telemetry, tools.Registry, calls, + blobs, evaluators, graph, call.Entries, @@ -356,6 +365,7 @@ private sealed record BootState( ITelemetrySession? Telemetry, ToolRegistry Tools, ICallStore Calls, + IBlobStore? Blobs, EvaluatorRegistry Evaluators, CompiledGraph Graph, EntryRegistry Entries, diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index df0886b1..512f0730 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -69,6 +69,9 @@ public sealed class AgentCoreOptions /// Gets the call store vendors the host registered, or . internal IReadOnlyList? CallStores { get; private set; } + /// Gets the blob store vendors the host registered, or . + internal IReadOnlyList? BlobStores { get; private set; } + /// Gets the speech vendors the host registered, or . internal IReadOnlyList? Speech { get; private set; } @@ -235,6 +238,16 @@ public AgentCoreOptions UseCallStores(params ICallStoreAdapter[] adapters) return this; } + /// Binds the blob store vendors, and the document picks one by providers.blobs.kind. + /// The vendors this host supports. + /// These options, so a host chains its calls. + public AgentCoreOptions UseBlobStores(params IBlobStoreAdapter[] adapters) + { + ArgumentNullException.ThrowIfNull(adapters); + BlobStores = adapters; + return this; + } + /// Binds the host's own readings of a call, beside the three this library keeps. /// /// What the host wants told about every call. Each one takes every fact, in the order the call diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs index 48bf8df5..9b089c8b 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs @@ -61,6 +61,7 @@ public static IServiceCollection AddAgentCore( services.AddSingleton(Boot(boot => boot.Telemetry!)); services.AddSingleton(Boot(boot => boot.Knowledge!)); + services.AddSingleton(Boot(boot => boot.Blobs!)); services.AddSingleton(Boot(boot => boot.CallAdapters!)); services.AddSingleton(Boot(boot => boot.SpeechAdapters!)); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/BlobStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/BlobStartup.cs new file mode 100644 index 00000000..1c2f4a8f --- /dev/null +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/BlobStartup.cs @@ -0,0 +1,24 @@ +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; + +namespace AgentCore.AspNetCore.DependencyInjection.Startup; + +/// Step 4d: open the blob store the document names, before the document is compiled. +internal static class BlobStartup +{ + /// Opens the store providers.blobs names, or nothing. + /// The loaded document. It carries providers.blobs. + /// The options the host filled. It carries the blob store vendors. + /// Cancels the store open. + /// The store, or when the document names none. + internal static ValueTask OpenAsync( + AgentCoreConfiguration configuration, + AgentCoreOptions options, + CancellationToken cancellationToken) + => BlobStoreFactory.OpenAsync( + configuration, + options.SecretResolver, + options.BlobStores ?? [], + cancellationToken); +} diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs index 95b242a5..af6d8161 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -30,6 +30,7 @@ internal static class CompilationStartup /// The factory step 3c built, which the compile table asks for every agent and for the extractor. /// The registry step 4 built. /// The store every call's row and every word of it is kept in. + /// The store step 4d opened, or when the document names no blob vendor. /// /// The registry the moderator comes out of. R3 puts moderation in the chat pipeline of every /// compiled agent, so it is bound here rather than on the session factory. @@ -46,6 +47,7 @@ internal static ValueTask CompileAsync( IChatClientFactory chatClients, ToolRegistry tools, ICallStore calls, + IBlobStore? blobs, EvaluatorRegistry evaluators, IKnowledgeRetrievalPort? knowledge, SkillCatalog? skills, @@ -64,6 +66,7 @@ internal static ValueTask CompileAsync( Guards = guards, Moderation = PromptModerator.FromRegistry(evaluators), CallStore = calls, + Blobs = blobs, Knowledge = knowledge, Skills = skills, Citations = citations, diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 533195ad..8902a11c 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -78,3 +78,4 @@ static AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.Ma static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.ConnectionLifetime -> System.TimeSpan static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.FirstRetryDelay -> System.TimeSpan static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.RequestDeadline -> System.TimeSpan +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseBlobStores(params AgentCore.Application.Ports.IBlobStoreAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! diff --git a/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs b/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs index 63e5e9c6..8445fb96 100644 --- a/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs +++ b/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs @@ -3,6 +3,7 @@ using AgentCore.AspNetCore.Vendors.TelnyxRelay; using AgentCore.Hosting.Secrets; using AgentCore.Infrastructure.Audit.Postgres; +using AgentCore.Infrastructure.Blobs.S3; using AgentCore.Infrastructure.Calls.Postgres; using AgentCore.Infrastructure.Embeddings.OpenAI; using AgentCore.Infrastructure.Evaluation.OpenAiModeration; @@ -131,6 +132,9 @@ private static void Configure( // providers.calls.kind picks the adapter. options.UseCallStores(new PostgresCallStoreAdapter()); + + // providers.blobs.kind picks the adapter. + options.UseBlobStores(new S3BlobStoreAdapter()); } /// Opens the client a transport: http MCP server is reached on. diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs new file mode 100644 index 00000000..b3675f9a --- /dev/null +++ b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs @@ -0,0 +1,125 @@ +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using Xunit; + +namespace AgentCore.Application.Tests.Blobs; + +/// +/// The blob vendor seam: providers.blobs, and what a document that names none gets. +/// +/// +/// Unlike the call store, there is no built-in kind. A document that names none gets +/// , and that null is what switches the capture provider off. +/// +public sealed class BlobStoreFactoryTests +{ + [Fact] + public async Task OpenAsync_NoBlobsBlock_GetsNullAndAsksNoAdapter() + { + // Arrange + var configuration = ConfigurationLoader.LoadYaml(Document()); + FakeBlobStoreAdapter adapter = new("s3"); + + // Act + var store = await BlobStoreFactory.OpenAsync( + configuration, secrets: null, [adapter], TestContext.Current.CancellationToken); + + // Assert + Assert.Null(store); + Assert.Equal(0, adapter.Opens); + } + + [Fact] + public async Task OpenAsync_TheKind_PicksOneAdapterAndHandsItTheWholeBlock() + { + // Arrange + var configuration = ConfigurationLoader.LoadYaml( + Document("kind: fake", "endpoint: https://s3.us-east-005.backblazeb2.com", "bucket: spirit", "region: us-east-005")); + FakeBlobStoreAdapter fake = new("fake"); + FakeBlobStoreAdapter other = new("s3"); + + // Act + var store = await BlobStoreFactory.OpenAsync( + configuration, secrets: null, [other, fake], TestContext.Current.CancellationToken); + + // Assert + Assert.Same(fake.Store, store); + Assert.Equal(0, other.Opens); + Assert.NotNull(fake.Entry); + Assert.Equal("https://s3.us-east-005.backblazeb2.com", fake.Entry.Endpoint); + Assert.Equal("spirit", fake.Entry.Bucket); + Assert.Equal("us-east-005", fake.Entry.Region); + } + + [Fact] + public async Task OpenAsync_AKindNoAdapterServes_FailsTheStartAndPointsAtTheKind() + { + // Arrange + var configuration = ConfigurationLoader.LoadYaml(Document("kind: s3")); + FakeBlobStoreAdapter adapter = new("fake"); + + // Act + var failure = await Assert.ThrowsAsync( + async () => await BlobStoreFactory.OpenAsync( + configuration, secrets: null, [adapter], TestContext.Current.CancellationToken)); + + // Assert + Assert.Contains("s3", failure.Message, StringComparison.Ordinal); + Assert.Equal("/providers/blobs/kind", failure.Errors[0].Pointer); + } + + [Fact] + public void LoadYaml_AnUnknownKeyUnderBlobs_IsRejectedBySchema() + { + // Act & Assert + Assert.Throws( + () => ConfigurationLoader.LoadYaml(Document("kind: s3", "path: /tmp"))); + } + + private const string KnowledgeLine = Configuration.ExampleDocument.LastProviderLine; + + /// Builds the section 8.1 document with one blobs block written into it. + private static string Document(params string[] entries) + => entries.Length == 0 + ? Configuration.ExampleDocument.Yaml + : Configuration.ExampleDocument.Yaml.Replace( + KnowledgeLine, + KnowledgeLine + "\n blobs:\n" + string.Join("\n", entries.Select(entry => " " + entry)), + StringComparison.Ordinal); + + /// An adapter that opens nothing and records what it was handed. + private sealed class FakeBlobStoreAdapter(string kind) : IBlobStoreAdapter + { + public string Kind => kind; + + public int Opens { get; private set; } + + public BlobProviderConfiguration? Entry { get; private set; } + + public IBlobStore Store { get; } = new FakeBlobStore(); + + public ValueTask OpenAsync( + BlobProviderConfiguration entry, + ISecretResolverPort? secrets, + CancellationToken cancellationToken = default) + { + Opens++; + Entry = entry; + return ValueTask.FromResult(Store); + } + } + + private sealed class FakeBlobStore : IBlobStore + { + public ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } +} From 203466fa1e070dbc4f2ffa0bbf953597f4836d49 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Wed, 16 Sep 2026 16:00:35 -0600 Subject: [PATCH 04/35] feat: implement OpenAiSandboxFilesClient and associated tests for handling container file citations --- .../Llm/OpenAI/OpenAiChatClientAdapter.cs | 18 +-- .../Llm/OpenAI/OpenAiSandboxFilesClient.cs | 90 +++++++++++ .../Llm/OpenAiSandboxFilesClientTests.cs | 151 ++++++++++++++++++ 3 files changed, 242 insertions(+), 17 deletions(-) create mode 100644 src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs diff --git a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs index 963f6788..742c5319 100644 --- a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs +++ b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs @@ -17,22 +17,6 @@ namespace AgentCore.Infrastructure.Llm.OpenAI; /// /// The OpenAI adapter behind . /// -/// -/// -/// This class owns the vendor only: the SDK client, the key, the model name of one entry. The -/// as map, the default entry, the temperature wrapper, and the client cache live in -/// CompositeChatClientFactory, which calls this adapter once for each providers.llm[] -/// entry whose kind is . The seam therefore moves to another vendor -/// by registering another adapter, and no code changes. -/// -/// -/// The API key never appears in this file. The first build hands -/// to , which -/// asks the chain and then falls back to the variable every OpenAI -/// tool already reads. No message and no exception of this class carries the value. One vendor -/// client serves every entry, so the key resolves once and a call costs one connection pool. -/// -/// public sealed class OpenAiChatClientAdapter : IChatClientAdapter { /// The one providers.llm[].kind value this adapter serves. @@ -64,7 +48,7 @@ await secrets var client = _client.GetResponsesClient().AsIChatClient(entry.Model); - return WithResponseDefaults(client, entry.ReasoningEffort); + return new OpenAiSandboxFilesClient(WithResponseDefaults(client, entry.ReasoningEffort), _client); } /// diff --git a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs new file mode 100644 index 00000000..6d33f38c --- /dev/null +++ b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs @@ -0,0 +1,90 @@ +#pragma warning disable OPENAI001 +#pragma warning disable MEAI001 // IHostedFileClient and HostedFileContent.Scope are evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using System.Runtime.CompilerServices; +using Microsoft.Extensions.AI; +using OpenAI; +using OpenAI.Responses; + +namespace AgentCore.Infrastructure.Llm.OpenAI; + +/// +/// Makes a file the OpenAI sandbox wrote look the way Microsoft.Extensions.AI says it should. +/// +internal sealed class OpenAiSandboxFilesClient : DelegatingChatClient +{ + private readonly IHostedFileClient _files; + + public OpenAiSandboxFilesClient(IChatClient inner, OpenAIClient openAi) + : base(inner) + { + ArgumentNullException.ThrowIfNull(openAi); + + _files = openAi.AsIHostedFileClient(); + } + + /// + public override object? GetService(Type serviceType, object? serviceKey = null) + => serviceKey is null && serviceType == typeof(IHostedFileClient) + ? _files + : base.GetService(serviceType, serviceKey); + + /// + public override async Task GetResponseAsync( + IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) + { + var response = await base.GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false); + + foreach (var message in response.Messages) + { + Surface(message.Contents); + } + + return response; + } + + /// + public override async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await foreach (var update in base.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false)) + { + Surface(update.Contents); + yield return update; + } + } + + /// Appends one for every container-file citation in the list. + private static void Surface(IList contents) + { + List? found = null; + + foreach (var content in contents) + { + if (content is not TextContent { Annotations: { } annotations }) + { + continue; + } + + foreach (var annotation in annotations) + { + if (annotation.RawRepresentation is ContainerFileCitationMessageAnnotation raw) + { + (found ??= []).Add(new HostedFileContent(raw.FileId) { Scope = raw.ContainerId, Name = raw.Filename }); + } + } + } + + if (found is null) + { + return; + } + + foreach (var file in found) + { + contents.Add(file); + } + } +} diff --git a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs new file mode 100644 index 00000000..a7ccd98d --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs @@ -0,0 +1,151 @@ +#pragma warning disable OPENAI001 +#pragma warning disable MEAI001 // IHostedFileClient and HostedFileContent.Scope are evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Runtime.CompilerServices; +using AgentCore.Infrastructure.Llm.OpenAI; +using Microsoft.Extensions.AI; +using OpenAI; +using OpenAI.Responses; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Llm; + +/// +/// The vendor middleware that turns a container_file_citation into a . +/// +/// +/// The wire shape is the OpenAI API reference's container_file_citation object. The +/// Microsoft.Extensions.AI.OpenAI adapter maps it to a and keeps +/// the SDK object on ; the container id lives only there. +/// +public sealed class OpenAiSandboxFilesClientTests +{ + private const string CitationJson = """ + { + "type": "container_file_citation", + "container_id": "cntr_68c8f1a2b3c4d5e6f7a8b9c0", + "file_id": "cfile_68c8f1a2b3c4d5e6f7a8b9c1", + "filename": "chart.png", + "start_index": 42, + "end_index": 71 + } + """; + + private static readonly OpenAIClient OpenAi = new(new ApiKeyCredential("sk-test")); + + [Fact] + public async Task GetResponseAsync_ContainerFileCitation_AddsOneHostedFileContent() + { + // Arrange + var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [CitedText()]))); + using var client = new OpenAiSandboxFilesClient(inner, OpenAi); + + // Act + var response = await client.GetResponseAsync("draw", cancellationToken: TestContext.Current.CancellationToken); + + // Assert + var file = Assert.Single(response.Messages[0].Contents.OfType()); + Assert.Equal("cfile_68c8f1a2b3c4d5e6f7a8b9c1", file.FileId); + Assert.Equal("cntr_68c8f1a2b3c4d5e6f7a8b9c0", file.Scope); + Assert.Equal("chart.png", file.Name); + Assert.Equal("Here is your chart: [Download](sandbox:/mnt/data/chart.png)", response.Text); + } + + [Fact] + public async Task GetStreamingResponseAsync_ContainerFileCitation_AddsItToThatUpdate() + { + // Arrange + var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [CitedText()]))); + using var client = new OpenAiSandboxFilesClient(inner, OpenAi); + + // Act + var files = new List(); + await foreach (var update in client.GetStreamingResponseAsync("draw", cancellationToken: TestContext.Current.CancellationToken)) + { + files.AddRange(update.Contents.OfType()); + } + + // Assert + Assert.Equal("cfile_68c8f1a2b3c4d5e6f7a8b9c1", Assert.Single(files).FileId); + } + + [Fact] + public async Task GetResponseAsync_CitationWithoutTheRawObject_AddsNothing() + { + // Arrange: a citation from some other source (a vector-store file, say) carries no container. + TextContent text = new("see [1]") + { + Annotations = [new CitationAnnotation { FileId = "file-abc", Title = "notes.txt" }], + }; + var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [text]))); + using var client = new OpenAiSandboxFilesClient(inner, OpenAi); + + // Act + var response = await client.GetResponseAsync("cite", cancellationToken: TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(response.Messages[0].Contents.OfType()); + } + + [Fact] + public void GetService_IHostedFileClient_AnswersThroughTheWrappersAbove() + { + // Arrange: the same wrappers the composite and the harness put above the vendor client. + using var client = new OpenAiSandboxFilesClient(new ScriptedChatClient(new ChatResponse()), OpenAi) + .AsBuilder() + .ConfigureOptions(options => options.Temperature ??= 0.2f) + .UseFunctionInvocation() + .Build(); + + // Act & Assert + Assert.NotNull(client.GetService()); + } + + [Fact] + public void GetService_IHostedFileClient_TheVendorClientAloneAnswersNothing() + { + // The reason the middleware exists. + using var vendor = OpenAi.GetResponsesClient().AsIChatClient("gpt-x"); + + Assert.Null(vendor.GetService()); + } + + private static TextContent CitedText() + { + var raw = ModelReaderWriter.Read(BinaryData.FromString(CitationJson))!; + + return new TextContent("Here is your chart: [Download](sandbox:/mnt/data/chart.png)") + { + Annotations = [new CitationAnnotation { FileId = raw.FileId, Title = raw.Filename, RawRepresentation = raw }], + }; + } + + /// An inner client that answers one fixed response, whole or as one update per message. + private sealed class ScriptedChatClient(ChatResponse response) : IChatClient + { + public Task GetResponseAsync( + IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) + => Task.FromResult(response); + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + foreach (var message in response.Messages) + { + yield return new ChatResponseUpdate(message.Role, [.. message.Contents]); + } + + await Task.CompletedTask; + } + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + + public void Dispose() + { + } + } +} From 017c57476aa4fff59b72ca7d4db2701c50810c52 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Wed, 16 Sep 2026 16:18:08 -0600 Subject: [PATCH 05/35] feat: implement background agent handling with new providers and capture functionality --- .../Compilation/AgentBackgroundCompiler.cs | 65 ++++++ .../Compilation/AgentCaptureCompiler.cs | 48 +++++ .../AgentContextProviderCompiler.cs | 7 +- .../Compilation/AgentHarnessProviders.cs | 60 +----- .../Compilation/ConfigurationCompiler.cs | 3 +- src/AgentCore.Application/Diagnostics/Log.cs | 32 +++ .../Runtime/GraphStateAgent.cs | 8 +- .../Runtime/Harness/BackgroundChildAgent.cs | 31 +++ .../Runtime/Harness/BlobOwnerKey.cs | 17 ++ .../Harness/HostedFileCaptureProvider.cs | 195 ++++++++++++++++++ .../Runtime/TurnInvocation.cs | 7 + .../Fakes/RecordingBlobStore.cs | 36 ++++ .../Fakes/ScriptedHostedFileClient.cs | 80 +++++++ .../Harness/BackgroundChildAgentTests.cs | 64 ++++++ .../Harness/HostedFileCaptureProviderTests.cs | 179 ++++++++++++++++ 15 files changed, 772 insertions(+), 60 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs create mode 100644 src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs create mode 100644 src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs create mode 100644 src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs create mode 100644 tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs create mode 100644 tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs new file mode 100644 index 00000000..89cf260d --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs @@ -0,0 +1,65 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Harness; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. + +/// +/// The provider behind one agent's background: list: its children, each wrapped so a child +/// session knows which call started it. +/// +internal static class AgentBackgroundCompiler +{ + /// Builds the provider that starts this agent's background children. + /// The agent being compiled. + /// This agent's JSON pointer, for a background: failure. + /// Resolves an agents.items id to its compiled agent, or when undeclared. + public static BackgroundAgentsProvider Build( + AgentConfiguration item, + string pointer, + Func resolve) + { + if (item.Background.Contains(item.Id, StringComparer.Ordinal)) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "background"), + $"the agent '{item.Id}' names itself in background:, so it would start itself as its own child. " + + "Remove it from the list, or point at another agent."); + } + + List children = new(item.Background.Count); + for (var index = 0; index < item.Background.Count; index++) + { + var childPointer = ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer(pointer, "background"), index); + + var childId = item.Background[index]; + + var child = resolve(childId) + ?? throw ConfigurationCompiler.Fail( + childPointer, + $"the agent '{childId}' is not declared in agents.items"); + + children.Add(new BackgroundChildAgent(child)); + } + + try + { + // Children run with their own compiled tools, which carry no approval-required tool + // today — every harness tool runs with approval off — so a child never stalls waiting + // for an approval the parent would only see as a completed task with empty output. + return new BackgroundAgentsProvider(children); + } + catch (ArgumentException exception) + { + // The provider keys children by name case-insensitively, so two ids that differ only + // by case collide here rather than at either declaration. + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "background"), + $"the agent '{item.Id}' declares background: children whose names collide: {exception.Message}"); + } + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs new file mode 100644 index 00000000..5a18eaa1 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs @@ -0,0 +1,48 @@ +#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Harness; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace AgentCore.Application.Configuration.Compilation; + +/// +/// The provider that keeps what an agent's sandbox wrote. It is added when three things hold: the +/// agent runs a hosted code tool, its vendor can download what the sandbox wrote, and the document +/// opened a blob store. The code.execute tool is the switch; no yaml on the agent names this. +/// +internal static class AgentCaptureCompiler +{ + /// Builds the capture provider, or nothing when there is nothing to capture. + /// The agents.defaults section, or . + /// The agent being compiled. + /// The compile-time seams, including the blob store and the chat clients. + /// This agent's compiled tools, or when it advertises none. + public static HostedFileCaptureProvider? Build( + AgentDefaults? defaults, + AgentConfiguration item, + AgentCompilationContext context, + IReadOnlyList? tools) + { + if (context.Blobs is not { } blobs || tools?.Any(static tool => tool is HostedCodeInterpreterTool) != true) + { + return null; + } + + var files = context.ChatClients.GetChatClient(item.Model ?? defaults?.Model).GetService(); + + if (files is null) + { + return null; + } + + return new HostedFileCaptureProvider( + files, + blobs, + BlobPolicy.Default, + context.Loggers?.CreateLogger() ?? NullLogger.Instance); + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index f0e109d6..f5a73a24 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -7,6 +7,7 @@ using AgentCore.Application.Skills; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Compaction; +using Microsoft.Extensions.AI; namespace AgentCore.Application.Configuration.Compilation; internal static class AgentContextProviderCompiler @@ -31,7 +32,8 @@ public static List Build( ResolvedClarification clarification, KnowledgeScopeConfiguration? scope, Func resolve, - ICollection? background = null) + ICollection? background = null, + IReadOnlyList? tools = null) { List providers = [new TurnContextProvider()]; @@ -71,7 +73,8 @@ public static List Build( loggerFactory: context.Loggers)); #pragma warning restore MAAI001 } - AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background); + + AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background, tools); if (AgentKnowledge.Compose(defaults, item) is not { } composed) { diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index a7563f25..9d383505 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Tools.Shell; +using Microsoft.Extensions.AI; namespace AgentCore.Application.Configuration.Compilation; @@ -66,6 +67,7 @@ internal static class AgentHarnessProviders /// This agent's JSON pointer, for a memory:, files:, shell:, or background: failure. /// Resolves an agents.items id to its compiled agent, or when undeclared. /// Collects the built background providers, so the call can release their sessions when it ends. + /// This agent's compiled tools, or when it advertises none. public static void Add( List providers, AgentDefaults? defaults, @@ -73,7 +75,8 @@ public static void Add( AgentCompilationContext context, string pointer, Func resolve, - ICollection? background = null) + ICollection? background = null, + IReadOnlyList? tools = null) { var harness = AgentHarness.Compose(defaults, item); @@ -106,10 +109,15 @@ public static void Add( if (item.Background.Count > 0) { - var provider = BuildBackgroundProvider(item, pointer, resolve); + var provider = AgentBackgroundCompiler.Build(item, pointer, resolve); providers.Add(provider); background?.Add(provider); } + + if (AgentCaptureCompiler.Build(defaults, item, context, tools) is { } capture) + { + providers.Add(capture); + } } #pragma warning restore MAAI001 @@ -214,54 +222,6 @@ internal static IReadOnlySet StateKeysOf(IEnumerable return keys; } -#pragma warning restore MAAI001 - -#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. - - private static BackgroundAgentsProvider BuildBackgroundProvider( - AgentConfiguration item, - string pointer, - Func resolve) - { - if (item.Background.Contains(item.Id, StringComparer.Ordinal)) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "background"), - $"the agent '{item.Id}' names itself in background:, so it would start itself as its own child. " - + "Remove it from the list, or point at another agent."); - } - - List children = new(item.Background.Count); - for (var index = 0; index < item.Background.Count; index++) - { - var childPointer = ConfigurationError.AppendPointer( - ConfigurationError.AppendPointer(pointer, "background"), index); - - var childId = item.Background[index]; - - children.Add(resolve(childId) - ?? throw ConfigurationCompiler.Fail( - childPointer, - $"the agent '{childId}' is not declared in agents.items")); - } - - try - { - // Children run with their own compiled tools, which carry no approval-required tool - // today — every harness tool runs with approval off — so a child never stalls waiting - // for an approval the parent would only see as a completed task with empty output. - return new BackgroundAgentsProvider(children); - } - catch (ArgumentException exception) - { - // The provider keys children by name case-insensitively, so two ids that differ only - // by case collide here rather than at either declaration. - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "background"), - $"the agent '{item.Id}' declares background: children whose names collide: {exception.Message}"); - } - } - #pragma warning restore MAAI001 private static FileMemoryProvider BuildMemoryProvider( diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index c39e92c4..fbdaa224 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -294,7 +294,8 @@ private static (Dictionary Agents, IReadOnlySet Harness clarification, configuration.Providers?.Knowledge?.Scope, Resolve, - backgroundProviders); + backgroundProviders, + compiledTools); harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); harnessStateKeys.UnionWith(AgentApproval.StateKeysFor(section.Defaults, item, compiledTools)); diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index f01ae6da..cd6e1e82 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -280,4 +280,36 @@ public static partial void KnowledgeScopeComposed( Level = LogLevel.Warning, Message = "Could not release the background agent sessions of the call '{CallId}'.")] public static partial void BackgroundReleaseFailed(ILogger logger, string callId, Exception exception); + + /// A sandbox file could not be kept: the run had no call to own it. + /// The logger of the provider. + /// The agent whose run produced the file. + [LoggerMessage( + EventId = 23, + Level = LogLevel.Warning, + Message = "A sandbox file of the agent '{Agent}' was not kept: the run has no call id. " + + "Files are kept only for a run through a CallSession, or a background child of one.")] + public static partial void SandboxFileHasNoOwner(ILogger logger, string agent); + + /// A sandbox file was refused by name or by policy, and the reply went out without it. + /// The logger of the provider. + /// The call that would have owned the file. + /// The name the sandbox gave the file. + /// Why it was refused. + [LoggerMessage( + EventId = 24, + Level = LogLevel.Warning, + Message = "The sandbox file '{Name}' of call {CallId} was not kept: {Reason}.")] + public static partial void SandboxFileRefused(ILogger logger, string callId, string name, string reason); + + /// A sandbox file could not be downloaded or stored, and the reply went out without it. + /// The logger of the provider. + /// The call that would have owned the file. + /// The name the sandbox gave the file. + /// The cause. + [LoggerMessage( + EventId = 25, + Level = LogLevel.Warning, + Message = "The sandbox file '{Name}' of call {CallId} could not be kept.")] + public static partial void SandboxFileCaptureFailed(ILogger logger, string callId, string name, Exception exception); } diff --git a/src/AgentCore.Application/Runtime/GraphStateAgent.cs b/src/AgentCore.Application/Runtime/GraphStateAgent.cs index 4020b9db..057d2e27 100644 --- a/src/AgentCore.Application/Runtime/GraphStateAgent.cs +++ b/src/AgentCore.Application/Runtime/GraphStateAgent.cs @@ -47,7 +47,7 @@ private List Filed(IEnumerable messages, AgentSession? { ArgumentNullException.ThrowIfNull(messages); - var invocation = TurnRegistry.For(session) ?? FromOptions(options); + var invocation = TurnRegistry.For(session) ?? TurnInvocation.From(options); var snapshot = invocation?.State?.Snapshot(); if (snapshot is null) @@ -59,10 +59,4 @@ private List Filed(IEnumerable messages, AgentSession? return [GraphStateCarrier.Build(snapshot), .. messages]; } - - private static TurnInvocation? FromOptions(AgentRunOptions? options) - => options is ChatClientAgentRunOptions run - && run.ChatOptions?.AdditionalProperties?.TryGetValue(TurnInvocation.ArgumentsKey, out var filed) == true - ? filed as TurnInvocation - : null; } diff --git a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs new file mode 100644 index 00000000..53b1b58b --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs @@ -0,0 +1,31 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime.Harness; + +/// +/// Wraps one background: child so every session it gets knows which call started it. +/// +/// +/// BackgroundAgentsProvider creates the child session inside the parent's tool call, before +/// it hands the run to a task. At that moment is still the +/// parent's run, and its options carry the parent's turn. That is the only place the call id can +/// cross from parent to child: the provider passes the child null run options and a fresh session, +/// and its task-to-session map is private. Proven by probe P2 against Microsoft.Agents.AI 1.21.0. +/// +internal sealed class BackgroundChildAgent(AIAgent inner) : DelegatingAIAgent(inner) +{ + /// + protected override async ValueTask CreateSessionCoreAsync(CancellationToken cancellationToken = default) + { + var parent = AIAgent.CurrentRunContext; + + var session = await InnerAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + + if (TurnInvocation.From(parent?.RunOptions)?.CallId is { } callId) + { + session.StateBag.SetValue(BlobOwnerKey.Value, callId); + } + + return session; + } +} diff --git a/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs b/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs new file mode 100644 index 00000000..14f487e4 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs @@ -0,0 +1,17 @@ +namespace AgentCore.Application.Runtime.Harness; + +/// +/// The key under which a background child's +/// session carries the id of the call that started it. +/// +/// +/// A parent run has a turn filed in TurnRegistry, so its providers read the call id there. +/// A child session has no turn: the framework starts it with fresh, empty state and null run +/// options. stamps this key when the session is created, and +/// reads it back when the turn lookup finds nothing. +/// +internal static class BlobOwnerKey +{ + /// The key. The value is the call id, a string. + public const string Value = "urn:agentcore:blob-owner"; +} diff --git a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs new file mode 100644 index 00000000..0dc1a8ae --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs @@ -0,0 +1,195 @@ +#pragma warning disable MEAI001 // IHostedFileClient and HostedFileContent.Scope are evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using AgentCore.Application.Blobs; +using AgentCore.Application.Diagnostics; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Runtime.Harness; + +/// +/// Copies every file the vendor's sandbox wrote during a run into the call's blob store. +/// +/// +/// +/// The model takes no action. It writes a file under /mnt/data and links it as +/// sandbox:/mnt/data/<name>, as it does unprompted. After the run this provider reads +/// each the vendor surfaced, downloads it, and stores it under +/// (callId, name). The host rewrites the link later; the model never learns a route. +/// +/// +/// A file that cannot be kept is logged, never thrown: the reply still goes out, with a link the +/// host cannot resolve. Capture runs once per run, at its end. The sandbox container idles out +/// after twenty minutes; a run that idles longer than that before it ends would lose the file. +/// +/// +internal sealed class HostedFileCaptureProvider : AIContextProvider +{ + private const string Instructions = + "When you produce a file (a chart, a PDF, a CSV), save it under /mnt/data with a short plain " + + "file name, and refer to it in your reply as sandbox:/mnt/data/."; + + private readonly IHostedFileClient _files; + + private readonly IBlobStore _blobs; + + private readonly BlobPolicy _policy; + + private readonly ILogger _logger; + + /// Creates the provider for one agent. + /// The vendor's downloader, taken off the agent's chat client. + /// The store providers.blobs opened. + /// The cap and the allowlist. + /// Where a file that could not be kept is reported. + public HostedFileCaptureProvider(IHostedFileClient files, IBlobStore blobs, BlobPolicy policy, ILogger logger) + { + ArgumentNullException.ThrowIfNull(files); + ArgumentNullException.ThrowIfNull(blobs); + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(logger); + + _files = files; + _blobs = blobs; + _policy = policy; + _logger = logger; + } + + /// + protected override ValueTask InvokingCoreAsync(InvokingContext context, CancellationToken cancellationToken = default) + => new(new AIContext { Instructions = Instructions }); + + /// + protected override async ValueTask InvokedCoreAsync(InvokedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + + List? found = null; + + foreach (var message in context.ResponseMessages ?? []) + { + foreach (var file in FilesIn(message)) + { + (found ??= []).Add(file); + } + } + + if (found is null) + { + return; + } + + if (OwnerOf(context.Session) is not { } callId) + { + Log.SandboxFileHasNoOwner(_logger, context.Agent.Name ?? context.Agent.Id); + return; + } + + foreach (var file in found) + { + await KeepAsync(callId, file, cancellationToken).ConfigureAwait(false); + } + } + + /// The call that owns this run's files: the filed turn, or the stamp a child session carries. + private static string? OwnerOf(AgentSession? session) + { + if (TurnRegistry.For(session)?.CallId is { } fromTurn) + { + return fromTurn; + } + + return session is not null && session.StateBag.TryGetValue(BlobOwnerKey.Value, out var stamped) + ? stamped + : null; + } + + /// Every sandbox file reference in one message: on the message, or inside an interpreter result. + private static IEnumerable FilesIn(ChatMessage message) + { + foreach (var content in message.Contents) + { + switch (content) + { + case HostedFileContent file: + yield return file; + break; + + case CodeInterpreterToolResultContent { Outputs: { } outputs }: + foreach (var output in outputs) + { + if (output is HostedFileContent nested) + { + yield return nested; + } + } + + break; + } + } + } + + private async ValueTask KeepAsync(string callId, HostedFileContent file, CancellationToken cancellationToken) + { + var name = file.Name ?? file.FileId; + + if (!BlobName.IsSafe(name)) + { + Log.SandboxFileRefused(_logger, callId, name, "the name is not a plain file name"); + return; + } + + try + { + await using var download = await _files + .DownloadAsync(file.FileId, new HostedFileClientOptions { Scope = file.Scope }, cancellationToken) + .ConfigureAwait(false); + + // The download stream rarely knows its length, and the policy needs one: read up to one + // byte past the cap, so an oversized file is refused without buffering all of it. + using MemoryStream buffer = new(); + await CopyCappedAsync(download, buffer, _policy.MaxBytes + 1, cancellationToken).ConfigureAwait(false); + + if (_policy.WhyRefused(name, buffer.Length) is { } reason) + { + Log.SandboxFileRefused(_logger, callId, name, reason); + return; + } + + buffer.Position = 0; + + var mediaType = download.MediaType ?? file.MediaType ?? "application/octet-stream"; + + await _blobs + .PutAsync(new BlobWrite(callId, name, mediaType, buffer, buffer.Length), cancellationToken) + .ConfigureAwait(false); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + Log.SandboxFileCaptureFailed(_logger, callId, name, exception); + } + } + + private static async ValueTask CopyCappedAsync(Stream source, Stream target, long cap, CancellationToken cancellationToken) + { + var chunk = new byte[81920]; + long copied = 0; + + while (copied < cap) + { + var wanted = (int)Math.Min(chunk.Length, cap - copied); + var read = await source.ReadAsync(chunk.AsMemory(0, wanted), cancellationToken).ConfigureAwait(false); + + if (read == 0) + { + return; + } + + await target.WriteAsync(chunk.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + copied += read; + } + } +} diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs index e9dc9f0f..10323b33 100644 --- a/src/AgentCore.Application/Runtime/TurnInvocation.cs +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -82,6 +82,13 @@ internal sealed record TurnInvocation public StateDocument? State { get; init; } /// Builds the per-run options carrying this turn to the invoking client. + /// Reads the turn filed on a run's options by , or null when there is none. + internal static TurnInvocation? From(AgentRunOptions? options) + => options is ChatClientAgentRunOptions run + && run.ChatOptions?.AdditionalProperties?.TryGetValue(ArgumentsKey, out var filed) == true + ? filed as TurnInvocation + : null; + internal ChatClientAgentRunOptions RunOptions() { ChatOptions chat = new() diff --git a/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs b/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs new file mode 100644 index 00000000..4d287cab --- /dev/null +++ b/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs @@ -0,0 +1,36 @@ +using AgentCore.Application.Blobs; +using AgentCore.Application.Ports; + +namespace AgentCore.Application.Tests.Fakes; + +/// An in-memory that keeps every write, so a test reads what was stored. +internal sealed class RecordingBlobStore : IBlobStore +{ + private readonly Dictionary<(string Owner, string Name), (string MediaType, byte[] Bytes)> _blobs = []; + + /// Gets every blob stored, keyed by owner and name, in no particular order. + public IReadOnlyDictionary<(string Owner, string Name), (string MediaType, byte[] Bytes)> Blobs => _blobs; + + public async ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default) + { + using MemoryStream copy = new(); + await write.Content.CopyToAsync(copy, cancellationToken); + _blobs[(write.OwnerId, write.Name)] = (write.MediaType, copy.ToArray()); + return new BlobRef(write.OwnerId, write.Name, write.MediaType, write.Length); + } + + public ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => ValueTask.FromResult(_blobs.TryGetValue((ownerId, name), out var blob) + ? new BlobRead(blob.MediaType, blob.Bytes.Length, new MemoryStream(blob.Bytes)) + : null); + + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) + { + foreach (var key in _blobs.Keys.Where(key => key.Owner == ownerId).ToList()) + { + _blobs.Remove(key); + } + + return ValueTask.CompletedTask; + } +} diff --git a/tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs b/tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs new file mode 100644 index 00000000..0452967e --- /dev/null +++ b/tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs @@ -0,0 +1,80 @@ +#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Tests.Fakes; + +/// An that serves fixed bytes per file id, and records each download's scope. +internal sealed class ScriptedHostedFileClient : IHostedFileClient +{ + private readonly Dictionary _files = new(StringComparer.Ordinal); + + /// Gets the scope each download asked for, keyed by file id. + public Dictionary ScopesAsked { get; } = new(StringComparer.Ordinal); + + public ScriptedHostedFileClient Serve(string fileId, byte[] bytes, string? mediaType = null) + { + _files[fileId] = (bytes, mediaType); + return this; + } + + public Task DownloadAsync(string fileId, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) + { + ScopesAsked[fileId] = options?.Scope; + + return _files.TryGetValue(fileId, out var file) + ? Task.FromResult(new FixedDownload(file.Bytes, file.MediaType)) + : throw new InvalidOperationException($"No such file '{fileId}'."); + } + + public Task UploadAsync(Stream content, string? mediaType = null, string? fileName = null, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public Task GetFileInfoAsync(string fileId, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public IAsyncEnumerable ListFilesAsync(HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public Task DeleteAsync(string fileId, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + + public void Dispose() + { + } + + private sealed class FixedDownload(byte[] bytes, string? mediaType) : HostedFileDownloadStream + { + private readonly MemoryStream _inner = new(bytes); + + public override string? MediaType => mediaType; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + _inner.Dispose(); + base.Dispose(disposing); + } + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs new file mode 100644 index 00000000..8d5837e1 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs @@ -0,0 +1,64 @@ +#pragma warning disable MAAI001 // The context types are evaluation-only in Microsoft.Agents.AI 1.21.0. + +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Tests.Fakes; +using Microsoft.Agents.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime.Harness; + +/// +/// A child session created inside the parent's run carries the parent's call id; one created +/// outside any run carries nothing. +/// +/// +/// BackgroundAgentsProvider creates the child session from inside the parent's tool call. +/// The test stands in for that with a provider that creates it from inside the parent's +/// InvokingAsync, which is the same run context. +/// +public sealed class BackgroundChildAgentTests +{ + [Fact] + public async Task CreateSessionAsync_InsideTheParentsRun_StampsTheParentsCallId() + { + // Arrange + var token = TestContext.Current.CancellationToken; + BackgroundChildAgent child = new(new ChatClientAgent(new ScriptedChatClient("child"))); + SessionCreatingProvider creating = new(child); + ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); + var turn = new TurnInvocation { CallId = "call-9", TurnIndex = 0, Stage = "s" }; + + // Act + await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); + + // Assert + Assert.NotNull(creating.Created); + Assert.True(creating.Created.StateBag.TryGetValue(BlobOwnerKey.Value, out var stamped)); + Assert.Equal("call-9", stamped); + } + + [Fact] + public async Task CreateSessionAsync_OutsideAnyRun_StampsNothing() + { + // Arrange + BackgroundChildAgent child = new(new ChatClientAgent(new ScriptedChatClient("child"))); + + // Act + var session = await child.CreateSessionAsync(TestContext.Current.CancellationToken); + + // Assert + Assert.False(session.StateBag.TryGetValue(BlobOwnerKey.Value, out _)); + } + + private sealed class SessionCreatingProvider(AIAgent child) : AIContextProvider + { + public AgentSession? Created { get; private set; } + + protected override async ValueTask InvokingCoreAsync(InvokingContext context, CancellationToken cancellationToken = default) + { + Created = await child.CreateSessionAsync(cancellationToken); + return new AIContext(); + } + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs new file mode 100644 index 00000000..a2d79829 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs @@ -0,0 +1,179 @@ +#pragma warning disable MEAI001 // HostedFileContent.Scope is evaluation-only in Microsoft.Extensions.AI 10.10.0. +#pragma warning disable MAAI001 // The context constructors are evaluation-only in Microsoft.Agents.AI 1.21.0. + +using AgentCore.Application.Blobs; +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Tests.Fakes; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime.Harness; + +/// +/// After a run: every sandbox file the vendor surfaced is downloaded and stored under the call. +/// +public sealed class HostedFileCaptureProviderTests +{ + private static readonly byte[] Png = [0x89, (byte)'P', (byte)'N', (byte)'G', 1, 2, 3]; + + [Fact] + public async Task InvokedAsync_FileOnTheMessage_StoresItUnderTheCallAndTheName() + { + // Arrange + var files = new ScriptedHostedFileClient().Serve("cfile_1", Png, "image/png"); + RecordingBlobStore blobs = new(); + var (agent, session) = await AgentWithFiledTurn("call-7"); + var response = Reply(new HostedFileContent("cfile_1") { Scope = "cntr_1", Name = "chart.png" }); + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + var stored = Assert.Single(blobs.Blobs); + Assert.Equal(("call-7", "chart.png"), stored.Key); + Assert.Equal("image/png", stored.Value.MediaType); + Assert.Equal(Png, stored.Value.Bytes); + Assert.Equal("cntr_1", files.ScopesAsked["cfile_1"]); + } + + [Fact] + public async Task InvokedAsync_FileInsideAnInterpreterResult_IsStoredToo() + { + // Arrange + var files = new ScriptedHostedFileClient().Serve("cfile_2", Png, "image/png"); + RecordingBlobStore blobs = new(); + var (agent, session) = await AgentWithFiledTurn("call-7"); + var response = Reply(new CodeInterpreterToolResultContent("call_x") + { + Outputs = [new HostedFileContent("cfile_2") { Name = "plot.png" }], + }); + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + Assert.True(blobs.Blobs.ContainsKey(("call-7", "plot.png"))); + } + + [Fact] + public async Task InvokedAsync_ChildSessionWithTheOwnerStamp_StoresUnderThatCall() + { + // Arrange: no turn filed, only the stamp BackgroundChildAgent leaves. + var files = new ScriptedHostedFileClient().Serve("cfile_3", Png, "image/png"); + RecordingBlobStore blobs = new(); + var agent = Agent(); + var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); + session.StateBag.SetValue(BlobOwnerKey.Value, "call-child"); + var response = Reply(new HostedFileContent("cfile_3") { Name = "rows.csv" }); + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + Assert.True(blobs.Blobs.ContainsKey(("call-child", "rows.csv"))); + } + + [Fact] + public async Task InvokedAsync_NoOwnerAtAll_StoresNothingAndDoesNotThrow() + { + // Arrange + var files = new ScriptedHostedFileClient().Serve("cfile_4", Png, "image/png"); + RecordingBlobStore blobs = new(); + var agent = Agent(); + var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); + var response = Reply(new HostedFileContent("cfile_4") { Name = "chart.png" }); + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(blobs.Blobs); + } + + [Theory] + [InlineData("../etc/passwd")] + [InlineData("page.html")] + public async Task InvokedAsync_UnsafeNameOrDisallowedExtension_IsRefusedNotStored(string name) + { + // Arrange + var files = new ScriptedHostedFileClient().Serve("cfile_5", Png, "image/png"); + RecordingBlobStore blobs = new(); + var (agent, session) = await AgentWithFiledTurn("call-7"); + var response = Reply(new HostedFileContent("cfile_5") { Name = name }); + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(blobs.Blobs); + } + + [Fact] + public async Task InvokedAsync_FileOverTheCap_IsRefusedWithoutBufferingAllOfIt() + { + // Arrange: a 100-byte cap, a 300-byte file. + var files = new ScriptedHostedFileClient().Serve("cfile_6", new byte[300], "image/png"); + RecordingBlobStore blobs = new(); + var (agent, session) = await AgentWithFiledTurn("call-7"); + var response = Reply(new HostedFileContent("cfile_6") { Name = "big.png" }); + var provider = new HostedFileCaptureProvider(files, blobs, new BlobPolicy(100, ["png"]), NullLogger.Instance); + + // Act + await provider.InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(blobs.Blobs); + } + + [Fact] + public async Task InvokedAsync_DownloadThrows_StoresNothingAndDoesNotThrow() + { + // Arrange: the client knows no such file. + ScriptedHostedFileClient files = new(); + RecordingBlobStore blobs = new(); + var (agent, session) = await AgentWithFiledTurn("call-7"); + var response = Reply(new HostedFileContent("cfile_missing") { Name = "chart.png" }); + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(blobs.Blobs); + } + + [Fact] + public async Task InvokingAsync_TellsTheModelWhereToSaveAndHowToLink() + { + // Arrange + var agent = Agent(); + var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); + + // Act + var context = await Provider(new ScriptedHostedFileClient(), new RecordingBlobStore()) + .InvokingAsync(new AIContextProvider.InvokingContext(agent, session, new AIContext()), TestContext.Current.CancellationToken); + + // Assert + Assert.Contains("/mnt/data", context.Instructions, StringComparison.Ordinal); + Assert.Contains("sandbox:/mnt/data/", context.Instructions, StringComparison.Ordinal); + } + + private static HostedFileCaptureProvider Provider(ScriptedHostedFileClient files, RecordingBlobStore blobs) + => new(files, blobs, BlobPolicy.Default, NullLogger.Instance); + + private static ChatClientAgent Agent() => new ChatClientAgent(new ScriptedChatClient("ok")); + + private static async Task<(AIAgent Agent, AgentSession Session)> AgentWithFiledTurn(string callId) + { + var agent = Agent(); + var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); + TurnRegistry.Set(session, new TurnInvocation { CallId = callId, TurnIndex = 0, Stage = "s" }); + return (agent, session); + } + + private static List Reply(params AIContent[] contents) + => [new ChatMessage(ChatRole.Assistant, [new TextContent("see sandbox:/mnt/data/x"), .. contents])]; +} From 6623793506ff3dc4042353fe841a35f8386c1647 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 13:29:13 -0600 Subject: [PATCH 06/35] Add Responses endpoint and related streaming functionality - Implement ResponsesRequestReader to handle reading user messages and conversation IDs from requests. - Create ResponsesTurnStream for streaming responses as server-sent events, including handling updates and tool calls. - Introduce TurnStreamFiles to manage sandbox file references during streaming. - Enhance TurnStreamParts to include TurnStreamFile for file references. - Extend S3BlobStore with StatAsync and LinkAsync methods for blob metadata and presigned URLs. - Add unit tests for blob linking, sandbox file management, and call repository functionalities. - Update dependency injection tests to reflect changes in service registrations. --- src/AgentCore.Application/Blobs/BlobLink.cs | 28 +++ .../Blobs/SandboxFileFacts.cs | 7 + .../Blobs/SandboxFileLink.cs | 6 + .../Blobs/SandboxFiles.cs | 166 ++++++++++++++ .../Calls/CallRepository.cs | 170 ++++++++++++++ src/AgentCore.Application/Ports/IBlobStore.cs | 14 ++ .../PublicAPI.Unshipped.txt | 65 ++++++ .../Harness/HostedFileCaptureProvider.cs | 51 +--- .../DependencyInjection/AgentCoreBoot.cs | 9 +- .../AgentCoreServiceCollectionExtensions.cs | 1 + .../Endpoints/ResponsesContracts.cs | 16 ++ .../Endpoints/ResponsesEndpoints.cs | 217 ++---------------- .../Endpoints/ResponsesRequestReader.cs | 94 ++++++++ .../Endpoints/ResponsesTurnStream.cs | 139 +++++++++++ .../Endpoints/TurnStreamFiles.cs | 65 ++++++ .../Endpoints/TurnStreamParts.cs | 3 + .../Blobs/S3/S3BlobStore.cs | 49 ++++ .../PublicAPI.Unshipped.txt | 2 + .../Blobs/BlobLinkTests.cs | 41 ++++ .../Blobs/BlobStoreFactoryTests.cs | 6 + .../Blobs/SandboxFilesTests.cs | 122 ++++++++++ .../Calls/CallRepositoryTests.cs | 152 ++++++++++++ .../Fakes/RecordingBlobStore.cs | 9 + .../Harness/HostedFileCaptureProviderTests.cs | 33 +++ .../DependencyInjection/AddAgentCoreTests.cs | 4 +- .../Endpoints/TurnStreamFilesTests.cs | 98 ++++++++ .../AgentCoreHostTests.cs | 7 +- .../Blobs/S3/S3BlobStoreLinkTests.cs | 79 +++++++ .../Blobs/S3/S3BlobStoreTests.cs | 45 ++++ 29 files changed, 1449 insertions(+), 249 deletions(-) create mode 100644 src/AgentCore.Application/Blobs/BlobLink.cs create mode 100644 src/AgentCore.Application/Blobs/SandboxFileFacts.cs create mode 100644 src/AgentCore.Application/Blobs/SandboxFileLink.cs create mode 100644 src/AgentCore.Application/Blobs/SandboxFiles.cs create mode 100644 src/AgentCore.Application/Calls/CallRepository.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs create mode 100644 tests/AgentCore.Application.Tests/Blobs/BlobLinkTests.cs create mode 100644 tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs create mode 100644 tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs diff --git a/src/AgentCore.Application/Blobs/BlobLink.cs b/src/AgentCore.Application/Blobs/BlobLink.cs new file mode 100644 index 00000000..80c8492b --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobLink.cs @@ -0,0 +1,28 @@ +namespace AgentCore.Application.Blobs; + +/// What every store agrees on when it hands a browser a link to a blob. +public static class BlobLink +{ + /// How long a link works. + public static TimeSpan Lifetime { get; } = TimeSpan.FromMinutes(15); + + /// + /// The Content-Disposition a link serves the blob with: inline for what a browser + /// draws safely, attachment for everything else. SVG and HTML are never inline: both run + /// script under the store's origin. + /// + /// The blob's IANA media type. + /// The file name the browser saves it under. + /// The header value. + public static string DispositionOf(string mediaType, string name) + { + ArgumentNullException.ThrowIfNull(mediaType); + ArgumentNullException.ThrowIfNull(name); + + var inline = mediaType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase) + || (mediaType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) + && !mediaType.Contains("svg", StringComparison.OrdinalIgnoreCase)); + + return (inline ? "inline" : "attachment") + "; filename*=UTF-8''" + Uri.EscapeDataString(name); + } +} diff --git a/src/AgentCore.Application/Blobs/SandboxFileFacts.cs b/src/AgentCore.Application/Blobs/SandboxFileFacts.cs new file mode 100644 index 00000000..011def97 --- /dev/null +++ b/src/AgentCore.Application/Blobs/SandboxFileFacts.cs @@ -0,0 +1,7 @@ +namespace AgentCore.Application.Blobs; + +/// What the capture recorded about one kept sandbox file, as read back off the reply. +/// The name the model gave it, which is the name it is stored under. +/// The IANA media type the store holds it as. +/// How many bytes the store holds. +public sealed record SandboxFileFacts(string Name, string MediaType, long Length); diff --git a/src/AgentCore.Application/Blobs/SandboxFileLink.cs b/src/AgentCore.Application/Blobs/SandboxFileLink.cs new file mode 100644 index 00000000..99145f3d --- /dev/null +++ b/src/AgentCore.Application/Blobs/SandboxFileLink.cs @@ -0,0 +1,6 @@ +namespace AgentCore.Application.Blobs; + +/// One file a call's sandbox wrote and the store kept. +/// The file's facts. +/// Where a browser fetches it from, or when the store has no web door. +public sealed record SandboxFileLink(BlobRef Blob, Uri? Url); diff --git a/src/AgentCore.Application/Blobs/SandboxFiles.cs b/src/AgentCore.Application/Blobs/SandboxFiles.cs new file mode 100644 index 00000000..7efc0cef --- /dev/null +++ b/src/AgentCore.Application/Blobs/SandboxFiles.cs @@ -0,0 +1,166 @@ +#pragma warning disable MEAI001 // HostedFileContent.Scope is evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using System.Text.Json; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Blobs; + +/// Finds the files a vendor's sandbox wrote, wherever the vendor surfaced them on a message. +public static class SandboxFiles +{ + /// The names of every sandbox file the contents reference, in order, each once. + /// The contents of one message or one streaming update. + /// The names a blob was, or would have been, stored under. Only names that pass . + public static IReadOnlyList NamesIn(IEnumerable contents) + { + ArgumentNullException.ThrowIfNull(contents); + + List names = []; + + foreach (var file in In(contents)) + { + var name = NameOf(file); + + if (BlobName.IsSafe(name) && !names.Contains(name, StringComparer.Ordinal)) + { + names.Add(name); + } + } + + return names; + } + + /// + /// The facts of every sandbox file the contents reference that the capture kept, in order, each + /// name once. A reference the capture never stamped, or stamped as refused, is not a file + /// anyone can fetch and is left out. + /// + /// + /// The facts are read off the message and never off the store, so a history read makes no + /// request per file. That is how every production chat keeps its attachments: the bytes in an + /// object store, the index on the message. + /// + /// The contents of one message or one streaming update. + /// The kept files, as the store described them at capture time. + public static IReadOnlyList KeptIn(IEnumerable contents) + { + ArgumentNullException.ThrowIfNull(contents); + + List kept = []; + + foreach (var file in In(contents)) + { + if (FactsOf(file) is not { } facts) + { + continue; + } + + // A second write with the same name replaced the first in the store, so the later + // facts win, in the place the first reference took. + var at = kept.FindIndex(known => string.Equals(known.Name, facts.Name, StringComparison.Ordinal)); + + if (at >= 0) + { + kept[at] = facts; + } + else + { + kept.Add(facts); + } + } + + return kept; + } + + /// Writes onto the reference what the store kept, so every later read has it without asking the store. + /// The vendor's reference, as it sits on the reply. + /// What the store wrote. + public static void MarkKept(HostedFileContent file, BlobRef blob) + { + ArgumentNullException.ThrowIfNull(file); + ArgumentNullException.ThrowIfNull(blob); + + file.MediaType = blob.MediaType; + + var properties = file.AdditionalProperties ??= []; + properties[KeptKey] = true; + properties[LengthKey] = blob.Length; + } + + /// Writes onto the reference that the store did not keep the file, so no read links it. + /// The vendor's reference, as it sits on the reply. + public static void MarkRefused(HostedFileContent file) + { + ArgumentNullException.ThrowIfNull(file); + + (file.AdditionalProperties ??= [])[KeptKey] = false; + } + + /// The name a sandbox file is stored under: what the model called it, else the vendor's id. + internal static string NameOf(HostedFileContent file) => file.Name ?? file.FileId; + + /// The key under which the capture records whether it kept the file. A wire format: it is stored. + private const string KeptKey = "agentcore.kept"; + + /// The key under which the capture records the stored length in bytes. A wire format: it is stored. + private const string LengthKey = "agentcore.length"; + + /// Reads the stamp off one reference, or when it was never kept. + private static SandboxFileFacts? FactsOf(HostedFileContent file) + { + var name = NameOf(file); + + if (!BlobName.IsSafe(name) + || file.AdditionalProperties is not { } properties + || !properties.TryGetValue(KeptKey, out var keptValue) + || !ReadBool(keptValue) + || !properties.TryGetValue(LengthKey, out var lengthValue) + || ReadLong(lengthValue) is not { } length) + { + return null; + } + + return new SandboxFileFacts(name, file.MediaType ?? "application/octet-stream", length); + } + + // A stored message comes back with JsonElement values; a fresh one holds the CLR values written. + private static bool ReadBool(object? value) => value switch + { + bool kept => kept, + JsonElement { ValueKind: JsonValueKind.True } => true, + _ => false, + }; + + private static long? ReadLong(object? value) => value switch + { + long length => length, + int length => length, + JsonElement { ValueKind: JsonValueKind.Number } element when element.TryGetInt64(out var length) => length, + _ => null, + }; + + /// Every sandbox file reference in the contents: on the message, or inside an interpreter result. + internal static IEnumerable In(IEnumerable contents) + { + foreach (var content in contents) + { + switch (content) + { + case HostedFileContent file: + yield return file; + break; + + case CodeInterpreterToolResultContent { Outputs: { } outputs }: + foreach (var output in outputs) + { + if (output is HostedFileContent nested) + { + yield return nested; + } + } + + break; + } + } + } +} diff --git a/src/AgentCore.Application/Calls/CallRepository.cs b/src/AgentCore.Application/Calls/CallRepository.cs new file mode 100644 index 00000000..513a05f8 --- /dev/null +++ b/src/AgentCore.Application/Calls/CallRepository.cs @@ -0,0 +1,170 @@ +using System.Text.Json; +using AgentCore.Application.Blobs; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Calls; + +/// +/// Everything a host or a consumer does with a stored call: its row, its words, and the files its +/// sandbox wrote. The one door; the stores behind it are adapters nobody else needs to name. +/// +public sealed class CallRepository : ICallStore +{ + private readonly ICallStore _calls; + + private readonly IBlobStore? _blobs; + + /// Makes the repository over the stores the document opened. + /// The store the rows and words live in. + /// The store the sandbox files live in, or when the document names none. + public CallRepository(ICallStore calls, IBlobStore? blobs) + { + ArgumentNullException.ThrowIfNull(calls); + + _calls = calls; + _blobs = blobs; + } + + /// Whether the document named a blob store, so a call can have files at all. + public bool KeepsFiles => _blobs is not null; + + /// The adapter the rows live in. For a host checking which vendor it opened; go through the repository for everything else. + public ICallStore Store => _calls; + + /// Links every sandbox file the messages reference and the capture kept, each once, in first-seen order. + /// + /// Read off the messages, never off the store: the capture stamped each reference with what it + /// kept, so a history read makes no request per file. The link is minted here on every read, so + /// it is fresh however old the reply is. A file the capture refused, or never saw, has no stamp + /// and gets no link: the reply's words still name it, and that is all there is to show. A blob + /// deleted behind a stamped message gives a link that answers 404, as every chat product's does. + /// + /// The call that owns the files. + /// The messages to read the references off: the stored transcript, or one turn's updates. + /// Cancels the signing. + /// One link per kept file. + public async Task> LinkFilesAsync( + string callId, + IEnumerable messages, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(callId); + ArgumentNullException.ThrowIfNull(messages); + + if (_blobs is null) + { + return []; + } + + List links = []; + + foreach (var facts in SandboxFiles.KeptIn(messages.SelectMany(message => message.Contents))) + { + BlobRef blob = new(callId, facts.Name, facts.MediaType, facts.Length); + + var url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); + + links.Add(new SandboxFileLink(blob, url)); + } + + return links; + } + + /// + public async ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default) + { + if (_blobs is not null) + { + await _blobs.DeleteByOwnerAsync(callId, cancellationToken).ConfigureAwait(false); + } + + await _calls.DeleteAsync(callId, cancellationToken).ConfigureAwait(false); + } + + /// + public ValueTask CreateAsync(string callId, CancellationToken cancellationToken = default) + => _calls.CreateAsync(callId, cancellationToken); + + /// + public ValueTask GetAsync(string callId, CancellationToken cancellationToken = default) + => _calls.GetAsync(callId, cancellationToken); + + /// + public ValueTask ListAsync( + string principalKey, + string? after, + int limit, + CallStatus? status = null, + CancellationToken cancellationToken = default) + => _calls.ListAsync(principalKey, after, limit, status, cancellationToken); + + /// + public ValueTask RenameAsync(string callId, string title, CancellationToken cancellationToken = default) + => _calls.RenameAsync(callId, title, cancellationToken); + + /// + public ValueTask SetStatusAsync(string callId, CallStatus status, CancellationToken cancellationToken = default) + => _calls.SetStatusAsync(callId, status, cancellationToken); + + /// + public ValueTask SetCustomAsync(string callId, JsonElement? custom, CancellationToken cancellationToken = default) + => _calls.SetCustomAsync(callId, custom, cancellationToken); + + /// + public ValueTask SetExternalIdAsync(string callId, string? externalId, CancellationToken cancellationToken = default) + => _calls.SetExternalIdAsync(callId, externalId, cancellationToken); + + /// + public ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, + CallSessionState? state = null, + CancellationToken cancellationToken = default) + => _calls.AppendAsync(callId, messages, state, cancellationToken); + + /// + public ValueTask AppendMessageAsync(string callId, ChatMessage message, CancellationToken cancellationToken = default) + => _calls.AppendMessageAsync(callId, message, cancellationToken); + + /// + public ValueTask RewriteAsync(string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => _calls.RewriteAsync(callId, messageId, content, cancellationToken); + + /// + public ValueTask> ReadAsync(string callId, CancellationToken cancellationToken = default) + => _calls.ReadAsync(callId, cancellationToken); + + /// + public ValueTask TruncateAsync(string callId, int fromOrdinal, CancellationToken cancellationToken = default) + => _calls.TruncateAsync(callId, fromOrdinal, cancellationToken); + + /// + public ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) + => _calls.EraseAsync(callId, cancellationToken); + + /// + public ValueTask SweepAsync(TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) + => _calls.SweepAsync(retention, batchSize, cancellationToken); + + /// + public ValueTask AttachPrincipalAsync(string callId, string principalKey, string role, CancellationToken cancellationToken = default) + => _calls.AttachPrincipalAsync(callId, principalKey, role, cancellationToken); + + /// + public ValueTask DetachPrincipalAsync(string callId, string principalKey, CancellationToken cancellationToken = default) + => _calls.DetachPrincipalAsync(callId, principalKey, cancellationToken); + + /// + public ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) + => _calls.SaveContinuationAsync(continuationId, envelope, cancellationToken); + + /// + public ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + => _calls.GetContinuationAsync(continuationId, cancellationToken); + + /// + public ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + => _calls.DeleteContinuationAsync(continuationId, cancellationToken); +} diff --git a/src/AgentCore.Application/Ports/IBlobStore.cs b/src/AgentCore.Application/Ports/IBlobStore.cs index e6201fb8..51d56803 100644 --- a/src/AgentCore.Application/Ports/IBlobStore.cs +++ b/src/AgentCore.Application/Ports/IBlobStore.cs @@ -20,6 +20,20 @@ public interface IBlobStore /// The blob, or when no such blob exists. The caller disposes it. ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default); + /// Reads one blob's facts without its bytes. + /// Who wrote it. + /// The name it was written under. + /// Cancels the read. + /// The blob, or when no such blob exists. + ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default); + + /// Makes a URL a browser can fetch the blob from, with no other credential. + /// The blob to link. Its media type decides whether the browser shows it or saves it. + /// How long the URL works. is the usual value. + /// Cancels the signing. + /// The URL, or when this store has no web door of its own. + ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default); + /// Deletes every blob an owner wrote. Nothing to delete is not an error. /// Whose blobs to delete. /// Cancels the delete. diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 7b2710da..4fcc09cf 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2203,3 +2203,68 @@ AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Blobs.in AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Blobs.get -> AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Blobs.init -> void static AgentCore.Application.Blobs.BlobStoreFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Blobs.BlobLink +static AgentCore.Application.Blobs.BlobLink.Lifetime.get -> System.TimeSpan +static AgentCore.Application.Blobs.BlobLink.DispositionOf(string! mediaType, string! name) -> string! +AgentCore.Application.Ports.IBlobStore.LinkAsync(AgentCore.Application.Blobs.BlobRef! blob, System.TimeSpan lifetime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IBlobStore.StatAsync(string! ownerId, string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Blobs.SandboxFiles +static AgentCore.Application.Blobs.SandboxFiles.NamesIn(System.Collections.Generic.IEnumerable! contents) -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Blobs.SandboxFileLink +AgentCore.Application.Blobs.SandboxFileLink.$() -> AgentCore.Application.Blobs.SandboxFileLink! +AgentCore.Application.Blobs.SandboxFileLink.Blob.get -> AgentCore.Application.Blobs.BlobRef! +AgentCore.Application.Blobs.SandboxFileLink.Blob.init -> void +AgentCore.Application.Blobs.SandboxFileLink.Deconstruct(out AgentCore.Application.Blobs.BlobRef! Blob, out System.Uri? Url) -> void +AgentCore.Application.Blobs.SandboxFileLink.Equals(AgentCore.Application.Blobs.SandboxFileLink? other) -> bool +AgentCore.Application.Blobs.SandboxFileLink.SandboxFileLink(AgentCore.Application.Blobs.BlobRef! Blob, System.Uri? Url) -> void +AgentCore.Application.Blobs.SandboxFileLink.Url.get -> System.Uri? +AgentCore.Application.Blobs.SandboxFileLink.Url.init -> void +AgentCore.Application.Calls.CallRepository +AgentCore.Application.Calls.CallRepository.AppendAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Calls.CallSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Calls.CallRepository.AppendMessageAsync(string! callId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.AttachPrincipalAsync(string! callId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.CallRepository(AgentCore.Application.Ports.ICallStore! calls, AgentCore.Application.Ports.IBlobStore? blobs) -> void +AgentCore.Application.Calls.CallRepository.CreateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.DeleteAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.DetachPrincipalAsync(string! callId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.EraseAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.GetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.KeepsFiles.get -> bool +AgentCore.Application.Calls.CallRepository.LinkFilesAsync(string! callId, System.Collections.Generic.IEnumerable! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +AgentCore.Application.Calls.CallRepository.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Calls.CallStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.ReadAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Calls.CallRepository.RenameAsync(string! callId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.RewriteAsync(string! callId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.SetCustomAsync(string! callId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.SetExternalIdAsync(string! callId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.SetStatusAsync(string! callId, AgentCore.Application.Calls.CallStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Calls.CallRepository.TruncateAsync(string! callId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +override AgentCore.Application.Blobs.SandboxFileLink.Equals(object? obj) -> bool +override AgentCore.Application.Blobs.SandboxFileLink.GetHashCode() -> int +override AgentCore.Application.Blobs.SandboxFileLink.ToString() -> string! +static AgentCore.Application.Blobs.SandboxFileLink.operator ==(AgentCore.Application.Blobs.SandboxFileLink? left, AgentCore.Application.Blobs.SandboxFileLink? right) -> bool +static AgentCore.Application.Blobs.SandboxFileLink.operator !=(AgentCore.Application.Blobs.SandboxFileLink? left, AgentCore.Application.Blobs.SandboxFileLink? right) -> bool +AgentCore.Application.Calls.CallRepository.Store.get -> AgentCore.Application.Ports.ICallStore! +AgentCore.Application.Blobs.SandboxFileFacts +AgentCore.Application.Blobs.SandboxFileFacts.$() -> AgentCore.Application.Blobs.SandboxFileFacts! +AgentCore.Application.Blobs.SandboxFileFacts.Deconstruct(out string! Name, out string! MediaType, out long Length) -> void +AgentCore.Application.Blobs.SandboxFileFacts.Equals(AgentCore.Application.Blobs.SandboxFileFacts? other) -> bool +AgentCore.Application.Blobs.SandboxFileFacts.Length.get -> long +AgentCore.Application.Blobs.SandboxFileFacts.Length.init -> void +AgentCore.Application.Blobs.SandboxFileFacts.MediaType.get -> string! +AgentCore.Application.Blobs.SandboxFileFacts.MediaType.init -> void +AgentCore.Application.Blobs.SandboxFileFacts.Name.get -> string! +AgentCore.Application.Blobs.SandboxFileFacts.Name.init -> void +AgentCore.Application.Blobs.SandboxFileFacts.SandboxFileFacts(string! Name, string! MediaType, long Length) -> void +override AgentCore.Application.Blobs.SandboxFileFacts.Equals(object? obj) -> bool +override AgentCore.Application.Blobs.SandboxFileFacts.GetHashCode() -> int +override AgentCore.Application.Blobs.SandboxFileFacts.ToString() -> string! +static AgentCore.Application.Blobs.SandboxFileFacts.operator ==(AgentCore.Application.Blobs.SandboxFileFacts? left, AgentCore.Application.Blobs.SandboxFileFacts? right) -> bool +static AgentCore.Application.Blobs.SandboxFileFacts.operator !=(AgentCore.Application.Blobs.SandboxFileFacts? left, AgentCore.Application.Blobs.SandboxFileFacts? right) -> bool +static AgentCore.Application.Blobs.SandboxFiles.KeptIn(System.Collections.Generic.IEnumerable! contents) -> System.Collections.Generic.IReadOnlyList! +static AgentCore.Application.Blobs.SandboxFiles.MarkKept(Microsoft.Extensions.AI.HostedFileContent! file, AgentCore.Application.Blobs.BlobRef! blob) -> void +static AgentCore.Application.Blobs.SandboxFiles.MarkRefused(Microsoft.Extensions.AI.HostedFileContent! file) -> void diff --git a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs index 0dc1a8ae..0ef54764 100644 --- a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs @@ -13,19 +13,6 @@ namespace AgentCore.Application.Runtime.Harness; /// /// Copies every file the vendor's sandbox wrote during a run into the call's blob store. /// -/// -/// -/// The model takes no action. It writes a file under /mnt/data and links it as -/// sandbox:/mnt/data/<name>, as it does unprompted. After the run this provider reads -/// each the vendor surfaced, downloads it, and stores it under -/// (callId, name). The host rewrites the link later; the model never learns a route. -/// -/// -/// A file that cannot be kept is logged, never thrown: the reply still goes out, with a link the -/// host cannot resolve. Capture runs once per run, at its end. The sandbox container idles out -/// after twenty minutes; a run that idles longer than that before it ends would lose the file. -/// -/// internal sealed class HostedFileCaptureProvider : AIContextProvider { private const string Instructions = @@ -71,7 +58,7 @@ protected override async ValueTask InvokedCoreAsync(InvokedContext context, Canc foreach (var message in context.ResponseMessages ?? []) { - foreach (var file in FilesIn(message)) + foreach (var file in SandboxFiles.In(message.Contents)) { (found ??= []).Add(file); } @@ -107,38 +94,14 @@ protected override async ValueTask InvokedCoreAsync(InvokedContext context, Canc : null; } - /// Every sandbox file reference in one message: on the message, or inside an interpreter result. - private static IEnumerable FilesIn(ChatMessage message) - { - foreach (var content in message.Contents) - { - switch (content) - { - case HostedFileContent file: - yield return file; - break; - - case CodeInterpreterToolResultContent { Outputs: { } outputs }: - foreach (var output in outputs) - { - if (output is HostedFileContent nested) - { - yield return nested; - } - } - - break; - } - } - } - private async ValueTask KeepAsync(string callId, HostedFileContent file, CancellationToken cancellationToken) { - var name = file.Name ?? file.FileId; + var name = SandboxFiles.NameOf(file); if (!BlobName.IsSafe(name)) { Log.SandboxFileRefused(_logger, callId, name, "the name is not a plain file name"); + SandboxFiles.MarkRefused(file); return; } @@ -156,6 +119,7 @@ private async ValueTask KeepAsync(string callId, HostedFileContent file, Cancell if (_policy.WhyRefused(name, buffer.Length) is { } reason) { Log.SandboxFileRefused(_logger, callId, name, reason); + SandboxFiles.MarkRefused(file); return; } @@ -163,13 +127,18 @@ private async ValueTask KeepAsync(string callId, HostedFileContent file, Cancell var mediaType = download.MediaType ?? file.MediaType ?? "application/octet-stream"; - await _blobs + var kept = await _blobs .PutAsync(new BlobWrite(callId, name, mediaType, buffer, buffer.Length), cancellationToken) .ConfigureAwait(false); + + // The reply is committed to the transcript after this provider runs, so the stamp is + // what every later read links from. No read ever asks the store whether the file exists. + SandboxFiles.MarkKept(file, kept); } catch (Exception exception) when (exception is not OperationCanceledException) { Log.SandboxFileCaptureFailed(_logger, callId, name, exception); + SandboxFiles.MarkRefused(file); } } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index b96e80dd..9fe03913 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Audit; +using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; @@ -75,7 +76,7 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers, internal ToolRegistry Tools => Started.Tools; /// Gets the backing every call's row and every word of it is kept in. - internal ICallStore Calls => Started.Calls; + internal CallRepository Calls => Started.Calls; /// Gets the registry the turn loop reads, and the offline golden set alike. internal EvaluatorRegistry Evaluators => Started.Evaluators; @@ -216,7 +217,7 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) ConfigurationValidator.ValidateSkillToolNames(configuration); - var calls = Track(await CallStartup + var store = Track(await CallStartup .OpenAsync(configuration, _options, _loggers, cancellationToken) .ConfigureAwait(false)); @@ -224,6 +225,8 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) .OpenAsync(configuration, _options, cancellationToken) .ConfigureAwait(false)); + CallRepository calls = new(store, blobs); + var evaluators = await EvaluationStartup .CreateRegistryAsync(configuration, _options, cancellationToken) .ConfigureAwait(false); @@ -364,7 +367,7 @@ private sealed record BootState( ResolvedSecrets Secrets, ITelemetrySession? Telemetry, ToolRegistry Tools, - ICallStore Calls, + CallRepository Calls, IBlobStore? Blobs, EvaluatorRegistry Evaluators, CompiledGraph Graph, diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs index 9b089c8b..b9c72656 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs @@ -46,6 +46,7 @@ public static IServiceCollection AddAgentCore( services.AddSingleton(Boot(boot => boot.Guards)); services.AddSingleton(Boot(boot => boot.Tools)); services.AddSingleton(Boot(boot => boot.Calls)); + services.AddSingleton(provider => provider.GetRequiredService()); services.AddSingleton(Boot(boot => boot.Entries)); services.AddSingleton(provider => provider.GetRequiredService()); services.AddSingleton(Boot(boot => boot.AuditQueue)); diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs index dc9c2e84..99def8e8 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs @@ -205,6 +205,22 @@ internal sealed record SourcePayload public required string Origin { get; init; } } +/// One file the sandbox wrote and the store kept, as the browser reads it. +internal sealed record FilePayload +{ + /// Gets the file name, as the model wrote it under /mnt/data. + public required string Name { get; init; } + + /// Gets the IANA media type, such as image/png. + public required string MediaType { get; init; } + + /// Gets how many bytes it holds. + public required long Length { get; init; } + + /// Gets the link to fetch it from, or when the store has no web door. + public string? Url { get; init; } +} + /// One thing a stream asks the browser to draw. internal sealed record RenderedPayload { diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index cecade37..79a43e37 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -65,7 +65,7 @@ private static async Task HandleAsync(HttpContext http, string entry) } catch (JsonException exception) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request body is not well-formed JSON: " + exception.Message, @@ -96,7 +96,7 @@ await WriteErrorAsync( // call, so read it off the body and run the answer alone. if (agentcore?.Approval is null) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request is not a Responses request: " + exception.Message, @@ -108,7 +108,7 @@ await WriteErrorAsync( runRequest = null; messages = []; - conversationId = ReadConversationId(body); + conversationId = ResponsesRequestReader.ReadConversationId(body); } AgentCoreAgent agent; @@ -118,7 +118,7 @@ await WriteErrorAsync( } catch (InvalidOperationException failure) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status503ServiceUnavailable, failure.Message, @@ -137,7 +137,7 @@ await WriteErrorAsync( // the same precedence off the body. var key = runRequest is not null ? OpenAIResponses.GetSessionStoreId(runRequest) - : ReadContinuationId(body); + : ResponsesRequestReader.ReadContinuationId(body); if (string.IsNullOrWhiteSpace(key)) { @@ -163,7 +163,7 @@ await WriteErrorAsync( { if (agentcore?.Approval is not null) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "an approval answer names the call it resumes. Send it with the conversation " @@ -174,7 +174,7 @@ await WriteErrorAsync( return; } - conversationId = NewConversationId(); + conversationId = ResponsesRequestReader.NewConversationId(); session = await agent.CreateSessionAsync(conversationId, cancellationToken).ConfigureAwait(false); } else if (namesNewCall) @@ -193,7 +193,7 @@ await WriteErrorAsync( catch (InvalidOperationException failure) { // A key minted by another entry is unknown to this one, never a cross-entry read. - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status404NotFound, failure.Message, @@ -208,7 +208,7 @@ await WriteErrorAsync( // Either an unknown response id — a turn no answer ever carried — or an unknown // conversation beside an approval-only body the parse refused. A conversation with words // reaches the namesNewCall branch; an approval never starts a call. - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status404NotFound, $"no call opens under '{key}'. Send the request with neither a conversation nor a " @@ -229,9 +229,9 @@ await WriteErrorAsync( ChatMessage input; if (agentcore?.Approval is { } approval) { - if (LastUserText(messages) is { Length: > 0 }) + if (ResponsesRequestReader.LastUserText(messages) is { Length: > 0 }) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request carries both a user message and an approval answer. One turn carries " @@ -246,7 +246,7 @@ await WriteErrorAsync( // and the queue the suspending turn filed — is still closed. This opens it first. if (await call.TryCreateApprovalAnswerAsync(approval.RequestId, approval.Approved, cancellationToken).ConfigureAwait(false) is not { } answer) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status409Conflict, $"the call queues no approval under id '{approval.RequestId}'. It was " @@ -259,9 +259,9 @@ await WriteErrorAsync( input = answer; } - else if (LastUserMessage(messages) is not { } user) + else if (ResponsesRequestReader.LastUserMessage(messages) is not { } user) { - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request carries no user message with text, so there is no turn to run.", @@ -296,7 +296,7 @@ await WriteErrorAsync( { // The dialect is opt-in by the member only our clients send: an OpenAI SDK // never carries agentcore, so its stream stays the framework's pure shapes. - await StreamTurnAsync(http, agent, sessions, session, call, input, origin, responseId, conversationId, agentcore is not null, cancellationToken) + await ResponsesTurnStream.WriteAsync(http, agent, sessions, session, call, input, origin, responseId, conversationId, agentcore is not null, cancellationToken) .ConfigureAwait(false); } else @@ -309,7 +309,7 @@ await WriteTurnAsync(http, agent, sessions, session, call, input, origin, respon { // The turn loop refuses a turn on a finished call, and refuses a second turn while one // runs. Both are a caller mistake and neither is a defect of this host. - await WriteErrorAsync( + await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status409Conflict, exception.Message, @@ -369,106 +369,6 @@ await http.Response .ConfigureAwait(false); } - /// Runs one turn and writes one Responses event for each update, filed under its ids. - /// - /// The session is filed after the enumeration ends, because the turn commits — - /// and the session only holds the turn — once the last update has left it. - /// The framework's frames carry text alone; when the request spoke the dialect, - /// each update's browser parts ride beside them as agentcore_* members, so drawings, - /// citations, tool halves, and approval asks stream. - /// - private static async Task StreamTurnAsync( - HttpContext http, - AgentCoreAgent agent, - AgentCoreAgentSessionStore sessions, - AgentSession session, - CallSession call, - ChatMessage input, - CallTurnOrigin? origin, - string responseId, - string? conversationId, - bool dialect, - CancellationToken cancellationToken) - { - http.Response.StatusCode = StatusCodes.Status200OK; - http.Response.ContentType = "text/event-stream"; - http.Response.Headers.CacheControl = "no-cache"; - - // The headers leave before the turn ends, so this one names the stage the turn speaks in. - http.Response.Headers[StageHeaderName] = call.Stage; - - // One turn's worth of ids: the pairing dies with the stream. - ToolCallNames toolNames = new(); - - var updates = StreamAgentUpdatesAsync(http, agent, call, input, origin, dialect, toolNames, cancellationToken); - await foreach (var frame in OpenAIResponses - .WriteResponseStreamAsync(updates, responseId, conversationId, cancellationToken) - .ConfigureAwait(false)) - { - await http.Response.WriteAsync(frame, cancellationToken).ConfigureAwait(false); - - // Without this the reply arrives in one piece, which defeats the whole streaming path. - await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); - } - - await SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) - .ConfigureAwait(false); - } - - /// Runs one streaming turn on the call, wrapping each update with the agent's id. - /// - /// The framework converter sees every update untouched: it ignores the contents it - /// knows nothing of, so dialect lines duplicate nothing and pure streams lose nothing. - /// - private static async IAsyncEnumerable StreamAgentUpdatesAsync( - HttpContext http, - AgentCoreAgent agent, - CallSession call, - ChatMessage input, - CallTurnOrigin? origin, - bool dialect, - ToolCallNames toolNames, - [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) - { - await foreach (var update in call - .RunTurnMessageStreamingAtOriginAsync(input, origin, cancellationToken) - .ConfigureAwait(false)) - { - if (dialect) - { - foreach (var part in TurnStreamParts.From(update, toolNames)) - { - await WritePartLineAsync(http, part, cancellationToken).ConfigureAwait(false); - } - } - - yield return new AgentResponseUpdate(update) { AgentId = agent.Id }; - } - } - - /// Writes one dialect event: one agentcore_* member, bare. - private static async Task WritePartLineAsync( - HttpContext http, TurnStreamPart part, CancellationToken cancellationToken) - { - JsonObject line = part switch - { - TurnStreamRender render - => new JsonObject { ["agentcore_data"] = JsonSerializer.SerializeToNode(render.Payload, ResponsesJson.Options) }, - TurnStreamSource source - => new JsonObject { ["agentcore_source"] = JsonSerializer.SerializeToNode(source.Payload, ResponsesJson.Options) }, - TurnStreamTool tool - => new JsonObject { ["agentcore_tool"] = JsonSerializer.SerializeToNode(tool.Payload, ResponsesJson.Options) }, - TurnStreamApproval approval - => new JsonObject { ["agentcore_approval"] = JsonSerializer.SerializeToNode(approval.Payload, ResponsesJson.Options) }, - _ => throw new InvalidOperationException($"Unknown stream part: {part.GetType()}."), - }; - - await http.Response.WriteAsync("data: ", cancellationToken).ConfigureAwait(false); - await http.Response.WriteAsync(line.ToJsonString(), cancellationToken).ConfigureAwait(false); - await http.Response.WriteAsync("\n\n", cancellationToken).ConfigureAwait(false); - await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); - } - /// Files the session the turn just advanced, under every id that names it now. /// /// A conversation id is stable across turns and a response id changes each one, @@ -476,7 +376,7 @@ TurnStreamApproval approval /// continue by either pointer. A chain turn without a conversation files under /// its new response id alone. /// - private static async Task SaveAsync( + internal static async Task SaveAsync( AgentCoreAgentSessionStore sessions, AIAgent agent, AgentSession session, @@ -491,87 +391,4 @@ private static async Task SaveAsync( await sessions.SaveSessionAsync(agent, responseId, session, cancellationToken).ConfigureAwait(false); } - - /// Reads the last user message that carries words, the session owning the rest. - private static ChatMessage? LastUserMessage(IReadOnlyList messages) - { - ChatMessage? picked = null; - foreach (var message in messages) - { - if (message.Role == ChatRole.User && message.Text is { Length: > 0 }) - { - picked = message; - } - } - - return picked; - } - - /// Reads whether any user message of the run carries words. - private static string? LastUserText(IReadOnlyList messages) - => LastUserMessage(messages)?.Text; - - /// Reads the conversation id off a body the protocol parse refused. - private static string? ReadConversationId(JsonElement body) - { - if (body.TryGetProperty("conversation", out var conversation)) - { - if (conversation.ValueKind == JsonValueKind.String) - { - return conversation.GetString(); - } - - if (conversation.ValueKind == JsonValueKind.Object - && conversation.TryGetProperty("id", out var id) - && id.ValueKind == JsonValueKind.String) - { - return id.GetString(); - } - } - - return null; - } - - /// Reads the continuation off a body the protocol parse refused. - private static string? ReadContinuationId(JsonElement body) - { - if (body.TryGetProperty("previous_response_id", out var response) - && response.ValueKind == JsonValueKind.String - && response.GetString() is { Length: > 0 } responseId) - { - return responseId; - } - - return ReadConversationId(body); - } - - /// Answers one failure in the shape an OpenAI client reads. - private static async Task WriteErrorAsync( - HttpContext http, - int status, - string message, - string type, - string code, - CancellationToken cancellationToken) - { - http.Response.StatusCode = status; - - await http.Response.WriteAsJsonAsync( - new JsonObject - { - ["error"] = new JsonObject - { - ["message"] = message, - ["type"] = type, - ["code"] = code, - ["param"] = null, - }, - }, - cancellationToken).ConfigureAwait(false); - } - - /// Builds the id of one conversation. - /// The id, in the shape an OpenAI client already reads. - private static string NewConversationId() - => string.Create(CultureInfo.InvariantCulture, $"conv_{Guid.NewGuid():N}"); } diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs new file mode 100644 index 00000000..ed50f27c --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs @@ -0,0 +1,94 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// What the Responses path reads off a request body, and how it answers a bad one. +internal static class ResponsesRequestReader +{ + /// Reads the last user message that carries words, the session owning the rest. + internal static ChatMessage? LastUserMessage(IReadOnlyList messages) + { + ChatMessage? picked = null; + foreach (var message in messages) + { + if (message.Role == ChatRole.User && message.Text is { Length: > 0 }) + { + picked = message; + } + } + + return picked; + } + + /// Reads whether any user message of the run carries words. + internal static string? LastUserText(IReadOnlyList messages) + => LastUserMessage(messages)?.Text; + + /// Reads the conversation id off a body the protocol parse refused. + internal static string? ReadConversationId(JsonElement body) + { + if (body.TryGetProperty("conversation", out var conversation)) + { + if (conversation.ValueKind == JsonValueKind.String) + { + return conversation.GetString(); + } + + if (conversation.ValueKind == JsonValueKind.Object + && conversation.TryGetProperty("id", out var id) + && id.ValueKind == JsonValueKind.String) + { + return id.GetString(); + } + } + + return null; + } + + /// Reads the continuation off a body the protocol parse refused. + internal static string? ReadContinuationId(JsonElement body) + { + if (body.TryGetProperty("previous_response_id", out var response) + && response.ValueKind == JsonValueKind.String + && response.GetString() is { Length: > 0 } responseId) + { + return responseId; + } + + return ReadConversationId(body); + } + + /// Answers one failure in the shape an OpenAI client reads. + internal static async Task WriteErrorAsync( + HttpContext http, + int status, + string message, + string type, + string code, + CancellationToken cancellationToken) + { + http.Response.StatusCode = status; + + await http.Response.WriteAsJsonAsync( + new JsonObject + { + ["error"] = new JsonObject + { + ["message"] = message, + ["type"] = type, + ["code"] = code, + ["param"] = null, + }, + }, + cancellationToken).ConfigureAwait(false); + } + + /// Builds the id of one conversation. + /// The id, in the shape an OpenAI client already reads. + internal static string NewConversationId() + => string.Create(CultureInfo.InvariantCulture, $"conv_{Guid.NewGuid():N}"); +} diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs new file mode 100644 index 00000000..fbb4e0d2 --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs @@ -0,0 +1,139 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.Application.Calls; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tools; +using AgentCore.AspNetCore.Sessions; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.Hosting.OpenAI; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; + +namespace AgentCore.AspNetCore.Endpoints; + +/// +/// The streaming half of the Responses path: one turn as server-sent events, with the dialect's +/// browser parts riding beside the framework's frames. +/// +internal static class ResponsesTurnStream +{ + /// Runs one turn and writes one Responses event for each update, filed under its ids. + /// + /// The session is filed after the enumeration ends, because the turn commits — + /// and the session only holds the turn — once the last update has left it. + /// The framework's frames carry text alone; when the request spoke the dialect, + /// each update's browser parts ride beside them as agentcore_* members, so drawings, + /// citations, tool halves, and approval asks stream. + /// + internal static async Task WriteAsync( + HttpContext http, + AgentCoreAgent agent, + AgentCoreAgentSessionStore sessions, + AgentSession session, + CallSession call, + ChatMessage input, + CallTurnOrigin? origin, + string responseId, + string? conversationId, + bool dialect, + CancellationToken cancellationToken) + { + http.Response.StatusCode = StatusCodes.Status200OK; + http.Response.ContentType = "text/event-stream"; + http.Response.Headers.CacheControl = "no-cache"; + + // The headers leave before the turn ends, so this one names the stage the turn speaks in. + http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = call.Stage; + + // One turn's worth of ids: the pairing dies with the stream. + ToolCallNames toolNames = new(); + + var updates = StreamAgentUpdatesAsync(http, agent, call, input, origin, dialect, toolNames, cancellationToken); + + await foreach (var frame in OpenAIResponses + .WriteResponseStreamAsync(updates, responseId, conversationId, cancellationToken) + .ConfigureAwait(false)) + { + await http.Response.WriteAsync(frame, cancellationToken).ConfigureAwait(false); + + // Without this the reply arrives in one piece, which defeats the whole streaming path. + await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + await ResponsesEndpointRouteBuilderExtensions.SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) + .ConfigureAwait(false); + } + + /// Runs one streaming turn on the call, wrapping each update with the agent's id. + /// + /// The framework converter sees every update untouched: it ignores the contents it + /// knows nothing of, so dialect lines duplicate nothing and pure streams lose nothing. + /// + private static async IAsyncEnumerable StreamAgentUpdatesAsync( + HttpContext http, + AgentCoreAgent agent, + CallSession call, + ChatMessage input, + CallTurnOrigin? origin, + bool dialect, + ToolCallNames toolNames, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + TurnStreamFiles files = new(); + + await foreach (var update in call + .RunTurnMessageStreamingAtOriginAsync(input, origin, cancellationToken) + .ConfigureAwait(false)) + { + if (dialect) + { + foreach (var part in TurnStreamParts.From(update, toolNames)) + { + await WritePartLineAsync(http, part, cancellationToken).ConfigureAwait(false); + } + + files.Note(update); + } + + yield return new AgentResponseUpdate(update) { AgentId = agent.Id }; + } + + if (dialect) + { + // The enumeration above ends only after the run's providers have finished, and the + // capture provider is one of them: by here the bytes are in the store or never will be. + var calls = http.RequestServices.GetRequiredService(); + + await foreach (var part in files.ResolveAsync(calls, call.CallId, cancellationToken).ConfigureAwait(false)) + { + await WritePartLineAsync(http, part, cancellationToken).ConfigureAwait(false); + } + } + } + + /// Writes one dialect event: one agentcore_* member, bare. + private static async Task WritePartLineAsync( + HttpContext http, TurnStreamPart part, CancellationToken cancellationToken) + { + JsonObject line = part switch + { + TurnStreamRender render + => new JsonObject { ["agentcore_data"] = JsonSerializer.SerializeToNode(render.Payload, ResponsesJson.Options) }, + TurnStreamSource source + => new JsonObject { ["agentcore_source"] = JsonSerializer.SerializeToNode(source.Payload, ResponsesJson.Options) }, + TurnStreamTool tool + => new JsonObject { ["agentcore_tool"] = JsonSerializer.SerializeToNode(tool.Payload, ResponsesJson.Options) }, + TurnStreamApproval approval + => new JsonObject { ["agentcore_approval"] = JsonSerializer.SerializeToNode(approval.Payload, ResponsesJson.Options) }, + TurnStreamFile file + => new JsonObject { ["agentcore_file"] = JsonSerializer.SerializeToNode(file.Payload, ResponsesJson.Options) }, + _ => throw new InvalidOperationException($"Unknown stream part: {part.GetType()}."), + }; + + await http.Response.WriteAsync("data: ", cancellationToken).ConfigureAwait(false); + await http.Response.WriteAsync(line.ToJsonString(), cancellationToken).ConfigureAwait(false); + await http.Response.WriteAsync("\n\n", cancellationToken).ConfigureAwait(false); + await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs new file mode 100644 index 00000000..b6a5d6d2 --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs @@ -0,0 +1,65 @@ +#pragma warning disable MEAI001 // HostedFileContent is evaluation-only in Microsoft.Extensions.AI 10.10.0. + +using System.Runtime.CompilerServices; +using AgentCore.Application.Calls; +using Microsoft.Extensions.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// +/// The sandbox files one turn surfaced, linked for the browser once the turn is over. +/// +/// +/// A file reference arrives mid-stream, but its bytes reach the store only after the run, when +/// the capture provider has downloaded them. A link handed out earlier would answer 404. So the +/// references are noted as they pass and linked after the last update, against what the store +/// holds: a file the policy refused, or the download lost, is simply not there and gets no part. +/// +internal sealed class TurnStreamFiles +{ + private readonly List _references = []; + + /// Notes every sandbox file reference one update carries. + /// One update of the stream. + internal void Note(ChatResponseUpdate update) + { + foreach (var content in update.Contents) + { + if (content is HostedFileContent or CodeInterpreterToolResultContent) + { + _references.Add(content); + } + } + } + + /// Links every noted file the store kept, in the order they were noted. + /// The door to the stored call. + /// The call that owns the files. + /// Cancels the lookups. + /// One part for each file the store holds. + internal async IAsyncEnumerable ResolveAsync( + CallRepository calls, + string callId, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + if (_references.Count == 0) + { + yield break; + } + + var links = await calls + .LinkFilesAsync(callId, [new ChatMessage(ChatRole.Assistant, _references)], cancellationToken) + .ConfigureAwait(false); + + foreach (var (blob, url) in links) + { + yield return new TurnStreamFile(new FilePayload + { + Name = blob.Name, + MediaType = blob.MediaType, + Length = blob.Length, + Url = url?.ToString(), + }); + } + } +} diff --git a/src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs index b3ee4870..78b77a3f 100644 --- a/src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs @@ -136,3 +136,6 @@ internal sealed record TurnStreamTool(ToolPayload Payload) : TurnStreamPart; /// One tool call waiting on the caller, as the browser reads it. internal sealed record TurnStreamApproval(ApprovalPayload Payload) : TurnStreamPart; + +/// One file the turn produced, as the browser reads it. +internal sealed record TurnStreamFile(FilePayload Payload) : TurnStreamPart; diff --git a/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs index 16f66107..d78f14de 100644 --- a/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs +++ b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs @@ -77,6 +77,55 @@ public async ValueTask PutAsync(BlobWrite write, CancellationToken canc return new BlobRead(response.Headers.ContentType, response.ContentLength, response.ResponseStream); } + /// + public async ValueTask StatAsync( + string ownerId, + string name, + CancellationToken cancellationToken = default) + { + var key = KeyOf(ownerId, name); + + GetObjectMetadataResponse head; + + try + { + head = await _client.GetObjectMetadataAsync(_bucket, key, cancellationToken).ConfigureAwait(false); + } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + + return new BlobRef(ownerId, name, head.Headers.ContentType, head.ContentLength); + } + + /// + /// + /// A presigned GET. Only host is signed: a browser sends no other header the bucket + /// could check. The media type and disposition ride as response overrides, which the + /// signature covers, so the link cannot be bent into serving the bytes another way. + /// + public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(blob); + + GetPreSignedUrlRequest request = new() + { + BucketName = _bucket, + Key = KeyOf(blob.OwnerId, blob.Name), + Verb = HttpVerb.GET, + Protocol = Protocol.HTTPS, + Expires = DateTime.UtcNow.Add(lifetime), + ResponseHeaderOverrides = + { + ContentType = blob.MediaType, + ContentDisposition = BlobLink.DispositionOf(blob.MediaType, blob.Name), + }, + }; + + return new(new Uri(_client.GetPreSignedURL(request))); + } + /// public async ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) { diff --git a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt index a981fd1e..c4b9fbe0 100644 --- a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt @@ -99,3 +99,5 @@ AgentCore.Infrastructure.Blobs.S3.S3BlobStore.PutAsync(AgentCore.Application.Blo AgentCore.Infrastructure.Blobs.S3.S3BlobStore.S3BlobStore(Amazon.S3.IAmazonS3! client, string! bucket) -> void const AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.DefaultRegion = "us-east-1" -> string! const AgentCore.Infrastructure.Blobs.S3.S3BlobStoreAdapter.ProviderKind = "s3" -> string! +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.LinkAsync(AgentCore.Application.Blobs.BlobRef! blob, System.TimeSpan lifetime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Infrastructure.Blobs.S3.S3BlobStore.StatAsync(string! ownerId, string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobLinkTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobLinkTests.cs new file mode 100644 index 00000000..d1740c04 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Blobs/BlobLinkTests.cs @@ -0,0 +1,41 @@ +using AgentCore.Application.Blobs; +using Xunit; + +namespace AgentCore.Application.Tests.Blobs; + +/// The disposition a link serves a blob with. RFC 6266 spells the header; the spec picks inline vs attachment. +public sealed class BlobLinkTests +{ + [Theory] + [InlineData("image/png", "chart.png", "inline; filename*=UTF-8''chart.png")] + [InlineData("application/pdf", "report.pdf", "inline; filename*=UTF-8''report.pdf")] + [InlineData("text/csv", "rows.csv", "attachment; filename*=UTF-8''rows.csv")] + [InlineData("image/svg+xml", "logo.svg", "attachment; filename*=UTF-8''logo.svg")] + [InlineData("text/html", "page.html", "attachment; filename*=UTF-8''page.html")] + [InlineData("application/octet-stream", "blob.bin", "attachment; filename*=UTF-8''blob.bin")] + public void DispositionOf_KnownMediaTypes_MatchesTheSpec(string mediaType, string name, string expected) + { + // Act + var header = BlobLink.DispositionOf(mediaType, name); + + // Assert + Assert.Equal(expected, header); + } + + [Fact] + public void DispositionOf_NameWithSpaceAndUnicode_PercentEncodesPerRfc5987() + { + // Act + var header = BlobLink.DispositionOf("image/png", "my chart é.png"); + + // Assert + Assert.Equal("inline; filename*=UTF-8''my%20chart%20%C3%A9.png", header); + } + + [Fact] + public void Lifetime_IsFifteenMinutes() + { + // Assert: decision 10 of the sandbox file capture spec. + Assert.Equal(TimeSpan.FromMinutes(15), BlobLink.Lifetime); + } +} diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs index b3675f9a..f1e163c8 100644 --- a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs @@ -119,6 +119,12 @@ public ValueTask PutAsync(BlobWrite write, CancellationToken cancellati public ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + public ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) => throw new NotSupportedException(); } diff --git a/tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs b/tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs new file mode 100644 index 00000000..2b2d6b1d --- /dev/null +++ b/tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs @@ -0,0 +1,122 @@ +#pragma warning disable MEAI001 + +using System.Text.Json; +using AgentCore.Application.Blobs; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Blobs; + +/// Which names a message's sandbox file references resolve to. +public sealed class SandboxFilesTests +{ + [Fact] + public void NamesIn_FileOnTheMessageAndInsideAnInterpreterResult_ReturnsBothInOrder() + { + // Arrange + AIContent[] contents = + [ + new TextContent("see the chart"), + new HostedFileContent("cfile_1") { Name = "chart.png" }, + new CodeInterpreterToolResultContent("call_ci") { Outputs = [new HostedFileContent("cfile_2") { Name = "rows.csv" }] }, + ]; + + // Act + var names = SandboxFiles.NamesIn(contents); + + // Assert + Assert.Equal(["chart.png", "rows.csv"], names); + } + + [Fact] + public void NamesIn_SameFileTwice_ReturnsItOnce() + { + // Arrange + AIContent[] contents = + [ + new HostedFileContent("cfile_1") { Name = "chart.png" }, + new HostedFileContent("cfile_1") { Name = "chart.png" }, + ]; + + // Act + var names = SandboxFiles.NamesIn(contents); + + // Assert + Assert.Equal(["chart.png"], names); + } + + [Fact] + public void NamesIn_NoName_FallsBackToTheVendorId() + { + // Act + var names = SandboxFiles.NamesIn([new HostedFileContent("cfile_abc")]); + + // Assert + Assert.Equal(["cfile_abc"], names); + } + + [Fact] + public void KeptIn_StampSurvivesTheTranscriptEncoder() + { + // Arrange: stamp a fresh reference, store the message, read it back. + HostedFileContent reference = new("cfile_1") { Name = "chart.png" }; + SandboxFiles.MarkKept(reference, new BlobRef("call-1", "chart.png", "image/png", 48213)); + ChatMessage reply = new(ChatRole.Assistant, [new TextContent("see"), reference]); + + var json = JsonSerializer.Serialize(reply, TranscriptJson.Options); + var restored = JsonSerializer.Deserialize(json, TranscriptJson.Options)!; + + // Act + var facts = SandboxFiles.KeptIn(restored.Contents); + + // Assert + Assert.Equal([new SandboxFileFacts("chart.png", "image/png", 48213)], facts); + } + + [Fact] + public void KeptIn_UnstampedOrRefusedReference_IsNotKept() + { + // Arrange + HostedFileContent unstamped = new("cfile_1") { Name = "chart.png", MediaType = "image/png" }; + HostedFileContent refused = new("cfile_2") { Name = "big.png" }; + SandboxFiles.MarkRefused(refused); + + // Act + var facts = SandboxFiles.KeptIn([unstamped, refused]); + + // Assert + Assert.Empty(facts); + } + + [Fact] + public void KeptIn_SameNameStampedTwice_TheLaterFactsWinInTheFirstPlace() + { + // Arrange: the model redrew chart.png after rows.csv; the store replaced the first. + HostedFileContent first = new("cfile_1") { Name = "chart.png" }; + HostedFileContent rows = new("cfile_2") { Name = "rows.csv" }; + HostedFileContent second = new("cfile_3") { Name = "chart.png" }; + SandboxFiles.MarkKept(first, new BlobRef("call-1", "chart.png", "image/png", 10)); + SandboxFiles.MarkKept(rows, new BlobRef("call-1", "rows.csv", "text/csv", 5)); + SandboxFiles.MarkKept(second, new BlobRef("call-1", "chart.png", "image/png", 20)); + + // Act + var facts = SandboxFiles.KeptIn([first, rows, second]); + + // Assert + Assert.Equal([new SandboxFileFacts("chart.png", "image/png", 20), new SandboxFileFacts("rows.csv", "text/csv", 5)], facts); + } + + [Theory] + [InlineData("../etc/passwd")] + [InlineData("a/b.png")] + [InlineData("")] + public void NamesIn_UnsafeName_IsDropped(string name) + { + // Act + var names = SandboxFiles.NamesIn([new HostedFileContent("cfile_1") { Name = name }]); + + // Assert + Assert.Empty(names); + } +} diff --git a/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs b/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs new file mode 100644 index 00000000..a0f3bf78 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs @@ -0,0 +1,152 @@ +#pragma warning disable MEAI001 + +using AgentCore.Application.Blobs; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Ports; +using AgentCore.Application.Tests.Fakes; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Calls; + +/// The one door to a stored call: its row, its words, and its files go together. +public sealed class CallRepositoryTests +{ + /// A reply whose references the capture stamped as kept, 3 bytes each. + private static ChatMessage ReplyWith(params (string Name, string MediaType)[] kept) + => new(ChatRole.Assistant, [new TextContent("see"), .. kept.Select(file => Kept(file.Name, file.MediaType))]); + + private static HostedFileContent Kept(string name, string mediaType) + { + HostedFileContent reference = new("cfile_" + name) { Name = name }; + SandboxFiles.MarkKept(reference, new BlobRef("call-1", name, mediaType, 3)); + return reference; + } + + private static HostedFileContent Refused(string name) + { + HostedFileContent reference = new("cfile_" + name) { Name = name }; + SandboxFiles.MarkRefused(reference); + return reference; + } + + private static async Task KeepAsync(RecordingBlobStore blobs, string callId, string name, string mediaType) + => await blobs.PutAsync(new BlobWrite(callId, name, mediaType, new MemoryStream([1, 2, 3]), 3), TestContext.Current.CancellationToken); + + [Fact] + public async Task DeleteAsync_DeletesTheFilesAndTheRow() + { + // Arrange + InMemoryCallStore store = new(); + RecordingBlobStore blobs = new(); + CallRepository calls = new(store, blobs); + var token = TestContext.Current.CancellationToken; + await calls.CreateAsync("call-1", token); + await KeepAsync(blobs, "call-1", "chart.png", "image/png"); + await KeepAsync(blobs, "call-2", "keep.png", "image/png"); + + // Act + await calls.DeleteAsync("call-1", token); + + // Assert + Assert.Null(await store.GetAsync("call-1", token)); + Assert.Equal([("call-2", "keep.png")], blobs.Blobs.Keys); + } + + [Fact] + public async Task DeleteAsync_NoBlobStore_DeletesTheRowAlone() + { + // Arrange + InMemoryCallStore store = new(); + CallRepository calls = new(store, blobs: null); + var token = TestContext.Current.CancellationToken; + await calls.CreateAsync("call-1", token); + + // Act + await calls.DeleteAsync("call-1", token); + + // Assert + Assert.Null(await store.GetAsync("call-1", token)); + Assert.False(calls.KeepsFiles); + } + + [Fact] + public async Task LinkFilesAsync_LinksFromTheStamp_EachOnce_InFirstSeenOrder_WithoutAskingTheStore() + { + // Arrange: the store is empty on purpose. The stamp is the index. + CountingBlobStore blobs = new(); + CallRepository calls = new(new InMemoryCallStore(), blobs); + + // Act + var links = await calls.LinkFilesAsync( + "call-1", + [ + new ChatMessage(ChatRole.Assistant, [Kept("chart.png", "image/png"), Refused("lost.pdf")]), + ReplyWith(("rows.csv", "text/csv"), ("chart.png", "image/png")), + ], + TestContext.Current.CancellationToken); + + // Assert + Assert.Collection( + links, + link => + { + Assert.Equal(new BlobRef("call-1", "chart.png", "image/png", 3), link.Blob); + Assert.Equal("https://blobs.test/call-1/chart.png?ttl=900", link.Url?.ToString()); + }, + link => Assert.Equal("rows.csv", link.Blob.Name)); + Assert.Equal(0, blobs.Stats); + } + + [Fact] + public async Task LinkFilesAsync_NoBlobStore_LinksNothing() + { + // Arrange + CallRepository calls = new(new InMemoryCallStore(), blobs: null); + + // Act + var links = await calls.LinkFilesAsync("call-1", [ReplyWith(("chart.png", "image/png"))], TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(links); + } + + [Fact] + public async Task LinkFilesAsync_FileInsideAnInterpreterResult_IsFound() + { + // Arrange + CallRepository calls = new(new InMemoryCallStore(), new RecordingBlobStore()); + ChatMessage reply = new(ChatRole.Assistant, [new CodeInterpreterToolResultContent("ci_1") { Outputs = [Kept("chart.png", "image/png")] }]); + + // Act + var links = await calls.LinkFilesAsync("call-1", [reply], TestContext.Current.CancellationToken); + + // Assert + Assert.Equal("chart.png", Assert.Single(links).Blob.Name); + } + + /// Links like the recording store, and counts how often anyone asks it whether a blob exists. + private sealed class CountingBlobStore : IBlobStore + { + public int Stats { get; private set; } + + public ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default) + { + Stats++; + return ValueTask.FromResult(null); + } + + public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) + => ValueTask.FromResult(new Uri($"https://blobs.test/{blob.OwnerId}/{blob.Name}?ttl={(int)lifetime.TotalSeconds}")); + + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } +} diff --git a/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs b/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs index 4d287cab..e44baf81 100644 --- a/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs +++ b/tests/AgentCore.Application.Tests/Fakes/RecordingBlobStore.cs @@ -24,6 +24,15 @@ public async ValueTask PutAsync(BlobWrite write, CancellationToken canc ? new BlobRead(blob.MediaType, blob.Bytes.Length, new MemoryStream(blob.Bytes)) : null); + public ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => ValueTask.FromResult(_blobs.TryGetValue((ownerId, name), out var blob) + ? new BlobRef(ownerId, name, blob.MediaType, blob.Bytes.Length) + : null); + + /// A recognisable fake link, so a test can see what was linked and for how long. + public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) + => ValueTask.FromResult(new Uri($"https://blobs.test/{blob.OwnerId}/{blob.Name}?ttl={(int)lifetime.TotalSeconds}")); + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) { foreach (var key in _blobs.Keys.Where(key => key.Owner == ownerId).ToList()) diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs index a2d79829..900165d2 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs @@ -40,6 +40,39 @@ public async Task InvokedAsync_FileOnTheMessage_StoresItUnderTheCallAndTheName() Assert.Equal("cntr_1", files.ScopesAsked["cfile_1"]); } + [Fact] + public async Task InvokedAsync_FileKept_StampsTheReferenceWithWhatWasStored() + { + // Arrange: the vendor's reference names no media type; the download does. + var files = new ScriptedHostedFileClient().Serve("cfile_1", Png, "image/png"); + RecordingBlobStore blobs = new(); + var (agent, session) = await AgentWithFiledTurn("call-7"); + HostedFileContent reference = new("cfile_1") { Name = "chart.png" }; + + // Act + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(reference)), TestContext.Current.CancellationToken); + + // Assert: a later read links from the stamp alone. + var facts = Assert.Single(SandboxFiles.KeptIn([reference])); + Assert.Equal(new SandboxFileFacts("chart.png", "image/png", Png.Length), facts); + } + + [Fact] + public async Task InvokedAsync_FileRefused_StampsTheReferenceAsNotKept() + { + // Arrange: a 100-byte cap, a 300-byte file. + var files = new ScriptedHostedFileClient().Serve("cfile_6", new byte[300], "image/png"); + var (agent, session) = await AgentWithFiledTurn("call-7"); + HostedFileContent reference = new("cfile_6") { Name = "big.png" }; + var provider = new HostedFileCaptureProvider(files, new RecordingBlobStore(), new BlobPolicy(100, ["png"]), NullLogger.Instance); + + // Act + await provider.InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(reference)), TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(SandboxFiles.KeptIn([reference])); + } + [Fact] public async Task InvokedAsync_FileInsideAnInterpreterResult_IsStoredToo() { diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index 90fdf790..c0fceb59 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -1340,7 +1340,7 @@ public async Task ADocumentThatNamesNoCallStoreProvider_StillOpensTheMemoryStore // The turn loop writes the words of every call whatever a document says, so this seam has a // working default rather than a null, and a first run needs no database. Assert.NotNull(provider.GetService()); - Assert.IsType(provider.GetRequiredService()); + Assert.IsType(provider.GetRequiredService().Store); } [Fact] @@ -1357,7 +1357,7 @@ public async Task ACallStoreVendorTheDocumentNames_IsTheStoreTheTurnWritesTo() // The host lists its vendors once and providers.calls.kind picks one. Nothing but the // document decides where the words of a call land. - Assert.Same(store, provider.GetRequiredService()); + Assert.Same(store, provider.GetRequiredService().Store); Assert.Equal(["user", "assistant"], store.Roles); } diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs new file mode 100644 index 00000000..8c2eb171 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs @@ -0,0 +1,98 @@ +#pragma warning disable MEAI001 + +using AgentCore.Application.Blobs; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Ports; +using AgentCore.AspNetCore.Endpoints; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.Endpoints; + +/// Which sandbox files reach the browser as a part, and with what link. +public sealed class TurnStreamFilesTests +{ + private static ChatResponseUpdate UpdateWith(params AIContent[] contents) + => new(ChatRole.Assistant, contents); + + /// A reference the capture provider stamped as kept, as it does before the stream ends. + private static HostedFileContent Kept(string name, string mediaType, long length) + { + HostedFileContent reference = new("cfile_" + name) { Name = name }; + SandboxFiles.MarkKept(reference, new BlobRef("call-1", name, mediaType, length)); + return reference; + } + + [Fact] + public async Task ResolveAsync_NotedFileTheCaptureKept_YieldsOnePartWithTheLink() + { + // Arrange: the same reference passes twice, as a re-yielded update would; a refused one passes too. + CallRepository calls = new(new InMemoryCallStore(), new StubBlobStore()); + TurnStreamFiles files = new(); + var chart = Kept("chart.png", "image/png", 48213); + HostedFileContent refused = new("cfile_2") { Name = "refused.png" }; + SandboxFiles.MarkRefused(refused); + files.Note(UpdateWith(new TextContent("see"), chart)); + files.Note(UpdateWith(chart)); + files.Note(UpdateWith(refused)); + + // Act + var parts = await files.ResolveAsync(calls, "call-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); + + // Assert: once, linked, and the refused file is not there. + var part = Assert.Single(parts); + Assert.Equal("chart.png", part.Payload.Name); + Assert.Equal("image/png", part.Payload.MediaType); + Assert.Equal(48213, part.Payload.Length); + Assert.Equal("https://blobs.test/call-1/chart.png?ttl=900", part.Payload.Url); + } + + [Fact] + public async Task ResolveAsync_StoreWithNoWebDoor_YieldsThePartWithoutAUrl() + { + // Arrange + CallRepository calls = new(new InMemoryCallStore(), new StubBlobStore { Links = false }); + TurnStreamFiles files = new(); + files.Note(UpdateWith(Kept("rows.csv", "text/csv", 8))); + + // Act + var parts = await files.ResolveAsync(calls, "call-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); + + // Assert + Assert.Null(Assert.Single(parts).Payload.Url); + } + + [Fact] + public async Task ResolveAsync_NothingNoted_YieldsNothing() + { + // Arrange + CallRepository calls = new(new InMemoryCallStore(), blobs: null); + + // Act + var parts = await new TurnStreamFiles().ResolveAsync(calls, "call-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(parts); + } + + private sealed class StubBlobStore : IBlobStore + { + public bool Links { get; init; } = true; + + public ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => throw new NotSupportedException("The read path links from the stamp and never asks the store."); + + public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) + => ValueTask.FromResult(Links ? new Uri($"https://blobs.test/{blob.OwnerId}/{blob.Name}?ttl={(int)lifetime.TotalSeconds}") : null); + + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } +} diff --git a/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs b/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs index 4c28985e..51225b41 100644 --- a/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs +++ b/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs @@ -1,6 +1,7 @@ using System.Text.Json.Nodes; using AgentCore.Application.Audit; using AgentCore.Application.Audit.Memory; +using AgentCore.Application.Calls; using AgentCore.Application.Calls.Memory; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; @@ -126,8 +127,8 @@ public async Task ADocumentNamingNoDurableVendorStillGetsTheInProcessStores() using var host = await StartAsync(); Assert.IsType(host.Services.GetRequiredService().Store); - Assert.IsType(host.Services.GetRequiredService()); - Assert.IsType(host.Services.GetRequiredService()); + Assert.IsType(host.Services.GetRequiredService().Store); + Assert.IsType(host.Services.GetRequiredService().Store); } [Fact] @@ -150,7 +151,7 @@ public async Task AHostCallStoreWinsOverTheDefaultVendorOnTheSameKind() options => options.UseCallStores(new FakeCallStoreAdapter()), Calls); - Assert.IsType(host.Services.GetRequiredService()); + Assert.IsType(host.Services.GetRequiredService().Store); } // --------------------------------------------------------------------------------------------- diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs new file mode 100644 index 00000000..5b9155b9 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs @@ -0,0 +1,79 @@ +using System.Web; +using AgentCore.Application.Blobs; +using AgentCore.Infrastructure.Blobs.S3; +using Amazon.Runtime; +using Amazon.S3; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Blobs.S3; + +/// +/// The presigned link, checked without a bucket: SigV4 signing is local. A browser GET sends +/// Host and nothing else the bucket can check, so X-Amz-SignedHeaders must be +/// exactly host; anything more and the bucket answers SignatureDoesNotMatch. +/// +public sealed class S3BlobStoreLinkTests +{ + private static S3BlobStore Open() + => new( + new AmazonS3Client( + new BasicAWSCredentials("fakeKeyId", "fakeSecret"), + new AmazonS3Config + { + ServiceURL = "https://s3.us-east-005.backblazeb2.com", + AuthenticationRegion = "us-east-005", + ForcePathStyle = true, + }), + "SpiritAI"); + + [Fact] + public async Task LinkAsync_SignsHostOnly_AndCarriesTheResponseOverrides() + { + // Arrange + using var store = Open(); + BlobRef blob = new("call-1", "chart.png", "image/png", 48213); + + // Act + var url = await store.LinkAsync(blob, TimeSpan.FromMinutes(15), TestContext.Current.CancellationToken); + + // Assert + Assert.NotNull(url); + Assert.Equal("https", url.Scheme); + Assert.Equal("s3.us-east-005.backblazeb2.com", url.Host); + Assert.Equal("/SpiritAI/call-1/chart.png", url.AbsolutePath); + + var query = HttpUtility.ParseQueryString(url.Query); + Assert.Equal("host", query["X-Amz-SignedHeaders"]); + Assert.Equal("900", query["X-Amz-Expires"]); + Assert.Equal("AWS4-HMAC-SHA256", query["X-Amz-Algorithm"]); + Assert.Equal("image/png", query["response-content-type"]); + Assert.Equal("inline; filename*=UTF-8''chart.png", query["response-content-disposition"]); + Assert.NotEmpty(query["X-Amz-Signature"]!); + } + + [Fact] + public async Task LinkAsync_Csv_IsServedAsAnAttachment() + { + // Arrange + using var store = Open(); + + // Act + var url = await store.LinkAsync(new BlobRef("call-1", "rows.csv", "text/csv", 8), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); + + // Assert + var query = HttpUtility.ParseQueryString(url!.Query); + Assert.Equal("attachment; filename*=UTF-8''rows.csv", query["response-content-disposition"]); + Assert.Equal("60", query["X-Amz-Expires"]); + } + + [Fact] + public async Task LinkAsync_UnsafeName_Throws() + { + // Arrange + using var store = Open(); + + // Act + Assert + await Assert.ThrowsAsync(async () => + await store.LinkAsync(new BlobRef("call-1", "../x.png", "image/png", 1), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken)); + } +} diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs index edb66975..daa4e3b0 100644 --- a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs @@ -124,6 +124,51 @@ public async Task DeleteByOwnerAsync_RemovesEveryBlobOfThatOwnerOnly() } } + [S3Fact] + public async Task StatAsync_StoredBlob_ReturnsItsFactsWithoutTheBytes() + { + // Arrange + var bytes = Encoding.UTF8.GetBytes("a,b\n1,2\n"); + var token = TestContext.Current.CancellationToken; + await Store.PutAsync(new BlobWrite(_owner, "rows.csv", "text/csv", new MemoryStream(bytes), bytes.Length), token); + + // Act + var stat = await Store.StatAsync(_owner, "rows.csv", token); + + // Assert + Assert.Equal(new BlobRef(_owner, "rows.csv", "text/csv", bytes.Length), stat); + } + + [S3Fact] + public async Task StatAsync_UnknownName_ReturnsNull() + { + // Act + var stat = await Store.StatAsync(_owner, "never.png", TestContext.Current.CancellationToken); + + // Assert + Assert.Null(stat); + } + + [S3Fact] + public async Task LinkAsync_StoredBlob_IsFetchableWithNoCredential() + { + // Arrange + var bytes = new byte[] { 0x89, 0x50, 0x4E, 0x47 }; + var token = TestContext.Current.CancellationToken; + var blob = await Store.PutAsync(new BlobWrite(_owner, "chart.png", "image/png", new MemoryStream(bytes), bytes.Length), token); + + // Act + var url = await Store.LinkAsync(blob, TimeSpan.FromMinutes(1), token); + using HttpClient anonymous = new(); + using var fetched = await anonymous.GetAsync(url, token); + + // Assert + Assert.Equal(System.Net.HttpStatusCode.OK, fetched.StatusCode); + Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType); + Assert.Equal("inline", fetched.Content.Headers.ContentDisposition?.DispositionType); + Assert.Equal(bytes, await fetched.Content.ReadAsByteArrayAsync(token)); + } + [S3Fact] public async Task DeleteByOwnerAsync_NothingStored_DoesNotThrow() { From aaf44a51217f48a2f389246ff88b4b3a77911857 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 14:40:31 -0600 Subject: [PATCH 07/35] feat: refactor various components for improved readability and performance --- src/AgentCore.Application/Blobs/BlobName.cs | 7 ++---- .../Compilation/CompiledAgentRegistry.cs | 11 +-------- .../Compilation/GraphStateEntry.cs | 2 +- .../Validation/ConfigurationValidator.cs | 21 +++++++++-------- .../Configuration/Validation/StateDomain.cs | 6 ++--- .../CompositeKnowledgeStoreFactory.cs | 14 ++++------- .../Llm/CompositeChatClientFactory.cs | 13 ++++++++--- .../AuditingFunctionInvokingChatClient.cs | 8 +++---- .../Runtime/Harness/CallShells.cs | 3 +-- .../Secrets/ResolvedSecrets.cs | 10 ++++---- .../Secrets/SecretName.cs | 10 ++++---- .../State/UnfilledSlotReminder.cs | 8 +++---- .../AgentCoreHttpClients.cs | 2 +- .../Startup/EntryRegistry.cs | 3 ++- .../Endpoints/ResponsesEndpoints.cs | 23 +++++++++++-------- .../Endpoints/TurnStreamFiles.cs | 8 +------ .../TelnyxRelay/TelnyxRelayConnection.cs | 6 ++--- .../Audit/AuditEventVocabulary.cs | 9 ++++---- .../Qdrant/QdrantKnowledgeAdapter.cs | 6 ++--- .../Tools/Mcp/McpServerSession.cs | 2 +- .../Tools/Mcp/McpTool.cs | 2 +- .../Runtime/Turn/TurnResultsTests.cs | 4 ++-- .../Tools/DeclaredToolTests.cs | 2 +- .../Blobs/S3/S3BlobStoreTests.cs | 4 +++- 24 files changed, 87 insertions(+), 97 deletions(-) diff --git a/src/AgentCore.Application/Blobs/BlobName.cs b/src/AgentCore.Application/Blobs/BlobName.cs index a3a958b3..e59daa38 100644 --- a/src/AgentCore.Application/Blobs/BlobName.cs +++ b/src/AgentCore.Application/Blobs/BlobName.cs @@ -26,12 +26,9 @@ public static bool IsSafe(string? name) return false; } - foreach (var c in name) + if (name.Any(c => c is '/' or '\\' || char.IsControl(c))) { - if (c is '/' or '\\' || char.IsControl(c)) - { - return false; - } + return false; } return Encoding.UTF8.GetByteCount(name) <= MaxBytes; diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs index 3687a2bd..9a45a6af 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs @@ -86,16 +86,7 @@ public IReadOnlyDictionary EnsureAll( private void CacheAllLocked(AgentCoreConfiguration configuration, AgentCompilationContext context) { - var missing = false; - foreach (var name in configuration.Entries.Keys) - { - if (!_compiled.ContainsKey(new EntryKey(configuration, name))) - { - missing = true; - break; - } - } - + var missing = configuration.Entries.Keys.Any(name => !_compiled.ContainsKey(new EntryKey(configuration, name))); if (!missing) { return; diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs b/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs index 4dc1e0fd..012b528d 100644 --- a/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs +++ b/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs @@ -23,7 +23,7 @@ protected override async ValueTask TakeTurnAsync( List messages, IWorkflowContext context, bool? emitEvents, - CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(messages); ArgumentNullException.ThrowIfNull(context); diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index e15e42a4..f3f76733 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -22,6 +22,9 @@ public static class ConfigurationValidator /// The increment: field of a counter slot. Named once, so the check below and the two maps under it cannot drift apart. private const string IncrementField = "increment"; + /// The agent: field an entry, tool, stage, or node points at. + private const string AgentField = "agent"; + /// Runs checks 2 to 8 and returns everything they find. /// The bound document. /// Every error and every partial-coverage warning. @@ -223,13 +226,13 @@ private static void CheckEntryShapes(AgentCoreConfiguration configuration, Decla if (string.IsNullOrWhiteSpace(agentId)) { errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "agent"), + ConfigurationError.AppendPointer(pointer, AgentField), $"the entry '{name}' names an empty agent:. It names one id from agents.items.")); } else if (!names.Agents.Contains(agentId)) { errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "agent"), + ConfigurationError.AppendPointer(pointer, AgentField), $"the agent '{agentId}' is not declared in agents.items")); } } @@ -263,7 +266,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar if (tool.Kind == ToolKind.Agent && tool.Agent is { } target && !names.Agents.Contains(target)) { errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Tool(index), "agent"), + ConfigurationError.AppendPointer(Pointer.Tool(index), AgentField), $"the agent '{target}' is not declared in agents.items")); } } @@ -333,7 +336,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar if (stage.Agent is { } agentId && !names.Agents.Contains(agentId)) { errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Stage(name, index), "agent"), + ConfigurationError.AppendPointer(Pointer.Stage(name, index), AgentField), $"the agent '{agentId}' is not declared in agents.items")); } @@ -376,7 +379,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar if (graph.Nodes[index].Agent is { } nodeAgent && !names.Agents.Contains(nodeAgent)) { errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Node(name, index), "agent"), + ConfigurationError.AppendPointer(Pointer.Node(name, index), AgentField), $"the agent '{nodeAgent}' is not declared in agents.items")); } } @@ -1285,12 +1288,10 @@ private static HashSet Reach(string root, Dictionary !seen.Contains(target))) { - if (seen.Add(target)) - { - pending.Push(target); - } + seen.Add(target); + pending.Push(target); } } diff --git a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs index 71636fea..a7c4972f 100644 --- a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs +++ b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs @@ -62,14 +62,14 @@ public static long CountPoints(IReadOnlyList domains) ArgumentNullException.ThrowIfNull(domains); var total = 1L; - foreach (var domain in domains) + foreach (var count in domains.Select(domain => domain.Points.Count)) { - if (domain.Points.Count == 0) + if (count == 0) { return 0; } - total *= domain.Points.Count; + total *= count; if (total > MaximumPoints) { return long.MaxValue; diff --git a/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs b/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs index 37a951be..cd91f0eb 100644 --- a/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs +++ b/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs @@ -114,15 +114,11 @@ private static bool CitationsDeclared(AgentCoreConfiguration configuration) /// Writes the registered kinds, so a failure names what the host does register. private static string Registered(IReadOnlyList adapters) { - HashSet seen = new(StringComparer.OrdinalIgnoreCase); - List kinds = []; - foreach (var adapter in adapters) - { - if (seen.Add(adapter.Kind)) - { - kinds.Add("'" + adapter.Kind + "'"); - } - } + var kinds = adapters + .Select(adapter => adapter.Kind) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(kind => "'" + kind + "'") + .ToList(); return kinds.Count == 0 ? "no adapter" : string.Join(", ", kinds); } diff --git a/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs b/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs index 1800c28c..b7ef04f2 100644 --- a/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs +++ b/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs @@ -118,9 +118,16 @@ public IChatClient GetChatClient(ModelReference? model) ArgumentNullException.ThrowIfNull(marker); ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) == 1, this); - var entry = model is null - ? _default - : _entries.TryGetValue(model.Ref, out var named) ? named : null; + LlmProviderConfiguration? entry; + if (model is null) + { + entry = _default; + } + else + { + _entries.TryGetValue(model.Ref, out entry); + } + if (entry is null || !_adapters.TryGetValue(entry.As, out var adapter)) { return null; diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index 9bbc4e76..b4200859 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -185,12 +185,12 @@ protected override IList CreateResponseMessages(ReadOnlySpan message.Contents)) { // Materialised before the loop below adds to the very list this reads: Contents is a // List underneath, and its enumerator throws on the next MoveNext once // anything has been appended, even where nothing further was left to enumerate. - foreach (var callId in message.Contents.OfType().Select(r => r.CallId).ToList()) + foreach (var callId in contents.OfType().Select(r => r.CallId).ToList()) { // A nested loop's calls drain nothing: their ids were registered under the // stripped copy, so removing the entry without draining keeps the outer drain @@ -200,12 +200,12 @@ protected override IList CreateResponseMessages(ReadOnlySpan GetEnvironmentAsync( _ = probe.ContinueWith( static (task, state) => { - if (task.IsFaulted || task.IsCanceled) + if ((task.IsFaulted || task.IsCanceled) && state is (CallShells shells, CallShellOptions key)) { - var (shells, key) = ((CallShells, CallShellOptions))state!; lock (shells._lock) { if (shells._environments.TryGetValue(key, out var current) diff --git a/src/AgentCore.Application/Secrets/ResolvedSecrets.cs b/src/AgentCore.Application/Secrets/ResolvedSecrets.cs index d4e15f72..e04071c5 100644 --- a/src/AgentCore.Application/Secrets/ResolvedSecrets.cs +++ b/src/AgentCore.Application/Secrets/ResolvedSecrets.cs @@ -56,17 +56,17 @@ public static async ValueTask ResolveAsync( Dictionary values = new(StringComparer.Ordinal); foreach (var (template, pointer) in Templates(configuration)) { - foreach (var reference in template.References) + foreach (var name in template.References.Select(reference => reference.Name)) { - if (values.ContainsKey(reference.Name)) + if (values.ContainsKey(name)) { // One name costs one read, however many strings reference it. continue; } - var value = await resolver.TryResolveAsync(reference.Name, cancellationToken).ConfigureAwait(false); - values[reference.Name] = value - ?? throw SecretResolutionException.Unresolved(reference.Name, pointer); + var value = await resolver.TryResolveAsync(name, cancellationToken).ConfigureAwait(false); + values[name] = value + ?? throw SecretResolutionException.Unresolved(name, pointer); } } diff --git a/src/AgentCore.Application/Secrets/SecretName.cs b/src/AgentCore.Application/Secrets/SecretName.cs index 5d9c6c8e..34b24156 100644 --- a/src/AgentCore.Application/Secrets/SecretName.cs +++ b/src/AgentCore.Application/Secrets/SecretName.cs @@ -1,3 +1,5 @@ +using System.Runtime.CompilerServices; + namespace AgentCore.Application.Secrets; /// @@ -27,10 +29,10 @@ namespace AgentCore.Application.Secrets; public sealed record SecretName(string Name, string VariableName) { /// Gets the name the resolver chain is asked for. - public string Name { get; } = Required(Name, nameof(Name)); + public string Name { get; } = Required(Name); /// Gets the environment variable read when the chain holds nothing. - public string VariableName { get; } = Required(VariableName, nameof(VariableName)); + public string VariableName { get; } = Required(VariableName); /// Writes both names, because neither one is a value. /// The text name (VARIABLE). @@ -38,10 +40,10 @@ public sealed record SecretName(string Name, string VariableName) /// Refuses a half that names nothing. /// The name given. - /// Which half it is, for the exception to report. + /// Which half it is, for the exception to report. Filled in by the compiler. /// The name. /// The name is null, empty, or blank. - private static string Required(string value, string parameter) + private static string Required(string value, [CallerArgumentExpression(nameof(value))] string parameter = "") { ArgumentException.ThrowIfNullOrWhiteSpace(value, parameter); return value; diff --git a/src/AgentCore.Application/State/UnfilledSlotReminder.cs b/src/AgentCore.Application/State/UnfilledSlotReminder.cs index eaaaaf43..3e84694e 100644 --- a/src/AgentCore.Application/State/UnfilledSlotReminder.cs +++ b/src/AgentCore.Application/State/UnfilledSlotReminder.cs @@ -105,17 +105,17 @@ public static IReadOnlyList UnfilledSlots(StateDocument state, StageConf /// private static void CollectStageExits(AgentCoreConfiguration configuration, StageConfiguration stage, HashSet names) { - foreach (var exit in stage.To) + foreach (var when in stage.To.Select(exit => exit.When)) { - if (exit.When is null) + if (when is null) { // An unconditional exit waits on no slots, so it adds nothing to read. continue; } - var rule = exit.When.Rule; + var rule = when.Rule; if (rule is null - && exit.When.Name is { } guardName + && when.Name is { } guardName && configuration.Guards.TryGetValue(guardName, out var named)) { rule = named; diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreHttpClients.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreHttpClients.cs index 9f35d04e..cb2af34d 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreHttpClients.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreHttpClients.cs @@ -46,7 +46,7 @@ public sealed class AgentCoreHttpClients : IHttpClientFactory, IHttpMessageHandl /// public AgentCoreHttpClients(HttpMessageHandler? primaryHandler = null, ILoggerFactory? loggers = null) { - ServiceCollection services = new(); + ServiceCollection services = []; services.AddLogging(); if (loggers is not null) diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs index 84bc8d1a..763c532a 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs @@ -29,6 +29,7 @@ public EntryRegistry( Factories = factories; Agents = agents; CallSessions = callSessions; + Entries = callSessions.Keys.ToArray(); } /// Gets the session factories, keyed by entry name. @@ -41,7 +42,7 @@ public EntryRegistry( public IReadOnlyDictionary CallSessions { get; } /// - public IReadOnlyCollection Entries => CallSessions.Keys.ToArray(); + public IReadOnlyCollection Entries { get; } /// Reads one entry's factory. /// The entry key a route named. diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index 79a43e37..7e119b4c 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -28,6 +28,9 @@ public static class ResponsesEndpointRouteBuilderExtensions /// The answer header that reports the stage the machine holds. public const string StageHeaderName = "X-AgentCore-Stage"; + /// The OpenAI error type every refused request reports. + private const string InvalidRequestError = "invalid_request_error"; + /// Maps the endpoint for one entry on . /// The route builder of the host. /// The entry key this route answers on. @@ -69,7 +72,7 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request body is not well-formed JSON: " + exception.Message, - "invalid_request_error", + InvalidRequestError, "malformed_body", cancellationToken).ConfigureAwait(false); return; @@ -100,7 +103,7 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request is not a Responses request: " + exception.Message, - "invalid_request_error", + InvalidRequestError, "invalid_body", cancellationToken).ConfigureAwait(false); return; @@ -122,7 +125,7 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status503ServiceUnavailable, failure.Message, - "invalid_request_error", + InvalidRequestError, "unknown_entry", cancellationToken).ConfigureAwait(false); return; @@ -168,7 +171,7 @@ await ResponsesRequestReader.WriteErrorAsync( StatusCodes.Status400BadRequest, "an approval answer names the call it resumes. Send it with the conversation " + "or previous response id the asking turn answered with.", - "invalid_request_error", + InvalidRequestError, "missing_session", cancellationToken).ConfigureAwait(false); return; @@ -197,7 +200,7 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status404NotFound, failure.Message, - "invalid_request_error", + InvalidRequestError, "continuation_not_found", cancellationToken).ConfigureAwait(false); return; @@ -213,7 +216,7 @@ await ResponsesRequestReader.WriteErrorAsync( StatusCodes.Status404NotFound, $"no call opens under '{key}'. Send the request with neither a conversation nor a " + "previous response id to start one.", - "invalid_request_error", + InvalidRequestError, "continuation_not_found", cancellationToken).ConfigureAwait(false); @@ -236,7 +239,7 @@ await ResponsesRequestReader.WriteErrorAsync( StatusCodes.Status400BadRequest, "the request carries both a user message and an approval answer. One turn carries " + "either words or an answer, never both.", - "invalid_request_error", + InvalidRequestError, "mixed_turn", cancellationToken).ConfigureAwait(false); return; @@ -251,7 +254,7 @@ await ResponsesRequestReader.WriteErrorAsync( StatusCodes.Status409Conflict, $"the call queues no approval under id '{approval.RequestId}'. It was " + "answered already, belongs to another call, or was never asked.", - "invalid_request_error", + InvalidRequestError, "no_pending_approval", cancellationToken).ConfigureAwait(false); return; @@ -265,7 +268,7 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request carries no user message with text, so there is no turn to run.", - "invalid_request_error", + InvalidRequestError, "no_user_message", cancellationToken).ConfigureAwait(false); return; @@ -313,7 +316,7 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status409Conflict, exception.Message, - "invalid_request_error", + InvalidRequestError, "turn_refused", cancellationToken).ConfigureAwait(false); } diff --git a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs index b6a5d6d2..c36c0878 100644 --- a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs @@ -23,13 +23,7 @@ internal sealed class TurnStreamFiles /// One update of the stream. internal void Note(ChatResponseUpdate update) { - foreach (var content in update.Contents) - { - if (content is HostedFileContent or CodeInterpreterToolResultContent) - { - _references.Add(content); - } - } + _references.AddRange(update.Contents.Where(content => content is HostedFileContent or CodeInterpreterToolResultContent)); } /// Links every noted file the store kept, in the order they were noted. diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs index 7b10f805..7764da1d 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs @@ -59,7 +59,6 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort { - private readonly HttpContext _http; private readonly TelnyxRelayOptions _options; private readonly ILogger _logger; private readonly Channel _outbound; @@ -109,7 +108,6 @@ private ICallSessions EntrySessions() private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOptions options, ILogger logger) { - _http = http; _options = options; _logger = logger; @@ -403,7 +401,7 @@ private async Task CloseSessionAsync(string callId) Task lastTurn, Task writing) { - if (reading.IsFaulted && reading.Exception!.GetBaseException() is RelayProtocolException protocol) + if (reading.IsFaulted && reading.Exception.GetBaseException() is RelayProtocolException protocol) { return (protocol.Status, protocol.Message); } @@ -419,7 +417,7 @@ private async Task CloseSessionAsync(string callId) } if (reading.IsFaulted - && reading.Exception!.GetBaseException() is not WebSocketException + && reading.Exception.GetBaseException() is not WebSocketException { WebSocketErrorCode: WebSocketError.ConnectionClosedPrematurely, }) diff --git a/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs b/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs index 0d974701..33dcac27 100644 --- a/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs +++ b/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs @@ -39,7 +39,7 @@ public static void Validate(AuditEvent auditEvent) // An empty value here is the one thing that cannot be true: every text hashes to 64 // characters, the empty string included, so an empty hash proves nothing and would leave // the row unverifiable against store 1 forever. - RequireHash(auditEvent, AuditPayloadKeys.ReplyTextSha256, replyText); + RequireHash(AuditPayloadKeys.ReplyTextSha256, replyText, nameof(auditEvent)); } RequirePromptFlagged(auditEvent); @@ -86,7 +86,7 @@ private static void RequireReplyInterrupted(AuditEvent auditEvent) nameof(auditEvent)); } - RequireHash(auditEvent, AuditPayloadKeys.UtteranceUntilInterruptSha256, utterance); + RequireHash(AuditPayloadKeys.UtteranceUntilInterruptSha256, utterance, nameof(auditEvent)); } } @@ -147,17 +147,16 @@ private static bool IsCommaSeparatedListWithNoEmptyMember(string? value) return true; } - /// /// Refuses a payload value that is not a SHA-256 digest. /// - private static void RequireHash(AuditEvent auditEvent, string key, string? value) + private static void RequireHash(string key, string? value, string paramName) { if (!AuditHash.TryParse(value, out _)) { throw new ArgumentException( $"The audit payload value of '{key}' is {AuditHash.Length} lowercase hexadecimal characters. This one is '{value}'.", - nameof(auditEvent)); + paramName); } } } diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs index 43797ef3..0d6c8ed6 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs @@ -420,7 +420,7 @@ private static void AssertPointKey( $"'{entry.Collection}' holds points keyed by number, and providers.knowledge.links.lookup " + $"is {links.Lookup.ToString().ToLowerInvariant()}, which builds a UUID key. Every " + "link expansion would silently return nothing. Set links.lookup: filter to match on " - + $"'{entry.Fields!.Id}' instead."); + + $"'{entry.Fields.Id}' instead."); } Guid expected; @@ -432,7 +432,7 @@ private static void AssertPointKey( $"'{entry.Collection}' holds a point whose '{entry.Fields.Id}' is '{cardId}', which is " + "not a GUID, but providers.knowledge.links.lookup is direct. Qdrant's point key is a " + "GUID or an unsigned integer, so a free-form id cannot be one. Set links.lookup: " - + $"filter to match on '{entry.Fields!.Id}' instead."); + + $"filter to match on '{entry.Fields.Id}' instead."); } } else @@ -448,7 +448,7 @@ private static void AssertPointKey( + $"{links.Lookup.ToString().ToLowerInvariant()} with namespace " + $"'{links.Namespace}' and prefix '{links.Prefix}', which derives {expected}. " + $"Every '{links.Field}' expansion would silently return nothing. Correct the " - + $"namespace or prefix, or set links.lookup: filter to match on '{entry.Fields!.Id}'."); + + $"namespace or prefix, or set links.lookup: filter to match on '{entry.Fields.Id}'."); } } diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs index 98cc8cb4..9fa11612 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs @@ -350,7 +350,7 @@ private async ValueTask ReconnectAsync(McpClient dead, CancellationTo } await ConnectAndListAsync(cancellationToken).ConfigureAwait(false); - return _client!; + return _client; } finally { diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs index 3c3bb28f..f3f0756a 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs @@ -84,7 +84,7 @@ public McpTool(McpServerSession session, McpToolDescriptor descriptor, string id var outgoing = arguments; if (_declared is { } declared) { - outgoing = new AIFunctionArguments(); + outgoing = []; foreach (var entry in arguments.Where(candidate => declared.Contains(candidate.Key))) { outgoing[entry.Key] = entry.Value; diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs index fe27687a..6aabbbc3 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs @@ -56,7 +56,7 @@ public void TheDataHandedOut_IsACopy_SoAScriptCannotChangeWhatWasRecorded() } [Theory] - [MemberData(nameof(StructuredResults))] + [MemberData(nameof(StructuredResults), DisableDiscoveryEnumeration = true)] public void AStructuredResult_IsRecorded_WhateverShapeTheToolAnsweredIn(object result, string expected) { TurnResults results = new(); @@ -75,7 +75,7 @@ public void AStructuredResult_IsRecorded_WhateverShapeTheToolAnsweredIn(object r }; [Theory] - [MemberData(nameof(UnstructuredResults))] + [MemberData(nameof(UnstructuredResults), DisableDiscoveryEnumeration = true)] public void AnUnstructuredResult_IsNotRecorded(object? result) { TurnResults results = new(); diff --git a/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs b/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs index 08b3d18e..5119b05d 100644 --- a/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs @@ -56,7 +56,7 @@ public sealed class DeclaredToolTests ]; [Theory] - [MemberData(nameof(RepresentativeFaults))] + [MemberData(nameof(RepresentativeFaults), DisableDiscoveryEnumeration = true)] public async Task AnyFaultTheBodyThrows_PropagatesUnfiltered(Exception failure) { var thrown = await Assert.ThrowsAnyAsync( diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs index daa4e3b0..7e0f0b99 100644 --- a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreTests.cs @@ -172,6 +172,8 @@ public async Task LinkAsync_StoredBlob_IsFetchableWithNoCredential() [S3Fact] public async Task DeleteByOwnerAsync_NothingStored_DoesNotThrow() { - await Store.DeleteByOwnerAsync(_owner, TestContext.Current.CancellationToken); + var error = await Record.ExceptionAsync(() => Store.DeleteByOwnerAsync(_owner, TestContext.Current.CancellationToken).AsTask()); + + Assert.Null(error); } } From 6c9a348fbe408213b8fa7aa490de6e0a2b4029b3 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 14:59:50 -0600 Subject: [PATCH 08/35] Refactor sandbox file handling to use FileContent class - Replaced instances of HostedFileContent with FileContent across the application. - Updated the HostedFileCaptureProvider to write file metadata directly onto FileContent. - Modified CallRepository and TurnStreamFiles to link files using the new FileContent structure. - Removed SandboxFiles utility class and its associated tests, as functionality is now integrated into FileContent. - Adjusted tests to validate the new FileContent behavior and ensure proper serialization/deserialization. --- .../Blobs/{SandboxFileLink.cs => FileLink.cs} | 2 +- .../Blobs/SandboxFileFacts.cs | 7 - .../Blobs/SandboxFiles.cs | 166 ------------------ .../Calls/CallRepository.cs | 40 +++-- .../PublicAPI.Unshipped.txt | 65 +++---- .../Harness/HostedFileCaptureProvider.cs | 29 +-- .../Transcript/FileContent.cs | 31 ++++ .../Transcript/TranscriptJson.cs | 4 + .../Endpoints/TurnStreamFiles.cs | 19 +- .../Llm/OpenAI/OpenAiSandboxFilesClient.cs | 18 +- .../Blobs/SandboxFilesTests.cs | 122 ------------- .../Calls/CallRepositoryTests.cs | 51 +++--- .../Harness/HostedFileCaptureProviderTests.cs | 62 +++---- .../Transcript/FileContentTests.cs | 36 ++++ .../Endpoints/TurnStreamFilesTests.cs | 20 +-- .../Llm/OpenAiSandboxFilesClientTests.cs | 17 +- 16 files changed, 233 insertions(+), 456 deletions(-) rename src/AgentCore.Application/Blobs/{SandboxFileLink.cs => FileLink.cs} (82%) delete mode 100644 src/AgentCore.Application/Blobs/SandboxFileFacts.cs delete mode 100644 src/AgentCore.Application/Blobs/SandboxFiles.cs create mode 100644 src/AgentCore.Application/Transcript/FileContent.cs delete mode 100644 tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs diff --git a/src/AgentCore.Application/Blobs/SandboxFileLink.cs b/src/AgentCore.Application/Blobs/FileLink.cs similarity index 82% rename from src/AgentCore.Application/Blobs/SandboxFileLink.cs rename to src/AgentCore.Application/Blobs/FileLink.cs index 99145f3d..54219318 100644 --- a/src/AgentCore.Application/Blobs/SandboxFileLink.cs +++ b/src/AgentCore.Application/Blobs/FileLink.cs @@ -3,4 +3,4 @@ namespace AgentCore.Application.Blobs; /// One file a call's sandbox wrote and the store kept. /// The file's facts. /// Where a browser fetches it from, or when the store has no web door. -public sealed record SandboxFileLink(BlobRef Blob, Uri? Url); +public sealed record FileLink(BlobRef Blob, Uri? Url); diff --git a/src/AgentCore.Application/Blobs/SandboxFileFacts.cs b/src/AgentCore.Application/Blobs/SandboxFileFacts.cs deleted file mode 100644 index 011def97..00000000 --- a/src/AgentCore.Application/Blobs/SandboxFileFacts.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace AgentCore.Application.Blobs; - -/// What the capture recorded about one kept sandbox file, as read back off the reply. -/// The name the model gave it, which is the name it is stored under. -/// The IANA media type the store holds it as. -/// How many bytes the store holds. -public sealed record SandboxFileFacts(string Name, string MediaType, long Length); diff --git a/src/AgentCore.Application/Blobs/SandboxFiles.cs b/src/AgentCore.Application/Blobs/SandboxFiles.cs deleted file mode 100644 index 7efc0cef..00000000 --- a/src/AgentCore.Application/Blobs/SandboxFiles.cs +++ /dev/null @@ -1,166 +0,0 @@ -#pragma warning disable MEAI001 // HostedFileContent.Scope is evaluation-only in Microsoft.Extensions.AI 10.10.0. - -using System.Text.Json; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Blobs; - -/// Finds the files a vendor's sandbox wrote, wherever the vendor surfaced them on a message. -public static class SandboxFiles -{ - /// The names of every sandbox file the contents reference, in order, each once. - /// The contents of one message or one streaming update. - /// The names a blob was, or would have been, stored under. Only names that pass . - public static IReadOnlyList NamesIn(IEnumerable contents) - { - ArgumentNullException.ThrowIfNull(contents); - - List names = []; - - foreach (var file in In(contents)) - { - var name = NameOf(file); - - if (BlobName.IsSafe(name) && !names.Contains(name, StringComparer.Ordinal)) - { - names.Add(name); - } - } - - return names; - } - - /// - /// The facts of every sandbox file the contents reference that the capture kept, in order, each - /// name once. A reference the capture never stamped, or stamped as refused, is not a file - /// anyone can fetch and is left out. - /// - /// - /// The facts are read off the message and never off the store, so a history read makes no - /// request per file. That is how every production chat keeps its attachments: the bytes in an - /// object store, the index on the message. - /// - /// The contents of one message or one streaming update. - /// The kept files, as the store described them at capture time. - public static IReadOnlyList KeptIn(IEnumerable contents) - { - ArgumentNullException.ThrowIfNull(contents); - - List kept = []; - - foreach (var file in In(contents)) - { - if (FactsOf(file) is not { } facts) - { - continue; - } - - // A second write with the same name replaced the first in the store, so the later - // facts win, in the place the first reference took. - var at = kept.FindIndex(known => string.Equals(known.Name, facts.Name, StringComparison.Ordinal)); - - if (at >= 0) - { - kept[at] = facts; - } - else - { - kept.Add(facts); - } - } - - return kept; - } - - /// Writes onto the reference what the store kept, so every later read has it without asking the store. - /// The vendor's reference, as it sits on the reply. - /// What the store wrote. - public static void MarkKept(HostedFileContent file, BlobRef blob) - { - ArgumentNullException.ThrowIfNull(file); - ArgumentNullException.ThrowIfNull(blob); - - file.MediaType = blob.MediaType; - - var properties = file.AdditionalProperties ??= []; - properties[KeptKey] = true; - properties[LengthKey] = blob.Length; - } - - /// Writes onto the reference that the store did not keep the file, so no read links it. - /// The vendor's reference, as it sits on the reply. - public static void MarkRefused(HostedFileContent file) - { - ArgumentNullException.ThrowIfNull(file); - - (file.AdditionalProperties ??= [])[KeptKey] = false; - } - - /// The name a sandbox file is stored under: what the model called it, else the vendor's id. - internal static string NameOf(HostedFileContent file) => file.Name ?? file.FileId; - - /// The key under which the capture records whether it kept the file. A wire format: it is stored. - private const string KeptKey = "agentcore.kept"; - - /// The key under which the capture records the stored length in bytes. A wire format: it is stored. - private const string LengthKey = "agentcore.length"; - - /// Reads the stamp off one reference, or when it was never kept. - private static SandboxFileFacts? FactsOf(HostedFileContent file) - { - var name = NameOf(file); - - if (!BlobName.IsSafe(name) - || file.AdditionalProperties is not { } properties - || !properties.TryGetValue(KeptKey, out var keptValue) - || !ReadBool(keptValue) - || !properties.TryGetValue(LengthKey, out var lengthValue) - || ReadLong(lengthValue) is not { } length) - { - return null; - } - - return new SandboxFileFacts(name, file.MediaType ?? "application/octet-stream", length); - } - - // A stored message comes back with JsonElement values; a fresh one holds the CLR values written. - private static bool ReadBool(object? value) => value switch - { - bool kept => kept, - JsonElement { ValueKind: JsonValueKind.True } => true, - _ => false, - }; - - private static long? ReadLong(object? value) => value switch - { - long length => length, - int length => length, - JsonElement { ValueKind: JsonValueKind.Number } element when element.TryGetInt64(out var length) => length, - _ => null, - }; - - /// Every sandbox file reference in the contents: on the message, or inside an interpreter result. - internal static IEnumerable In(IEnumerable contents) - { - foreach (var content in contents) - { - switch (content) - { - case HostedFileContent file: - yield return file; - break; - - case CodeInterpreterToolResultContent { Outputs: { } outputs }: - foreach (var output in outputs) - { - if (output is HostedFileContent nested) - { - yield return nested; - } - } - - break; - } - } - } -} diff --git a/src/AgentCore.Application/Calls/CallRepository.cs b/src/AgentCore.Application/Calls/CallRepository.cs index 513a05f8..13277b95 100644 --- a/src/AgentCore.Application/Calls/CallRepository.cs +++ b/src/AgentCore.Application/Calls/CallRepository.cs @@ -33,19 +33,12 @@ public CallRepository(ICallStore calls, IBlobStore? blobs) /// The adapter the rows live in. For a host checking which vendor it opened; go through the repository for everything else. public ICallStore Store => _calls; - /// Links every sandbox file the messages reference and the capture kept, each once, in first-seen order. - /// - /// Read off the messages, never off the store: the capture stamped each reference with what it - /// kept, so a history read makes no request per file. The link is minted here on every read, so - /// it is fresh however old the reply is. A file the capture refused, or never saw, has no stamp - /// and gets no link: the reply's words still name it, and that is all there is to show. A blob - /// deleted behind a stamped message gives a link that answers 404, as every chat product's does. - /// + /// Links every sandbox file the messages carry and the capture kept, each name once, in first-seen order. /// The call that owns the files. /// The messages to read the references off: the stored transcript, or one turn's updates. /// Cancels the signing. /// One link per kept file. - public async Task> LinkFilesAsync( + public async Task> LinkFilesAsync( string callId, IEnumerable messages, CancellationToken cancellationToken = default) @@ -58,15 +51,34 @@ public async Task> LinkFilesAsync( return []; } - List links = []; + List kept = []; - foreach (var facts in SandboxFiles.KeptIn(messages.SelectMany(message => message.Contents))) + foreach (var file in messages.SelectMany(message => message.Contents).OfType()) { - BlobRef blob = new(callId, facts.Name, facts.MediaType, facts.Length); + if (!file.Kept || !BlobName.IsSafe(file.Name)) + { + continue; + } + + BlobRef blob = new(callId, file.Name, file.MediaType, file.Length); + var at = kept.FindIndex(known => string.Equals(known.Name, blob.Name, StringComparison.Ordinal)); + + if (at >= 0) + { + kept[at] = blob; + } + else + { + kept.Add(blob); + } + } - var url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); + List links = []; - links.Add(new SandboxFileLink(blob, url)); + foreach (var blob in kept) + { + var url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); + links.Add(new FileLink(blob, url)); } return links; diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 4fcc09cf..745e65a6 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2208,17 +2208,15 @@ static AgentCore.Application.Blobs.BlobLink.Lifetime.get -> System.TimeSpan static AgentCore.Application.Blobs.BlobLink.DispositionOf(string! mediaType, string! name) -> string! AgentCore.Application.Ports.IBlobStore.LinkAsync(AgentCore.Application.Blobs.BlobRef! blob, System.TimeSpan lifetime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Ports.IBlobStore.StatAsync(string! ownerId, string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Blobs.SandboxFiles -static AgentCore.Application.Blobs.SandboxFiles.NamesIn(System.Collections.Generic.IEnumerable! contents) -> System.Collections.Generic.IReadOnlyList! -AgentCore.Application.Blobs.SandboxFileLink -AgentCore.Application.Blobs.SandboxFileLink.$() -> AgentCore.Application.Blobs.SandboxFileLink! -AgentCore.Application.Blobs.SandboxFileLink.Blob.get -> AgentCore.Application.Blobs.BlobRef! -AgentCore.Application.Blobs.SandboxFileLink.Blob.init -> void -AgentCore.Application.Blobs.SandboxFileLink.Deconstruct(out AgentCore.Application.Blobs.BlobRef! Blob, out System.Uri? Url) -> void -AgentCore.Application.Blobs.SandboxFileLink.Equals(AgentCore.Application.Blobs.SandboxFileLink? other) -> bool -AgentCore.Application.Blobs.SandboxFileLink.SandboxFileLink(AgentCore.Application.Blobs.BlobRef! Blob, System.Uri? Url) -> void -AgentCore.Application.Blobs.SandboxFileLink.Url.get -> System.Uri? -AgentCore.Application.Blobs.SandboxFileLink.Url.init -> void +AgentCore.Application.Blobs.FileLink +AgentCore.Application.Blobs.FileLink.$() -> AgentCore.Application.Blobs.FileLink! +AgentCore.Application.Blobs.FileLink.Blob.get -> AgentCore.Application.Blobs.BlobRef! +AgentCore.Application.Blobs.FileLink.Blob.init -> void +AgentCore.Application.Blobs.FileLink.Deconstruct(out AgentCore.Application.Blobs.BlobRef! Blob, out System.Uri? Url) -> void +AgentCore.Application.Blobs.FileLink.Equals(AgentCore.Application.Blobs.FileLink? other) -> bool +AgentCore.Application.Blobs.FileLink.FileLink(AgentCore.Application.Blobs.BlobRef! Blob, System.Uri? Url) -> void +AgentCore.Application.Blobs.FileLink.Url.get -> System.Uri? +AgentCore.Application.Blobs.FileLink.Url.init -> void AgentCore.Application.Calls.CallRepository AgentCore.Application.Calls.CallRepository.AppendAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Calls.CallSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Calls.CallRepository.AppendMessageAsync(string! callId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask @@ -2232,7 +2230,7 @@ AgentCore.Application.Calls.CallRepository.EraseAsync(string! callId, System.Thr AgentCore.Application.Calls.CallRepository.GetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Calls.CallRepository.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Calls.CallRepository.KeepsFiles.get -> bool -AgentCore.Application.Calls.CallRepository.LinkFilesAsync(string! callId, System.Collections.Generic.IEnumerable! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +AgentCore.Application.Calls.CallRepository.LinkFilesAsync(string! callId, System.Collections.Generic.IEnumerable! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! AgentCore.Application.Calls.CallRepository.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Calls.CallStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Calls.CallRepository.ReadAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Calls.CallRepository.RenameAsync(string! callId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask @@ -2243,28 +2241,23 @@ AgentCore.Application.Calls.CallRepository.SetExternalIdAsync(string! callId, st AgentCore.Application.Calls.CallRepository.SetStatusAsync(string! callId, AgentCore.Application.Calls.CallStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Calls.CallRepository.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Calls.CallRepository.TruncateAsync(string! callId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -override AgentCore.Application.Blobs.SandboxFileLink.Equals(object? obj) -> bool -override AgentCore.Application.Blobs.SandboxFileLink.GetHashCode() -> int -override AgentCore.Application.Blobs.SandboxFileLink.ToString() -> string! -static AgentCore.Application.Blobs.SandboxFileLink.operator ==(AgentCore.Application.Blobs.SandboxFileLink? left, AgentCore.Application.Blobs.SandboxFileLink? right) -> bool -static AgentCore.Application.Blobs.SandboxFileLink.operator !=(AgentCore.Application.Blobs.SandboxFileLink? left, AgentCore.Application.Blobs.SandboxFileLink? right) -> bool +override AgentCore.Application.Blobs.FileLink.Equals(object? obj) -> bool +override AgentCore.Application.Blobs.FileLink.GetHashCode() -> int +override AgentCore.Application.Blobs.FileLink.ToString() -> string! +static AgentCore.Application.Blobs.FileLink.operator ==(AgentCore.Application.Blobs.FileLink? left, AgentCore.Application.Blobs.FileLink? right) -> bool +static AgentCore.Application.Blobs.FileLink.operator !=(AgentCore.Application.Blobs.FileLink? left, AgentCore.Application.Blobs.FileLink? right) -> bool AgentCore.Application.Calls.CallRepository.Store.get -> AgentCore.Application.Ports.ICallStore! -AgentCore.Application.Blobs.SandboxFileFacts -AgentCore.Application.Blobs.SandboxFileFacts.$() -> AgentCore.Application.Blobs.SandboxFileFacts! -AgentCore.Application.Blobs.SandboxFileFacts.Deconstruct(out string! Name, out string! MediaType, out long Length) -> void -AgentCore.Application.Blobs.SandboxFileFacts.Equals(AgentCore.Application.Blobs.SandboxFileFacts? other) -> bool -AgentCore.Application.Blobs.SandboxFileFacts.Length.get -> long -AgentCore.Application.Blobs.SandboxFileFacts.Length.init -> void -AgentCore.Application.Blobs.SandboxFileFacts.MediaType.get -> string! -AgentCore.Application.Blobs.SandboxFileFacts.MediaType.init -> void -AgentCore.Application.Blobs.SandboxFileFacts.Name.get -> string! -AgentCore.Application.Blobs.SandboxFileFacts.Name.init -> void -AgentCore.Application.Blobs.SandboxFileFacts.SandboxFileFacts(string! Name, string! MediaType, long Length) -> void -override AgentCore.Application.Blobs.SandboxFileFacts.Equals(object? obj) -> bool -override AgentCore.Application.Blobs.SandboxFileFacts.GetHashCode() -> int -override AgentCore.Application.Blobs.SandboxFileFacts.ToString() -> string! -static AgentCore.Application.Blobs.SandboxFileFacts.operator ==(AgentCore.Application.Blobs.SandboxFileFacts? left, AgentCore.Application.Blobs.SandboxFileFacts? right) -> bool -static AgentCore.Application.Blobs.SandboxFileFacts.operator !=(AgentCore.Application.Blobs.SandboxFileFacts? left, AgentCore.Application.Blobs.SandboxFileFacts? right) -> bool -static AgentCore.Application.Blobs.SandboxFiles.KeptIn(System.Collections.Generic.IEnumerable! contents) -> System.Collections.Generic.IReadOnlyList! -static AgentCore.Application.Blobs.SandboxFiles.MarkKept(Microsoft.Extensions.AI.HostedFileContent! file, AgentCore.Application.Blobs.BlobRef! blob) -> void -static AgentCore.Application.Blobs.SandboxFiles.MarkRefused(Microsoft.Extensions.AI.HostedFileContent! file) -> void +AgentCore.Application.Transcript.FileContent +AgentCore.Application.Transcript.FileContent.FileId.get -> string! +AgentCore.Application.Transcript.FileContent.FileId.set -> void +AgentCore.Application.Transcript.FileContent.Kept.get -> bool +AgentCore.Application.Transcript.FileContent.Kept.set -> void +AgentCore.Application.Transcript.FileContent.Length.get -> long +AgentCore.Application.Transcript.FileContent.Length.set -> void +AgentCore.Application.Transcript.FileContent.MediaType.get -> string! +AgentCore.Application.Transcript.FileContent.MediaType.set -> void +AgentCore.Application.Transcript.FileContent.Name.get -> string! +AgentCore.Application.Transcript.FileContent.Name.set -> void +AgentCore.Application.Transcript.FileContent.FileContent() -> void +AgentCore.Application.Transcript.FileContent.Scope.get -> string? +AgentCore.Application.Transcript.FileContent.Scope.set -> void diff --git a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs index 0ef54764..bbfffd80 100644 --- a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs @@ -1,5 +1,6 @@ -#pragma warning disable MEAI001 // IHostedFileClient and HostedFileContent.Scope are evaluation-only in Microsoft.Extensions.AI 10.10.0. +#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. +using AgentCore.Application.Transcript; using AgentCore.Application.Blobs; using AgentCore.Application.Diagnostics; using AgentCore.Application.Ports; @@ -11,7 +12,8 @@ namespace AgentCore.Application.Runtime.Harness; /// -/// Copies every file the vendor's sandbox wrote during a run into the call's blob store. +/// Copies every file the vendor's sandbox wrote during a run into the call's blob store, and +/// writes what it kept onto the file's . /// internal sealed class HostedFileCaptureProvider : AIContextProvider { @@ -54,11 +56,11 @@ protected override async ValueTask InvokedCoreAsync(InvokedContext context, Canc { ArgumentNullException.ThrowIfNull(context); - List? found = null; + List? found = null; foreach (var message in context.ResponseMessages ?? []) { - foreach (var file in SandboxFiles.In(message.Contents)) + foreach (var file in message.Contents.OfType()) { (found ??= []).Add(file); } @@ -94,14 +96,14 @@ protected override async ValueTask InvokedCoreAsync(InvokedContext context, Canc : null; } - private async ValueTask KeepAsync(string callId, HostedFileContent file, CancellationToken cancellationToken) + // Kept stays false on every path that does not store the file, so a refusal writes nothing. + private async ValueTask KeepAsync(string callId, FileContent file, CancellationToken cancellationToken) { - var name = SandboxFiles.NameOf(file); + var name = file.Name; if (!BlobName.IsSafe(name)) { Log.SandboxFileRefused(_logger, callId, name, "the name is not a plain file name"); - SandboxFiles.MarkRefused(file); return; } @@ -119,26 +121,27 @@ private async ValueTask KeepAsync(string callId, HostedFileContent file, Cancell if (_policy.WhyRefused(name, buffer.Length) is { } reason) { Log.SandboxFileRefused(_logger, callId, name, reason); - SandboxFiles.MarkRefused(file); return; } buffer.Position = 0; - var mediaType = download.MediaType ?? file.MediaType ?? "application/octet-stream"; + var mediaType = download.MediaType ?? file.MediaType; var kept = await _blobs .PutAsync(new BlobWrite(callId, name, mediaType, buffer, buffer.Length), cancellationToken) .ConfigureAwait(false); - // The reply is committed to the transcript after this provider runs, so the stamp is - // what every later read links from. No read ever asks the store whether the file exists. - SandboxFiles.MarkKept(file, kept); + // The reply is committed to the transcript after this provider runs, so what is written + // here is what every later read links from. No read ever asks the store whether the + // file exists. + file.MediaType = kept.MediaType; + file.Length = kept.Length; + file.Kept = true; } catch (Exception exception) when (exception is not OperationCanceledException) { Log.SandboxFileCaptureFailed(_logger, callId, name, exception); - SandboxFiles.MarkRefused(file); } } diff --git a/src/AgentCore.Application/Transcript/FileContent.cs b/src/AgentCore.Application/Transcript/FileContent.cs new file mode 100644 index 00000000..49a2ab4d --- /dev/null +++ b/src/AgentCore.Application/Transcript/FileContent.cs @@ -0,0 +1,31 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Transcript; + +/// +/// A file the reply produced, carried by the message that produced it. This is the only shape a +/// reader sees: where the file came from, and how the vendor reported it, is AgentCore's business. +/// +public sealed class FileContent : AIContent +{ + /// The name the model gave the file. It is the name the store keeps it under. + public required string Name { get; set; } + + /// The vendor's id for the file. What the capture downloads by. + public required string FileId { get; set; } + + /// The vendor's container the file sits in, or when the vendor has none. + public string? Scope { get; set; } + + /// The IANA media type. The vendor's guess until the capture keeps the file, then the store's. + public string MediaType { get; set; } = "application/octet-stream"; + + /// How many bytes the store holds. Zero until the capture keeps the file. + public long Length { get; set; } + + /// + /// Whether the store holds the file. until the capture keeps it, and + /// for good when the policy refused it, the download failed, or no capture ran at all. + /// + public bool Kept { get; set; } +} diff --git a/src/AgentCore.Application/Transcript/TranscriptJson.cs b/src/AgentCore.Application/Transcript/TranscriptJson.cs index 4aa45107..8d4abf6c 100644 --- a/src/AgentCore.Application/Transcript/TranscriptJson.cs +++ b/src/AgentCore.Application/Transcript/TranscriptJson.cs @@ -23,6 +23,7 @@ private static JsonSerializerOptions Build() options.AddAIContentType(RenderContentTypeId); options.AddAIContentType(SourceContentTypeId); + options.AddAIContentType(FileContentTypeId); options.MakeReadOnly(); return options; @@ -33,4 +34,7 @@ private static JsonSerializerOptions Build() /// The discriminator a stored SourceContent is written with. It is a wire format. private const string SourceContentTypeId = "agentcore.source"; + + /// The discriminator a stored FileContent is written with. It is a wire format. + private const string FileContentTypeId = "agentcore.file"; } diff --git a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs index c36c0878..8543b353 100644 --- a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs @@ -1,5 +1,4 @@ -#pragma warning disable MEAI001 // HostedFileContent is evaluation-only in Microsoft.Extensions.AI 10.10.0. - +using AgentCore.Application.Transcript; using System.Runtime.CompilerServices; using AgentCore.Application.Calls; using Microsoft.Extensions.AI; @@ -9,21 +8,15 @@ namespace AgentCore.AspNetCore.Endpoints; /// /// The sandbox files one turn surfaced, linked for the browser once the turn is over. /// -/// -/// A file reference arrives mid-stream, but its bytes reach the store only after the run, when -/// the capture provider has downloaded them. A link handed out earlier would answer 404. So the -/// references are noted as they pass and linked after the last update, against what the store -/// holds: a file the policy refused, or the download lost, is simply not there and gets no part. -/// internal sealed class TurnStreamFiles { - private readonly List _references = []; + private readonly List _files = []; - /// Notes every sandbox file reference one update carries. + /// Notes every sandbox file one update carries. /// One update of the stream. internal void Note(ChatResponseUpdate update) { - _references.AddRange(update.Contents.Where(content => content is HostedFileContent or CodeInterpreterToolResultContent)); + _files.AddRange(update.Contents.OfType()); } /// Links every noted file the store kept, in the order they were noted. @@ -36,13 +29,13 @@ internal async IAsyncEnumerable ResolveAsync( string callId, [EnumeratorCancellation] CancellationToken cancellationToken) { - if (_references.Count == 0) + if (_files.Count == 0) { yield break; } var links = await calls - .LinkFilesAsync(callId, [new ChatMessage(ChatRole.Assistant, _references)], cancellationToken) + .LinkFilesAsync(callId, [new ChatMessage(ChatRole.Assistant, _files)], cancellationToken) .ConfigureAwait(false); foreach (var (blob, url) in links) diff --git a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs index 6d33f38c..a11c7e0b 100644 --- a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs +++ b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs @@ -1,6 +1,7 @@ #pragma warning disable OPENAI001 -#pragma warning disable MEAI001 // IHostedFileClient and HostedFileContent.Scope are evaluation-only in Microsoft.Extensions.AI 10.10.0. +#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. +using AgentCore.Application.Transcript; using System.Runtime.CompilerServices; using Microsoft.Extensions.AI; using OpenAI; @@ -9,7 +10,9 @@ namespace AgentCore.Infrastructure.Llm.OpenAI; /// -/// Makes a file the OpenAI sandbox wrote look the way Microsoft.Extensions.AI says it should. +/// Surfaces every file the OpenAI sandbox wrote as one flat on the +/// reply. OpenAI reports a file only as a citation on the text, and Microsoft.Extensions.AI keeps it +/// there, so this is the one place that knows the vendor's shape. /// internal sealed class OpenAiSandboxFilesClient : DelegatingChatClient { @@ -56,10 +59,10 @@ public override async IAsyncEnumerable GetStreamingResponseA } } - /// Appends one for every container-file citation in the list. + /// Appends one for every container-file citation in the list. private static void Surface(IList contents) { - List? found = null; + List? found = null; foreach (var content in contents) { @@ -72,7 +75,12 @@ private static void Surface(IList contents) { if (annotation.RawRepresentation is ContainerFileCitationMessageAnnotation raw) { - (found ??= []).Add(new HostedFileContent(raw.FileId) { Scope = raw.ContainerId, Name = raw.Filename }); + (found ??= []).Add(new FileContent + { + Name = raw.Filename ?? raw.FileId, + FileId = raw.FileId, + Scope = raw.ContainerId, + }); } } } diff --git a/tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs b/tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs deleted file mode 100644 index 2b2d6b1d..00000000 --- a/tests/AgentCore.Application.Tests/Blobs/SandboxFilesTests.cs +++ /dev/null @@ -1,122 +0,0 @@ -#pragma warning disable MEAI001 - -using System.Text.Json; -using AgentCore.Application.Blobs; -using AgentCore.Application.Transcript; -using Microsoft.Extensions.AI; -using Xunit; - -namespace AgentCore.Application.Tests.Blobs; - -/// Which names a message's sandbox file references resolve to. -public sealed class SandboxFilesTests -{ - [Fact] - public void NamesIn_FileOnTheMessageAndInsideAnInterpreterResult_ReturnsBothInOrder() - { - // Arrange - AIContent[] contents = - [ - new TextContent("see the chart"), - new HostedFileContent("cfile_1") { Name = "chart.png" }, - new CodeInterpreterToolResultContent("call_ci") { Outputs = [new HostedFileContent("cfile_2") { Name = "rows.csv" }] }, - ]; - - // Act - var names = SandboxFiles.NamesIn(contents); - - // Assert - Assert.Equal(["chart.png", "rows.csv"], names); - } - - [Fact] - public void NamesIn_SameFileTwice_ReturnsItOnce() - { - // Arrange - AIContent[] contents = - [ - new HostedFileContent("cfile_1") { Name = "chart.png" }, - new HostedFileContent("cfile_1") { Name = "chart.png" }, - ]; - - // Act - var names = SandboxFiles.NamesIn(contents); - - // Assert - Assert.Equal(["chart.png"], names); - } - - [Fact] - public void NamesIn_NoName_FallsBackToTheVendorId() - { - // Act - var names = SandboxFiles.NamesIn([new HostedFileContent("cfile_abc")]); - - // Assert - Assert.Equal(["cfile_abc"], names); - } - - [Fact] - public void KeptIn_StampSurvivesTheTranscriptEncoder() - { - // Arrange: stamp a fresh reference, store the message, read it back. - HostedFileContent reference = new("cfile_1") { Name = "chart.png" }; - SandboxFiles.MarkKept(reference, new BlobRef("call-1", "chart.png", "image/png", 48213)); - ChatMessage reply = new(ChatRole.Assistant, [new TextContent("see"), reference]); - - var json = JsonSerializer.Serialize(reply, TranscriptJson.Options); - var restored = JsonSerializer.Deserialize(json, TranscriptJson.Options)!; - - // Act - var facts = SandboxFiles.KeptIn(restored.Contents); - - // Assert - Assert.Equal([new SandboxFileFacts("chart.png", "image/png", 48213)], facts); - } - - [Fact] - public void KeptIn_UnstampedOrRefusedReference_IsNotKept() - { - // Arrange - HostedFileContent unstamped = new("cfile_1") { Name = "chart.png", MediaType = "image/png" }; - HostedFileContent refused = new("cfile_2") { Name = "big.png" }; - SandboxFiles.MarkRefused(refused); - - // Act - var facts = SandboxFiles.KeptIn([unstamped, refused]); - - // Assert - Assert.Empty(facts); - } - - [Fact] - public void KeptIn_SameNameStampedTwice_TheLaterFactsWinInTheFirstPlace() - { - // Arrange: the model redrew chart.png after rows.csv; the store replaced the first. - HostedFileContent first = new("cfile_1") { Name = "chart.png" }; - HostedFileContent rows = new("cfile_2") { Name = "rows.csv" }; - HostedFileContent second = new("cfile_3") { Name = "chart.png" }; - SandboxFiles.MarkKept(first, new BlobRef("call-1", "chart.png", "image/png", 10)); - SandboxFiles.MarkKept(rows, new BlobRef("call-1", "rows.csv", "text/csv", 5)); - SandboxFiles.MarkKept(second, new BlobRef("call-1", "chart.png", "image/png", 20)); - - // Act - var facts = SandboxFiles.KeptIn([first, rows, second]); - - // Assert - Assert.Equal([new SandboxFileFacts("chart.png", "image/png", 20), new SandboxFileFacts("rows.csv", "text/csv", 5)], facts); - } - - [Theory] - [InlineData("../etc/passwd")] - [InlineData("a/b.png")] - [InlineData("")] - public void NamesIn_UnsafeName_IsDropped(string name) - { - // Act - var names = SandboxFiles.NamesIn([new HostedFileContent("cfile_1") { Name = name }]); - - // Assert - Assert.Empty(names); - } -} diff --git a/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs b/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs index a0f3bf78..bb147a2a 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs @@ -1,5 +1,4 @@ -#pragma warning disable MEAI001 - +using AgentCore.Application.Transcript; using AgentCore.Application.Blobs; using AgentCore.Application.Calls; using AgentCore.Application.Calls.Memory; @@ -13,23 +12,15 @@ namespace AgentCore.Application.Tests.Calls; /// The one door to a stored call: its row, its words, and its files go together. public sealed class CallRepositoryTests { - /// A reply whose references the capture stamped as kept, 3 bytes each. + /// A reply whose files the capture kept, 3 bytes each. private static ChatMessage ReplyWith(params (string Name, string MediaType)[] kept) => new(ChatRole.Assistant, [new TextContent("see"), .. kept.Select(file => Kept(file.Name, file.MediaType))]); - private static HostedFileContent Kept(string name, string mediaType) - { - HostedFileContent reference = new("cfile_" + name) { Name = name }; - SandboxFiles.MarkKept(reference, new BlobRef("call-1", name, mediaType, 3)); - return reference; - } + private static FileContent Kept(string name, string mediaType, long length = 3) + => new() { Name = name, FileId = "cfile_" + name, MediaType = mediaType, Length = length, Kept = true }; - private static HostedFileContent Refused(string name) - { - HostedFileContent reference = new("cfile_" + name) { Name = name }; - SandboxFiles.MarkRefused(reference); - return reference; - } + private static FileContent Refused(string name) + => new() { Name = name, FileId = "cfile_" + name }; private static async Task KeepAsync(RecordingBlobStore blobs, string callId, string name, string mediaType) => await blobs.PutAsync(new BlobWrite(callId, name, mediaType, new MemoryStream([1, 2, 3]), 3), TestContext.Current.CancellationToken); @@ -72,9 +63,9 @@ public async Task DeleteAsync_NoBlobStore_DeletesTheRowAlone() } [Fact] - public async Task LinkFilesAsync_LinksFromTheStamp_EachOnce_InFirstSeenOrder_WithoutAskingTheStore() + public async Task LinkFilesAsync_LinksFromTheContent_EachOnce_InFirstSeenOrder_WithoutAskingTheStore() { - // Arrange: the store is empty on purpose. The stamp is the index. + // Arrange: the store is empty on purpose. The content is the index. CountingBlobStore blobs = new(); CallRepository calls = new(new InMemoryCallStore(), blobs); @@ -113,17 +104,35 @@ public async Task LinkFilesAsync_NoBlobStore_LinksNothing() } [Fact] - public async Task LinkFilesAsync_FileInsideAnInterpreterResult_IsFound() + public async Task LinkFilesAsync_SameNameKeptTwice_TheLaterFactsWinInTheFirstPlace() { - // Arrange + // Arrange: the model redrew chart.png after rows.csv; the store replaced the first. CallRepository calls = new(new InMemoryCallStore(), new RecordingBlobStore()); - ChatMessage reply = new(ChatRole.Assistant, [new CodeInterpreterToolResultContent("ci_1") { Outputs = [Kept("chart.png", "image/png")] }]); + ChatMessage reply = new(ChatRole.Assistant, [Kept("chart.png", "image/png", 10), Kept("rows.csv", "text/csv", 5), Kept("chart.png", "image/png", 20)]); // Act var links = await calls.LinkFilesAsync("call-1", [reply], TestContext.Current.CancellationToken); // Assert - Assert.Equal("chart.png", Assert.Single(links).Blob.Name); + Assert.Equal( + [new BlobRef("call-1", "chart.png", "image/png", 20), new BlobRef("call-1", "rows.csv", "text/csv", 5)], + links.Select(link => link.Blob)); + } + + [Theory] + [InlineData("../etc/passwd")] + [InlineData("a/b.png")] + [InlineData("")] + public async Task LinkFilesAsync_UnsafeName_IsNotLinked(string name) + { + // Arrange + CallRepository calls = new(new InMemoryCallStore(), new RecordingBlobStore()); + + // Act + var links = await calls.LinkFilesAsync("call-1", [new ChatMessage(ChatRole.Assistant, [Kept(name, "image/png")])], TestContext.Current.CancellationToken); + + // Assert + Assert.Empty(links); } /// Links like the recording store, and counts how often anyone asks it whether a blob exists. diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs index 900165d2..48e4ad1a 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs @@ -1,6 +1,6 @@ -#pragma warning disable MEAI001 // HostedFileContent.Scope is evaluation-only in Microsoft.Extensions.AI 10.10.0. #pragma warning disable MAAI001 // The context constructors are evaluation-only in Microsoft.Agents.AI 1.21.0. +using AgentCore.Application.Transcript; using AgentCore.Application.Blobs; using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Harness; @@ -14,7 +14,8 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// -/// After a run: every sandbox file the vendor surfaced is downloaded and stored under the call. +/// After a run: every sandbox file the vendor surfaced is downloaded and stored under the call, and +/// the content it rode in on says what was kept. /// public sealed class HostedFileCaptureProviderTests { @@ -27,7 +28,7 @@ public async Task InvokedAsync_FileOnTheMessage_StoresItUnderTheCallAndTheName() var files = new ScriptedHostedFileClient().Serve("cfile_1", Png, "image/png"); RecordingBlobStore blobs = new(); var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(new HostedFileContent("cfile_1") { Scope = "cntr_1", Name = "chart.png" }); + var response = Reply(File("cfile_1", "chart.png", "cntr_1")); // Act await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); @@ -41,55 +42,37 @@ public async Task InvokedAsync_FileOnTheMessage_StoresItUnderTheCallAndTheName() } [Fact] - public async Task InvokedAsync_FileKept_StampsTheReferenceWithWhatWasStored() + public async Task InvokedAsync_FileKept_WritesWhatWasStoredOntoTheContent() { - // Arrange: the vendor's reference names no media type; the download does. + // Arrange: the vendor names no media type; the download does. var files = new ScriptedHostedFileClient().Serve("cfile_1", Png, "image/png"); RecordingBlobStore blobs = new(); var (agent, session) = await AgentWithFiledTurn("call-7"); - HostedFileContent reference = new("cfile_1") { Name = "chart.png" }; + var file = File("cfile_1", "chart.png"); // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(reference)), TestContext.Current.CancellationToken); + await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(file)), TestContext.Current.CancellationToken); - // Assert: a later read links from the stamp alone. - var facts = Assert.Single(SandboxFiles.KeptIn([reference])); - Assert.Equal(new SandboxFileFacts("chart.png", "image/png", Png.Length), facts); + // Assert: a later read links from the content alone. + Assert.True(file.Kept); + Assert.Equal("image/png", file.MediaType); + Assert.Equal(Png.Length, file.Length); } [Fact] - public async Task InvokedAsync_FileRefused_StampsTheReferenceAsNotKept() + public async Task InvokedAsync_FileRefused_LeavesTheContentNotKept() { // Arrange: a 100-byte cap, a 300-byte file. var files = new ScriptedHostedFileClient().Serve("cfile_6", new byte[300], "image/png"); var (agent, session) = await AgentWithFiledTurn("call-7"); - HostedFileContent reference = new("cfile_6") { Name = "big.png" }; + var file = File("cfile_6", "big.png"); var provider = new HostedFileCaptureProvider(files, new RecordingBlobStore(), new BlobPolicy(100, ["png"]), NullLogger.Instance); // Act - await provider.InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(reference)), TestContext.Current.CancellationToken); + await provider.InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(file)), TestContext.Current.CancellationToken); // Assert - Assert.Empty(SandboxFiles.KeptIn([reference])); - } - - [Fact] - public async Task InvokedAsync_FileInsideAnInterpreterResult_IsStoredToo() - { - // Arrange - var files = new ScriptedHostedFileClient().Serve("cfile_2", Png, "image/png"); - RecordingBlobStore blobs = new(); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(new CodeInterpreterToolResultContent("call_x") - { - Outputs = [new HostedFileContent("cfile_2") { Name = "plot.png" }], - }); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - Assert.True(blobs.Blobs.ContainsKey(("call-7", "plot.png"))); + Assert.False(file.Kept); } [Fact] @@ -101,7 +84,7 @@ public async Task InvokedAsync_ChildSessionWithTheOwnerStamp_StoresUnderThatCall var agent = Agent(); var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); session.StateBag.SetValue(BlobOwnerKey.Value, "call-child"); - var response = Reply(new HostedFileContent("cfile_3") { Name = "rows.csv" }); + var response = Reply(File("cfile_3", "rows.csv")); // Act await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); @@ -118,7 +101,7 @@ public async Task InvokedAsync_NoOwnerAtAll_StoresNothingAndDoesNotThrow() RecordingBlobStore blobs = new(); var agent = Agent(); var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - var response = Reply(new HostedFileContent("cfile_4") { Name = "chart.png" }); + var response = Reply(File("cfile_4", "chart.png")); // Act await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); @@ -136,7 +119,7 @@ public async Task InvokedAsync_UnsafeNameOrDisallowedExtension_IsRefusedNotStore var files = new ScriptedHostedFileClient().Serve("cfile_5", Png, "image/png"); RecordingBlobStore blobs = new(); var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(new HostedFileContent("cfile_5") { Name = name }); + var response = Reply(File("cfile_5", name)); // Act await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); @@ -152,7 +135,7 @@ public async Task InvokedAsync_FileOverTheCap_IsRefusedWithoutBufferingAllOfIt() var files = new ScriptedHostedFileClient().Serve("cfile_6", new byte[300], "image/png"); RecordingBlobStore blobs = new(); var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(new HostedFileContent("cfile_6") { Name = "big.png" }); + var response = Reply(File("cfile_6", "big.png")); var provider = new HostedFileCaptureProvider(files, blobs, new BlobPolicy(100, ["png"]), NullLogger.Instance); // Act @@ -169,7 +152,7 @@ public async Task InvokedAsync_DownloadThrows_StoresNothingAndDoesNotThrow() ScriptedHostedFileClient files = new(); RecordingBlobStore blobs = new(); var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(new HostedFileContent("cfile_missing") { Name = "chart.png" }); + var response = Reply(File("cfile_missing", "chart.png")); // Act await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); @@ -207,6 +190,9 @@ private static HostedFileCaptureProvider Provider(ScriptedHostedFileClient files return (agent, session); } + private static FileContent File(string fileId, string name, string? scope = null) + => new() { Name = name, FileId = fileId, Scope = scope }; + private static List Reply(params AIContent[] contents) => [new ChatMessage(ChatRole.Assistant, [new TextContent("see sandbox:/mnt/data/x"), .. contents])]; } diff --git a/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs b/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs new file mode 100644 index 00000000..392e2de7 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using AgentCore.Application.Blobs; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Transcript; + +/// A kept file survives the trip through the transcript store. +public sealed class FileContentTests +{ + [Fact] + public void Kept_SurvivesTheTranscriptEncoder() + { + // Arrange: what the capture wrote, stored, read back. + FileContent file = new() + { + Name = "chart.png", + FileId = "cfile_1", + Scope = "cntr_1", + MediaType = "image/png", + Length = 48213, + Kept = true, + }; + ChatMessage reply = new(ChatRole.Assistant, [new TextContent("see"), file]); + + // Act + var json = JsonSerializer.Serialize(reply, TranscriptJson.Options); + var restored = JsonSerializer.Deserialize(json, TranscriptJson.Options)!; + + // Assert + var read = Assert.Single(restored.Contents.OfType()); + Assert.Equal(("chart.png", "cfile_1", "cntr_1", "image/png", 48213L, true), (read.Name, read.FileId, read.Scope, read.MediaType, read.Length, read.Kept)); + Assert.Contains("\"agentcore.file\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs index 8c2eb171..ce6c3ba4 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs @@ -1,5 +1,4 @@ -#pragma warning disable MEAI001 - +using AgentCore.Application.Transcript; using AgentCore.Application.Blobs; using AgentCore.Application.Calls; using AgentCore.Application.Calls.Memory; @@ -16,23 +15,18 @@ public sealed class TurnStreamFilesTests private static ChatResponseUpdate UpdateWith(params AIContent[] contents) => new(ChatRole.Assistant, contents); - /// A reference the capture provider stamped as kept, as it does before the stream ends. - private static HostedFileContent Kept(string name, string mediaType, long length) - { - HostedFileContent reference = new("cfile_" + name) { Name = name }; - SandboxFiles.MarkKept(reference, new BlobRef("call-1", name, mediaType, length)); - return reference; - } + /// A file the capture provider kept, as it writes onto the content before the stream ends. + private static FileContent Kept(string name, string mediaType, long length) + => new() { Name = name, FileId = "cfile_" + name, MediaType = mediaType, Length = length, Kept = true }; [Fact] public async Task ResolveAsync_NotedFileTheCaptureKept_YieldsOnePartWithTheLink() { - // Arrange: the same reference passes twice, as a re-yielded update would; a refused one passes too. + // Arrange: the same content passes twice, as a re-yielded update would; a refused one passes too. CallRepository calls = new(new InMemoryCallStore(), new StubBlobStore()); TurnStreamFiles files = new(); var chart = Kept("chart.png", "image/png", 48213); - HostedFileContent refused = new("cfile_2") { Name = "refused.png" }; - SandboxFiles.MarkRefused(refused); + FileContent refused = new() { Name = "refused.png", FileId = "cfile_2" }; files.Note(UpdateWith(new TextContent("see"), chart)); files.Note(UpdateWith(chart)); files.Note(UpdateWith(refused)); @@ -87,7 +81,7 @@ public ValueTask PutAsync(BlobWrite write, CancellationToken cancellati => throw new NotSupportedException(); public ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default) - => throw new NotSupportedException("The read path links from the stamp and never asks the store."); + => throw new NotSupportedException("The read path links from the content and never asks the store."); public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) => ValueTask.FromResult(Links ? new Uri($"https://blobs.test/{blob.OwnerId}/{blob.Name}?ttl={(int)lifetime.TotalSeconds}") : null); diff --git a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs index a7ccd98d..a73d9e04 100644 --- a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs @@ -1,9 +1,11 @@ #pragma warning disable OPENAI001 -#pragma warning disable MEAI001 // IHostedFileClient and HostedFileContent.Scope are evaluation-only in Microsoft.Extensions.AI 10.10.0. +#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. +using AgentCore.Application.Transcript; using System.ClientModel; using System.ClientModel.Primitives; using System.Runtime.CompilerServices; +using AgentCore.Application.Blobs; using AgentCore.Infrastructure.Llm.OpenAI; using Microsoft.Extensions.AI; using OpenAI; @@ -13,7 +15,7 @@ namespace AgentCore.Infrastructure.Tests.Llm; /// -/// The vendor middleware that turns a container_file_citation into a . +/// The vendor middleware that turns a container_file_citation into a . /// /// /// The wire shape is the OpenAI API reference's container_file_citation object. The @@ -36,7 +38,7 @@ public sealed class OpenAiSandboxFilesClientTests private static readonly OpenAIClient OpenAi = new(new ApiKeyCredential("sk-test")); [Fact] - public async Task GetResponseAsync_ContainerFileCitation_AddsOneHostedFileContent() + public async Task GetResponseAsync_ContainerFileCitation_AddsOneFileContent() { // Arrange var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [CitedText()]))); @@ -46,10 +48,11 @@ public async Task GetResponseAsync_ContainerFileCitation_AddsOneHostedFileConten var response = await client.GetResponseAsync("draw", cancellationToken: TestContext.Current.CancellationToken); // Assert - var file = Assert.Single(response.Messages[0].Contents.OfType()); + var file = Assert.Single(response.Messages[0].Contents.OfType()); Assert.Equal("cfile_68c8f1a2b3c4d5e6f7a8b9c1", file.FileId); Assert.Equal("cntr_68c8f1a2b3c4d5e6f7a8b9c0", file.Scope); Assert.Equal("chart.png", file.Name); + Assert.False(file.Kept); Assert.Equal("Here is your chart: [Download](sandbox:/mnt/data/chart.png)", response.Text); } @@ -61,10 +64,10 @@ public async Task GetStreamingResponseAsync_ContainerFileCitation_AddsItToThatUp using var client = new OpenAiSandboxFilesClient(inner, OpenAi); // Act - var files = new List(); + var files = new List(); await foreach (var update in client.GetStreamingResponseAsync("draw", cancellationToken: TestContext.Current.CancellationToken)) { - files.AddRange(update.Contents.OfType()); + files.AddRange(update.Contents.OfType()); } // Assert @@ -86,7 +89,7 @@ public async Task GetResponseAsync_CitationWithoutTheRawObject_AddsNothing() var response = await client.GetResponseAsync("cite", cancellationToken: TestContext.Current.CancellationToken); // Assert - Assert.Empty(response.Messages[0].Contents.OfType()); + Assert.Empty(response.Messages[0].Contents.OfType()); } [Fact] From 139a3f58773d42b87b8ebf86bebf6779e2149b19 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 15:51:00 -0600 Subject: [PATCH 09/35] refactor: break out configuration validator --- .../Validation/AmbiguityCheck.cs | 94 ++ .../Validation/ConfigurationValidator.cs | 1337 +---------------- .../Configuration/Validation/DeclaredNames.cs | 39 + .../Validation/DelegationCycleCheck.cs | 108 ++ .../Validation/EntryShapeCheck.cs | 84 ++ .../Validation/ExitExclusivityCheck.cs | 110 ++ .../Configuration/Validation/GraphReach.cs | 51 + .../Validation/GraphWellFormednessCheck.cs | 74 + .../Validation/GuardRuleCheck.cs | 97 ++ .../Validation/KnowledgeScopeCheck.cs | 149 ++ .../Configuration/Validation/McpCheck.cs | 71 + .../Validation/ReachabilityCheck.cs | 76 + .../Validation/ReferenceCheck.cs | 174 +++ .../Validation/ServedReferenceCheck.cs | 105 ++ .../Validation/SlotWriterCheck.cs | 74 + .../Validation/ValidationErrors.cs | 70 + .../Validation/ValidationPointer.cs | 56 + 17 files changed, 1462 insertions(+), 1307 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Validation/AmbiguityCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/DeclaredNames.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/EntryShapeCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/GraphReach.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/GraphWellFormednessCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/GuardRuleCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/McpCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/ReachabilityCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/ReferenceCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/SlotWriterCheck.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/ValidationPointer.cs diff --git a/src/AgentCore.Application/Configuration/Validation/AmbiguityCheck.cs b/src/AgentCore.Application/Configuration/Validation/AmbiguityCheck.cs new file mode 100644 index 00000000..383fd3be --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/AmbiguityCheck.cs @@ -0,0 +1,94 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 2, ambiguity: section 10 of the ambiguity design. +internal static class AmbiguityCheck +{ + /// Refuses an ambiguity: block that could not do what it declares. + public static void Run(AgentCoreConfiguration configuration, List errors, List warnings) + { + var knowledge = configuration.Providers?.Knowledge; + + if (knowledge?.Ambiguity is not { } ambiguity) + { + return; + } + + if (knowledge.Mapper is not null) + { + errors.Add(Reference( + ValidationPointer.Mapper, + "providers.knowledge.ambiguity is declared, and providers.knowledge.mapper names a " + + "custom mapper. The probe reads each card's facet values out of Extras, which only " + + "the built-in field mapper fills, so every probe would find no values and the " + + "channel would stay silent.")); + } + + if (knowledge.Scope.Wildcard is null) + { + errors.Add(Reference( + ValidationPointer.Ambiguity, + "providers.knowledge.ambiguity is declared and providers.knowledge.scope.wildcard is " + + "absent. The probe drops a facet the wildcard filled, so with no wildcard it has " + + "nothing to drop and the channel can never fire.")); + } + + CheckRanges(ambiguity, errors); + + // A probe drops one of the scope's own facets, so it needs a second one left to search by. + // Zero is as unreachable as one, and reaches this line whenever the host supplies every facet. + if ((knowledge.Scope.FromState ?? []).Count <= 1) + { + warnings.Add(Reference( + ValidationPointer.Ambiguity, + "providers.knowledge.ambiguity is declared and scope.fromState names at most one " + + "facet. That deployment has no droppable facet other than its only one, so the probe " + + "is unreachable unless the host sets one too.")); + } + } + + private static void CheckRanges(KnowledgeAmbiguityConfiguration ambiguity, List errors) + { + CheckRange( + ambiguity.MaxCandidates, + 2, + int.MaxValue, + ConfigurationError.AppendPointer(ValidationPointer.Ambiguity, "maxCandidates"), + "ambiguity.maxCandidates", + "Below 2, the ask could never name a spread of candidates.", + errors); + + CheckRange( + ambiguity.MaxAsks, + 0, + int.MaxValue, + ConfigurationError.AppendPointer(ValidationPointer.Ambiguity, "maxAsks"), + "ambiguity.maxAsks", + "0 is legal and means gate only; a negative count is not.", + errors); + + CheckRange( + ambiguity.ProbeDeadlineSeconds, + 1, + MaxIntervalSeconds, + ConfigurationError.AppendPointer(ValidationPointer.Ambiguity, "probeDeadlineSeconds"), + "ambiguity.probeDeadlineSeconds", + "A budget below one second leaves the probe unable to complete even the fastest real " + + "search, and one above the range throws out of the CancelAfter that arms it.", + errors); + + CheckRange( + ambiguity.ProbeWaitMarginSeconds, + 1, + MaxIntervalSeconds, + ConfigurationError.AppendPointer(ValidationPointer.Ambiguity, "probeWaitMarginSeconds"), + "ambiguity.probeWaitMarginSeconds", + "A margin of 0 reinstates the race it exists to close: the loser's wait would end as the " + + "winner's own search does, leaving a margin equal to the arrival spread. Above the " + + "range, the deadline this is added to no longer fits the wait it arms.", + errors); + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index f3f76733..043a139e 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -1,30 +1,14 @@ -using System.Globalization; -using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; -using Microsoft.Agents.AI; namespace AgentCore.Application.Configuration.Validation; /// -/// Checks 2 to 8 of section 8.5, over one bound document. +/// Checks 2 to 8 of section 8.5, over one bound document. Each check lives in its own +/// *Check class in this folder; this type only orders them and shapes the result. /// public static class ConfigurationValidator { - /// - /// The longest interval, in seconds, that every timer these values reach will accept. - /// CancellationTokenSource.CancelAfter, Task.WaitAsync and PeriodicTimer each - /// throw above milliseconds, from a call site that carries no pointer - /// into the document. - /// - private const int MaxIntervalSeconds = int.MaxValue / 1000; - - /// The increment: field of a counter slot. Named once, so the check below and the two maps under it cannot drift apart. - private const string IncrementField = "increment"; - - /// The agent: field an entry, tool, stage, or node points at. - private const string AgentField = "agent"; - /// Runs checks 2 to 8 and returns everything they find. /// The bound document. /// Every error and every partial-coverage warning. @@ -35,7 +19,7 @@ public static ConfigurationValidationResult Evaluate(AgentCoreConfiguration conf var declaredToolIds = configuration.Tools.Select(static tool => tool.Id).ToHashSet(StringComparer.Ordinal); var toolErrors = new List(); - CheckToolReferences(configuration, declaredToolIds, toolErrors); + ServedReferenceCheck.Tools(configuration, declaredToolIds, toolErrors); if (toolErrors.Count == 0) { @@ -54,15 +38,7 @@ public static ConfigurationValidationResult Evaluate(AgentCoreConfiguration conf /// The result, so a caller can read the partial-coverage warnings of check 5. /// The document fails one or more checks. public static ConfigurationValidationResult Validate(AgentCoreConfiguration configuration) - { - var result = Evaluate(configuration); - if (result.Errors.Count > 0) - { - throw new ConfigurationLoadException(result.Errors); - } - - return result; - } + => ThrowOnErrors(Evaluate(configuration)); /// /// Runs every check of section 8.5 except tool-reference resolution, and returns everything they @@ -77,19 +53,20 @@ public static ConfigurationValidationResult EvaluateStructure(AgentCoreConfigura var errors = new List(); var warnings = new List(); var names = DeclaredNames.From(configuration); - CheckEntryShapes(configuration, names, errors); - CheckReferences(configuration, names, errors); + + EntryShapeCheck.Run(configuration, names, errors); + ReferenceCheck.Run(configuration, names, errors); ReasoningTemperatureCheck.Run(configuration, errors); - CheckSlotWriters(configuration, errors); - CheckKnowledgeScopeSlots(configuration, errors); - CheckAmbiguity(configuration, errors, warnings); - CheckGuardRules(configuration, errors); - CheckExclusivity(configuration, errors, warnings); - CheckReachability(configuration, errors); - CheckGraphWellFormedness(configuration, errors); - CheckDelegationCycles(configuration, errors); - CheckMcpServerIds(configuration, errors); - CheckMcpSecretPlacement(configuration, errors); + SlotWriterCheck.Run(configuration, errors); + KnowledgeScopeCheck.Run(configuration, errors); + AmbiguityCheck.Run(configuration, errors, warnings); + GuardRuleCheck.Run(configuration, errors); + ExitExclusivityCheck.Run(configuration, errors, warnings); + ReachabilityCheck.Run(configuration, errors); + GraphWellFormednessCheck.Run(configuration, errors); + DelegationCycleCheck.Run(configuration, errors); + McpCheck.ServerIds(configuration, errors); + McpCheck.SecretPlacement(configuration, errors); if (errors.Count == 0 && warnings.Count == 0) { @@ -111,15 +88,7 @@ public static ConfigurationValidationResult EvaluateStructure(AgentCoreConfigura /// The result, so a caller can read the partial-coverage warnings of check 5. /// The document fails one or more checks. public static ConfigurationValidationResult ValidateStructure(AgentCoreConfiguration configuration) - { - var result = EvaluateStructure(configuration); - if (result.Errors.Count > 0) - { - throw new ConfigurationLoadException(result.Errors); - } - - return result; - } + => ThrowOnErrors(EvaluateStructure(configuration)); /// /// Resolves every tool reference in the document against the ids the tool registry actually @@ -134,12 +103,8 @@ public static void ValidateToolReferences(AgentCoreConfiguration configuration, ArgumentNullException.ThrowIfNull(servedToolIds); var errors = new List(); - CheckToolReferences(configuration, servedToolIds, errors); - - if (errors.Count > 0) - { - throw new ConfigurationLoadException(errors); - } + ServedReferenceCheck.Tools(configuration, servedToolIds, errors); + ThrowOnErrors(errors); } /// @@ -155,12 +120,8 @@ public static void ValidateSkillReferences(AgentCoreConfiguration configuration, ArgumentNullException.ThrowIfNull(servedSkillNames); var errors = new List(); - CheckSkillReferences(configuration, servedSkillNames, errors); - - if (errors.Count > 0) - { - throw new ConfigurationLoadException(errors); - } + ServedReferenceCheck.Skills(configuration, servedSkillNames, errors); + ThrowOnErrors(errors); } /// @@ -175,1259 +136,21 @@ public static void ValidateSkillToolNames(AgentCoreConfiguration configuration) ArgumentNullException.ThrowIfNull(configuration); var errors = new List(); - CheckSkillToolNames(configuration, errors); - - if (errors.Count > 0) - { - throw new ConfigurationLoadException(errors); - } - } - - // --------------------------------------------------------------------------------------------- - // Check 2, entry shapes: each entry holds exactly one of agent:/policy:/graph:. - // --------------------------------------------------------------------------------------------- - private static void CheckEntryShapes(AgentCoreConfiguration configuration, DeclaredNames names, List errors) - { - if (configuration.Agents.Items.Count == 0) - { - errors.Add(Reference( - "/agents/items", - "the document declares no agents:, so no entry can resolve an agent.")); - } - - if (configuration.Entries.Count == 0) - { - errors.Add(Reference( - "/entries", - "the document declares no entries:, so it compiles to nothing.")); - return; - } - - foreach (var (name, entry) in configuration.Entries) - { - var pointer = Pointer.Entry(name); - var shapes = (entry.Agent is null ? 0 : 1) + (entry.Policy is null ? 0 : 1) + (entry.Graph is null ? 0 : 1); - - if (shapes == 0) - { - errors.Add(Reference( - pointer, - $"the entry '{name}' declares none of agent:, policy:, or graph:. It holds exactly one.")); - } - else if (shapes > 1) - { - errors.Add(Reference( - pointer, - $"the entry '{name}' declares more than one of agent:, policy:, and graph:. It holds exactly one.")); - } - - if (entry.Agent is { } agentId) - { - if (string.IsNullOrWhiteSpace(agentId)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, AgentField), - $"the entry '{name}' names an empty agent:. It names one id from agents.items.")); - } - else if (!names.Agents.Contains(agentId)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, AgentField), - $"the agent '{agentId}' is not declared in agents.items")); - } - } - - if (entry.FallbackReply is { } fallback && string.IsNullOrWhiteSpace(fallback)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "fallbackReply"), - $"the entry '{name}' sets a blank fallbackReply, so a failed turn would speak nothing.")); - } - - if (entry.RefusalReply is { } refusal && string.IsNullOrWhiteSpace(refusal)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "refusalReply"), - $"the entry '{name}' sets a blank refusalReply, so a refused turn would speak nothing.")); - } - } - } - - // --------------------------------------------------------------------------------------------- - // Check 2: reference resolution. - // --------------------------------------------------------------------------------------------- - private static void CheckReferences(AgentCoreConfiguration configuration, DeclaredNames names, List errors) - { - // A kind: agent tool names the agent it runs, and that name resolves whether or not any agent - // lists the tool. The compiler catches only the listed case, and only after the load passes. - for (var index = 0; index < configuration.Tools.Count; index++) - { - var tool = configuration.Tools[index]; - if (tool.Kind == ToolKind.Agent && tool.Agent is { } target && !names.Agents.Contains(target)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Tool(index), AgentField), - $"the agent '{target}' is not declared in agents.items")); - } - } - - if (configuration.Extractor is { } extractor) - { - AddUnknownModel(extractor.Model, "/extractor/model/ref", names, errors); - } - - if (configuration.Evaluation is { } evaluation) - { - AddUnknownModel(evaluation.Judge, "/evaluation/judge/ref", names, errors); - } - - if (configuration.Titler is { } titler) - { - AddUnknownModel(titler.Model, "/titler/model/ref", names, errors); - } - - var items = configuration.Agents.Items; - if (configuration.Agents.Defaults is { } defaults) - { - AddUnknownModel(defaults.Model, "/agents/defaults/model/ref", names, errors); - } - - for (var index = 0; index < items.Count; index++) - { - var agent = items[index]; - - AddUnknownModel( - agent.Model, - ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Pointer.Agent(index), "model"), "ref"), - names, - errors); - - for (var child = 0; child < agent.Background.Count; child++) - { - var childId = agent.Background[child]; - - if (!names.Agents.Contains(childId)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer( - ConfigurationError.AppendPointer(Pointer.Agent(index), "background"), child), - $"the agent '{childId}' is not declared in agents.items")); - } - } - } - - foreach (var (name, entry) in configuration.Entries) - { - if (entry.Policy is { } policy) - { - var stages = names.Stages[name]; - - if (!stages.Contains(policy.Initial)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Policy(name), "initial"), - $"the stage '{policy.Initial}' is not declared in policy.stages in entry '{name}'")); - } - - for (var index = 0; index < policy.Stages.Count; index++) - { - var stage = policy.Stages[index]; - - if (stage.Agent is { } agentId && !names.Agents.Contains(agentId)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Stage(name, index), AgentField), - $"the agent '{agentId}' is not declared in agents.items")); - } - - for (var exit = 0; exit < stage.To.Count; exit++) - { - var transition = stage.To[exit]; - var pointer = Pointer.Transition(name, index, exit); - - if (!stages.Contains(transition.Stage)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "stage"), - $"the stage '{transition.Stage}' is not declared in policy.stages in entry '{name}'")); - } - - AddUnknownGuard(transition.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors); - } - } - } - - if (entry.Graph is not { } graph) - { - continue; - } - - var nodes = names.Nodes[name]; - - for (var index = 0; index < graph.Agents.Count; index++) - { - if (!names.Agents.Contains(graph.Agents[index])) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.GraphAgents(name), index), - $"the agent '{graph.Agents[index]}' is not declared in agents.items")); - } - } - - for (var index = 0; index < graph.Nodes.Count; index++) - { - if (graph.Nodes[index].Agent is { } nodeAgent && !names.Agents.Contains(nodeAgent)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Node(name, index), AgentField), - $"the agent '{nodeAgent}' is not declared in agents.items")); - } - } - - for (var index = 0; index < graph.Edges.Count; index++) - { - var edge = graph.Edges[index]; - var pointer = Pointer.Edge(name, index); - - if (!nodes.Contains(edge.From)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "from"), - $"the node '{edge.From}' is not declared in graph.nodes in entry '{name}'")); - } - - if (!nodes.Contains(edge.To)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "to"), - $"the node '{edge.To}' is not declared in graph.nodes in entry '{name}'")); - } - - AddUnknownGuard(edge.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors); - } - } - } - - private static void AddUnknownGuard(GuardReference? guard, string pointer, DeclaredNames names, List errors) - { - if (guard?.Name is { } name && !names.Guards.Contains(name)) - { - errors.Add(Reference(pointer, $"the guard '{name}' is not declared in guards:")); - } - } - - /// Resolves one model reference against the as: names of providers.llm. - private static void AddUnknownModel(ModelReference? model, string pointer, DeclaredNames names, List errors) - { - if (model is { } reference && !names.Models.Contains(reference.Ref)) - { - errors.Add(Reference(pointer, $"the model '{reference.Ref}' is not declared in providers.llm")); - } - } - - // --------------------------------------------------------------------------------------------- - // Check 2, tool ids: the other half of reference resolution. - // --------------------------------------------------------------------------------------------- - /// - /// Resolves the two reference kinds that name a tool id: a from: state slot and an agent's - /// tools: entry. Decision 15 keeps this separate from because - /// these are the only reference kinds an MCP server's discovery can satisfy, so this is the only - /// half of check 2 that has to wait for it. - /// - private static void CheckToolReferences(AgentCoreConfiguration configuration, IReadOnlySet servedToolIds, List errors) - { - foreach (var slot in configuration.State) - { - if (slot.Value.From is { } from && !servedToolIds.Contains(from.ToolId)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.State(slot.Key), "from"), - $"nothing serves the tool '{from.ToolId}'. Declare it in tools:, or check that an mcp: server offers it.")); - } - } - - var items = configuration.Agents.Items; - for (var index = 0; index < items.Count; index++) - { - var agent = items[index]; - for (var slot = 0; slot < agent.Tools.Count; slot++) - { - if (!servedToolIds.Contains(agent.Tools[slot])) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Pointer.Agent(index), "tools"), slot), - $"nothing serves the tool '{agent.Tools[slot]}'. Declare it in tools:, or check that an mcp: server offers it.")); - } - } - } - } - - /// Resolves every agent's skills: entry against what the bound folder serves. - /// The bound document. - /// Every skill name the bound folder serves. - /// The list every failure is added to. - private static void CheckSkillReferences( - AgentCoreConfiguration configuration, - IReadOnlySet servedSkillNames, - List errors) - { - var served = string.Join(", ", servedSkillNames.Order(StringComparer.Ordinal)); - var items = configuration.Agents.Items; - - for (var index = 0; index < items.Count; index++) - { - var agent = items[index]; - - for (var slot = 0; slot < agent.Skills.Count; slot++) - { - if (servedSkillNames.Contains(agent.Skills[slot])) - { - continue; - } - - errors.Add(Reference( - ConfigurationError.AppendPointer( - ConfigurationError.AppendPointer(Pointer.Agent(index), "skills"), slot), - $"the skill '{agent.Skills[slot]}' is not in the bound skills folder. " - + $"The folder serves: {served}.")); - } - } - } - - /// Refuses a declared tool id that the skills provider registers under the same name. - /// The bound document. - /// The list every failure is added to. - private static void CheckSkillToolNames(AgentCoreConfiguration configuration, List errors) - { - var items = configuration.Agents.Items; - if (!items.Any(agent => agent.Skills.Count > 0)) - { - return; - } - - string[] reserved = - [ - AgentSkillsProvider.LoadSkillToolName, - AgentSkillsProvider.ReadSkillResourceToolName, - AgentSkillsProvider.RunSkillScriptToolName, - ]; - - var tools = configuration.Tools; - for (var index = 0; index < tools.Count; index++) - { - if (!reserved.Contains(tools[index].Id, StringComparer.Ordinal)) - { - continue; - } - - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Tool(index), "id"), - $"the tool id '{tools[index].Id}' is reserved while any agent declares a skills: " - + "list, because the skills provider registers a tool of that name. Rename the tool.")); - } - } - - // --------------------------------------------------------------------------------------------- - // Check 2, mcp: ids: a duplicate connects twice and its collision surfaces only at boot, naming - // the served tool id rather than the mcp: entry that caused it. This runs before any connection - // opens, so it costs nothing to check here. - // --------------------------------------------------------------------------------------------- - private static void CheckMcpServerIds(AgentCoreConfiguration configuration, List errors) - { - var seen = new HashSet(StringComparer.Ordinal); - for (var index = 0; index < configuration.Mcp.Count; index++) - { - var server = configuration.Mcp[index]; - if (!seen.Add(server.Id)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Mcp(index), "id"), - $"two mcp: entries declare the id '{server.Id}'. An id names one server, so rename " - + "one of them.")); - } - } - } - - // --------------------------------------------------------------------------------------------- - // mcp: secret placement. command: becomes the child's argv, which every user on the box can read - // out of ps, and url: is logged by proxies and reverse proxies along the way. Neither is a - // SecretTemplate, so a reference written there would be passed through as its literal characters - // and would leak while not even working. The schema cannot express "this string may not hold that - // substring", so it is checked here. - // --------------------------------------------------------------------------------------------- - private static void CheckMcpSecretPlacement(AgentCoreConfiguration configuration, List errors) - { - for (var index = 0; index < configuration.Mcp.Count; index++) - { - var server = configuration.Mcp[index]; - - for (var word = 0; word < server.Command.Count; word++) - { - if (!server.Command[word].Contains(SecretReference.Prefix, StringComparison.Ordinal)) - { - continue; - } - - errors.Add(Reference( - ConfigurationError.AppendPointer( - ConfigurationError.AppendPointer(Pointer.Mcp(index), "command"), word), - $"the mcp: server '{server.Id}' writes a ${{secret:...}} reference in command:. A " - + "command becomes the child process's argv, which every user on this machine can " - + "read out of ps, and nothing resolves a reference there — it would be passed " - + "through as its own characters. Put the credential in env: instead.")); - } - - if (server.Url is { } url && url.Contains(SecretReference.Prefix, StringComparison.Ordinal)) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(Pointer.Mcp(index), "url"), - $"the mcp: server '{server.Id}' writes a ${{secret:...}} reference in url:. A URL is " - + "logged by every proxy it passes, and nothing resolves a reference there — it " - + "would be passed through as its own characters. Put the credential in headers: " - + "instead.")); - } - } - } - - // --------------------------------------------------------------------------------------------- - // Check 2, knowledge scope: a state-built scope must not produce a filter nobody meant. - // --------------------------------------------------------------------------------------------- - - /// Refuses a scope built from state that could produce a filter nobody meant. - /// - /// These are document checks, not store checks: KnowledgeStartup skips the store factory - /// for a host-supplied port, but the session composes the scope either way. - /// - private static void CheckKnowledgeScopeSlots( - AgentCoreConfiguration configuration, List errors) - { - if (configuration.Providers?.Knowledge?.Scope is not { } scope) - { - return; - } - - KnowledgeFilterValidator.Check(scope, errors); - - if (scope.Wildcard is { } wildcard) - { - if (string.IsNullOrWhiteSpace(wildcard.Value)) - { - errors.Add(Reference( - Pointer.WildcardValue, - "the wildcard value is blank, so it names no payload value a card could carry.")); - } - - if (wildcard.Facets.Count == 0) - { - errors.Add(Reference( - Pointer.WildcardFacets, - "the wildcard names no facets, so it widens nothing. Name the reach facets, and " - + "never an isolation facet such as a customer id.")); - } - } - - // A wildcard without fromState is a supported shape: the deployment resolves its own facets - // and passes them as the call's scope, which the store still widens. See - // StateKnowledgeScope.Compose and KnowledgeStartup's K19 branch. Only the reverse is refused. - if (scope.FromState.Count == 0) - { - return; - } - - if (scope.Wildcard is not { } widened) - { - errors.Add(Reference( - Pointer.Wildcard, - "fromState is set and no wildcard is. An unknown slot would then leave its facet out " - + "of the scope, putting no condition on it, and every value of that facet would be " - + "in reach. Declare the wildcard, or drop fromState.")); - } - else - { - foreach (var facet in widened.Facets.Where(facet => !scope.FromState.Contains(facet, StringComparer.Ordinal))) - { - errors.Add(Reference( - Pointer.WildcardFacets, - $"wildcard.facets names '{facet}' and fromState does not. The scope filter only " - + $"ever puts a condition on a fromState facet, so there is no condition on " - + $"'{facet}' for the wildcard to widen.")); - } - - foreach (var name in scope.FromState.Where(name => !widened.Facets.Contains(name, StringComparer.Ordinal))) - { - errors.Add(Reference( - Pointer.WildcardFacets, - $"fromState names '{name}' and wildcard.facets does not, so an unfilled '{name}' " - + "would be searched for the literal wildcard rather than widened by it.")); - } - } - - if (configuration.Extractor is null) - { - errors.Add(Reference( - "/extractor", - "fromState names extractor slots and this document declares no extractor, so no slot " - + "is ever filled and every call searches only what the wildcard admits.")); - } - - foreach (var name in scope.FromState) - { - if (!configuration.State.TryGetValue(name, out var slot)) - { - errors.Add(Reference( - Pointer.FromState, - $"fromState names the slot '{name}', which this document does not declare.")); - continue; - } - - var pointer = Pointer.State(name); - - if (slot.Default is not null) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "default"), - $"the facet slot '{name}' declares a default. An unfilled slot reads as its " - + "default, so every call before the caller says otherwise would be scoped to a " - + "guess, with no error.")); - } - - if (slot.Type != StateSlotType.String) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "type"), - $"the facet slot '{name}' is not type string. A facet holds one string value.")); - } - - if (slot.Writer != StateWriter.Extractor) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "writer"), - $"the facet slot '{name}' is not written by the extractor. A const slot is filled " - + "before turn 1 and would scope every call to it; a tool slot could change the " - + "scope mid-call.")); - } - - if (slot.EnumValues is not { Count: > 0 }) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "enum"), - $"the facet slot '{name}' declares no enum. Nothing would then stop a value the " - + "corpus has never been tagged with, which the wildcard turns into an answer " - + "from the wrong bucket rather than an empty result.")); - } - } - } - - // --------------------------------------------------------------------------------------------- - // Check 2, ambiguity: section 10 of the ambiguity design. - // --------------------------------------------------------------------------------------------- - - /// Refuses an ambiguity: block that could not do what it declares. - private static void CheckAmbiguity( - AgentCoreConfiguration configuration, List errors, List warnings) - { - var knowledge = configuration.Providers?.Knowledge; - - if (knowledge?.Ambiguity is not { } ambiguity) - { - return; - } - - if (knowledge.Mapper is not null) - { - errors.Add(Reference( - Pointer.Mapper, - "providers.knowledge.ambiguity is declared, and providers.knowledge.mapper names a " - + "custom mapper. The probe reads each card's facet values out of Extras, which only " - + "the built-in field mapper fills, so every probe would find no values and the " - + "channel would stay silent.")); - } - - if (knowledge.Scope.Wildcard is null) - { - errors.Add(Reference( - Pointer.Ambiguity, - "providers.knowledge.ambiguity is declared and providers.knowledge.scope.wildcard is " - + "absent. The probe drops a facet the wildcard filled, so with no wildcard it has " - + "nothing to drop and the channel can never fire.")); - } - - CheckRange( - ambiguity.MaxCandidates, - 2, - int.MaxValue, - ConfigurationError.AppendPointer(Pointer.Ambiguity, "maxCandidates"), - "ambiguity.maxCandidates", - "Below 2, the ask could never name a spread of candidates.", - errors); - - CheckRange( - ambiguity.MaxAsks, - 0, - int.MaxValue, - ConfigurationError.AppendPointer(Pointer.Ambiguity, "maxAsks"), - "ambiguity.maxAsks", - "0 is legal and means gate only; a negative count is not.", - errors); - - CheckRange( - ambiguity.ProbeDeadlineSeconds, - 1, - MaxIntervalSeconds, - ConfigurationError.AppendPointer(Pointer.Ambiguity, "probeDeadlineSeconds"), - "ambiguity.probeDeadlineSeconds", - "A budget below one second leaves the probe unable to complete even the fastest real " - + "search, and one above the range throws out of the CancelAfter that arms it.", - errors); - - CheckRange( - ambiguity.ProbeWaitMarginSeconds, - 1, - MaxIntervalSeconds, - ConfigurationError.AppendPointer(Pointer.Ambiguity, "probeWaitMarginSeconds"), - "ambiguity.probeWaitMarginSeconds", - "A margin of 0 reinstates the race it exists to close: the loser's wait would end as the " - + "winner's own search does, leaving a margin equal to the arrival spread. Above the " - + "range, the deadline this is added to no longer fits the wait it arms.", - errors); - - // A probe drops one of the scope's own facets, so it needs a second one left to search by. - // Zero is as unreachable as one, and reaches this line whenever the host supplies every facet. - if ((knowledge.Scope.FromState ?? []).Count <= 1) - { - warnings.Add(Reference( - Pointer.Ambiguity, - "providers.knowledge.ambiguity is declared and scope.fromState names at most one " - + "facet. That deployment has no droppable facet other than its only one, so the probe " - + "is unreachable unless the host sets one too.")); - } - } - - // --------------------------------------------------------------------------------------------- - // Check 3: one writer for each slot. - // --------------------------------------------------------------------------------------------- - private static void CheckSlotWriters(AgentCoreConfiguration configuration, List errors) - { - foreach (var entry in configuration.State) - { - var pointer = Pointer.State(entry.Key); - var slot = entry.Value; - - if (ReservedStateSlots.Contains(entry.Key)) - { - errors.Add(Writers( - pointer, - $"the slot has two writers: '{entry.Key}' is a reserved read-only slot that is always present, and state: declares it again")); - } - - var owner = OwnerField(slot.Writer); - if (owner is not null && FieldValue(slot, owner) is null) - { - errors.Add(Writers( - pointer, - $"the slot has zero writers: writer: {WriterName(slot.Writer)} fills the slot from '{owner}:', and the slot declares none")); - } - - foreach (var field in new[] { "from", IncrementField, "value" }) - { - if (string.Equals(field, owner, StringComparison.Ordinal) || FieldValue(slot, field) is null) - { - continue; - } - - errors.Add(Writers( - ConfigurationError.AppendPointer(pointer, field), - $"the slot has two writers: writer: {WriterName(slot.Writer)} owns it, and '{field}:' names a second")); - } - } - } - - private static string? OwnerField(StateWriter writer) - => writer switch - { - StateWriter.Tool => "from", - StateWriter.Counter => IncrementField, - StateWriter.Const => "value", - _ => null, - }; - - private static string WriterName(StateWriter writer) - => writer switch - { - StateWriter.Tool => "tool", - StateWriter.Counter => "counter", - StateWriter.Const => "const", - _ => "extractor", - }; - - private static object? FieldValue(StateSlotConfiguration slot, string field) - => field switch - { - "from" => slot.From, - IncrementField => slot.Increment, - _ => slot.Value, - }; - - // --------------------------------------------------------------------------------------------- - // Check 4: guard operators and variables. - // --------------------------------------------------------------------------------------------- - private static void CheckGuardRules(AgentCoreConfiguration configuration, List errors) - { - foreach (var guard in configuration.Guards) - { - CheckOneRule(configuration, guard.Value, Pointer.Guard(guard.Key), errors); - } - - foreach (var slot in configuration.State) - { - if (slot.Value.Increment is { } increment) - { - CheckOneRule(configuration, increment, ConfigurationError.AppendPointer(Pointer.State(slot.Key), IncrementField), errors); - } - } - foreach (var (name, entry) in configuration.Entries) - { - if (entry.Policy is { } policy) - { - for (var index = 0; index < policy.Stages.Count; index++) - { - var stage = policy.Stages[index]; - for (var exit = 0; exit < stage.To.Count; exit++) - { - if (stage.To[exit].When?.Rule is { } rule) - { - CheckOneRule(configuration, rule, ConfigurationError.AppendPointer(Pointer.Transition(name, index, exit), "when"), errors); - } - } - } - } - - if (entry.Graph is not { } graph) - { - continue; - } - - for (var index = 0; index < graph.Edges.Count; index++) - { - if (graph.Edges[index].When?.Rule is { } rule) - { - CheckOneRule(configuration, rule, ConfigurationError.AppendPointer(Pointer.Edge(name, index), "when"), errors); - } - } - } + ServedReferenceCheck.SkillToolNames(configuration, errors); + ThrowOnErrors(errors); } - private static void CheckOneRule(AgentCoreConfiguration configuration, JsonNode rule, string pointer, List errors) + private static ConfigurationValidationResult ThrowOnErrors(ConfigurationValidationResult result) { - var facts = new GuardRuleFacts(); - facts.Collect(rule); - - foreach (var name in facts.Operators.Where(name => !GuardOperators.IsAllowed(name))) - { - errors.Add(Operators(pointer, GuardOperators.DescribeRejection(name))); - } - - if (facts.HasDoubleNegationSugar) - { - errors.Add(Operators(pointer, GuardOperators.DoubleNegationSugarRejection)); - } - - foreach (var slot in facts.Variables.Where(slot => - !configuration.State.ContainsKey(slot) && !ReservedStateSlots.Contains(slot))) - { - errors.Add(Operators(pointer, $"the rule reads the slot '{slot}', and state: does not declare it")); - } - - foreach (var comparison in facts.NumericComparisons) - { - if (configuration.State.TryGetValue(comparison.Value, out var slot) && slot.Type == StateSlotType.Boolean) - { - errors.Add(Operators( - pointer, - $"the operator '{comparison.Key}' compares the slot '{comparison.Value}', and that slot is a boolean rather than a number")); - } - } - } - - // --------------------------------------------------------------------------------------------- - // Check 5: exclusivity and coverage by evaluation. - // --------------------------------------------------------------------------------------------- - private static void CheckExclusivity(AgentCoreConfiguration configuration, List errors, List warnings) - { - var evaluator = new GuardEvaluator(configuration.Guards); - - foreach (var (name, entry) in configuration.Entries) - { - if (entry.Policy is { } policy) - { - for (var index = 0; index < policy.Stages.Count; index++) - { - var stage = policy.Stages[index]; - var exits = new List(stage.To.Count); - - for (var exit = 0; exit < stage.To.Count; exit++) - { - var transition = stage.To[exit]; - var pointer = Pointer.Transition(name, index, exit); - - exits.Add(new SiblingExit( - DescribeExit(transition.When, "exit", transition.Stage), - transition.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"), - transition.When)); - } - - var pinned = new Dictionary(StringComparer.Ordinal) - { - [ReservedStateSlots.Stage] = JsonValue.Create(stage.Id), - }; - - GuardExclusivityCheck.Run( - exits, - ConfigurationError.AppendPointer(Pointer.Stage(name, index), "to"), - $"the stage '{stage.Id}'", - evaluator, - configuration.State, - pinned, - errors, - warnings); - } - } - - if (entry.Graph is not { } graph || graph.Edges.Count == 0) - { - continue; - } - - foreach (var group in graph.Edges.Select(static (edge, index) => (edge, index)).GroupBy(static pair => pair.edge.From, StringComparer.Ordinal)) - { - var exits = new List(); - - foreach (var pair in group) - { - var pointer = Pointer.Edge(name, pair.index); - exits.Add(new SiblingExit( - DescribeExit(pair.edge.When, "edge", pair.edge.To), - pair.edge.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"), - pair.edge.When)); - } - - GuardExclusivityCheck.Run( - exits, - Pointer.GraphEdges(name), - $"the node '{group.Key}'", - evaluator, - configuration.State, - new Dictionary(StringComparer.Ordinal), - errors, - warnings); - } - } - } - - private static string DescribeExit(GuardReference? guard, string kind, string target) - => guard switch - { - null => $"the unconditional {kind} to '{target}'", - { Name: { } name } => $"the guard '{name}'", - _ => $"the inline rule on the {kind} to '{target}'", - }; - - // --------------------------------------------------------------------------------------------- - // Check 6: reachability. - // --------------------------------------------------------------------------------------------- - private static void CheckReachability(AgentCoreConfiguration configuration, List errors) - { - foreach (var (name, entry) in configuration.Entries) - { - if (entry.Policy is { } policy) - { - var edges = new Dictionary>(StringComparer.Ordinal); - foreach (var stage in policy.Stages) - { - edges[stage.Id] = [.. stage.To.Select(static transition => transition.Stage)]; - } - - var reachable = Reach(policy.Initial, edges); - - for (var index = 0; index < policy.Stages.Count; index++) - { - var stage = policy.Stages[index]; - if (!reachable.Contains(stage.Id)) - { - errors.Add(Reachability( - Pointer.Stage(name, index), - $"the stage '{stage.Id}' is unreachable from the initial stage '{policy.Initial}' in entry '{name}'")); - } - - if (!stage.Terminal && stage.To.Count == 0) - { - errors.Add(Reachability( - Pointer.Stage(name, index), - $"the stage '{stage.Id}' is not terminal and has no exit")); - } - } - } - - if (entry.Graph is not { } graph || graph.Nodes.Count == 0) - { - continue; - } - - var starts = graph.Nodes.Where(static node => node.Start).Select(static node => node.Id).ToList(); - if (starts.Count != 1) - { - continue; - } - - var forward = BuildAdjacency(graph); - var live = Reach(starts[0], forward); - - for (var index = 0; index < graph.Nodes.Count; index++) - { - if (!live.Contains(graph.Nodes[index].Id)) - { - errors.Add(Reachability( - Pointer.Node(name, index), - $"the node '{graph.Nodes[index].Id}' is unreachable from the start node '{starts[0]}' in entry '{name}'")); - } - } - } - } - - // --------------------------------------------------------------------------------------------- - private static void CheckGraphWellFormedness(AgentCoreConfiguration configuration, List errors) - { - foreach (var (name, entry) in configuration.Entries) - { - if (entry.Graph is not { } graph || graph.Nodes.Count == 0) - { - continue; - } - - var starts = graph.Nodes.Count(static node => node.Start); - if (starts != 1) - { - errors.Add(WellFormedness( - Pointer.GraphNodes(name), - string.Create(CultureInfo.InvariantCulture, $"the graph in entry '{name}' declares {starts} start nodes, and check 7 needs exactly one"))); - } - - var outgoing = new HashSet(StringComparer.Ordinal); - var incoming = new HashSet(StringComparer.Ordinal); - - foreach (var edge in graph.Edges) - { - outgoing.Add(edge.From); - incoming.Add(edge.To); - } - - for (var index = 0; index < graph.Nodes.Count; index++) - { - var node = graph.Nodes[index]; - if (!outgoing.Contains(node.Id) && !incoming.Contains(node.Id)) - { - errors.Add(WellFormedness( - Pointer.Node(name, index), - $"the node '{node.Id}' is an orphan: no edge reaches it and no edge leaves it")); - } - } - - var outputs = graph.Nodes.Where(static node => node.Output).Select(static node => node.Id).ToHashSet(StringComparer.Ordinal); - if (outputs.Count == 0) - { - errors.Add(WellFormedness(Pointer.GraphNodes(name), "the graph declares no output node, so no path reaches an output")); - continue; - } - - var forward = BuildAdjacency(graph); - for (var index = 0; index < graph.Nodes.Count; index++) - { - var node = graph.Nodes[index]; - var reachable = Reach(node.Id, forward); - if (!reachable.Overlaps(outputs)) - { - errors.Add(WellFormedness( - Pointer.Node(name, index), - $"no path from the node '{node.Id}' reaches an output node")); - } - } - } - } - - // --------------------------------------------------------------------------------------------- - // Check 8: delegation cycles. - // --------------------------------------------------------------------------------------------- - private static void CheckDelegationCycles(AgentCoreConfiguration configuration, List errors) - { - var items = configuration.Agents.Items; - if (items.Count == 0) - { - return; - } - - var tools = configuration.Tools.ToDictionary(static tool => tool.Id, static tool => tool, StringComparer.Ordinal); - - // One edge for each agent-as-tool: the agent lists a tool, and that tool declares kind: agent. - // The 'agent:' field is the one explicit delegation edge in the document. 'uses:' names a - // built-in and 'binds:' names a host delegate, so neither ever names an agent, and a tool id - // that matches an agent id is a coincidence. - var edges = new Dictionary>(StringComparer.Ordinal); - - for (var index = 0; index < items.Count; index++) - { - var agent = items[index]; - var outgoing = new List<(string, int, int)>(); - - for (var slot = 0; slot < agent.Tools.Count; slot++) - { - if (!tools.TryGetValue(agent.Tools[slot], out var tool)) - { - continue; - } - - if (tool.Kind == ToolKind.Agent && tool.Agent is { } target) - { - outgoing.Add((target, index, slot)); - } - } - - edges[agent.Id] = outgoing; - } - - var state = new Dictionary(StringComparer.Ordinal); - var path = new List(); - var reported = new HashSet(StringComparer.Ordinal); - - foreach (var agent in items) - { - Visit(agent.Id, edges, state, path, reported, errors); - } - } - - private static void Visit( - string agent, - Dictionary> edges, - Dictionary state, - List path, - HashSet reported, - List errors) - { - if (state.TryGetValue(agent, out var mark) && mark != 0) - { - return; - } - - state[agent] = 1; - path.Add(agent); - - var outgoing = edges.TryGetValue(agent, out var found) ? found : []; - foreach (var edge in outgoing) - { - var start = path.IndexOf(edge.Target); - if (start >= 0) - { - var cycle = string.Join(" -> ", path.Skip(start).Append(edge.Target)); - if (reported.Add(cycle)) - { - errors.Add(new ConfigurationError - { - Pointer = ConfigurationError.AppendPointer( - ConfigurationError.AppendPointer(Pointer.Agent(edge.Agent), "tools"), - edge.Slot), - // The compiler prints the same chain in the same 'first -> second -> first' - // form, and gives the same reason. The two messages agree rather than compete. - Message = $"this tool runs the agent '{edge.Target}', and that closes the delegation cycle " - + $"{cycle}. The call would never return.", - Check = ConfigurationCheck.DelegationCycles, - }); - } - - continue; - } - - Visit(edge.Target, edges, state, path, reported, errors); - } - - path.RemoveAt(path.Count - 1); - state[agent] = 2; - } - - // --------------------------------------------------------------------------------------------- - // Shared helpers. - // --------------------------------------------------------------------------------------------- - private static Dictionary> BuildAdjacency(GraphConfiguration graph) - { - var forward = new Dictionary>(StringComparer.Ordinal); - foreach (var node in graph.Nodes) - { - forward[node.Id] = []; - } - - foreach (var edge in graph.Edges) - { - if (forward.TryGetValue(edge.From, out var targets)) - { - targets.Add(edge.To); - } - } - - return forward; - } - - private static HashSet Reach(string root, Dictionary> edges) - { - var seen = new HashSet(StringComparer.Ordinal) { root }; - var pending = new Stack(); - pending.Push(root); - - while (pending.Count > 0) - { - var current = pending.Pop(); - if (!edges.TryGetValue(current, out var targets)) - { - continue; - } - - foreach (var target in targets.Where(target => !seen.Contains(target))) - { - seen.Add(target); - pending.Push(target); - } - } - - return seen; + ThrowOnErrors(result.Errors); + return result; } - private static ConfigurationError Reference(string pointer, string message) - => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.ReferenceResolution }; - - private static ConfigurationError Range(string pointer, string message) - => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.ValueRange }; - - /// Refuses a count or an interval that falls outside the range the runtime accepts. - /// The configured value. - /// The lowest accepted value, inclusive. - /// The highest accepted value, inclusive. means no ceiling. - /// The pointer at the field itself. - /// How the message names the field, as a noun phrase. - /// One or more sentences saying what the range protects. - /// Collects the refusal. - /// - /// Both bounds go through one call so a field cannot be given a floor and left without a ceiling: - /// every ceiling here stands between a document and a raw throw out of a timer at boot or mid-turn. - /// - private static void CheckRange( - int value, - int min, - int max, - string pointer, - string subject, - string why, - List errors) + private static void ThrowOnErrors(IReadOnlyList errors) { - if (value >= min && value <= max) + if (errors.Count > 0) { - return; + throw new ConfigurationLoadException(errors); } - - var accepted = max == int.MaxValue - ? $"the lowest accepted value is {min.ToString(CultureInfo.InvariantCulture)}" - : $"the accepted range is {min.ToString(CultureInfo.InvariantCulture)} to " - + max.ToString(CultureInfo.InvariantCulture); - - errors.Add(Range( - pointer, - $"{subject} is {value.ToString(CultureInfo.InvariantCulture)}, and {accepted}. {why}")); - } - - private static ConfigurationError Writers(string pointer, string message) - => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.SlotWriters }; - - private static ConfigurationError Operators(string pointer, string message) - => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.GuardOperators }; - - private static ConfigurationError Reachability(string pointer, string message) - => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.Reachability }; - - private static ConfigurationError WellFormedness(string pointer, string message) - => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.GraphWellFormedness }; - - private sealed class DeclaredNames - { - public required HashSet Agents { get; init; } - - public required HashSet Guards { get; init; } - - public required HashSet Models { get; init; } - - public required Dictionary> Stages { get; init; } - - public required Dictionary> Nodes { get; init; } - - public static DeclaredNames From(AgentCoreConfiguration configuration) - => new() - { - Agents = configuration.Agents.Items - .Select(static agent => agent.Id).ToHashSet(StringComparer.Ordinal), - Guards = configuration.Guards.Keys.ToHashSet(StringComparer.Ordinal), - Stages = configuration.Entries.ToDictionary( - static entry => entry.Key, - entry => (entry.Value.Policy?.Stages ?? []) - .Select(static stage => stage.Id).ToHashSet(StringComparer.Ordinal), - StringComparer.Ordinal), - Nodes = configuration.Entries.ToDictionary( - static entry => entry.Key, - entry => (entry.Value.Graph?.Nodes ?? []) - .Select(static node => node.Id).ToHashSet(StringComparer.Ordinal), - StringComparer.Ordinal), - Models = (configuration.Providers?.Llm ?? []) - .Select(static provider => provider.As).ToHashSet(StringComparer.Ordinal), - }; - } - - private static class Pointer - { - public const string Wildcard = "/providers/knowledge/scope/wildcard"; - - public const string WildcardValue = Wildcard + "/value"; - - public const string WildcardFacets = Wildcard + "/facets"; - - public const string FromState = "/providers/knowledge/scope/fromState"; - - public const string Ambiguity = "/providers/knowledge/ambiguity"; - - public const string Mapper = "/providers/knowledge/mapper"; - - public static string State(string slot) => ConfigurationError.AppendPointer("/state", slot); - - public static string Guard(string name) => ConfigurationError.AppendPointer("/guards", name); - - public static string Agent(int index) => ConfigurationError.AppendPointer("/agents/items", index); - - public static string Tool(int index) => ConfigurationError.AppendPointer("/tools", index); - - public static string Mcp(int index) => ConfigurationError.AppendPointer("/mcp", index); - - public static string Entry(string name) => ConfigurationError.AppendPointer("/entries", name); - - public static string Policy(string name) => ConfigurationError.AppendPointer(Entry(name), "policy"); - - public static string Graph(string name) => ConfigurationError.AppendPointer(Entry(name), "graph"); - - public static string GraphAgents(string name) => ConfigurationError.AppendPointer(Graph(name), "agents"); - - public static string GraphNodes(string name) => ConfigurationError.AppendPointer(Graph(name), "nodes"); - - public static string GraphEdges(string name) => ConfigurationError.AppendPointer(Graph(name), "edges"); - - public static string Stage(string name, int index) => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Policy(name), "stages"), index); - - public static string Transition(string name, int stage, int exit) - => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Stage(name, stage), "to"), exit); - - public static string Node(string name, int index) => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Graph(name), "nodes"), index); - - public static string Edge(string name, int index) => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Graph(name), "edges"), index); } } diff --git a/src/AgentCore.Application/Configuration/Validation/DeclaredNames.cs b/src/AgentCore.Application/Configuration/Validation/DeclaredNames.cs new file mode 100644 index 00000000..dd0363e5 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/DeclaredNames.cs @@ -0,0 +1,39 @@ +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Configuration.Validation; + +/// Every name the document declares, indexed once so each reference check resolves in O(1). +internal sealed class DeclaredNames +{ + public required HashSet Agents { get; init; } + + public required HashSet Guards { get; init; } + + public required HashSet Models { get; init; } + + /// Stage ids of each entry's policy, keyed by entry name. + public required Dictionary> Stages { get; init; } + + /// Node ids of each entry's graph, keyed by entry name. + public required Dictionary> Nodes { get; init; } + + public static DeclaredNames From(AgentCoreConfiguration configuration) + => new() + { + Agents = configuration.Agents.Items + .Select(static agent => agent.Id).ToHashSet(StringComparer.Ordinal), + Guards = configuration.Guards.Keys.ToHashSet(StringComparer.Ordinal), + Stages = configuration.Entries.ToDictionary( + static entry => entry.Key, + entry => (entry.Value.Policy?.Stages ?? []) + .Select(static stage => stage.Id).ToHashSet(StringComparer.Ordinal), + StringComparer.Ordinal), + Nodes = configuration.Entries.ToDictionary( + static entry => entry.Key, + entry => (entry.Value.Graph?.Nodes ?? []) + .Select(static node => node.Id).ToHashSet(StringComparer.Ordinal), + StringComparer.Ordinal), + Models = (configuration.Providers?.Llm ?? []) + .Select(static provider => provider.As).ToHashSet(StringComparer.Ordinal), + }; +} diff --git a/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs b/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs new file mode 100644 index 00000000..1b997020 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs @@ -0,0 +1,108 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 8: no agent reaches itself through a chain of kind: agent tools. +internal static class DelegationCycleCheck +{ + private sealed record Edge(string Target, int Agent, int Slot); + + public static void Run(AgentCoreConfiguration configuration, List errors) + { + var items = configuration.Agents.Items; + if (items.Count == 0) + { + return; + } + + var edges = BuildEdges(configuration); + var state = new Dictionary(StringComparer.Ordinal); + var path = new List(); + var reported = new HashSet(StringComparer.Ordinal); + + foreach (var agent in items) + { + Visit(agent.Id, edges, state, path, reported, errors); + } + } + + // One edge for each agent-as-tool: the agent lists a tool, and that tool declares kind: agent. + // The 'agent:' field is the one explicit delegation edge in the document. 'uses:' names a + // built-in and 'binds:' names a host delegate, so neither ever names an agent, and a tool id + // that matches an agent id is a coincidence. + private static Dictionary> BuildEdges(AgentCoreConfiguration configuration) + { + var tools = configuration.Tools.ToDictionary(static tool => tool.Id, static tool => tool, StringComparer.Ordinal); + var edges = new Dictionary>(StringComparer.Ordinal); + var items = configuration.Agents.Items; + + for (var index = 0; index < items.Count; index++) + { + var agent = items[index]; + var outgoing = new List(); + + for (var slot = 0; slot < agent.Tools.Count; slot++) + { + if (tools.TryGetValue(agent.Tools[slot], out var tool) + && tool.Kind == ToolKind.Agent + && tool.Agent is { } target) + { + outgoing.Add(new Edge(target, index, slot)); + } + } + + edges[agent.Id] = outgoing; + } + + return edges; + } + + private static void Visit( + string agent, + Dictionary> edges, + Dictionary state, + List path, + HashSet reported, + List errors) + { + if (state.TryGetValue(agent, out var mark) && mark != 0) + { + return; + } + + state[agent] = 1; + path.Add(agent); + + var outgoing = edges.TryGetValue(agent, out var found) ? found : []; + foreach (var edge in outgoing) + { + var start = path.IndexOf(edge.Target); + if (start < 0) + { + Visit(edge.Target, edges, state, path, reported, errors); + continue; + } + + var cycle = string.Join(" -> ", path.Skip(start).Append(edge.Target)); + if (reported.Add(cycle)) + { + errors.Add(CycleError(edge, cycle)); + } + } + + path.RemoveAt(path.Count - 1); + state[agent] = 2; + } + + private static ConfigurationError CycleError(Edge edge, string cycle) + => new() + { + Pointer = ValidationPointer.AgentTool(edge.Agent, edge.Slot), + // The compiler prints the same chain in the same 'first -> second -> first' form, and + // gives the same reason. The two messages agree rather than compete. + Message = $"this tool runs the agent '{edge.Target}', and that closes the delegation cycle " + + $"{cycle}. The call would never return.", + Check = ConfigurationCheck.DelegationCycles, + }; +} diff --git a/src/AgentCore.Application/Configuration/Validation/EntryShapeCheck.cs b/src/AgentCore.Application/Configuration/Validation/EntryShapeCheck.cs new file mode 100644 index 00000000..824341c7 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/EntryShapeCheck.cs @@ -0,0 +1,84 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 2, entry shapes: each entry holds exactly one of agent:, policy:, or graph:. +internal static class EntryShapeCheck +{ + public static void Run(AgentCoreConfiguration configuration, DeclaredNames names, List errors) + { + if (configuration.Agents.Items.Count == 0) + { + errors.Add(Reference( + "/agents/items", + "the document declares no agents:, so no entry can resolve an agent.")); + } + + if (configuration.Entries.Count == 0) + { + errors.Add(Reference( + "/entries", + "the document declares no entries:, so it compiles to nothing.")); + return; + } + + foreach (var (name, entry) in configuration.Entries) + { + var pointer = ValidationPointer.Entry(name); + + CheckShapeCount(name, entry, pointer, errors); + CheckAgent(name, entry.Agent, pointer, names, errors); + CheckReply(name, entry.FallbackReply, "fallbackReply", "a failed turn", pointer, errors); + CheckReply(name, entry.RefusalReply, "refusalReply", "a refused turn", pointer, errors); + } + } + + private static void CheckShapeCount(string name, EntryConfiguration entry, string pointer, List errors) + { + var shapes = (entry.Agent is null ? 0 : 1) + (entry.Policy is null ? 0 : 1) + (entry.Graph is null ? 0 : 1); + + if (shapes == 0) + { + errors.Add(Reference( + pointer, + $"the entry '{name}' declares none of agent:, policy:, or graph:. It holds exactly one.")); + } + else if (shapes > 1) + { + errors.Add(Reference( + pointer, + $"the entry '{name}' declares more than one of agent:, policy:, and graph:. It holds exactly one.")); + } + } + + private static void CheckAgent(string name, string? agentId, string pointer, DeclaredNames names, List errors) + { + if (agentId is null) + { + return; + } + + var field = ConfigurationError.AppendPointer(pointer, ValidationPointer.AgentField); + + if (string.IsNullOrWhiteSpace(agentId)) + { + errors.Add(Reference(field, $"the entry '{name}' names an empty agent:. It names one id from agents.items.")); + } + else if (!names.Agents.Contains(agentId)) + { + errors.Add(Reference(field, $"the agent '{agentId}' is not declared in agents.items")); + } + } + + private static void CheckReply(string name, string? reply, string field, string turn, string pointer, List errors) + { + if (reply is not null && string.IsNullOrWhiteSpace(reply)) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(pointer, field), + $"the entry '{name}' sets a blank {field}, so {turn} would speak nothing.")); + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs b/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs new file mode 100644 index 00000000..6db5853a --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs @@ -0,0 +1,110 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Configuration.Validation; + +/// +/// Check 5: exclusivity and coverage by evaluation. Gathers the sibling exits of each stage and +/// each graph node, then hands each set to . +/// +internal static class ExitExclusivityCheck +{ + public static void Run(AgentCoreConfiguration configuration, List errors, List warnings) + { + var evaluator = new GuardEvaluator(configuration.Guards); + + foreach (var (name, entry) in configuration.Entries) + { + if (entry.Policy is { } policy) + { + CheckStages(configuration, name, policy, evaluator, errors, warnings); + } + + if (entry.Graph is { } graph && graph.Edges.Count > 0) + { + CheckNodes(configuration, name, graph, evaluator, errors, warnings); + } + } + } + + private static void CheckStages( + AgentCoreConfiguration configuration, + string name, + PolicyConfiguration policy, + GuardEvaluator evaluator, + List errors, + List warnings) + { + for (var index = 0; index < policy.Stages.Count; index++) + { + var stage = policy.Stages[index]; + var exits = new List(stage.To.Count); + + for (var exit = 0; exit < stage.To.Count; exit++) + { + var transition = stage.To[exit]; + exits.Add(Exit(transition.When, "exit", transition.Stage, ValidationPointer.Transition(name, index, exit))); + } + + var pinned = new Dictionary(StringComparer.Ordinal) + { + [ReservedStateSlots.Stage] = JsonValue.Create(stage.Id), + }; + + GuardExclusivityCheck.Run( + exits, + ConfigurationError.AppendPointer(ValidationPointer.Stage(name, index), "to"), + $"the stage '{stage.Id}'", + evaluator, + configuration.State, + pinned, + errors, + warnings); + } + } + + private static void CheckNodes( + AgentCoreConfiguration configuration, + string name, + GraphConfiguration graph, + GuardEvaluator evaluator, + List errors, + List warnings) + { + var byFrom = graph.Edges + .Select(static (edge, index) => (edge, index)) + .GroupBy(static pair => pair.edge.From, StringComparer.Ordinal); + + foreach (var group in byFrom) + { + var exits = group + .Select(pair => Exit(pair.edge.When, "edge", pair.edge.To, ValidationPointer.Edge(name, pair.index))) + .ToList(); + + GuardExclusivityCheck.Run( + exits, + ValidationPointer.GraphEdges(name), + $"the node '{group.Key}'", + evaluator, + configuration.State, + new Dictionary(StringComparer.Ordinal), + errors, + warnings); + } + } + + private static SiblingExit Exit(GuardReference? guard, string kind, string target, string pointer) + => new( + DescribeExit(guard, kind, target), + guard is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"), + guard); + + private static string DescribeExit(GuardReference? guard, string kind, string target) + => guard switch + { + null => $"the unconditional {kind} to '{target}'", + { Name: { } name } => $"the guard '{name}'", + _ => $"the inline rule on the {kind} to '{target}'", + }; +} diff --git a/src/AgentCore.Application/Configuration/Validation/GraphReach.cs b/src/AgentCore.Application/Configuration/Validation/GraphReach.cs new file mode 100644 index 00000000..dd291a98 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/GraphReach.cs @@ -0,0 +1,51 @@ +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Configuration.Validation; + +/// Forward adjacency and reachability over a policy or a graph, shared by checks 6 and 7. +internal static class GraphReach +{ + public static Dictionary> BuildAdjacency(GraphConfiguration graph) + { + var forward = new Dictionary>(StringComparer.Ordinal); + foreach (var node in graph.Nodes) + { + forward[node.Id] = []; + } + + foreach (var edge in graph.Edges) + { + if (forward.TryGetValue(edge.From, out var targets)) + { + targets.Add(edge.To); + } + } + + return forward; + } + + /// Every id reachable from , including the root itself. + public static HashSet Reach(string root, Dictionary> edges) + { + var seen = new HashSet(StringComparer.Ordinal) { root }; + var pending = new Stack(); + pending.Push(root); + + while (pending.Count > 0) + { + var current = pending.Pop(); + if (!edges.TryGetValue(current, out var targets)) + { + continue; + } + + foreach (var target in targets.Where(target => !seen.Contains(target))) + { + seen.Add(target); + pending.Push(target); + } + } + + return seen; + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/GraphWellFormednessCheck.cs b/src/AgentCore.Application/Configuration/Validation/GraphWellFormednessCheck.cs new file mode 100644 index 00000000..379829ea --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/GraphWellFormednessCheck.cs @@ -0,0 +1,74 @@ +using System.Globalization; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 7: one start node, no orphan, and a path from every node to an output. +internal static class GraphWellFormednessCheck +{ + public static void Run(AgentCoreConfiguration configuration, List errors) + { + foreach (var (name, entry) in configuration.Entries) + { + if (entry.Graph is { } graph && graph.Nodes.Count > 0) + { + CheckGraph(name, graph, errors); + } + } + } + + private static void CheckGraph(string name, GraphConfiguration graph, List errors) + { + var starts = graph.Nodes.Count(static node => node.Start); + if (starts != 1) + { + errors.Add(WellFormedness( + ValidationPointer.GraphNodes(name), + string.Create(CultureInfo.InvariantCulture, $"the graph in entry '{name}' declares {starts} start nodes, and check 7 needs exactly one"))); + } + + CheckOrphans(name, graph, errors); + + var outputs = graph.Nodes.Where(static node => node.Output).Select(static node => node.Id).ToHashSet(StringComparer.Ordinal); + if (outputs.Count == 0) + { + errors.Add(WellFormedness(ValidationPointer.GraphNodes(name), "the graph declares no output node, so no path reaches an output")); + return; + } + + var forward = GraphReach.BuildAdjacency(graph); + for (var index = 0; index < graph.Nodes.Count; index++) + { + var node = graph.Nodes[index]; + if (!GraphReach.Reach(node.Id, forward).Overlaps(outputs)) + { + errors.Add(WellFormedness( + ValidationPointer.Node(name, index), + $"no path from the node '{node.Id}' reaches an output node")); + } + } + } + + private static void CheckOrphans(string name, GraphConfiguration graph, List errors) + { + var connected = new HashSet(StringComparer.Ordinal); + foreach (var edge in graph.Edges) + { + connected.Add(edge.From); + connected.Add(edge.To); + } + + for (var index = 0; index < graph.Nodes.Count; index++) + { + var node = graph.Nodes[index]; + if (!connected.Contains(node.Id)) + { + errors.Add(WellFormedness( + ValidationPointer.Node(name, index), + $"the node '{node.Id}' is an orphan: no edge reaches it and no edge leaves it")); + } + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/GuardRuleCheck.cs b/src/AgentCore.Application/Configuration/Validation/GuardRuleCheck.cs new file mode 100644 index 00000000..fa9811d0 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/GuardRuleCheck.cs @@ -0,0 +1,97 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 4: guard operators and variables, over every rule the document holds. +internal static class GuardRuleCheck +{ + public static void Run(AgentCoreConfiguration configuration, List errors) + { + foreach (var guard in configuration.Guards) + { + CheckOneRule(configuration, guard.Value, ValidationPointer.Guard(guard.Key), errors); + } + + foreach (var slot in configuration.State) + { + if (slot.Value.Increment is { } increment) + { + CheckOneRule(configuration, increment, ConfigurationError.AppendPointer(ValidationPointer.State(slot.Key), "increment"), errors); + } + } + + foreach (var (name, entry) in configuration.Entries) + { + if (entry.Policy is { } policy) + { + CheckPolicyRules(configuration, name, policy, errors); + } + + if (entry.Graph is { } graph) + { + CheckGraphRules(configuration, name, graph, errors); + } + } + } + + private static void CheckPolicyRules(AgentCoreConfiguration configuration, string name, PolicyConfiguration policy, List errors) + { + for (var index = 0; index < policy.Stages.Count; index++) + { + var stage = policy.Stages[index]; + for (var exit = 0; exit < stage.To.Count; exit++) + { + if (stage.To[exit].When?.Rule is { } rule) + { + CheckOneRule(configuration, rule, ConfigurationError.AppendPointer(ValidationPointer.Transition(name, index, exit), "when"), errors); + } + } + } + } + + private static void CheckGraphRules(AgentCoreConfiguration configuration, string name, GraphConfiguration graph, List errors) + { + for (var index = 0; index < graph.Edges.Count; index++) + { + if (graph.Edges[index].When?.Rule is { } rule) + { + CheckOneRule(configuration, rule, ConfigurationError.AppendPointer(ValidationPointer.Edge(name, index), "when"), errors); + } + } + } + + private static void CheckOneRule(AgentCoreConfiguration configuration, JsonNode rule, string pointer, List errors) + { + var facts = new GuardRuleFacts(); + facts.Collect(rule); + + foreach (var name in facts.Operators.Where(name => !GuardOperators.IsAllowed(name))) + { + errors.Add(Operators(pointer, GuardOperators.DescribeRejection(name))); + } + + if (facts.HasDoubleNegationSugar) + { + errors.Add(Operators(pointer, GuardOperators.DoubleNegationSugarRejection)); + } + + foreach (var slot in facts.Variables.Where(slot => + !configuration.State.ContainsKey(slot) && !ReservedStateSlots.Contains(slot))) + { + errors.Add(Operators(pointer, $"the rule reads the slot '{slot}', and state: does not declare it")); + } + + foreach (var comparison in facts.NumericComparisons) + { + if (configuration.State.TryGetValue(comparison.Value, out var slot) && slot.Type == StateSlotType.Boolean) + { + errors.Add(Operators( + pointer, + $"the operator '{comparison.Key}' compares the slot '{comparison.Value}', and that slot is a boolean rather than a number")); + } + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs b/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs new file mode 100644 index 00000000..8ea49804 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs @@ -0,0 +1,149 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 2, knowledge scope: a state-built scope must not produce a filter nobody meant. +/// +/// These are document checks, not store checks: KnowledgeStartup skips the store factory +/// for a host-supplied port, but the session composes the scope either way. +/// +internal static class KnowledgeScopeCheck +{ + public static void Run(AgentCoreConfiguration configuration, List errors) + { + if (configuration.Providers?.Knowledge?.Scope is not { } scope) + { + return; + } + + KnowledgeFilterValidator.Check(scope, errors); + + if (scope.Wildcard is { } wildcard) + { + CheckWildcardShape(wildcard, errors); + } + + // A wildcard without fromState is a supported shape: the deployment resolves its own facets + // and passes them as the call's scope, which the store still widens. See + // StateKnowledgeScope.Compose and KnowledgeStartup's K19 branch. Only the reverse is refused. + if (scope.FromState.Count == 0) + { + return; + } + + CheckWildcardCoversFromState(scope, errors); + + if (configuration.Extractor is null) + { + errors.Add(Reference( + "/extractor", + "fromState names extractor slots and this document declares no extractor, so no slot " + + "is ever filled and every call searches only what the wildcard admits.")); + } + + foreach (var name in scope.FromState) + { + if (configuration.State.TryGetValue(name, out var slot)) + { + CheckFacetSlot(name, slot, errors); + } + else + { + errors.Add(Reference( + ValidationPointer.FromState, + $"fromState names the slot '{name}', which this document does not declare.")); + } + } + } + + private static void CheckWildcardShape(KnowledgeWildcardConfiguration wildcard, List errors) + { + if (string.IsNullOrWhiteSpace(wildcard.Value)) + { + errors.Add(Reference( + ValidationPointer.WildcardValue, + "the wildcard value is blank, so it names no payload value a card could carry.")); + } + + if (wildcard.Facets.Count == 0) + { + errors.Add(Reference( + ValidationPointer.WildcardFacets, + "the wildcard names no facets, so it widens nothing. Name the reach facets, and " + + "never an isolation facet such as a customer id.")); + } + } + + /// The wildcard facets and the fromState names must be the same set. + private static void CheckWildcardCoversFromState(KnowledgeScopeConfiguration scope, List errors) + { + if (scope.Wildcard is not { } widened) + { + errors.Add(Reference( + ValidationPointer.Wildcard, + "fromState is set and no wildcard is. An unknown slot would then leave its facet out " + + "of the scope, putting no condition on it, and every value of that facet would be " + + "in reach. Declare the wildcard, or drop fromState.")); + return; + } + + foreach (var facet in widened.Facets.Where(facet => !scope.FromState.Contains(facet, StringComparer.Ordinal))) + { + errors.Add(Reference( + ValidationPointer.WildcardFacets, + $"wildcard.facets names '{facet}' and fromState does not. The scope filter only " + + $"ever puts a condition on a fromState facet, so there is no condition on " + + $"'{facet}' for the wildcard to widen.")); + } + + foreach (var name in scope.FromState.Where(name => !widened.Facets.Contains(name, StringComparer.Ordinal))) + { + errors.Add(Reference( + ValidationPointer.WildcardFacets, + $"fromState names '{name}' and wildcard.facets does not, so an unfilled '{name}' " + + "would be searched for the literal wildcard rather than widened by it.")); + } + } + + /// A facet slot is a string enum the extractor fills, with no default. + private static void CheckFacetSlot(string name, StateSlotConfiguration slot, List errors) + { + var pointer = ValidationPointer.State(name); + + if (slot.Default is not null) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(pointer, "default"), + $"the facet slot '{name}' declares a default. An unfilled slot reads as its " + + "default, so every call before the caller says otherwise would be scoped to a " + + "guess, with no error.")); + } + + if (slot.Type != StateSlotType.String) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(pointer, "type"), + $"the facet slot '{name}' is not type string. A facet holds one string value.")); + } + + if (slot.Writer != StateWriter.Extractor) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(pointer, "writer"), + $"the facet slot '{name}' is not written by the extractor. A const slot is filled " + + "before turn 1 and would scope every call to it; a tool slot could change the " + + "scope mid-call.")); + } + + if (slot.EnumValues is not { Count: > 0 }) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(pointer, "enum"), + $"the facet slot '{name}' declares no enum. Nothing would then stop a value the " + + "corpus has never been tagged with, which the wildcard turns into an answer " + + "from the wrong bucket rather than an empty result.")); + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/McpCheck.cs b/src/AgentCore.Application/Configuration/Validation/McpCheck.cs new file mode 100644 index 00000000..34b1c336 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/McpCheck.cs @@ -0,0 +1,71 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 2 over the mcp: list: unique ids, and no secret where it would leak. +internal static class McpCheck +{ + /// + /// Refuses a duplicate id. A duplicate connects twice and its collision surfaces only at boot, + /// naming the served tool id rather than the mcp: entry that caused it. This runs before any + /// connection opens, so it costs nothing to check here. + /// + public static void ServerIds(AgentCoreConfiguration configuration, List errors) + { + var seen = new HashSet(StringComparer.Ordinal); + for (var index = 0; index < configuration.Mcp.Count; index++) + { + var server = configuration.Mcp[index]; + if (!seen.Add(server.Id)) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(ValidationPointer.Mcp(index), "id"), + $"two mcp: entries declare the id '{server.Id}'. An id names one server, so rename " + + "one of them.")); + } + } + } + + /// + /// Refuses a secret reference in command: or url:. command: becomes the child's + /// argv, which every user on the box can read out of ps, and url: is logged by proxies and + /// reverse proxies along the way. Neither is a SecretTemplate, so a reference written there + /// would be passed through as its literal characters and would leak while not even working. + /// The schema cannot express "this string may not hold that substring", so it is checked here. + /// + public static void SecretPlacement(AgentCoreConfiguration configuration, List errors) + { + for (var index = 0; index < configuration.Mcp.Count; index++) + { + var server = configuration.Mcp[index]; + + for (var word = 0; word < server.Command.Count; word++) + { + if (!server.Command[word].Contains(SecretReference.Prefix, StringComparison.Ordinal)) + { + continue; + } + + errors.Add(Reference( + ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer(ValidationPointer.Mcp(index), "command"), word), + $"the mcp: server '{server.Id}' writes a ${{secret:...}} reference in command:. A " + + "command becomes the child process's argv, which every user on this machine can " + + "read out of ps, and nothing resolves a reference there — it would be passed " + + "through as its own characters. Put the credential in env: instead.")); + } + + if (server.Url is { } url && url.Contains(SecretReference.Prefix, StringComparison.Ordinal)) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(ValidationPointer.Mcp(index), "url"), + $"the mcp: server '{server.Id}' writes a ${{secret:...}} reference in url:. A URL is " + + "logged by every proxy it passes, and nothing resolves a reference there — it " + + "would be passed through as its own characters. Put the credential in headers: " + + "instead.")); + } + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/ReachabilityCheck.cs b/src/AgentCore.Application/Configuration/Validation/ReachabilityCheck.cs new file mode 100644 index 00000000..adee7866 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/ReachabilityCheck.cs @@ -0,0 +1,76 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 6: every stage is reachable from the initial stage, and every node from the start node. +internal static class ReachabilityCheck +{ + public static void Run(AgentCoreConfiguration configuration, List errors) + { + foreach (var (name, entry) in configuration.Entries) + { + if (entry.Policy is { } policy) + { + CheckPolicy(name, policy, errors); + } + + if (entry.Graph is { } graph && graph.Nodes.Count > 0) + { + CheckGraph(name, graph, errors); + } + } + } + + private static void CheckPolicy(string name, PolicyConfiguration policy, List errors) + { + var edges = new Dictionary>(StringComparer.Ordinal); + foreach (var stage in policy.Stages) + { + edges[stage.Id] = [.. stage.To.Select(static transition => transition.Stage)]; + } + + var reachable = GraphReach.Reach(policy.Initial, edges); + + for (var index = 0; index < policy.Stages.Count; index++) + { + var stage = policy.Stages[index]; + if (!reachable.Contains(stage.Id)) + { + errors.Add(Reachability( + ValidationPointer.Stage(name, index), + $"the stage '{stage.Id}' is unreachable from the initial stage '{policy.Initial}' in entry '{name}'")); + } + + if (!stage.Terminal && stage.To.Count == 0) + { + errors.Add(Reachability( + ValidationPointer.Stage(name, index), + $"the stage '{stage.Id}' is not terminal and has no exit")); + } + } + } + + // A graph with zero or several start nodes is refused by check 7, so this check stays silent on it. + private static void CheckGraph(string name, GraphConfiguration graph, List errors) + { + var starts = graph.Nodes.Where(static node => node.Start).Select(static node => node.Id).ToList(); + if (starts.Count != 1) + { + return; + } + + var live = GraphReach.Reach(starts[0], GraphReach.BuildAdjacency(graph)); + + for (var index = 0; index < graph.Nodes.Count; index++) + { + if (!live.Contains(graph.Nodes[index].Id)) + { + errors.Add(Reachability( + ValidationPointer.Node(name, index), + $"the node '{graph.Nodes[index].Id}' is unreachable from the start node '{starts[0]}' in entry '{name}'")); + } + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/ReferenceCheck.cs b/src/AgentCore.Application/Configuration/Validation/ReferenceCheck.cs new file mode 100644 index 00000000..cb8afaec --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/ReferenceCheck.cs @@ -0,0 +1,174 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// +/// Check 2, reference resolution: every agent, model, guard, stage, and node a document names is +/// one it declares. Tool ids are the other half, in . +/// +internal static class ReferenceCheck +{ + public static void Run(AgentCoreConfiguration configuration, DeclaredNames names, List errors) + { + CheckAgentTools(configuration.Tools, names, errors); + CheckTopLevelModels(configuration, names, errors); + CheckAgents(configuration.Agents, names, errors); + + foreach (var (name, entry) in configuration.Entries) + { + if (entry.Policy is { } policy) + { + CheckPolicy(name, policy, names, errors); + } + + if (entry.Graph is { } graph) + { + CheckGraph(name, graph, names, errors); + } + } + } + + // A kind: agent tool names the agent it runs, and that name resolves whether or not any agent + // lists the tool. The compiler catches only the listed case, and only after the load passes. + private static void CheckAgentTools(IReadOnlyList tools, DeclaredNames names, List errors) + { + for (var index = 0; index < tools.Count; index++) + { + var tool = tools[index]; + if (tool.Kind == ToolKind.Agent && tool.Agent is { } target) + { + AddUnknownAgent(target, ConfigurationError.AppendPointer(ValidationPointer.Tool(index), ValidationPointer.AgentField), names, errors); + } + } + } + + private static void CheckTopLevelModels(AgentCoreConfiguration configuration, DeclaredNames names, List errors) + { + AddUnknownModel(configuration.Extractor?.Model, "/extractor/model/ref", names, errors); + AddUnknownModel(configuration.Evaluation?.Judge, "/evaluation/judge/ref", names, errors); + AddUnknownModel(configuration.Titler?.Model, "/titler/model/ref", names, errors); + AddUnknownModel(configuration.Agents.Defaults?.Model, "/agents/defaults/model/ref", names, errors); + } + + private static void CheckAgents(AgentsConfiguration agents, DeclaredNames names, List errors) + { + var items = agents.Items; + for (var index = 0; index < items.Count; index++) + { + var agent = items[index]; + var pointer = ValidationPointer.Agent(index); + + AddUnknownModel( + agent.Model, + ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "model"), "ref"), + names, + errors); + + for (var child = 0; child < agent.Background.Count; child++) + { + AddUnknownAgent( + agent.Background[child], + ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "background"), child), + names, + errors); + } + } + } + + private static void CheckPolicy(string name, PolicyConfiguration policy, DeclaredNames names, List errors) + { + var stages = names.Stages[name]; + + AddUnknownStage(name, policy.Initial, ConfigurationError.AppendPointer(ValidationPointer.Policy(name), "initial"), stages, errors); + + for (var index = 0; index < policy.Stages.Count; index++) + { + var stage = policy.Stages[index]; + + if (stage.Agent is { } agentId) + { + AddUnknownAgent(agentId, ConfigurationError.AppendPointer(ValidationPointer.Stage(name, index), ValidationPointer.AgentField), names, errors); + } + + for (var exit = 0; exit < stage.To.Count; exit++) + { + var transition = stage.To[exit]; + var pointer = ValidationPointer.Transition(name, index, exit); + + AddUnknownStage(name, transition.Stage, ConfigurationError.AppendPointer(pointer, "stage"), stages, errors); + AddUnknownGuard(transition.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors); + } + } + } + + private static void CheckGraph(string name, GraphConfiguration graph, DeclaredNames names, List errors) + { + var nodes = names.Nodes[name]; + + for (var index = 0; index < graph.Agents.Count; index++) + { + AddUnknownAgent(graph.Agents[index], ConfigurationError.AppendPointer(ValidationPointer.GraphAgents(name), index), names, errors); + } + + for (var index = 0; index < graph.Nodes.Count; index++) + { + if (graph.Nodes[index].Agent is { } nodeAgent) + { + AddUnknownAgent(nodeAgent, ConfigurationError.AppendPointer(ValidationPointer.Node(name, index), ValidationPointer.AgentField), names, errors); + } + } + + for (var index = 0; index < graph.Edges.Count; index++) + { + var edge = graph.Edges[index]; + var pointer = ValidationPointer.Edge(name, index); + + AddUnknownNode(name, edge.From, ConfigurationError.AppendPointer(pointer, "from"), nodes, errors); + AddUnknownNode(name, edge.To, ConfigurationError.AppendPointer(pointer, "to"), nodes, errors); + AddUnknownGuard(edge.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors); + } + } + + private static void AddUnknownAgent(string agentId, string pointer, DeclaredNames names, List errors) + { + if (!names.Agents.Contains(agentId)) + { + errors.Add(Reference(pointer, $"the agent '{agentId}' is not declared in agents.items")); + } + } + + private static void AddUnknownStage(string entry, string stage, string pointer, HashSet stages, List errors) + { + if (!stages.Contains(stage)) + { + errors.Add(Reference(pointer, $"the stage '{stage}' is not declared in policy.stages in entry '{entry}'")); + } + } + + private static void AddUnknownNode(string entry, string node, string pointer, HashSet nodes, List errors) + { + if (!nodes.Contains(node)) + { + errors.Add(Reference(pointer, $"the node '{node}' is not declared in graph.nodes in entry '{entry}'")); + } + } + + private static void AddUnknownGuard(GuardReference? guard, string pointer, DeclaredNames names, List errors) + { + if (guard?.Name is { } name && !names.Guards.Contains(name)) + { + errors.Add(Reference(pointer, $"the guard '{name}' is not declared in guards:")); + } + } + + /// Resolves one model reference against the as: names of providers.llm. + private static void AddUnknownModel(ModelReference? model, string pointer, DeclaredNames names, List errors) + { + if (model is { } reference && !names.Models.Contains(reference.Ref)) + { + errors.Add(Reference(pointer, $"the model '{reference.Ref}' is not declared in providers.llm")); + } + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs b/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs new file mode 100644 index 00000000..105c72e5 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs @@ -0,0 +1,105 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using Microsoft.Agents.AI; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// +/// Check 2, tool ids and skill names: the references only a registry or a bound folder can satisfy. +/// Decision 15 keeps these apart from because an MCP server's +/// discovery is the only thing that can satisfy a tool reference, so this half has to wait for it. +/// +internal static class ServedReferenceCheck +{ + /// Resolves every from: state slot and every agent's tools: entry against what is served. + public static void Tools(AgentCoreConfiguration configuration, IReadOnlySet servedToolIds, List errors) + { + foreach (var slot in configuration.State) + { + if (slot.Value.From is { } from && !servedToolIds.Contains(from.ToolId)) + { + errors.Add(Reference( + ConfigurationError.AppendPointer(ValidationPointer.State(slot.Key), "from"), + UnservedTool(from.ToolId))); + } + } + + var items = configuration.Agents.Items; + for (var index = 0; index < items.Count; index++) + { + var agent = items[index]; + for (var slot = 0; slot < agent.Tools.Count; slot++) + { + if (!servedToolIds.Contains(agent.Tools[slot])) + { + errors.Add(Reference(ValidationPointer.AgentTool(index, slot), UnservedTool(agent.Tools[slot]))); + } + } + } + } + + /// Resolves every agent's skills: entry against what the bound folder serves. + public static void Skills(AgentCoreConfiguration configuration, IReadOnlySet servedSkillNames, List errors) + { + var served = string.Join(", ", servedSkillNames.Order(StringComparer.Ordinal)); + var items = configuration.Agents.Items; + + for (var index = 0; index < items.Count; index++) + { + var agent = items[index]; + + for (var slot = 0; slot < agent.Skills.Count; slot++) + { + if (servedSkillNames.Contains(agent.Skills[slot])) + { + continue; + } + + errors.Add(Reference( + ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer(ValidationPointer.Agent(index), "skills"), slot), + $"the skill '{agent.Skills[slot]}' is not in the bound skills folder. " + + $"The folder serves: {served}.")); + } + } + } + + /// + /// Refuses a declared tool id that the skills provider registers under the same name. The + /// provider's tools are added per agent and never pass through the tool registry, so a + /// collision is invisible until the model receives two tools of one name. + /// + public static void SkillToolNames(AgentCoreConfiguration configuration, List errors) + { + var items = configuration.Agents.Items; + if (!items.Any(agent => agent.Skills.Count > 0)) + { + return; + } + + string[] reserved = + [ + AgentSkillsProvider.LoadSkillToolName, + AgentSkillsProvider.ReadSkillResourceToolName, + AgentSkillsProvider.RunSkillScriptToolName, + ]; + + var tools = configuration.Tools; + for (var index = 0; index < tools.Count; index++) + { + if (!reserved.Contains(tools[index].Id, StringComparer.Ordinal)) + { + continue; + } + + errors.Add(Reference( + ConfigurationError.AppendPointer(ValidationPointer.Tool(index), "id"), + $"the tool id '{tools[index].Id}' is reserved while any agent declares a skills: " + + "list, because the skills provider registers a tool of that name. Rename the tool.")); + } + } + + private static string UnservedTool(string toolId) + => $"nothing serves the tool '{toolId}'. Declare it in tools:, or check that an mcp: server offers it."; +} diff --git a/src/AgentCore.Application/Configuration/Validation/SlotWriterCheck.cs b/src/AgentCore.Application/Configuration/Validation/SlotWriterCheck.cs new file mode 100644 index 00000000..4aacb33a --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/SlotWriterCheck.cs @@ -0,0 +1,74 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using static AgentCore.Application.Configuration.Validation.ValidationErrors; + +namespace AgentCore.Application.Configuration.Validation; + +/// Check 3: one writer for each slot. +internal static class SlotWriterCheck +{ + /// The increment: field of a counter slot. Named once, so the check and the two maps under it cannot drift apart. + private const string IncrementField = "increment"; + + public static void Run(AgentCoreConfiguration configuration, List errors) + { + foreach (var entry in configuration.State) + { + var pointer = ValidationPointer.State(entry.Key); + var slot = entry.Value; + + if (ReservedStateSlots.Contains(entry.Key)) + { + errors.Add(Writers( + pointer, + $"the slot has two writers: '{entry.Key}' is a reserved read-only slot that is always present, and state: declares it again")); + } + + var owner = OwnerField(slot.Writer); + if (owner is not null && FieldValue(slot, owner) is null) + { + errors.Add(Writers( + pointer, + $"the slot has zero writers: writer: {WriterName(slot.Writer)} fills the slot from '{owner}:', and the slot declares none")); + } + + foreach (var field in new[] { "from", IncrementField, "value" }) + { + if (string.Equals(field, owner, StringComparison.Ordinal) || FieldValue(slot, field) is null) + { + continue; + } + + errors.Add(Writers( + ConfigurationError.AppendPointer(pointer, field), + $"the slot has two writers: writer: {WriterName(slot.Writer)} owns it, and '{field}:' names a second")); + } + } + } + + private static string? OwnerField(StateWriter writer) + => writer switch + { + StateWriter.Tool => "from", + StateWriter.Counter => IncrementField, + StateWriter.Const => "value", + _ => null, + }; + + private static string WriterName(StateWriter writer) + => writer switch + { + StateWriter.Tool => "tool", + StateWriter.Counter => "counter", + StateWriter.Const => "const", + _ => "extractor", + }; + + private static object? FieldValue(StateSlotConfiguration slot, string field) + => field switch + { + "from" => slot.From, + IncrementField => slot.Increment, + _ => slot.Value, + }; +} diff --git a/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs b/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs new file mode 100644 index 00000000..8554cc68 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs @@ -0,0 +1,70 @@ +using System.Globalization; +using AgentCore.Application.Configuration.Parsing; + +namespace AgentCore.Application.Configuration.Validation; + +/// Builds a tagged with the check that found it. +internal static class ValidationErrors +{ + /// + /// The longest interval, in seconds, that every timer these values reach will accept. + /// CancellationTokenSource.CancelAfter, Task.WaitAsync and PeriodicTimer each + /// throw above milliseconds, from a call site that carries no pointer + /// into the document. + /// + public const int MaxIntervalSeconds = int.MaxValue / 1000; + + public static ConfigurationError Reference(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.ReferenceResolution }; + + public static ConfigurationError Range(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.ValueRange }; + + public static ConfigurationError Writers(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.SlotWriters }; + + public static ConfigurationError Operators(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.GuardOperators }; + + public static ConfigurationError Reachability(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.Reachability }; + + public static ConfigurationError WellFormedness(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.GraphWellFormedness }; + + /// Refuses a count or an interval that falls outside the range the runtime accepts. + /// The configured value. + /// The lowest accepted value, inclusive. + /// The highest accepted value, inclusive. means no ceiling. + /// The pointer at the field itself. + /// How the message names the field, as a noun phrase. + /// One or more sentences saying what the range protects. + /// Collects the refusal. + /// + /// Both bounds go through one call so a field cannot be given a floor and left without a ceiling: + /// every ceiling here stands between a document and a raw throw out of a timer at boot or mid-turn. + /// + public static void CheckRange( + int value, + int min, + int max, + string pointer, + string subject, + string why, + List errors) + { + if (value >= min && value <= max) + { + return; + } + + var accepted = max == int.MaxValue + ? $"the lowest accepted value is {min.ToString(CultureInfo.InvariantCulture)}" + : $"the accepted range is {min.ToString(CultureInfo.InvariantCulture)} to " + + max.ToString(CultureInfo.InvariantCulture); + + errors.Add(Range( + pointer, + $"{subject} is {value.ToString(CultureInfo.InvariantCulture)}, and {accepted}. {why}")); + } +} diff --git a/src/AgentCore.Application/Configuration/Validation/ValidationPointer.cs b/src/AgentCore.Application/Configuration/Validation/ValidationPointer.cs new file mode 100644 index 00000000..a1601c17 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/ValidationPointer.cs @@ -0,0 +1,56 @@ +using AgentCore.Application.Configuration.Parsing; +namespace AgentCore.Application.Configuration.Validation; + +/// JSON pointers into the bound document, shared by every check of section 8.5. +internal static class ValidationPointer +{ + public const string Wildcard = "/providers/knowledge/scope/wildcard"; + + public const string WildcardValue = Wildcard + "/value"; + + public const string WildcardFacets = Wildcard + "/facets"; + + public const string FromState = "/providers/knowledge/scope/fromState"; + + public const string Ambiguity = "/providers/knowledge/ambiguity"; + + public const string Mapper = "/providers/knowledge/mapper"; + + /// The agent: field an entry, tool, stage, or node points at. + public const string AgentField = "agent"; + + public static string State(string slot) => ConfigurationError.AppendPointer("/state", slot); + + public static string Guard(string name) => ConfigurationError.AppendPointer("/guards", name); + + public static string Agent(int index) => ConfigurationError.AppendPointer("/agents/items", index); + + public static string AgentTool(int agent, int slot) + => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Agent(agent), "tools"), slot); + + public static string Tool(int index) => ConfigurationError.AppendPointer("/tools", index); + + public static string Mcp(int index) => ConfigurationError.AppendPointer("/mcp", index); + + public static string Entry(string name) => ConfigurationError.AppendPointer("/entries", name); + + public static string Policy(string name) => ConfigurationError.AppendPointer(Entry(name), "policy"); + + public static string Graph(string name) => ConfigurationError.AppendPointer(Entry(name), "graph"); + + public static string GraphAgents(string name) => ConfigurationError.AppendPointer(Graph(name), "agents"); + + public static string GraphNodes(string name) => ConfigurationError.AppendPointer(Graph(name), "nodes"); + + public static string GraphEdges(string name) => ConfigurationError.AppendPointer(Graph(name), "edges"); + + public static string Stage(string name, int index) + => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Policy(name), "stages"), index); + + public static string Transition(string name, int stage, int exit) + => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Stage(name, stage), "to"), exit); + + public static string Node(string name, int index) => ConfigurationError.AppendPointer(GraphNodes(name), index); + + public static string Edge(string name, int index) => ConfigurationError.AppendPointer(GraphEdges(name), index); +} From 0310271ec87021f4fe05910480e0202732428644 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 15:58:27 -0600 Subject: [PATCH 10/35] feat: implement CallTurnCommit and related transcript handling classes --- .../Runtime/CallSession/CallTurnCommit.cs | 130 +++++++ .../Runtime/CallSession/CallTurnCompletion.cs | 321 +++++++----------- .../Runtime/CallSession/ReplyOutcome.cs | 18 + .../Runtime/CallSession/TranscriptEntry.cs | 8 + 4 files changed, 286 insertions(+), 191 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/ReplyOutcome.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/TranscriptEntry.cs diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs new file mode 100644 index 00000000..796dbf0b --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs @@ -0,0 +1,130 @@ +using AgentCore.Domain; +using AgentCore.Domain.Audit; + +namespace AgentCore.Application.Runtime; + +/// +/// The publish half of a turn: appends the transcript, writes the turn's events, and tears the +/// call down when it is over. decides the turn; this commits it. +/// +internal sealed class CallTurnCommit +{ + private readonly CallSession _session; + + internal CallTurnCommit(CallSession session) + { + ArgumentNullException.ThrowIfNull(session); + _session = session; + } + + // One lock, one moment. A late barge-in reads all four of these together, so a window in + // which LastTurn already names this turn while the span or the ordinal still names the one + // before it would let an amendment rewrite the wrong part of the transcript. + internal TurnResult Publish(CallTurn turn, ReplyOutcome outcome, TranscriptEntry addition, TurnResult result, CallInterruptionTracker.Interruption? interruption) + { + lock (_session.InterruptLock) + { + // What the caller said and what the caller heard, written together. + if (_session.SessionCarriesHistory) + { + _session.LastReplyMessageId = _session.History.AppendTurn( + turn.Session, [turn.Spoken, .. addition.Written], _session.Snapshot(), turn.MessageId); + } + else + { + // Rows 3 and 4 answer with one reply per node, and the caller hears one of them. + // Store 1 holds the caller-facing turn alone, so the deliberation that produced the + // answer never enters the record and never reaches a later turn. + _session.LastReplyMessageId = _session.History.AppendCallerFacingTurn( + turn.Session, turn.Spoken, addition.Heard, _session.Snapshot(), turn.MessageId); + } + + // Only now. The chain stores a hash of the spoken text and store 1 stores the text, so a + // reply.interrupted raised before the append would name a hash of words nothing holds. + var completedEventId = _session.Events.WriteTurnEvents( + turn.Index, + result.EndedAt, + turn.StageBefore, + result.StageAfter, + outcome.Reply, + outcome.SpokenReply, + outcome.ToolFault, + outcome.InterruptedAfter); + + // A turn one barge-in already cut is not amendable again, so it is not published here. + _session.AmendableEventId = outcome.InterruptedAfter is null ? completedEventId : null; + _session.LastTurn = result; + + // The second read. The first one happened before the extractor await, and that await is + // bounded only by TurnCompletionTimeout, so a barge-in has five whole seconds in which + // to land after this turn already decided it was not interrupted. On a streaming turn it + // finds _runCancellation still set and the run still audible, because EndRun does not + // run until this method has returned, so it takes the in-flight path, cancels a run that + // has already stopped, and answers true — and true, on the contract of Interrupt, means + // the barge-in is recorded. (A turn that never streamed was never audible, so its frame + // already took the amendment path against the turn before this one and never lands + // here.) Nothing recorded the streaming frame. Reading _interruption again here, one + // statement after _amendable and LastTurn were published, hands that frame to the very + // path a frame arriving one instant later would have taken: the tested amendment, which + // writes the TurnCompleted then ReplyInterrupted pair T23 asks for. The _amendableEventId + // guard above already fits: it is published exactly when interruptedAfter is null, which + // is the only state this window can be reached in. + if (interruption is null + && _session.Interruption is { } late + && _session.Interruptions.AmendLastTurn(late) + && _session.LastTurn is { } amended) + { + // The amendment republished LastTurn, so the turn this method returns and the + // duration the telemetry reads must both come from it and not from the record + // built before the frame landed. + result = amended; + } + + // Consumed, on whichever path recorded it: the in-flight read at the top of the turn + // fed WriteTurnEvents, and the amendment above wrote its own pair. Nothing downstream + // may handle one frame twice. + _session.Interruption = null; + + // The turn is committed, so the run is no longer what the caller is hearing. This is the + // tail of the same defect the read above fixes: a barge-in landing between this lock and + // EndRun would otherwise still find the run audible, take the in-flight path, and be + // recorded nowhere at all. Cleared here, under the lock that just published LastTurn, it + // reaches AmendLastTurn against this turn instead. EndRun still runs and still owns + // disposing the source; clearing the field twice costs nothing. + _session.RunCancellation = null; + _session.Interruptions.RunIsAudible = false; + } + + return result; + } + + internal async Task EndCallIfOverAsync(DateTimeOffset endedAt, string stageAfter) + { + if (_session.IsComplete) + { + // The machine reached a terminal stage, so the call is over and the chain closes here. + // The stage rides as detail, because the reason a report counts is the same one for + // every terminal stage the document declares. + _session.Events.EndCall(CallEndReason.AgentCompleted, endedAt, stageAfter); + } + + if (!_session.IsComplete && !_session.Events.HasEnded) + { + return; + } + + // Children before shells: a cancelled child may be inside a shell tool the next line + // tears down. + await _session.Lifetime.ReleaseBackgroundSessionsAsync().ConfigureAwait(false); + + // Shells first: a Docker executor's bind mount is this workspace, and it must not be + // deleted out from under a still-live container. + await _session.Lifetime.DisposeShellsAsync().ConfigureAwait(false); + + // A tool running mid-turn (a file_memory_write, say) can call EndCall itself, which + // deletes the workspace and then IsComplete overwrites the flag when the policy also + // reaches a terminal stage. _events.HasEnded survives that overwrite, so the folder a + // tool recreated after the mid-turn delete is still cleaned up here. + _session.Lifetime.DeleteWorkspace(); + } +} diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs index 499e77da..a962b6ca 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs @@ -11,11 +11,13 @@ namespace AgentCore.Application.Runtime; internal sealed class CallTurnCompletion { private readonly CallSession _session; + private readonly CallTurnCommit _commit; internal CallTurnCompletion(CallSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; + _commit = new CallTurnCommit(session); } /// Runs every writer, then lets the machine pick the stage of the next turn. @@ -61,6 +63,78 @@ internal async Task CompleteTurnAsync( var refused = disposition?.Moderation is ModerationOutcome.Flagged; _session.Events.RaiseModeration(turn.Index, disposition); + var outcome = ResolveReply(turn, response, interruption, disposition, toolFault); + var addition = TranscriptAddition(response, outcome); + + // The per-turn writers run from here, in the order the constructor documents: tool results + // first. + _session.Writers.ApplyToolResults(response.Messages); + + // A refused turn runs no extractor. The words moderation flagged are the extractor's only + // input, so a slot filled from them would carry the flagged content into the state document + // and into every later prompt. The refusal itself says nothing worth extracting either, and + // the extractor costs a model call, so this also spends nothing on a turn nobody answered. + // A pending turn runs none either: the run suspended instead of answering, so there is + // nothing decided to read. + var extractionFailure = refused || outcome.Approvals.Count > 0 + ? null + : await ExtractAsync(turn, response, cancellationToken).ConfigureAwait(false); + + // The clock fields write next. The clock comes from the injected provider, so a test owns + // it. The same read stamps every audit event of this turn. + var endedAt = _session.Time.GetUtcNow(); + _session.State.TurnIndex++; + _session.State.CallDurationSeconds = (endedAt - _session.StartedAt).TotalSeconds; + + // The counters write last. + _session.Counters.Apply(_session.State); + + var stageAfter = AdvanceStage(turn); + + TurnResult result = new( + _session.CallId, + turn.Index, + turn.StageBefore, + stageAfter, + outcome.Reply, + _session.IsComplete, + extractionFailure, + outcome.Failure, + outcome.InterruptedAfter, + endedAt) + { + Approvals = outcome.Approvals, + }; + + // A graph row that reuses its session persists it here, before the commit below reads + // it into store 0: the next turn resumes from these checkpoints, and a resumed call + // rebuilds them. Rows 1 and 2 need nothing — their session outlives the call. + if (_session.ReusesGraphSession && _session.GraphSession is { } shared) + { + _session.GraphBlob = await turn.Agent.SerializeSessionAsync(shared, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + result = _commit.Publish(turn, outcome, addition, result, interruption); + + AgentCoreTelemetry.EndTurn( + turn.Activity, + _session.Time.GetElapsedTime(turn.StartedAt), + Outcome(result.Failure, result.InterruptedAfter), + stageAfter, + result.Failure); + + await _commit.EndCallIfOverAsync(endedAt, stageAfter).ConfigureAwait(false); + + return result; + } + + private ReplyOutcome ResolveReply( + CallTurn turn, + AgentResponse response, + CallInterruptionTracker.Interruption? interruption, + TurnDisposition? disposition, + string? toolFault) + { // R1 reaches the turn through the fallback layer, and a fault above every chat client — a // graph that matched no edge — still reaches the catch in the run methods. Both are the // same row-six fact. @@ -69,13 +143,10 @@ internal async Task CompleteTurnAsync( : null; var reply = SpokenReply.From(response.Messages); - var spokenReply = reply; - TimeSpan? interruptedAfter = null; - string? failure = toolFault is null ? null : CallSession.ToolFailureReason + " " + toolFault; - + // The tool calls still waiting on a human answer. A pending turn is not a failure: the // run suspended instead of answering, so the empty-reply substitution below is skipped, // the extractor has nothing decided to read, and the requests ride TurnResult to the host. @@ -110,66 +181,63 @@ internal async Task CompleteTurnAsync( _session.Events.RaiseDiagnostic(CallEventKind.EmptyReply, _session.Time.GetUtcNow(), turn.Index); } - // What this turn adds to the transcript. It is built here and written at the end of the - // method, in one lock with the rest of what a late barge-in may still amend: the transcript - // span, the ordinal the amendment must reference, and LastTurn itself. Nothing between here - // and there reads the transcript — the extractor reads the finished turn, and the writers - // read the state document — so building it now and committing it once costs nothing. + return new ReplyOutcome(reply, spokenReply, failure, toolFault, interruptedAfter, approvals); + } + + // Built before the writers run and committed at the end of the turn, in one lock with the rest + // of what a late barge-in may still amend: the transcript span, the ordinal the amendment must + // reference, and LastTurn itself. Nothing in between reads the transcript — the extractor reads + // the finished turn, and the writers read the state document — so building it early and + // committing it once costs nothing. + private TranscriptEntry TranscriptAddition(AgentResponse response, ReplyOutcome outcome) + { // A barge-in inside the first 100 ms leaves no heard text, and an empty assistant message // teaches the model nothing. pipecat and livekit both guard this. Both row shapes read this // one value, so what counts as words the caller heard is decided once. - var heard = reply.Length > 0 ? new ChatMessage(ChatRole.Assistant, reply) : null; + var heard = outcome.Reply.Length > 0 ? new ChatMessage(ChatRole.Assistant, outcome.Reply) : null; // Rows 3 and 4 record the caller-facing turn alone, so `written` stays empty for them: a // node's tool pair and a node's line to the next node are neither said nor heard, and the - // commit below takes the heard reply straight. - List written = []; - if (_session.SessionCarriesHistory) + // commit takes the heard reply straight. + if (!_session.SessionCarriesHistory) { - if (interruptedAfter is not null || failure is not null) - { - // The transcript holds what the caller heard. A run that stopped mid-round would - // otherwise leave a tool call with no result behind, and the next turn would send - // it. So the pairs that finished are kept and only an unpaired call is dropped: a - // side effect that ran must stay visible to the next turn. livekit/agents fixed the - // same defect in issue 3702. - written = [.. TurnMessages.FinishedToolMessages(response.Messages)]; - - if (heard is not null) - { - written.Add(heard); - } - } - else - { - written = [.. response.Messages]; - } + return new TranscriptEntry(heard, []); } - // The per-turn writers run from here, in the order the constructor documents: tool results - // first. - _session.Writers.ApplyToolResults(response.Messages); + if (outcome.InterruptedAfter is null && outcome.Failure is null) + { + return new TranscriptEntry(heard, [.. response.Messages]); + } - // The extractor writes next. Its deadline is here and not on the whole method, because the - // raise of the turn's events and the stage advance must always run. - string? extractionFailure = null; + // The transcript holds what the caller heard. A run that stopped mid-round would + // otherwise leave a tool call with no result behind, and the next turn would send + // it. So the pairs that finished are kept and only an unpaired call is dropped: a + // side effect that ran must stay visible to the next turn. livekit/agents fixed the + // same defect in issue 3702. + List written = [.. TurnMessages.FinishedToolMessages(response.Messages)]; + if (heard is not null) + { + written.Add(heard); + } - // A refused turn runs no extractor. The words moderation flagged are the extractor's only - // input, so a slot filled from them would carry the flagged content into the state document - // and into every later prompt. The refusal itself says nothing worth extracting either, and - // the extractor costs a model call, so this also spends nothing on a turn nobody answered. - if (!refused && approvals.Count == 0) + return new TranscriptEntry(heard, written); + } + + // The extractor's deadline is here and not on the whole turn, because the raise of the turn's + // events and the stage advance must always run. + private async Task ExtractAsync(CallTurn turn, AgentResponse response, CancellationToken cancellationToken) + { + string? extractionFailure; + + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(CallSession.TurnCompletionTimeout); + try { - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - deadline.CancelAfter(CallSession.TurnCompletionTimeout); - try - { - extractionFailure = await _session.Writers.ExtractAsync(turn, response, deadline.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) - { - extractionFailure = CallSession.ExtractionTimedOutReason; - } + extractionFailure = await _session.Writers.ExtractAsync(turn, response, deadline.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + extractionFailure = CallSession.ExtractionTimedOutReason; } if (extractionFailure is not null) @@ -187,149 +255,20 @@ internal async Task CompleteTurnAsync( }); } - // The clock fields write next. The clock comes from the injected provider, so a test owns - // it. The same read stamps every audit event of this turn. - var endedAt = _session.Time.GetUtcNow(); - _session.State.TurnIndex++; - _session.State.CallDurationSeconds = (endedAt - _session.StartedAt).TotalSeconds; - - // The counters write last. - _session.Counters.Apply(_session.State); - - var stageAfter = turn.StageBefore; - if (_session.Policy is not null) - { - stageAfter = _session.Policy.Advance(_session.State.Snapshot()); - _session.State.Stage = stageAfter; - _session.IsComplete = _session.Policy.IsTerminal; - } - - TurnResult result = new( - _session.CallId, - turn.Index, - turn.StageBefore, - stageAfter, - reply, - _session.IsComplete, - extractionFailure, - failure, - interruptedAfter, - endedAt) - { - Approvals = approvals, - }; - - // A graph row that reuses its session persists it here, before the commit below reads - // it into store 0: the next turn resumes from these checkpoints, and a resumed call - // rebuilds them. Rows 1 and 2 need nothing — their session outlives the call. - if (_session.ReusesGraphSession && _session.GraphSession is { } shared) - { - _session.GraphBlob = await turn.Agent.SerializeSessionAsync(shared, cancellationToken: cancellationToken).ConfigureAwait(false); - } - - // One lock, one moment. A late barge-in reads all four of these together, so a window in - // which LastTurn already names this turn while the span or the ordinal still names the one - // before it would let an amendment rewrite the wrong part of the transcript. - lock (_session.InterruptLock) - { - // What the caller said and what the caller heard, written together. - if (_session.SessionCarriesHistory) - { - _session.LastReplyMessageId = _session.History.AppendTurn( - turn.Session, [turn.Spoken, .. written], _session.Snapshot(), turn.MessageId); - } - else - { - // Rows 3 and 4 answer with one reply per node, and the caller hears one of them. - // Store 1 holds the caller-facing turn alone, so the deliberation that produced the - // answer never enters the record and never reaches a later turn. - _session.LastReplyMessageId = _session.History.AppendCallerFacingTurn( - turn.Session, turn.Spoken, heard, _session.Snapshot(), turn.MessageId); - } - - // Only now. The chain stores a hash of the spoken text and store 1 stores the text, so a - // reply.interrupted raised before the append would name a hash of words nothing holds. - var completedEventId = _session.Events.WriteTurnEvents( - turn.Index, endedAt, turn.StageBefore, stageAfter, reply, spokenReply, toolFault, interruptedAfter); - - // A turn one barge-in already cut is not amendable again, so it is not published here. - _session.AmendableEventId = interruptedAfter is null ? completedEventId : null; - _session.LastTurn = result; - - // The second read. The first one happened before the extractor await, and that await is - // bounded only by TurnCompletionTimeout, so a barge-in has five whole seconds in which - // to land after this turn already decided it was not interrupted. On a streaming turn it - // finds _runCancellation still set and the run still audible, because EndRun does not - // run until this method has returned, so it takes the in-flight path, cancels a run that - // has already stopped, and answers true — and true, on the contract of Interrupt, means - // the barge-in is recorded. (A turn that never streamed was never audible, so its frame - // already took the amendment path against the turn before this one and never lands - // here.) Nothing recorded the streaming frame. Reading _interruption again here, one - // statement after _amendable and LastTurn were published, hands that frame to the very - // path a frame arriving one instant later would have taken: the tested amendment, which - // writes the TurnCompleted then ReplyInterrupted pair T23 asks for. The _amendableEventId - // guard above already fits: it is published exactly when interruptedAfter is null, which - // is the only state this window can be reached in. - if (interruption is null - && _session.Interruption is { } late - && _session.Interruptions.AmendLastTurn(late) - && _session.LastTurn is { } amended) - { - // The amendment republished LastTurn, so the turn this method returns and the - // duration the metric below reads must both come from it and not from the record - // built before the frame landed. - result = amended; - interruptedAfter = amended.InterruptedAfter; - } - - // Consumed, on whichever path recorded it: the in-flight read at the top of this method - // fed WriteTurnEvents, and the amendment above wrote its own pair. Nothing downstream - // may handle one frame twice. - _session.Interruption = null; - - // The turn is committed, so the run is no longer what the caller is hearing. This is the - // tail of the same defect the read above fixes: a barge-in landing between this lock and - // EndRun would otherwise still find the run audible, take the in-flight path, and be - // recorded nowhere at all. Cleared here, under the lock that just published LastTurn, it - // reaches AmendLastTurn against this turn instead. EndRun still runs and still owns - // disposing the source; clearing the field twice costs nothing. - _session.RunCancellation = null; - _session.Interruptions.RunIsAudible = false; - } - - AgentCoreTelemetry.EndTurn( - turn.Activity, - _session.Time.GetElapsedTime(turn.StartedAt), - Outcome(failure, interruptedAfter), - stageAfter, - failure); - - if (_session.IsComplete) - { - // The machine reached a terminal stage, so the call is over and the chain closes here. - // The stage rides as detail, because the reason a report counts is the same one for - // every terminal stage the document declares. - _session.Events.EndCall(CallEndReason.AgentCompleted, endedAt, stageAfter); - } + return extractionFailure; + } - if (_session.IsComplete || _session.Events.HasEnded) + private string AdvanceStage(CallTurn turn) + { + if (_session.Policy is null) { - // Children before shells: a cancelled child may be inside a shell tool the next line - // tears down. - await _session.Lifetime.ReleaseBackgroundSessionsAsync().ConfigureAwait(false); - - // Shells first: a Docker executor's bind mount is this workspace, and it must not be - // deleted out from under a still-live container. - await _session.Lifetime.DisposeShellsAsync().ConfigureAwait(false); - - // A tool running mid-turn (a file_memory_write, say) can call EndCall itself, which - // deletes the workspace and then IsComplete overwrites the flag when the policy also - // reaches a terminal stage. _events.HasEnded survives that overwrite, so the folder a - // tool recreated after the mid-turn delete is still cleaned up here. - _session.Lifetime.DeleteWorkspace(); + return turn.StageBefore; } - return result; + var stageAfter = _session.Policy.Advance(_session.State.Snapshot()); + _session.State.Stage = stageAfter; + _session.IsComplete = _session.Policy.IsTerminal; + return stageAfter; } /// Reads the closed outcome value of one finished turn. diff --git a/src/AgentCore.Application/Runtime/CallSession/ReplyOutcome.cs b/src/AgentCore.Application/Runtime/CallSession/ReplyOutcome.cs new file mode 100644 index 00000000..8349c4b3 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/ReplyOutcome.cs @@ -0,0 +1,18 @@ +using AgentCore.Domain; + +namespace AgentCore.Application.Runtime; + +/// What the turn said, what the caller heard, and why they differ if they do. +/// The text the record holds: what the caller heard. +/// The text the model produced, before any barge-in cut it. +/// The section 8.7 reason, or . +/// The row-six fault, from the run or from the fallback layer. +/// The played duration of a cut reply, or . +/// The tool calls still waiting on a human answer. +internal sealed record ReplyOutcome( + string Reply, + string SpokenReply, + string? Failure, + string? ToolFault, + TimeSpan? InterruptedAfter, + List Approvals); diff --git a/src/AgentCore.Application/Runtime/CallSession/TranscriptEntry.cs b/src/AgentCore.Application/Runtime/CallSession/TranscriptEntry.cs new file mode 100644 index 00000000..5bd3cb59 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/TranscriptEntry.cs @@ -0,0 +1,8 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +/// What this turn adds to the transcript. +/// The assistant message the caller heard, or when nothing was. +/// Every message store 0 appends after the caller's own; empty for rows 3 and 4. +internal sealed record TranscriptEntry(ChatMessage? Heard, List Written); From 6c1a5d882201fd488a0a12410a15975f0ef77576 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 15:58:33 -0600 Subject: [PATCH 11/35] feat: implement CallTurnCommit and related transcript handling classes --- .../Runtime/CallSession/CallTurnCompletion.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs index a962b6ca..c1cbf492 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs @@ -11,6 +11,7 @@ namespace AgentCore.Application.Runtime; internal sealed class CallTurnCompletion { private readonly CallSession _session; + private readonly CallTurnCommit _commit; internal CallTurnCompletion(CallSession session) From e789c30063c57a1d51fd479a3fbac884c77542f6 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 16:35:00 -0600 Subject: [PATCH 12/35] feat: Add clock and base instructions support to agent harness and instructions --- config/example.yaml | 10 +++ .../Compilation/AgentCompilationContext.cs | 6 ++ .../Configuration/Compilation/AgentHarness.cs | 14 ++-- .../Compilation/AgentHarnessProviders.cs | 9 ++- .../Compilation/AgentInstructions.cs | 48 ++++++++++--- .../Schema/AgentsConfiguration.cs | 12 ++++ .../Schema/agentcore-v1.schema.json | 16 +++++ .../PublicAPI.Unshipped.txt | 22 +++++- .../Runtime/CallSession/CallTurnRunner.cs | 8 +++ .../Runtime/Harness/BackgroundChildAgent.cs | 12 +++- .../Runtime/Harness/CallerTimeZone.cs | 57 +++++++++++++++ .../Runtime/Harness/ClockContextProvider.cs | 49 +++++++++++++ .../Runtime/TurnInvocation.cs | 3 + .../DependencyInjection/AgentCoreBoot.cs | 3 +- .../Startup/CompilationStartup.cs | 5 +- .../Endpoints/ResponsesEndpoints.cs | 13 ++++ .../PublicAPI.Unshipped.txt | 1 + .../Configuration/AgentHarnessTests.cs | 35 ++++++++- .../Compilation/CompileTableTests.cs | 40 ++++++++--- .../Harness/BackgroundChildAgentTests.cs | 20 ++++++ .../Runtime/Harness/CallerTimeZoneTests.cs | 34 +++++++++ .../Harness/ClockContextProviderTests.cs | 35 +++++++++ .../Runtime/Turn/TurnContextProviderTests.cs | 4 ++ .../CallSessionResumeTestSupport.cs | 2 + .../CallSessionStoreFailureTests.cs | 2 + .../Transcript/CallSessionTranscriptTests.cs | 2 + .../Endpoints/TimeZoneHeaderTests.cs | 71 +++++++++++++++++++ .../Fakes/ResponsesHost.cs | 17 +++-- 28 files changed, 512 insertions(+), 38 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs create mode 100644 src/AgentCore.Application/Runtime/Harness/ClockContextProvider.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/CallerTimeZoneTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/ClockContextProviderTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs diff --git a/config/example.yaml b/config/example.yaml index 7a3d2ee2..aa09aa4b 100644 --- a/config/example.yaml +++ b/config/example.yaml @@ -212,6 +212,16 @@ agents: model: { ref: reply, temperature: 0.3 } instructions: | + # Two posture switches sit ON until you turn them off, per agent or here for all of them. + # baseInstructions: puts the framework's base above the prefix: resolve before you ask, own + # what you cannot do, do not repeat a failed call, finish. It names no persona and yields to + # everything below it. clock: tells the model the date, time, and zone once per turn, as a + # message below the cached prefix, so "the past ten days" has an anchor and nobody has to + # type the year. The zone is the server's unless the request carries X-AgentCore-Time-Zone + # with the browser's IANA id; then it is the person's. Turn either off only for an agent + # whose prompt is measured byte for byte. + # baseInstructions: true + # clock: true # citations defaults to false and scoped defaults to true. A forgotten flag is then silent # and safe, and the dangerous direction is the one you type on purpose. # diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs index 075197f0..91ce598c 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs @@ -76,6 +76,12 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// public ILoggerFactory? Loggers { get; init; } + /// + /// Gets or sets the clock a clock: agent reads the date from, or + /// for . + /// + public TimeProvider? Clock { get; init; } + /// /// Gets or sets the root a memory: block's files are kept under, or /// when the host bound no workspace root. diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs index 2b0feac7..cba1ae08 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs @@ -5,11 +5,15 @@ namespace AgentCore.Application.Configuration.Compilation; /// One agent's harness switches, fully resolved. /// Whether the agent gets the todo tools. /// Whether the agent gets the mode tools. -public sealed record ResolvedHarness(bool Todos, bool Mode); +/// Whether the agent is told the current date and time each turn. +/// Whether the framework's base instructions sit above the document's own. +public sealed record ResolvedHarness(bool Todos, bool Mode, bool Clock, bool BaseInstructions); /// -/// Composes one agent's harness switches (todos:, mode:) from -/// agents.defaults and the agent's own keys, key by key. +/// Composes one agent's harness switches (todos:, mode:, clock:, +/// baseInstructions:) from agents.defaults and the agent's own keys, key by key. +/// The tool switches are off until named; the two posture switches are on until named, so an +/// agent has to opt out of knowing the date or of the base instructions rather than opt in. /// public static class AgentHarness { @@ -22,6 +26,8 @@ public static ResolvedHarness Compose(AgentDefaults? defaults, AgentConfiguratio return new ResolvedHarness( agent.Todos ?? defaults?.Todos ?? false, - agent.Mode ?? defaults?.Mode ?? false); + agent.Mode ?? defaults?.Mode ?? false, + agent.Clock ?? defaults?.Clock ?? true, + agent.BaseInstructions ?? defaults?.BaseInstructions ?? true); } } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 9d383505..283d3f38 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -11,7 +11,7 @@ namespace AgentCore.Application.Configuration.Compilation; /// /// The context providers behind one agent's harness switches (todos:, mode:, -/// memory:, files:, shell:, background:), added into the provider list +/// clock:, memory:, files:, shell:, background:), added into the provider list /// builds. /// internal static class AgentHarnessProviders @@ -59,7 +59,7 @@ internal static class AgentHarnessProviders #pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. - /// Adds this agent's harness providers, in declaration order: todos, mode, memory, files, shell, background. + /// Adds this agent's harness providers, in declaration order: todos, mode, clock, memory, files, shell, background. /// The provider list under construction. /// The agents.defaults section, or . /// The agent being compiled. @@ -90,6 +90,11 @@ public static void Add( providers.Add(new AgentModeProvider()); } + if (harness.Clock) + { + providers.Add(new ClockContextProvider(context.Clock ?? TimeProvider.System)); + } + if (item.Memory is { Store: AgentFileStoreKind.Workspace }) { providers.Add(BuildMemoryProvider(item, context, pointer)); diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs index 38e3dd9b..7bd4d92d 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs @@ -3,14 +3,16 @@ namespace AgentCore.Application.Configuration.Compilation; /// -/// Composes the instructions of one agent from the shared prefix and the stage delta. +/// Composes the instructions of one agent from the framework's base, the shared prefix, and the +/// stage delta. /// /// /// /// Section 8.1 states one caching rule, and it is a cost rule only. /// agents.defaults.instructions is the stable cached prefix, and each stage appends a delta /// below it. Anything that changes per turn must sit below the prefix, or it defeats the cache for -/// every later turn. +/// every later turn. is the same for every agent in every document, so it sits +/// above the prefix and is part of it. /// /// /// OpenAI caches automatically with no marker, at a 1,024-token minimum prefix, and a cached prompt @@ -20,27 +22,51 @@ namespace AgentCore.Application.Configuration.Compilation; /// public static class AgentInstructions { - /// The separator between the cached prefix and the stage delta. + /// The separator between the base, the cached prefix, and the stage delta. public const string Separator = "\n\n"; - /// Puts the shared prefix above the delta of one agent. + /// + /// The posture every agent starts from: resolve before asking, own what you cannot do, do not + /// repeat a failed call, and finish. It names no persona, no tone, and no domain, and it yields + /// to whatever the document says below it. baseInstructions: false drops it. + /// + public static string Base { get; } = + "Resolve what you can from what you know and what you are given. Ask only for what you " + + "cannot resolve, and ask for one thing at a time.\n" + + "If the request needs something you cannot do, say so in one sentence and offer the " + + "nearest thing you can do.\n" + + "If a tool fails or returns nothing, change your approach once. Do not repeat the same call.\n" + + "Never invent a fact, a value, or a source.\n" + + "Finish the task. Do not stop at the easy part.\n" + + "The instructions below take priority over these."; + + /// Puts the base and the shared prefix above the delta of one agent. /// The agents.defaults section, or . /// The agent whose delta goes below the prefix. - /// The composed instructions, or when neither part exists. + /// The composed instructions, or when no part exists. public static string? Compose(AgentDefaults? defaults, AgentConfiguration agent) { ArgumentNullException.ThrowIfNull(agent); - var prefix = Trim(defaults?.Instructions); - var delta = Trim(agent.Instructions); + var parts = new List(3); + + if (AgentHarness.Compose(defaults, agent).BaseInstructions) + { + parts.Add(Base); + } + + // The prefix always comes before the delta. Nothing per-turn inside either. + if (Trim(defaults?.Instructions) is { } prefix) + { + parts.Add(prefix); + } - if (prefix is null) + if (Trim(agent.Instructions) is { } delta) { - return delta; + parts.Add(delta); } - // The prefix always comes first. Nothing above it, and nothing per-turn inside it. - return delta is null ? prefix : prefix + Separator + delta; + return parts.Count == 0 ? null : string.Join(Separator, parts); } private static string? Trim(string? text) diff --git a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs index 4926a495..4455decb 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs @@ -57,6 +57,12 @@ public sealed record AgentDefaults /// Gets whether agents inherit the mode tools, or to name nothing. public bool? Mode { get; init; } + /// Gets whether agents are told the current date and time each turn, or to name nothing. + public bool? Clock { get; init; } + + /// Gets whether the framework's base instructions sit above , or to name nothing. + public bool? BaseInstructions { get; init; } + /// Gets the shared approval: block, or when the document declares none. public ApprovalConfiguration? Approval { get; init; } } @@ -99,6 +105,12 @@ public sealed record AgentConfiguration /// Gets whether this agent gets the mode tools, or to inherit. public bool? Mode { get; init; } + /// Gets whether this agent is told the current date and time each turn, or to inherit. + public bool? Clock { get; init; } + + /// Gets whether the framework's base instructions sit above this agent's, or to inherit. + public bool? BaseInstructions { get; init; } + /// Gets this agent's memory: block, or for none. public AgentMemoryConfiguration? Memory { get; init; } diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index 4f4c0625..dba4d385 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -660,6 +660,14 @@ "type": "boolean", "description": "Whether agents inherit the mode tools." }, + "clock": { + "type": "boolean", + "description": "Whether agents are told the current date and time each turn. Defaults to true." + }, + "baseInstructions": { + "type": "boolean", + "description": "Whether the framework's base instructions sit above instructions. Defaults to true." + }, "approval": { "$ref": "#/$defs/approval", "description": "The standing approval rules every agent inherits." @@ -733,6 +741,14 @@ "type": "boolean", "description": "The agent gets the mode tools (AgentModeProvider)." }, + "clock": { + "type": "boolean", + "description": "The agent is told the current date and time each turn (ClockContextProvider). Defaults to true." + }, + "baseInstructions": { + "type": "boolean", + "description": "The framework's base instructions sit above this agent's own. Defaults to true." + }, "memory": { "$ref": "#/$defs/memory", "description": "The file-memory tools over a store." diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 745e65a6..7de2bc0b 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -226,11 +226,11 @@ AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Trigger.get - AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Trigger.init -> void AgentCore.Application.Configuration.Compilation.ResolvedHarness AgentCore.Application.Configuration.Compilation.ResolvedHarness.$() -> AgentCore.Application.Configuration.Compilation.ResolvedHarness! -AgentCore.Application.Configuration.Compilation.ResolvedHarness.Deconstruct(out bool Todos, out bool Mode) -> void +AgentCore.Application.Configuration.Compilation.ResolvedHarness.Deconstruct(out bool Todos, out bool Mode, out bool Clock, out bool BaseInstructions) -> void AgentCore.Application.Configuration.Compilation.ResolvedHarness.Equals(AgentCore.Application.Configuration.Compilation.ResolvedHarness? other) -> bool AgentCore.Application.Configuration.Compilation.ResolvedHarness.Mode.get -> bool AgentCore.Application.Configuration.Compilation.ResolvedHarness.Mode.init -> void -AgentCore.Application.Configuration.Compilation.ResolvedHarness.ResolvedHarness(bool Todos, bool Mode) -> void +AgentCore.Application.Configuration.Compilation.ResolvedHarness.ResolvedHarness(bool Todos, bool Mode, bool Clock, bool BaseInstructions) -> void AgentCore.Application.Configuration.Compilation.ResolvedHarness.Todos.get -> bool AgentCore.Application.Configuration.Compilation.ResolvedHarness.Todos.init -> void AgentCore.Application.Configuration.Compilation.ResolvedKnowledge @@ -2261,3 +2261,21 @@ AgentCore.Application.Transcript.FileContent.Name.set -> void AgentCore.Application.Transcript.FileContent.FileContent() -> void AgentCore.Application.Transcript.FileContent.Scope.get -> string? AgentCore.Application.Transcript.FileContent.Scope.set -> void +AgentCore.Application.Configuration.Compilation.ResolvedHarness.Clock.get -> bool +AgentCore.Application.Configuration.Compilation.ResolvedHarness.Clock.init -> void +AgentCore.Application.Configuration.Compilation.ResolvedHarness.BaseInstructions.get -> bool +AgentCore.Application.Configuration.Compilation.ResolvedHarness.BaseInstructions.init -> void +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Clock.get -> System.TimeProvider? +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Clock.init -> void +AgentCore.Application.Configuration.Schema.AgentDefaults.Clock.get -> bool? +AgentCore.Application.Configuration.Schema.AgentDefaults.Clock.init -> void +AgentCore.Application.Configuration.Schema.AgentDefaults.BaseInstructions.get -> bool? +AgentCore.Application.Configuration.Schema.AgentDefaults.BaseInstructions.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Clock.get -> bool? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Clock.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.BaseInstructions.get -> bool? +AgentCore.Application.Configuration.Schema.AgentConfiguration.BaseInstructions.init -> void +static AgentCore.Application.Configuration.Compilation.AgentInstructions.Base.get -> string! +AgentCore.Application.Runtime.Harness.CallerTimeZone +static AgentCore.Application.Runtime.Harness.CallerTimeZone.Parse(string? id) -> System.TimeZoneInfo? +static AgentCore.Application.Runtime.Harness.CallerTimeZone.Set(Microsoft.Agents.AI.AgentSession! session, System.TimeZoneInfo! zone) -> void diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs index 4898b336..f0389d9b 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs @@ -22,6 +22,8 @@ internal sealed class CallTurnRunner private bool _hasScreen; + private TimeZoneInfo? _timeZone; + internal CallTurnRunner(CallSession session) { ArgumentNullException.ThrowIfNull(session); @@ -47,6 +49,11 @@ internal void SetDelegatedTools(string delegatingToolId, IReadOnlyList t /// internal void SetHasScreen(bool hasScreen) => _hasScreen = hasScreen; + /// + /// Tells this call which zone the person is in, so the clock line reads their date. + /// + internal void SetTimeZone(TimeZoneInfo zone) => _timeZone = zone; + /// Runs one turn of the call against the session the call holds. /// What the caller said or answered. /// Where the turn hangs, or null for a caller that does not say. @@ -298,6 +305,7 @@ internal TurnInvocation TurnInvocationOf(CallTurn turn) TurnIndex = turn.Index, Stage = turn.StageBefore, Instructions = turn.Reminder, + TimeZone = _timeZone, Workspace = _session.Workspace, Shells = _session.Shells, Knowledge = turn.Knowledge, diff --git a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs index 53b1b58b..3f12125a 100644 --- a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs +++ b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs @@ -3,7 +3,8 @@ namespace AgentCore.Application.Runtime.Harness; /// -/// Wraps one background: child so every session it gets knows which call started it. +/// Wraps one background: child so every session it gets knows which call started it, and +/// which zone the person on that call is in. /// /// /// BackgroundAgentsProvider creates the child session inside the parent's tool call, before @@ -21,11 +22,18 @@ protected override async ValueTask CreateSessionCoreAsync(Cancella var session = await InnerAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); - if (TurnInvocation.From(parent?.RunOptions)?.CallId is { } callId) + var turn = TurnInvocation.From(parent?.RunOptions); + + if (turn?.CallId is { } callId) { session.StateBag.SetValue(BlobOwnerKey.Value, callId); } + if (turn?.TimeZone is { } zone) + { + CallerTimeZone.Stamp(session, zone); + } + return session; } } diff --git a/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs b/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs new file mode 100644 index 00000000..43febd1d --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs @@ -0,0 +1,57 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime.Harness; + +/// +/// The time zone the person on a call is in, as the host learned it — from the browser, on the +/// request. The clock line reads the date in it instead of the server's zone. It is set per +/// request, not once: a person who travels moves the clock with them, and a request that names +/// no zone leaves the last one in place. +/// +public static class CallerTimeZone +{ + /// The state key a background child's session carries the zone under. The value is a zone id. + internal const string Key = "urn:agentcore:time-zone"; + + /// Reads a zone id the way the host received it, or nothing when it names no zone. + /// An IANA id such as America/Chicago, or a Windows id. + /// The zone, or for an empty or unknown id. + public static TimeZoneInfo? Parse(string? id) + { + if (string.IsNullOrWhiteSpace(id)) + { + return null; + } + + return TimeZoneInfo.TryFindSystemTimeZoneById(id.Trim(), out var zone) ? zone : null; + } + + /// Puts the caller's zone on the call a session carries, replacing what was there. + /// A session this framework created: it names the call. + /// The zone the caller is in. + /// The session names no call. + public static void Set(AgentSession session, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(zone); + + if (session.GetService() is not { } call) + { + throw new InvalidOperationException( + "The session is not one this agent created, so it names no call to put the zone on."); + } + + call.Runner.SetTimeZone(zone); + } + + /// Stamps the zone onto a child session, so a run on it reads the caller's date. + /// The child's session. + /// The zone the caller is in. + internal static void Stamp(AgentSession session, TimeZoneInfo zone) + => session.StateBag.SetValue(Key, zone.Id); + + /// Reads the zone stamped on a child session, or nothing when none was. + /// The session, or . + internal static TimeZoneInfo? Stamped(AgentSession? session) + => session is not null && session.StateBag.TryGetValue(Key, out var id) ? Parse(id) : null; +} diff --git a/src/AgentCore.Application/Runtime/Harness/ClockContextProvider.cs b/src/AgentCore.Application/Runtime/Harness/ClockContextProvider.cs new file mode 100644 index 00000000..489bfb34 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/ClockContextProvider.cs @@ -0,0 +1,49 @@ +using System.Globalization; +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime.Harness; + +/// +/// Tells the model the current date and time, once per turn, as a system message below the +/// cached instructions. Without it a relative date such as "the past ten days" has no anchor +/// and the model has to ask the person for one. The zone is the caller's when the host named +/// one (), else the clock's own. +/// +internal sealed class ClockContextProvider(TimeProvider clock) : AIContextProvider +{ + private readonly TimeProvider _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + + /// + protected override ValueTask ProvideAIContextAsync( + InvokingContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + + // The turn's own session carries the zone on a loop-built run; a background child's session + // carries it stamped; anything else reads the server's zone. + var zone = TurnRegistry.For(context.Session)?.TimeZone + ?? CallerTimeZone.Stamped(context.Session) + ?? _clock.LocalTimeZone; + + return new(new AIContext { Messages = [new ChatMessage(ChatRole.System, Describe(_clock, zone))] }); + } + + /// The one line the model reads, for one zone. + /// The clock to read. + /// The zone to read it in. + internal static string Describe(TimeProvider clock, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(zone); + + var now = TimeZoneInfo.ConvertTime(clock.GetUtcNow(), zone); + var offset = now.Offset; + var sign = offset < TimeSpan.Zero ? "-" : "+"; + + return string.Create( + CultureInfo.InvariantCulture, + $"Today is {now:dddd}, {now:yyyy-MM-dd}. The local time is {now:HH:mm}, {zone.Id} (UTC{sign}{offset:hh\\:mm})."); + } +} diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs index 10323b33..113b1f6c 100644 --- a/src/AgentCore.Application/Runtime/TurnInvocation.cs +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -42,6 +42,9 @@ internal sealed record TurnInvocation /// Gets the instructions for this one invocation, or for none. public string? Instructions { get; init; } + /// Gets the zone the person on the call is in, or when the host named none. + public TimeZoneInfo? TimeZone { get; init; } + /// Gets whether this row's session carries the caller's own history. public bool CarriesHistory { get; init; } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index 9fe03913..33d4d7f5 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -243,7 +243,8 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) skills, KnowledgeCitationFormatterFactory.Resolve(configuration, _options.KnowledgeCitations), _loggers, - _options.WorkspaceRoot) + _options.WorkspaceRoot, + _options.TimeProvider) .ConfigureAwait(false); var seams = CallSeamStartup.Build(configuration, _options); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs index af6d8161..296cfca4 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -40,6 +40,7 @@ internal static class CompilationStartup /// The wording providers.knowledge.citation named. /// The factory the guard evaluator and the knowledge provider take their loggers from. /// The root options.UseWorkspace(...) bound, or . + /// The clock the host bound, or for the system clock. /// The compiled entries, and the seams that made them. /// An entry does not compile. internal static ValueTask CompileAsync( @@ -53,7 +54,8 @@ internal static ValueTask CompileAsync( SkillCatalog? skills, IKnowledgeCitationFormatter citations, ILoggerFactory loggers, - string? workspaceRoot = null) + string? workspaceRoot = null, + TimeProvider? clock = null) { GuardEvaluator guards = new(configuration.Guards, loggers.CreateLogger()); CompiledAgentRegistry registry = new(); @@ -72,6 +74,7 @@ internal static ValueTask CompileAsync( Citations = citations, Loggers = loggers, WorkspaceRoot = workspaceRoot, + Clock = clock, }); return ValueTask.FromResult(new CompiledGraph(chatClients, guards, registry, entries)); diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index 7e119b4c..9a0ec95c 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -2,6 +2,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Tools; using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.DependencyInjection; @@ -28,6 +29,13 @@ public static class ResponsesEndpointRouteBuilderExtensions /// The answer header that reports the stage the machine holds. public const string StageHeaderName = "X-AgentCore-Stage"; + /// + /// The request header that names the zone the person is in, as an IANA id such as + /// America/Chicago. The browser knows it and the server does not. Read on every turn, + /// so a person who travels moves the clock with them; a bad or missing value changes nothing. + /// + public const string TimeZoneHeaderName = "X-AgentCore-Time-Zone"; + /// The OpenAI error type every refused request reports. private const string InvalidRequestError = "invalid_request_error"; @@ -293,6 +301,11 @@ await ResponsesRequestReader.WriteErrorAsync( // Set per request, not once: the session outlives a request and the branch can differ per turn. call.SetHasScreen(streaming); + if (CallerTimeZone.Parse(http.Request.Headers[TimeZoneHeaderName]) is { } zone) + { + CallerTimeZone.Set(session, zone); + } + try { if (streaming) diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 8902a11c..9a12690f 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -79,3 +79,4 @@ static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.Co static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.FirstRetryDelay -> System.TimeSpan static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.RequestDeadline -> System.TimeSpan AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseBlobStores(params AgentCore.Application.Ports.IBlobStoreAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! +const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.TimeZoneHeaderName = "X-AgentCore-Time-Zone" -> string! diff --git a/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs b/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs index ceb2273f..adb118a8 100644 --- a/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs @@ -5,8 +5,8 @@ namespace AgentCore.Application.Tests.Configuration; /// -/// : the key-by-key merge of one agent's todos: / mode: -/// switches against agents.defaults. +/// : the key-by-key merge of one agent's todos: / mode: / +/// clock: / baseInstructions: switches against agents.defaults. /// public sealed class AgentHarnessTests { @@ -19,6 +19,37 @@ public void Compose_NoKeyAnywhere_BothFalse() Assert.False(resolved.Mode); } + [Fact] + public void Compose_NoKeyAnywhere_ClockAndBaseAreOn() + { + var resolved = AgentHarness.Compose(defaults: null, Agent(todos: null, mode: null)); + + Assert.True(resolved.Clock); + Assert.True(resolved.BaseInstructions); + } + + [Fact] + public void Compose_DefaultsFalse_TurnsClockAndBaseOff() + { + var resolved = AgentHarness.Compose( + new AgentDefaults { Clock = false, BaseInstructions = false }, + Agent(todos: null, mode: null)); + + Assert.False(resolved.Clock); + Assert.False(resolved.BaseInstructions); + } + + [Fact] + public void Compose_AgentTrueOverDefaultsFalse_TakesTheAgent() + { + var resolved = AgentHarness.Compose( + new AgentDefaults { Clock = false, BaseInstructions = false }, + Agent(todos: null, mode: null) with { Clock = true, BaseInstructions = true }); + + Assert.True(resolved.Clock); + Assert.True(resolved.BaseInstructions); + } + [Fact] public void Compose_DefaultsOnly_IsInherited() { diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs index 8416922e..57bfa28c 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs @@ -332,19 +332,40 @@ public void TheCachedPrefix_SitsAboveTheStageDelta() var composed = AgentInstructions.Compose(document.Agents!.Defaults, document.Agents.Items[0]); - Assert.Equal("the stable cached prefix" + AgentInstructions.Separator + "the stage delta", composed); - Assert.StartsWith("the stable cached prefix", composed, StringComparison.Ordinal); + Assert.Equal( + AgentInstructions.Base + AgentInstructions.Separator + + "the stable cached prefix" + AgentInstructions.Separator + "the stage delta", + composed); + Assert.StartsWith(AgentInstructions.Base, composed, StringComparison.Ordinal); } [Fact] - public void AnAgentWithNoDelta_KeepsThePrefixAlone() + public void TheBase_SitsAboveThePrefix_AndBaseInstructionsFalseDropsIt() { AgentDefaults defaults = new() { Instructions = "prefix" }; + AgentConfiguration agent = new() { Id = "solo", Instructions = "delta" }; + + Assert.Equal( + AgentInstructions.Base + AgentInstructions.Separator + "prefix" + AgentInstructions.Separator + "delta", + AgentInstructions.Compose(defaults, agent)); + Assert.Equal( + "prefix" + AgentInstructions.Separator + "delta", + AgentInstructions.Compose(defaults with { BaseInstructions = false }, agent)); + Assert.Equal( + "prefix" + AgentInstructions.Separator + "delta", + AgentInstructions.Compose(defaults, agent with { BaseInstructions = false })); + Assert.Equal(AgentInstructions.Base, AgentInstructions.Compose(null, new AgentConfiguration { Id = "bare" })); + } + + [Fact] + public void AnAgentWithNoDelta_KeepsThePrefixAlone() + { + AgentDefaults defaults = new() { Instructions = "prefix", BaseInstructions = false }; AgentConfiguration agent = new() { Id = "solo" }; Assert.Equal("prefix", AgentInstructions.Compose(defaults, agent)); - Assert.Equal("delta", AgentInstructions.Compose(null, agent with { Instructions = "delta" })); - Assert.Null(AgentInstructions.Compose(null, agent)); + Assert.Equal("delta", AgentInstructions.Compose(null, agent with { Instructions = "delta", BaseInstructions = false })); + Assert.Null(AgentInstructions.Compose(null, agent with { BaseInstructions = false })); } [Fact] @@ -360,10 +381,11 @@ public void EveryCompiledAgent_CarriesTheCachedPrefixAboveItsOwnDelta() // Section 8.1 makes agents.defaults.instructions a cached prefix, and the compiler has one // build path for every agent. This asserts that path and not AgentInstructions.Compose: an // agent the compiler built without the prefix would defeat the cache for every later turn. - Assert.Equal(SharedPrefix + AgentInstructions.Separator + "the greeter delta", greeter.Instructions); - Assert.Equal(SharedPrefix + AgentInstructions.Separator + "the closer delta", closer.Instructions); - Assert.StartsWith(SharedPrefix, greeter.Instructions, StringComparison.Ordinal); - Assert.StartsWith(SharedPrefix, closer.Instructions, StringComparison.Ordinal); + var above = AgentInstructions.Base + AgentInstructions.Separator + SharedPrefix + AgentInstructions.Separator; + Assert.Equal(above + "the greeter delta", greeter.Instructions); + Assert.Equal(above + "the closer delta", closer.Instructions); + Assert.StartsWith(AgentInstructions.Base, greeter.Instructions, StringComparison.Ordinal); + Assert.StartsWith(AgentInstructions.Base, closer.Instructions, StringComparison.Ordinal); } [Fact] diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs index 8d5837e1..86dce9fe 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs @@ -38,6 +38,26 @@ public async Task CreateSessionAsync_InsideTheParentsRun_StampsTheParentsCallId( Assert.Equal("call-9", stamped); } + [Fact] + public async Task CreateSessionAsync_InsideAParentRunWithAZone_StampsTheZoneOnTheChild() + { + // Arrange + var token = TestContext.Current.CancellationToken; + BackgroundChildAgent child = new(new ChatClientAgent(new ScriptedChatClient("child"))); + SessionCreatingProvider creating = new(child); + ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); + var zone = TimeZoneInfo.CreateCustomTimeZone("Asia/Taipei", TimeSpan.FromHours(8), "Taipei", "Taipei"); + var turn = new TurnInvocation { CallId = "call-9", TurnIndex = 0, Stage = "s", TimeZone = zone }; + + // Act + await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); + + // Assert + Assert.NotNull(creating.Created); + Assert.True(creating.Created.StateBag.TryGetValue(CallerTimeZone.Key, out var stamped)); + Assert.Equal("Asia/Taipei", stamped); + } + [Fact] public async Task CreateSessionAsync_OutsideAnyRun_StampsNothing() { diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallerTimeZoneTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallerTimeZoneTests.cs new file mode 100644 index 00000000..5b65e6fc --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallerTimeZoneTests.cs @@ -0,0 +1,34 @@ +using AgentCore.Application.Runtime.Harness; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime.Harness; + +/// +/// : an IANA id the system knows becomes a zone; anything else +/// becomes nothing, so a bad header never changes the clock. +/// +public sealed class CallerTimeZoneTests +{ + [Theory] + [InlineData("America/Chicago")] + [InlineData(" Asia/Taipei ")] + [InlineData("UTC")] + public void Parse_AKnownId_IsThatZone(string id) + { + var zone = CallerTimeZone.Parse(id); + + Assert.NotNull(zone); + Assert.Equal(id.Trim(), zone.Id); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("Mars/Olympus_Mons")] + [InlineData("+08:00")] + public void Parse_AnythingElse_IsNothing(string? id) + { + Assert.Null(CallerTimeZone.Parse(id)); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/ClockContextProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ClockContextProviderTests.cs new file mode 100644 index 00000000..5653cbe4 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ClockContextProviderTests.cs @@ -0,0 +1,35 @@ +using AgentCore.Application.Runtime.Harness; +using AgentCore.TestSupport; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime.Harness; + +/// +/// The one line a clock: agent reads each turn: the weekday, the date, and the time in the +/// zone it is given, with the zone named so a relative date has an anchor. +/// +public sealed class ClockContextProviderTests +{ + [Fact] + public void Describe_ReadsTheClockInTheGivenZone() + { + // 2026-09-17 19:05 UTC is Thursday 14:05 in a zone five hours behind. + FakeTimeProvider clock = new(new DateTimeOffset(2026, 9, 17, 19, 5, 0, TimeSpan.Zero)); + var zone = TimeZoneInfo.CreateCustomTimeZone("America/Chicago", TimeSpan.FromHours(-5), "Central", "Central"); + + var line = ClockContextProvider.Describe(clock, zone); + + Assert.Equal("Today is Thursday, 2026-09-17. The local time is 14:05, America/Chicago (UTC-05:00).", line); + } + + [Fact] + public void Describe_AZoneAheadOfUtc_CarriesAPlusSignAndTheNextDay() + { + FakeTimeProvider clock = new(new DateTimeOffset(2026, 9, 17, 23, 30, 0, TimeSpan.Zero)); + var zone = TimeZoneInfo.CreateCustomTimeZone("Asia/Taipei", TimeSpan.FromHours(8), "Taipei", "Taipei"); + + var line = ClockContextProvider.Describe(clock, zone); + + Assert.Equal("Today is Friday, 2026-09-18. The local time is 07:30, Asia/Taipei (UTC+08:00).", line); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs index e5abd099..4acee378 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs @@ -42,6 +42,10 @@ public sealed class TurnContextProviderTests agents: defaults: model: { ref: reply } + # The assertions below read the instructions block byte for byte, and the first + # system message: neither the base nor the clock line belongs in that reading. + baseInstructions: false + clock: false items: - { id: greeter, instructions: "greet the caller", tools: [ ask_specialist ] } - { id: specialist, model: { ref: specialist }, instructions: "answer the greeter" } diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs index 4ca6e0db..1489bd5e 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs @@ -17,6 +17,8 @@ internal static class CallSessionResumeTestSupport internal const string OneAgentYaml = """ apiVersion: agentcore/v1 agents: + # These tests read the exact messages the model sees; the clock line would be one more. + defaults: { clock: false } items: - { id: only, instructions: "ok" } entries: diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs index dd01ab33..fa254583 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs @@ -23,6 +23,8 @@ public sealed class CallSessionStoreFailureTests private const string OneAgentYaml = """ apiVersion: agentcore/v1 agents: + # These tests read the exact messages the model sees; the clock line would be one more. + defaults: { clock: false } items: - { id: only, instructions: "ok" } entries: diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs index f6800548..2332a01b 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs @@ -23,6 +23,8 @@ public sealed class CallSessionTranscriptTests private const string OneAgentYaml = """ apiVersion: agentcore/v1 agents: + # These tests read the exact messages the model sees; the clock line would be one more. + defaults: { clock: false } items: - { id: only, instructions: "ok" } entries: diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs new file mode 100644 index 00000000..e18fd0f0 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs @@ -0,0 +1,71 @@ +using System.Net; +using AgentCore.Application.Runtime.Harness; +using AgentCore.AspNetCore.Endpoints; +using AgentCore.AspNetCore.Tests.Fakes; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.Endpoints; + +/// +/// The X-AgentCore-Time-Zone header: the browser's zone reaches the clock line the model +/// reads, and a missing or unknown zone leaves the server's own in place. +/// +public sealed class TimeZoneHeaderTests +{ + private const string OneAgentYaml = + """ + apiVersion: agentcore/v1 + agents: + items: + - { id: solo, instructions: "answer" } + entries: + main: + agent: solo + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + // 2026-09-17 23:30 UTC: still Thursday in Chicago, already Friday morning in Taipei. + private static readonly DateTimeOffset Instant = new(2026, 9, 17, 23, 30, 0, TimeSpan.Zero); + + [Fact] + public async Task HeaderNamesAZone_TheClockLineReadsTheDateInIt() + { + using FragmentingChatClient reply = new("answer"); + FakeTimeProvider clock = new(Instant); + await using var host = await ResponsesHost.StartAsync(OneAgentYaml, reply, options => options.TimeProvider = clock); + + using var response = await host.PostAsync( + """{ "stream": false, "input": "what day is it" }""", + new Dictionary { [ResponsesEndpointRouteBuilderExtensions.TimeZoneHeaderName] = "Asia/Taipei" }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains( + reply.LastRequest!, + message => message.Role == ChatRole.System + && message.Text == "Today is Friday, 2026-09-18. The local time is 07:30, Asia/Taipei (UTC+08:00)."); + } + + [Fact] + public async Task HeaderNamesNoKnownZone_TheClockLineReadsTheServerZone() + { + using FragmentingChatClient reply = new("answer"); + FakeTimeProvider clock = new(Instant); + await using var host = await ResponsesHost.StartAsync(OneAgentYaml, reply, options => options.TimeProvider = clock); + + using var response = await host.PostAsync( + """{ "stream": false, "input": "what day is it" }""", + new Dictionary { [ResponsesEndpointRouteBuilderExtensions.TimeZoneHeaderName] = "Mars/Olympus_Mons" }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var expected = ClockContextProvider.Describe(clock, clock.LocalTimeZone); + Assert.Contains(reply.LastRequest!, message => message.Role == ChatRole.System && message.Text == expected); + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs index 83f487ce..adda85f1 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs @@ -73,12 +73,21 @@ public static async Task StartAsync( /// Sends one Responses request body. /// The request body. + /// Request headers to send beside the body, or none. /// The answer. - public async Task PostAsync(string json) + public async Task PostAsync(string json, IReadOnlyDictionary? headers = null) { - using var content = new StringContent(json, Encoding.UTF8, "application/json"); - return await Client.PostAsync( - ResponsesEndpointRouteBuilderExtensions.DefaultPattern, content, TestContext.Current.CancellationToken); + using HttpRequestMessage request = new(HttpMethod.Post, ResponsesEndpointRouteBuilderExtensions.DefaultPattern) + { + Content = new StringContent(json, Encoding.UTF8, "application/json"), + }; + + foreach (var (name, value) in headers ?? new Dictionary()) + { + request.Headers.TryAddWithoutValidation(name, value); + } + + return await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken); } /// Reads every server-sent event of one answer. From b97776f6fe677ff0a2c6bdbadc699ec8194f62ae Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 16:35:07 -0600 Subject: [PATCH 13/35] feat: Add clock and base instructions support to agent harness and instructions --- .../Configuration/Compilation/AgentInstructions.cs | 14 -------------- .../Endpoints/ResponsesEndpoints.cs | 3 +-- 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs index 7bd4d92d..fba709b9 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs @@ -6,20 +6,6 @@ namespace AgentCore.Application.Configuration.Compilation; /// Composes the instructions of one agent from the framework's base, the shared prefix, and the /// stage delta. /// -/// -/// -/// Section 8.1 states one caching rule, and it is a cost rule only. -/// agents.defaults.instructions is the stable cached prefix, and each stage appends a delta -/// below it. Anything that changes per turn must sit below the prefix, or it defeats the cache for -/// every later turn. is the same for every agent in every document, so it sits -/// above the prefix and is part of it. -/// -/// -/// OpenAI caches automatically with no marker, at a 1,024-token minimum prefix, and a cached prompt -/// still counts in full against the rate limit. Breaking the prefix is therefore a billing bug and -/// never a capacity one. -/// -/// public static class AgentInstructions { /// The separator between the base, the cached prefix, and the stage delta. diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index 9a0ec95c..56aa3bd5 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -31,8 +31,7 @@ public static class ResponsesEndpointRouteBuilderExtensions /// /// The request header that names the zone the person is in, as an IANA id such as - /// America/Chicago. The browser knows it and the server does not. Read on every turn, - /// so a person who travels moves the clock with them; a bad or missing value changes nothing. + /// America/Chicago. /// public const string TimeZoneHeaderName = "X-AgentCore-Time-Zone"; From 5a0b6a046bbd83d07a32d2276b623495726bbac4 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Thu, 17 Sep 2026 17:18:15 -0600 Subject: [PATCH 14/35] feat: Update agent instructions and enhance HostedFileCaptureProvider with context preservation tests --- .../Compilation/AgentInstructions.cs | 19 ++++++++++---- .../Harness/HostedFileCaptureProvider.cs | 2 +- .../Harness/HostedFileCaptureProviderTests.cs | 26 +++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs index fba709b9..7a351a6f 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs @@ -12,16 +12,25 @@ public static class AgentInstructions public const string Separator = "\n\n"; /// - /// The posture every agent starts from: resolve before asking, own what you cannot do, do not - /// repeat a failed call, and finish. It names no persona, no tone, and no domain, and it yields - /// to whatever the document says below it. baseInstructions: false drops it. + /// The posture every agent starts from. /// public static string Base { get; } = - "Resolve what you can from what you know and what you are given. Ask only for what you " + "You are a helpful AI assistant that uses tools to complete tasks.\n" + + "\n" + + "## General guidelines\n" + + "\n" + + "- Think through the task before acting. Break complex work into clear steps.\n" + + "- Use the tools available to you to gather information, perform actions, and verify results.\n" + + "- Explain your reasoning and thought process as you work through tasks.\n" + + "- Explain what you learned and what you are going to do next between tool calls, so the user can follow along with your thought process.\n" + + "- Avoid making more than 4 tool calls in a row without explaining what you are doing.\n" + + "- If a tool call fails or returns unexpected results, adapt your approach rather than repeating the same call.\n" + + "- When you have completed the task, present a clear and concise summary of what you did and what you found.\n" + + "\n" + + "Resolve what you can from what you know and what you are given. Ask only for what you " + "cannot resolve, and ask for one thing at a time.\n" + "If the request needs something you cannot do, say so in one sentence and offer the " + "nearest thing you can do.\n" - + "If a tool fails or returns nothing, change your approach once. Do not repeat the same call.\n" + "Never invent a fact, a value, or a source.\n" + "Finish the task. Do not stop at the easy part.\n" + "The instructions below take priority over these."; diff --git a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs index bbfffd80..e97e71b6 100644 --- a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs @@ -48,7 +48,7 @@ public HostedFileCaptureProvider(IHostedFileClient files, IBlobStore blobs, Blob } /// - protected override ValueTask InvokingCoreAsync(InvokingContext context, CancellationToken cancellationToken = default) + protected override ValueTask ProvideAIContextAsync(InvokingContext context, CancellationToken cancellationToken = default) => new(new AIContext { Instructions = Instructions }); /// diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs index 48e4ad1a..4f8c5324 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs @@ -177,6 +177,32 @@ public async Task InvokingAsync_TellsTheModelWhereToSaveAndHowToLink() Assert.Contains("sandbox:/mnt/data/", context.Instructions, StringComparison.Ordinal); } + [Fact] + public async Task InvokingAsync_KeepsWhatTheEarlierProvidersBuilt() + { + // Arrange + var agent = Agent(); + var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); + var tool = AIFunctionFactory.Create(() => "ok", "count_orders"); + ChatMessage asked = new(ChatRole.User, "How many orders?"); + AIContext incoming = new() + { + Instructions = "You answer the Spirit agent.", + Messages = [asked], + Tools = [tool], + }; + + // Act + var context = await Provider(new ScriptedHostedFileClient(), new RecordingBlobStore()) + .InvokingAsync(new AIContextProvider.InvokingContext(agent, session, incoming), TestContext.Current.CancellationToken); + + // Assert + Assert.Contains("You answer the Spirit agent.", context.Instructions, StringComparison.Ordinal); + Assert.Contains("/mnt/data", context.Instructions, StringComparison.Ordinal); + Assert.Same(asked, Assert.Single(context.Messages!)); + Assert.Same(tool, Assert.Single(context.Tools!)); + } + private static HostedFileCaptureProvider Provider(ScriptedHostedFileClient files, RecordingBlobStore blobs) => new(files, blobs, BlobPolicy.Default, NullLogger.Instance); From c8926010c92ed457ca014b4e988324111d3cf7c5 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 18 Sep 2026 12:37:15 -0600 Subject: [PATCH 15/35] Refactor Responses and Call Endpoints to Use Entry Parameter --- README.md | 2 + config/example.yaml | 641 +++++++++--------- .../Call/AgentCoreEntryMetadata.cs | 6 - .../CallEndpointRouteBuilderExtensions.cs | 76 ++- src/AgentCore.AspNetCore/Call/CallSeams.cs | 13 - .../Call/ICallTransportAdapter.cs | 11 +- .../DependencyInjection/AgentCoreBoot.cs | 51 +- .../Startup/CallSeamStartup.cs | 22 +- .../Endpoints/ResponsesEndpoints.cs | 132 +--- .../Endpoints/ResponsesSessionFiling.cs | 25 + .../Endpoints/ResponsesTurnReply.cs | 63 ++ .../Endpoints/ResponsesTurnStream.cs | 2 +- .../PublicAPI.Unshipped.txt | 19 +- .../TelnyxRelay/TelnyxRelayCallAdapter.cs | 4 +- .../TelnyxRelay/TelnyxRelayConnection.cs | 21 +- .../TelnyxRelay/TelnyxRelayEndpoints.cs | 19 +- .../Vendors/TelnyxRelay/TelnyxRelayOptions.cs | 3 - .../AgentCoreHostEndpointExtensions.cs | 17 +- src/AgentCore.Hosting/PublicAPI.Unshipped.txt | 2 +- .../Configuration/ExampleDocument.cs | 2 +- .../Call/CallRouteSelectionTests.cs | 25 +- .../TelnyxRelayThroughTheCallSeamTests.cs | 2 +- .../Fakes/FakeWebSocket.cs | 4 +- .../Fakes/ResponsesHost.cs | 4 +- .../Fakes/TelnyxRelayHost.cs | 16 +- .../TelnyxRelay/TelnyxRelayEndpointTests.cs | 4 +- .../AgentCoreHostTests.cs | 50 +- 27 files changed, 647 insertions(+), 589 deletions(-) delete mode 100644 src/AgentCore.AspNetCore/Call/AgentCoreEntryMetadata.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesSessionFiling.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs diff --git a/README.md b/README.md index 54eb8433..d27856e3 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,8 @@ app.Run(); ``` `AddAgentCoreHost` loads the document (`config/example.yaml` unless `AgentCore__ConfigurationPath` names another) and binds every vendor seam. `MapAgentCoreHost` serves the health check, the OpenAI-compatible Responses endpoint, and the call socket. +Every entry under `entries:` answers on `POST /v1/{entry}/responses` and on the call socket at `/v1/{entry}/call`. +An OpenAI SDK reaches one entry through its base URL alone: `base_url = https://host/v1/phone`. A document it cannot find is a startup failure, never a silent default. ## Install diff --git a/config/example.yaml b/config/example.yaml index aa09aa4b..0d77c40e 100644 --- a/config/example.yaml +++ b/config/example.yaml @@ -1,69 +1,87 @@ -# AgentCore configuration, the worked example of section 8.1. +# AgentCore configuration: the worked example. # -# One document carries the whole schema. This file parses, and it passes check 1 of section 8.5. -# The real config.yaml belongs to the consuming project and is not committed here. +# WHAT THIS FILE IS +# One document that shows every section of the schema. It parses, and it passes every startup +# check. Your real config.yaml lives in your own project. It is not committed here. +# The same document loads identically as YAML and as JSON. # -# The same document loads identically as YAML and as JSON. See rule 17 of section 11. - -# The document version. agentcore/v1 is the only value this release accepts. +# HOW TO READ IT +# - Every key has its comment ABOVE it. +# - The first line of a comment says what the key does. +# - "Optional" or "Required", and "Default:", follow when they apply. +# - A key written as "# key: value" is a shape this example does not use. Uncomment it to use it. +# - ${secret:name} is a reference to a secret, never a value. ISecretResolverPort resolves it at +# startup. +# +# SECTIONS +# 1. document apiVersion, fallbackReply, refusalReply +# 2. state typed slots the guards read +# 3. extractor the model call that fills the extractor slots +# 4. guards named JSONLogic rules the stage machine tests +# 5. tools what an agent may call +# 6. agents models, prompts, knowledge, compaction +# 7. entries what a caller reaches: a stage machine or one agent +# 8. providers adapters: llm, call, speech, telephony, moderation, embeddings, knowledge, +# telemetry +# 9. evaluation the judge that scores finished turns + + +# ============================================================================================= +# 1. document +# ============================================================================================= + +# The schema version. Required. agentcore/v1 is the only value this release accepts. apiVersion: agentcore/v1 -# The entry key names each agent: one deployment serves one brand per entry. -# There is no root name:. Section E8 gives the name to the entries: key. - -# The line the caller hears when a turn fails. Section 8.7 names the two failures that reach it: a -# run that returns no text after 40 tool rounds, and a tool that fails four times in a row. The key -# sits at the root because every entry speaks it, and each entry may override it with its own -# fallbackReply:. The key is optional. The default is: -# "I am sorry. I could not finish that. Please say it again." -# An empty line is silence on a voice call, so a blank value is a load error. +# What the caller hears when a turn fails. Two failures reach it: a run that returns no text +# after 40 tool rounds, and a tool that fails four times in a row. Every entry speaks this line. +# An entry may override it with its own fallbackReply: (see 7. entries). +# Optional. Default: the value shown. Blank is a load error, because blank is silence on a call. fallbackReply: "I am sorry. I could not finish that. Please say it again." -# The line the caller hears when the agent refuses. Content moderation reads the caller's spoken -# input before the model runs, and the agent refuses the turn when the endpoint flags it. The key -# is optional. The default is: -# "I am sorry. I cannot help with that request." -# fallbackReply cannot serve here. Its default asks the caller to say it again, and after a refusal -# that invites the harmful request a second time. Section 8.7 also gives fallbackReply to a turn -# that FAILED, and a refusal is not a failure: the model was never asked. -# An empty line is silence on a voice call, so a blank value is a load error. +# What the caller hears when moderation flags their input and the agent refuses the turn. +# This is a separate line on purpose: fallbackReply asks the caller to say it again, and after +# a refusal that would invite the harmful request a second time. +# Optional. Default: the value shown. Blank is a load error. refusalReply: "I am sorry. I cannot help with that request." -# --------------------------------------------------------------------------------------------- -# state: the slots the guards read. + +# ============================================================================================= +# 2. state: typed slots the guards read +# ============================================================================================= # -# Every slot has exactly one writer, and section 8.3 lists the four writers. Three slots are -# reserved, always present, and read-only: stage, turnIndex, and callDurationSeconds. A document -# may read them in a rule and may not declare them here. -# --------------------------------------------------------------------------------------------- +# Every slot has exactly one writer: +# extractor a model call fills it from the finished turn (see 3. extractor) +# tool a named field of a named tool result fills it +# counter it adds one whenever its increment: rule is true +# +# Three slots are reserved, always present, and read-only: stage, turnIndex, and +# callDurationSeconds. A rule may read them. Do not declare them here. state: - # writer: extractor. A model call fills these from the finished turn. Every extractor slot is - # nullable on the wire, and a null leaves the slot at its previous value. + # writer: extractor. Nullable on the wire. A null leaves the slot at its previous value. callerAskedForHuman: { type: boolean, default: false, writer: extractor } callerSaidGoodbye: { type: boolean, default: false, writer: extractor } machineIdentified: { type: boolean, default: false, writer: extractor } resolved: { type: boolean, default: false, writer: extractor } - # writer: tool. The value comes from a named field of a named tool result. A tool result has no - # declared shape, so check 2 verifies only that the tool id exists. The declared type wins: - # AgentCore coerces the value, and leaves the slot at its default when coercion fails. + # writer: tool. from: is .. Startup checks that the tool id exists. A + # tool result has no declared shape, so the field is not checked. The value is coerced to + # type:. A value that will not coerce leaves the slot at its default. orderStatus: { type: string, writer: tool, from: lookup_order.status } - # writer: extractor, and also named in providers.knowledge.scope.fromState below, which is what - # turns these two into the turn's knowledge facets. A fromState slot has to be this exact shape — - # writer: extractor, type: string, an enum:, and no default — and the boot check says which of the - # four is missing rather than failing the load with no pointer. enum: is enforced on every write, - # not merely requested of the model: a value outside it is refused and the slot keeps its previous - # value, so a resumed call whose stored blob carries a value the corpus was never tagged with comes - # back with that slot unfilled rather than scoped to a typo. + # Knowledge facets. providers.knowledge.scope.fromState names these two, and that turns them + # into the turn's knowledge scope. A fromState slot must have exactly this shape: + # writer: extractor, type: string, an enum:, and no default. Startup names the missing piece. + # + # enum: is enforced on every write. A value outside it is refused, and the slot keeps its + # previous value. # - # applies_to breaks this file's camelCase slot naming on purpose. A fromState slot name IS the - # facet key, and scope.template turns it straight into the payload path, so these two names have to - # be spelled the way the collection spells them rather than the way the schema spells its own keys. + # The slot name IS the facet key, and scope.template turns it into the payload path. So spell + # it the way the collection spells it (applies_to), not the way this file spells its own keys. brand: { type: string, writer: extractor, description: "The brand of the caller's machine.", enum: [sole, spirit] } applies_to: { type: string, writer: extractor, description: "The model, as printed on the machine.", enum: [f63, f65, f80] } - # writer: counter. The slot increments whenever the increment rule is true. + # writer: counter. Adds one whenever increment: is true. failedResolveTurns: type: integer default: 0 @@ -73,27 +91,30 @@ state: - { "===": [ { var: stage }, "resolve" ] } - { "!": { var: resolved } } -# --------------------------------------------------------------------------------------------- -# extractor: the bridge from prose to typed state. + +# ============================================================================================= +# 3. extractor: the model call that fills the extractor slots +# ============================================================================================= # # AgentCore builds one JSON Schema from every writer: extractor slot, all nullable, and asks the # model to fill what the turn shows. The extractor never speaks, holds no tools, and decides # nothing. The guards decide. -# --------------------------------------------------------------------------------------------- extractor: - # The model this calls. The name points at providers.llm[].as. + # The model to call. ref: names a providers.llm[].as value. model: { ref: fill } - # after_reply is the only value agentcore/v1 defines. The reply streams first, the turn ends, - # and the extractor runs while the caller speaks. This is D21. + # When it runs. after_reply is the only value agentcore/v1 defines: the reply streams first, + # the turn ends, and the extractor runs while the caller speaks. when: after_reply -# --------------------------------------------------------------------------------------------- -# guards: a name mapped to a JSONLogic rule. + +# ============================================================================================= +# 4. guards: named JSONLogic rules +# ============================================================================================= # -# A name renders in the live Stateless mermaid diagram; an inline rule renders as a blob. Section -# 8.4 holds the operator allow-list, and check 4 enforces it. Use ===, never ==. -# --------------------------------------------------------------------------------------------- +# A stage exit names a guard by its key (see 7. entries). A named guard renders by name in the +# live diagram. An inline rule renders as a blob. +# Startup enforces an operator allow-list. Use ===, never ==. guards: saidGoodbye: { var: callerSaidGoodbye } @@ -125,21 +146,25 @@ guards: - { "!": { var: resolved } } - { ">=": [ { var: failedResolveTurns }, 3 ] } -# --------------------------------------------------------------------------------------------- -# tools: the four kinds. + +# ============================================================================================= +# 5. tools: what an agent may call +# ============================================================================================= # -# builtin a tool AgentCore ships. uses: names it. -# http one HTTP call. request: describes it. -# binding a host delegate. binds: names it. -# agent another declared agent. agent: names it. +# Four kinds: +# http one HTTP call. request: describes it. +# binding a host delegate. binds: names it. +# builtin a tool AgentCore ships. uses: names it. +# agent another declared agent. agent: names it. # -# A builtin tool returns an error result and does not throw. See section 8.7. -# --------------------------------------------------------------------------------------------- +# Every tool has an id:. An agent lists tool ids in its tools: (see 6. agents). +# A builtin tool returns an error result. It does not throw. tools: + # kind: http - id: lookup_order kind: http description: Read one order by its identifier. - # The raw JSON Schema of the arguments. AgentCore passes it to the model unchanged. + # The JSON Schema of the arguments. AgentCore passes it to the model unchanged. parameters: type: object properties: { orderId: { type: string } } @@ -148,14 +173,11 @@ tools: method: GET # A {name} placeholder takes its value from the tool arguments. url: "https://api.example.com/orders/{orderId}" - # ${secret:name} is a reference and never a value. The parser reads it, and - # ISecretResolverPort resolves it at startup through the four-step chain in D22. headers: { Authorization: "Bearer ${secret:orders-api-key}" } - # A binds: name is registered one of two ways, and the way decides who writes the schema. - # - # options.Bind("CreateCase", (json, ct) => ...) reads the arguments as one JSON object, so the - # declaration writes parameters: below and the host digs the values out by hand. + # kind: binding, JSON form. The host registered + # options.Bind("CreateCase", (json, ct) => ...) + # The host reads the arguments as one JSON object, so this declaration writes parameters:. - id: create_case kind: binding binds: CreateCase @@ -165,31 +187,29 @@ tools: properties: { summary: { type: string } } required: [ summary ] - # Markers, not code: each tells the model provider it may run something hosted, and only a - # provider that runs it acts on it. AgentToolCompiler drops a hosted marker, per agent, for a - # model providers.llm[] vetoed with webSearch: false or codeExecute: false, or whose adapter - # resolves no marker — a warning at compile time, never a boot failure. + # kind: builtin. These are markers, not code. Each tells the model provider it may run a hosted + # tool. A provider that does not run it ignores it. AgentToolCompiler drops the marker for a + # model vetoed with webSearch: false or codeExecute: false (see 8. providers). That is a + # warning at compile time, never a boot failure. - { id: search, kind: builtin, uses: web.search } - { id: python, kind: builtin, uses: code.execute } - # options.Bind("CloseCase", (string caseId, string reason) => ...) registers a typed method - # instead. Its parameters are the arguments, and their schema, so this declaration writes no - # parameters: at all. Writing one anyway is a boot failure: the two would drift apart. - # A [Description] attribute on a parameter is what the model reads about it. + # kind: binding, typed form. Not used in this example. The host registered + # options.Bind("CloseCase", (string caseId, string reason) => ...) + # The method parameters ARE the schema, so write no parameters: here. Writing one is a boot + # failure. A [Description] attribute on a parameter is what the model reads about it. # # - id: close_case # kind: binding # binds: CloseCase # description: Close a service case once the customer is happy. - # kind: agent is agent-as-tool, and it is not handoff. The outer agent calls the inner agent, - # reads the reply, and keeps control. graph: with pattern: handoff transfers control instead, - # so the two do not overlap. The compiler wraps the inner agent with AsAIFunction(), and the - # inner agent is the same process singleton every other caller shares. See T44. - # - # description: and parameters: both matter here, because the calling model reads both to decide - # when to delegate. AgentCore hands the filled arguments to the inner agent as one JSON object. - # Check 8 of section 8.5 walks the agent: field and rejects a delegation cycle at load. + # kind: agent. Not used in this example. This is agent-as-tool: the outer agent calls the inner + # agent, reads the reply, and keeps control. It is not a handoff. A handoff transfers control, + # and that is graph: with pattern: handoff. The inner agent is the same process singleton every + # other caller shares. + # The model reads description: and parameters: to decide when to delegate. The filled arguments + # reach the inner agent as one JSON object. Startup rejects a delegation cycle. # # - id: ask_specialist # kind: agent @@ -200,86 +220,106 @@ tools: # properties: { question: { type: string } } # required: [ question ] -# --------------------------------------------------------------------------------------------- -# agents: one stable prefix, and one delta for each stage. + +# ============================================================================================= +# 6. agents: models, prompts, knowledge, compaction +# ============================================================================================= +# +# defaults: applies to every item. An item overrides a key by declaring it. # -# defaults.instructions is the cached prefix. Anything that changes per turn must sit below it, or -# it defeats the cache for every later turn. A cache miss is a billing bug and never a capacity -# one, because a cached prompt still counts in full against the rate limit. -# --------------------------------------------------------------------------------------------- +# defaults.instructions is the cached prompt prefix. Anything that changes per turn must sit +# below it, or it defeats the cache for every later turn. A cache miss costs money, not capacity: +# a cached prompt still counts in full against the rate limit. agents: defaults: + # ref: names a providers.llm[].as value. model: { ref: reply, temperature: 0.3 } + + # The stable, cached prefix: persona, safety, transfer rules, and tool etiquette. instructions: | - # Two posture switches sit ON until you turn them off, per agent or here for all of them. - # baseInstructions: puts the framework's base above the prefix: resolve before you ask, own - # what you cannot do, do not repeat a failed call, finish. It names no persona and yields to - # everything below it. clock: tells the model the date, time, and zone once per turn, as a - # message below the cached prefix, so "the past ten days" has an anchor and nobody has to - # type the year. The zone is the server's unless the request carries X-AgentCore-Time-Zone - # with the browser's IANA id; then it is the person's. Turn either off only for an agent - # whose prompt is measured byte for byte. + + # Two posture switches. Both default to true. Set them here for every agent, or on one item. + # baseInstructions puts the framework's base prompt above the prefix: resolve before you + # ask, own what you cannot do, do not repeat a failed call, finish. It + # names no persona and yields to everything below it. + # clock tells the model the date, time, and zone once per turn, as a message + # below the cached prefix. The zone is the server's, unless the request + # carries X-AgentCore-Time-Zone with the browser's IANA id. + # Turn either off only for an agent whose prompt is measured byte for byte. # baseInstructions: true # clock: true - # citations defaults to false and scoped defaults to true. A forgotten flag is then silent - # and safe, and the dangerous direction is the one you type on purpose. + + # How an agent reads the knowledge store (providers.knowledge). + # mode prefetch: search before the model runs and inject the cards. One round trip. + # tool: give the model a search function and let it decide. + # limit cards per search. Maximum 20. + # citations the model sees the source label. Default: false. + # scoped searches are confined to the turn's facets. Default: true. + # A forgotten flag is silent and safe. The dangerous direction is the one you type on purpose. # - # scoped: true is what makes providers.knowledge.scope.template required above: a scoped turn - # filters on facets, and only this document knows where this collection keeps them. It also - # means the HOST must open a KnowledgeScope for the turn -- AgentCore opens none for you, and a - # scoped agent with no scope open says it cannot look the answer up rather than searching - # everything. Set scoped: false on an agent that is meant to read the whole corpus. + # scoped: true is why providers.knowledge.scope.template is required. It also means the HOST + # must open a KnowledgeScope for the turn. AgentCore opens none. A scoped agent with no scope + # open says it cannot look the answer up. Set scoped: false on an agent that must read the + # whole corpus. knowledge: { mode: prefetch, limit: 5, citations: false } - # Every strategy here is deterministic: the same messages give the same result, from empty - # state. Summarization is not offered on purpose — a resumed call rebuilds a new session and - # re-derives from the replayed words, so a strategy that called a model would give one call two - # different histories. tool_result folds old tool-call groups into one short line each; the - # other three are truncate, sliding_window and context_window. trigger: names exactly one of - # tokens, messages, turns or groups — naming zero or two is a load error. keep: is how many - # newest groups the strategy never touches; foldResultChars: is how much of a tool result - # tool_result carries forward per fold. There is no per-agent opt-out: an omitted block inherits - # this one, so give compaction to some agents and not others by declaring the block on those - # agents instead of here. + # Bounds the conversation an agent carries. Every strategy is deterministic: the same messages + # give the same result. There is no summarization on purpose. A resumed call rebuilds from + # the replayed words, and a model-written summary would give one call two histories. + # strategy truncate | sliding_window | tool_result | context_window + # tool_result folds old function-tool groups into one short line each. + # context_window folds first, then truncates whole groups. + # trigger exactly ONE of tokens, messages, turns, groups. Zero or two is a load + # error. + # keep the newest groups the strategy never touches. + # foldResultChars how much of a tool result one fold keeps. + # There is no per-agent opt-out. An item with no block inherits this one. To compact some + # agents only, declare the block on those items instead of here. # - # context_window here, not tool_result: tool_result folds only function tool calls, and the - # analyst agent below carries search, a hosted tool whose results are no such thing — tool_result - # would leave them growing the conversation forever. context_window folds tool_result's own work - # first and then truncates, and truncate drops whole groups regardless of what is inside them, so - # it still bounds a conversation a hosted tool is filling. + # context_window, not tool_result, here: the analyst below carries search, a hosted tool. + # tool_result folds function tools only, so a hosted tool's results would grow for ever. compaction: { strategy: context_window, trigger: { messages: 40 }, keep: 6, foldResultChars: 300 } + items: - # voice, scripted — one model round trip, no source labels spoken aloud. Inherits mode: - # prefetch, limit: 5, citations: false from defaults above. + # Voice, scripted. One round trip, no source labels spoken. Inherit knowledge from defaults. - { id: greeter, instructions: "", tools: [] } - { id: identifier, instructions: "", tools: [ lookup_order ] } - { id: resolver, instructions: "", tools: [] } - { id: escalator, instructions: "", tools: [ create_case ] } - { id: closer, instructions: "", tools: [] } - # internal — everything on, and it searches every product on purpose + # Internal. Everything on. scoped: false searches every product on purpose. - { id: analyst, instructions: "", tools: [ lookup_order, create_case, search, python ], knowledge: { mode: tool, limit: 8, citations: true, scoped: false } } - # customer facing — tools yes, citations no. It sets two keys and inherits limit: 5. + # Customer facing. Tools yes, citations no. Sets two keys and inherits limit: 5. - { id: webchat, instructions: "", tools: [ lookup_order ], knowledge: { mode: tool, citations: false } } -# --------------------------------------------------------------------------------------------- -# entries: the agents this document serves, keyed by entry name. + +# ============================================================================================= +# 7. entries: what a caller reaches +# ============================================================================================= # -# Each entry holds exactly one shape — agent:, policy:, or graph: — plus optional spoken-line -# overrides. The phone entry below runs the stage machine over string stages, run by Stateless. -# The machine picks a stage each turn, and the stage names one agent. Check 5 evaluates the exits -# of one stage as siblings: two true at the same time is a startup error. Zero true is normal and -# means the stage stays where it is; a stage may set onNoMatch: error to reject that. +# The entry key is the agent's public name. It is the {entry} in /v1/{entry}/call. There is no +# root name: key. # -# The chat entry names one agents.items id and runs it directly. -# --------------------------------------------------------------------------------------------- +# Each entry holds exactly one shape: +# agent: one agents.items id, run directly +# policy: a stage machine. Each stage names one agent. +# graph: not shown here +# plus optional fallbackReply: and refusalReply: overrides. +# +# Stage machine rules. Each turn the machine picks a stage, and the stage names the agent. After +# the turn, the exits (to:) of the current stage are tested as siblings: +# zero true the stage stays. This is normal. Set onNoMatch: error on a stage to reject it. +# one true move to that stage. +# two true a startup error. +# An exit with no when: always fires. entries: phone: - # The voice line for this entry. Overrides the root fallbackReply above. + # Overrides the root fallbackReply for this entry. fallbackReply: "Sorry — say it again." policy: initial: greeting @@ -310,144 +350,131 @@ entries: terminal: true chat: - # One agents.items id, run directly with no stage machine. + # One agents.items id, run directly. No stage machine. agent: webchat - # The refusal line for this entry. Overrides the root refusalReply above. + # Overrides the root refusalReply for this entry. refusalReply: "Sorry — I can't help with that here." -# --------------------------------------------------------------------------------------------- -# providers: the seam where the ports of section 7 bind. + +# ============================================================================================= +# 8. providers: adapters +# ============================================================================================= # -# This section configures adapters and never changes agent shape. -# --------------------------------------------------------------------------------------------- +# This section binds adapters to ports. It never changes agent shape. providers: + # The models. as: is the name every model: { ref: ... } in this file points at. + # webSearch: false and codeExecute: false are vetoes, not defaults. Omitted or true both leave + # the choice to the vendor's adapter. cheap is the least capable model, so vetoing both there + # costs nothing and stops a future hosted tool from running on it by accident. llm: - { kind: openai, model: gpt-4.1-mini, as: reply } # the voice path, chosen on latency - { kind: openai, model: gpt-5.4-nano, as: fill } # the extractor, chosen on null discipline - { kind: openai, model: gpt-4.1, as: judge } # evaluation only, chosen on judgement - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false, codeExecute: false } - # webSearch: false and codeExecute: false above are vetoes, not defaults: omitted or true both - # leave the choice to the vendor's adapter. cheap is the least capable model, so vetoing both here - # costs nothing and stops a future hosted tool from ever running on it by accident. - # Three planes, and they are not duplicates. call is the media pipe and owns the inbound route. - # speech is recognition and synthesis. telephony is call control, which must outlive any one - # media leg because a warm transfer creates a second one. - call: { kind: telnyx-relay } # the pipe: who carries the call and owns /v1/call - speech: # the ears and the mouth, named one role at a time - stt: { kind: telnyx-relay } # recognition. Bundled here, so it matches call - tts: { kind: telnyx-relay } # synthesis. Bundled here, so it matches call - telephony: { kind: telnyx } # dial, transfer, hang up. Not the pipe — that is call - moderation: { kind: openai } # reads what the CALLER said, before the model runs - # a flagged turn never reaches the model and speaks refusalReply instead. It needs the - # openai-api-key secret, the same one the llm entries above read. Remove this line to moderate - # nothing: the adapter is then never asked to build, and no key is read for it. + + # Three voice planes. They are not duplicates. + # call the media pipe. It carries the audio and owns the route /v1/{entry}/call. + # speech recognition (stt) and synthesis (tts), one role at a time. + # telephony call control: dial, transfer, hang up. It must outlive any one media leg, + # because a warm transfer creates a second leg. + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } # bundled with the relay, so it matches call + tts: { kind: telnyx-relay } # bundled with the relay, so it matches call + telephony: { kind: telnyx } + + # Reads what the CALLER said, before the model runs. A flagged turn never reaches the model and + # speaks refusalReply instead. Reads the openai-api-key secret, the same one llm reads. + # Optional. Remove the line to moderate nothing. The adapter is then never built. + moderation: { kind: openai } + + # The model that turns a query into a vector. It MUST be the model the collection was built + # with, or the startup width check refuses to open the store. Reads the openai-api-key secret. + # dimensions: is optional. Write it only if your ingester asked for a narrower vector than the + # model's own width. embeddings: { kind: openai, model: text-embedding-3-small } - # the model that turns a query into a vector. It must be the model the collection was BUILT with, - # or the startup width check refuses to open the store. It reads the same openai-api-key secret - # the llm entries read. dimensions: is optional; write it only if your ingester asked the vendor - # for a narrower vector than the model's own width. + # ------------------------------------------------------------------------------------------- - # knowledge: the collection this deployment reads, and the ONLY description of it that exists. - # - # AgentCore ships no payload field names. Not one. It does not know that a card id is usually - # called card_id, or that a body is usually called body, because "usually" is a fact about one - # ingester and this framework serves any of them. Every name below is here because THIS - # collection is shaped this way; a collection built by another tool writes a different block, - # and neither shape is privileged. + # 8.1 knowledge: the collection this deployment reads # - # The cost of that is a longer block. The benefit is that getting it wrong is LOUD. At startup - # the adapter scrolls one point and proves every role this block maps is really carried, with - # the right type, and refuses to open the store if it is not. Before that check existed, a - # mismapped source: produced a blank citation on every card, on every turn, for the life of the - # deployment, and logged nothing. + # AgentCore ships no payload field names. Every name below is here because THIS collection is + # shaped this way. A collection built by another tool writes a different block. # - # A role this collection does not carry is declared with an explicit null, never left out and - # hoped about: `source: null` means "no citation label", and the startup proof then skips it. + # Getting it wrong is loud on purpose. At startup the adapter reads one point and proves every + # role mapped below is really carried, with the right type. It refuses to open the store if not. + # A role this collection does not carry is declared with an explicit null (source: null), and + # the startup proof then skips it. # ------------------------------------------------------------------------------------------- knowledge: kind: qdrant endpoint: https://qdrant.example.com:6334 + + # Whatever this deployment's ingester writes. Point it at an alias if the ingester swaps + # collections on a rebuild. AgentCore never CREATES a collection. A missing name fails the + # start. collection: kb - # collection is whatever this deployment's ingester writes. Point it at an alias if the - # ingester swaps collections on a rebuild, and this document then never changes. - # - # AgentCore never CREATES a collection. A missing name fails the start rather than standing up - # an empty one where the ingester's alias belongs. - vector: dense # The named vector every query searches. OMIT it for a collection with one anonymous vector, - # which is the shape most Qdrant tooling creates. Naming a vector the collection does not have - # would miss every point on search with no error, so the start checks this too. + # which is what most Qdrant tooling creates. Startup checks the name exists, because a wrong + # name would miss every point with no error. + vector: dense + # Payload paths for each role. A dotted name walks into a nested struct. + # id the card id. Unmapped, the point's own key stands in. + # body required. The one role the built-in mapping cannot do without. + # lexical the full-text field the required-term leg matches on. + # source the citation label. + # locator where in the source. + # authority an INTEGER. The startup proof knows not to demand a string here. fields: - id: card_id # unmapped, the point's own key stands in for the card id - body: body # the one role the built-in mapping cannot do without - lexical: text # the full-text field the required-term leg matches on - source: source.ref # a dotted name walks into a nested struct + id: card_id + body: body + lexical: text + source: source.ref locator: source.locator - authority: authority # an INTEGER role; the startup proof knows not to demand a string + authority: authority + # How a turn's facets narrow a search. scope: + # How one facet key becomes a payload path. Flat facets are "{key}". Facets nested under + # one struct are "facets.{key}". No default. Required as soon as any agent has scoped: true, + # which is the default, so most documents need it. template: "facets.{key}" - # How one facet key becomes a payload path. There is no default, because a template is a claim - # about where one collection keeps its facets. Flat facets are "{key}"; facets nested under one - # struct are "facets.{key}". Required as soon as ANY agent declares scoped: true — which is the - # default, so most documents need it. + # How a card opts out of exact-match scoping, one facet at a time. A card tagged + # facets.brand: "*" is reachable from a scope open on any brand. That is where opening + # hours, returns, and warranty terms belong. + # Name only REACH facets here. Never name an isolation facet such as a customer id. A + # wildcard on that would serve one mis-tagged card to every caller, silently. + # Optional. Leave it out and the emitted filter is unchanged. + # Configure the wildcard first, then tag the corpus. A "*" tag on a corpus without this + # block is refused by exact match until the block lands. wildcard: value: "*" facets: [brand, applies_to] - # How a card opts out of exact-match scoping, one facet at a time — never the whole scope. A - # card tagged facets.brand: "*" is reachable from a scope open on any brand, which is where - # opening hours, returns and warranty terms belong: they are true of no single machine. Name - # only the REACH facets here, and never an isolation facet such as a customer id — a wildcard - # on that would serve one mis-tagged card to every caller on every call, silently. The block is - # opt-in: leave it out and the emitted filter is byte-identical to a document that has never - # heard of it. - # - # Configure the wildcard first, and tag the corpus after. Re-tagging a company-wide card to - # facets.brand: "*" while this block is still absent means exact match keeps refusing it for - # the whole re-tag window; flipped first, the same tag starts working the moment it lands, and - # an untagged corpus answers exactly as it did before the block existed. + # The state slots the turn's scope is built from, on top of what the host opens. Each name + # must be a state: slot with writer: extractor, type: string, an enum:, and no default. + # A slot nothing has filled yet still appears in the scope, holding the wildcard. Leaving + # it out would put no condition on that facet at all. fromState: [brand, applies_to] - # The state slots the turn's scope is built from, on top of whatever the host itself opens. - # Each name must point at a slot declared under state: above with writer: extractor, - # type: string, an enum:, and no default. A slot nothing has filled yet still appears in the - # scope, holding the wildcard, rather than being left out — leaving it out would put no - # condition on that facet at all, and every value of it would be in reach before the caller has - # said anything. - filterable: - - key: applies_to - description: "The machine the question is about, as one tag, such as ct900 or f63-2019." - # The facets a mode: tool agent may narrow its own search by. Each entry becomes one choice in - # the search tool's filters argument, and the description is the only thing the model reads - # before it picks a value — so write it for the model, not for the deployer. Adding a facet - # here is the whole job: no host writes code for one. + # The facets a mode: tool agent may narrow its own search by. Each entry is one choice in + # the search tool's filters argument. The model reads description: and nothing else before + # it picks a value, so write it for the model. Prefetch agents ignore this block. # - # A filter can only ever narrow. A facet the host opened or the extractor filled is left - # exactly as it was, because those two are who is asking and what they said; only a facet - # holding the wildcard, or one the scope does not carry at all, is open for the model to write. - # So this is safe to name a reach facet in, and still never a way out of an isolation facet. + # A filter can only narrow. A facet the host opened or the extractor filled stays as it is. + # Only a facet holding the wildcard, or one the scope does not carry, is open to the model. + # A filter that clears no card is dropped, and the search runs once more without it. # - # A filter that clears no card at all is dropped and the search runs once more without it. The - # model's filter is its guess at the subject, and a wrong guess must not become "nothing is - # documented". That costs one extra search only on a filtered search that found nothing. + # A key that matches a vocabulary: slot is matched through that slot's fold, so "the 2023 + # LCR" reaches the stored lcr-2023. A key with no such slot is matched exactly as the model + # wrote it. Prefer a key that has a slot. # - # A key whose name matches a vocabulary: slot is matched through that slot's fold, so a mention - # written "the 2023 LCR" reaches the stored lcr-2023 rather than filtering on a string no card - # carries, and a value the collection has never held is dropped rather than searched for. A key - # with no such slot is matched exactly as the model wrote it. - # - # Prefer a key that HAS such a slot. Without one nothing checks what the model invents, so it - # filters on values no card carries and the retry pays for a second search most times out. - # A facet worth filtering by is usually worth a vocabulary: slot of its own. - # - # When the vocabulary is too big for a slot or a prompt — thousands of machine tags — give the - # facet a resolve: block instead. It names a lookup the MODEL runs before it filters: one - # search narrowed to the index cards under another facet, then the value copied off the card - # it finds. The host prints the recipe on the search tool and runs nothing itself. + # When the vocabulary is too big for a slot, give the facet a resolve: block. It names a + # lookup the MODEL runs before it filters: one search under another facet, then the value + # copied off the card it finds. The host runs nothing itself. + # via must name another filterable facet, and that one may not resolve in turn. One hop. # # - key: lookup # description: "The only value is model-numbers. It returns the model cards and nothing else." @@ -457,101 +484,89 @@ providers: # via: { key: lookup, value: model-numbers } # query: " model number" # read: the Tag column of the row for the person's year - # - # via must name another filterable facet, and that one may not resolve in turn: one hop only. - # The start refuses a resolve that points at itself, at a key not listed here, or at a facet - # that has a resolve of its own. - # - # Prefetch agents ignore this block: they advertise no function, so there is no argument to fill. + filterable: + - key: applies_to + description: "The machine the question is about, as one tag, such as ct900 or f63-2019." + # Link expansion: follow a card's see-also ids to their cards. + # field the payload field that holds the ids. + # lookup uuid5 | direct | filter. filter matches on fields.id and works on any + # collection. uuid5 and direct derive the point key from the id, and startup + # proves the derivation lands on the point that holds it. + # namespace url | dns | oid | x500 | . The RFC 4122 names. + # prefix what the ingester hashed in front of the id. Default: empty. + # Optional. Omit the block to turn link expansion off. Every mode reads fields.id, so a + # links: block without one is refused. links: field: see_also - lookup: uuid5 # uuid5 | direct | filter - namespace: url # url | dns | oid | x500 | . RFC 4122's own names. - prefix: "kb:" # what the ingester hashed in front of the id. Defaults to EMPTY. - # Omit the whole block to turn link expansion off. `filter` works on any collection and matches - # on fields.id; `uuid5` and `direct` derive the point key from the id instead, and the start - # proves the derivation really lands on the point that holds it. Every mode reads fields.id, so - # a links: block without one is refused. - - analyzer: none - # Picks the terms a result MUST contain, on top of vector similarity. `none` is the only - # analyzer AgentCore ships, and it is what this line names: require nothing, rank by vector - # alone. - # - # Anything cleverer is a claim about ONE corpus's vocabulary — that a short letter run followed - # by a short digit run is a fault code, say. That is true of some collections and false of - # others, and a term wrongly made mandatory drops good answers with no error and no log line. - # So the framework holds no such rule, for the same reason it holds no field names. Write your - # own IKnowledgeQueryAnalyzer, register it with options.UseKnowledgeQueryAnalyzers, and name it + lookup: uuid5 + namespace: url + prefix: "kb:" + + # Picks the terms a result MUST contain, on top of vector similarity. none is the only + # analyzer AgentCore ships: require nothing, rank by vector alone. Anything cleverer is a + # claim about one corpus's vocabulary, so the framework holds no such rule. Write your own + # IKnowledgeQueryAnalyzer, register it with options.UseKnowledgeQueryAnalyzers, and name it # here. + analyzer: none + # How a card's source label is worded, for agents with citations: true. The shipped wording + # joins source and locator with a comma. Register your own with + # options.UseKnowledgeCitationFormatters and name it here. Registering under this same name + # replaces the shipped wording for every agent. citation: source-locator - # How each card's source label is worded, for agents that declare citations: true. The shipped - # wording joins the two roles above with a comma. Register your own with - # options.UseKnowledgeCitationFormatters and name it here; it can read anything the mapper put - # on the card, including fields no role above names. Registering under this same name replaces - # the shipped wording for every agent without touching this document. + # The cosine similarity a card must score strictly above, 0 to 1. A question the corpus does + # not answer then returns nothing instead of its nearest cards. 0 disables the floor. + # On text-embedding-3-small, 0.25 was too low to tell the two apart; 0.35 was not. scoreFloor: 0.35 - # The cosine similarity a card must score strictly above, 0 to 1. Qdrant applies it on the - # dense prefetch, so a question the corpus does not answer returns nothing instead of its three - # nearest cards. On text-embedding-3-small, 0.25 was too low to tell the two apart; 0.35 was not. - # 0 disables the floor. + # An IKnowledgePointMapper registered with options.UseKnowledgePointMappers. Not used here. + # Named, it owns the payload shape and replaces the fields: block entirely. The built-in + # mapping is public (FieldsPointMapper), so a custom mapper can compose it. # mapper: my-mapper - # An IKnowledgePointMapper registered with options.UseKnowledgePointMappers. Named, it owns the - # payload shape and replaces the fields: block entirely — for a collection whose card cannot be - # expressed as field paths at all. The built-in mapping is public (FieldsPointMapper), so a - # mapper that wants the paths plus one thing of its own composes it rather than reimplementing - # the dotted-path walk. - - # telemetry is absent here on purpose, and this host therefore exports nothing. Spans and - # measurements are still written, where they cost almost nothing with nobody listening, and log - # lines go to the console alone. Uncomment to send all three signals to Grafana Cloud (D26): + + # ------------------------------------------------------------------------------------------- + # 8.2 telemetry: not used here + # + # Absent, this host exports nothing. Spans and measurements are still written, and log lines go + # to the console alone. Uncomment to send all three signals to Grafana Cloud. # + # The endpoint is the OTLP gateway. It takes logs, traces, and metrics at one URL under one + # basic credential, so there is ONE credential here, not three. It speaks HTTP with protobuf + # bodies, not gRPC. The adapter sets that for you. + # + # Secrets: grafana-cloud-instance-id and grafana-cloud-api-token. Both optional together. + # Naming the instance id makes the token required. A missing token stops the host at startup. + # Naming neither exports with no credential, which is what a collector beside this process + # wants. + # + # sources and meters are the built-in .NET names. An EMPTY list is not an absent one: [] listens + # to AgentCore alone, which buys back the ~1,750 active series a normal replica spends against + # the 10,000 series ceiling. + # ------------------------------------------------------------------------------------------- # telemetry: # kind: grafana # endpoint: https://otlp-gateway-prod-us-east-0.grafana.net/otlp # serviceName: service-voice - # exportIntervalMs: 60000 # T61 floor. A smaller number is raised to 60000, never refused. + # exportIntervalMs: 60000 # floor. A smaller number is raised to 60000, never refused. # sources: [Microsoft.AspNetCore, System.Net.Http] # meters: [Microsoft.AspNetCore.Hosting, Microsoft.AspNetCore.Server.Kestrel, System.Net.Http] - # - # That one endpoint is the OTLP gateway, and it is why there is ONE credential here rather than - # three. Grafana Cloud's native path gives Loki, Tempo and Mimir an endpoint and a numeric user id - # each; the gateway takes all three signals at one URL under one basic credential and fans them - # out on its side. It speaks HTTP with protobuf bodies and does not answer gRPC, which the adapter - # sets for you because the OpenTelemetry .NET default on net10.0 is gRPC. - # - # It reads two secrets, and both are optional together. grafana-cloud-instance-id is the switch: - # naming one makes grafana-cloud-api-token required, and a missing token then stops the host at - # startup rather than sending telemetry Grafana answers 401 to. Naming neither exports with no - # credential at all, which is what a collector running beside this process wants. - # - # sources and meters are the built-in .NET names, so no instrumentation package is involved. An - # EMPTY list is not an absent one: [] listens to AgentCore alone, which is how a deployment buys - # back the ~1,750 active series a normal replica spends against the 10,000 ceiling of item 12. -# --------------------------------------------------------------------------------------------- -# evaluation: the share of finished turns a judge scores. + +# ============================================================================================= +# 9. evaluation: the judge that scores finished turns +# ============================================================================================= # -# Triage row T18 says the sample rate comes from configuration. A judge never blocks a turn, which -# is D9, so the rate selects a turn that already ended. -# --------------------------------------------------------------------------------------------- +# A judge never blocks a turn. The sample rate selects a turn that already ended. evaluation: - # The share of finished turns to evaluate, from 0 through 1. The key is optional and the default - # is 0, which evaluates no turn. A value outside 0 through 1 is a load error. + # The share of finished turns to score, 0 to 1. + # Optional. Default: 0, which scores no turn. A value outside 0 to 1 is a load error. sampleRate: 0 - # The model that scores a turn. It points at an `as` name of providers.llm, exactly as every other - # model reference does, so the judge reads the same vendor adapter and the same secret. The key is - # optional: a document that omits it still runs every evaluator that calls no model, and an - # evaluator that needs a judge returns no value instead of a score. - # - # The offline golden set of tests/AgentCore.Evals reads this same key, so one document tunes the - # online path and the offline gate together. - # - # temperature: 0 is the setting a judge needs. A score that moves for the same input cannot gate a - # merge. + # The model that scores a turn. ref: names a providers.llm[].as value. + # Optional. Without it, every evaluator that calls no model still runs, and an evaluator that + # needs a judge returns no value instead of a score. + # temperature: 0 is what a judge needs. A score that moves for the same input cannot gate a + # merge. The offline golden set in tests/AgentCore.Evals reads this same key. judge: { ref: judge, temperature: 0 } diff --git a/src/AgentCore.AspNetCore/Call/AgentCoreEntryMetadata.cs b/src/AgentCore.AspNetCore/Call/AgentCoreEntryMetadata.cs deleted file mode 100644 index 985d9179..00000000 --- a/src/AgentCore.AspNetCore/Call/AgentCoreEntryMetadata.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace AgentCore.AspNetCore.Call; - -/// Which entry one mapped route answers on. -/// The entry key the host named. -/// The route family: Call, Responses, or TelnyxRelay. -internal sealed record AgentCoreEntryMetadata(string Entry, string Surface); diff --git a/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs b/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs index b4bf67a3..d50b0701 100644 --- a/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs +++ b/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs @@ -11,39 +11,56 @@ namespace AgentCore.AspNetCore.Call; /// -/// Maps one inbound call route per entry, onto whichever transport the document names. +/// Maps the inbound call route, with the URL naming the entry, onto whichever transport the +/// document names. /// public static class CallEndpointRouteBuilderExtensions { - /// The route the call transport answers on when the host names none. - public const string DefaultPattern = "/v1/call"; + /// The route parameter that names the entry, as {entry} in a pattern. + public const string EntryRouteParameter = "entry"; - /// Maps the inbound call route for one entry on . + /// The route every entry answers on when the host names none. + public const string DefaultPattern = "/v1/{" + EntryRouteParameter + "}/call"; + + /// Maps every entry on , with the URL naming the entry. /// The route builder of the host. - /// The entry key this route answers on. /// The mapped endpoint, so a host adds its own conventions. - public static IEndpointConventionBuilder MapCall(this IEndpointRouteBuilder endpoints, string entry) - => endpoints.MapCall(DefaultPattern, entry); + public static IEndpointConventionBuilder MapCall(this IEndpointRouteBuilder endpoints) + => endpoints.MapCall(DefaultPattern); - /// Maps the inbound call route for one entry on one route. + /// Maps every entry on one route, with the URL naming the entry. /// The route builder of the host. - /// The route to answer on. - /// The entry key this route answers on. + /// The route to answer on. It must carry the {entry} parameter. /// The mapped endpoint, so a host adds its own conventions. - public static IEndpointConventionBuilder MapCall( - this IEndpointRouteBuilder endpoints, string pattern, string entry) + /// carries no {entry}. + public static IEndpointConventionBuilder MapCall(this IEndpointRouteBuilder endpoints, string pattern) { ArgumentNullException.ThrowIfNull(endpoints); ArgumentException.ThrowIfNullOrEmpty(pattern); - ArgumentException.ThrowIfNullOrEmpty(entry); + + if (!pattern.Contains("{" + EntryRouteParameter + "}", StringComparison.Ordinal)) + { + throw new ArgumentException( + $"The pattern '{pattern}' carries no {{{EntryRouteParameter}}} parameter, so no URL can name " + + "an entry.", + nameof(pattern)); + } // Map, and not MapGet. An HTTP/2 WebSocket arrives as CONNECT rather than GET, and MapGet // would answer 405 to it. - return endpoints.Map(pattern, (HttpContext http) => DispatchAsync(http, pattern, entry)) - .WithMetadata(new AgentCoreEntryMetadata(entry, "Call")); + return endpoints.Map(pattern, (HttpContext http) => DispatchAsync(http, pattern)); + } + + /// Reads the entry the URL names, off the {entry} route parameter. + /// The request on a call route. + /// The entry key, or the empty string when the route carries none. + public static string EntryOf(HttpContext http) + { + ArgumentNullException.ThrowIfNull(http); + return http.Request.RouteValues[EntryRouteParameter] as string ?? string.Empty; } - private static Task DispatchAsync(HttpContext http, string pattern, string entry) + private static Task DispatchAsync(HttpContext http, string pattern) { // GetService and never GetRequiredService, on purpose. A host may map this route with no // AgentCore registration at all, and such a host must get a readable reason rather than a @@ -53,14 +70,16 @@ private static Task DispatchAsync(HttpContext http, string pattern, string entry return NotRoutedAsync(http, pattern, "this host registered no AgentCore services"); } - if (boot.CallHandlers is not { } handlers) + if (boot.CallHandler is not { } handler) { return NotRoutedAsync(http, pattern, boot.CallUnroutable ?? "this host routes no inbound call"); } - return handlers.TryGetValue(entry, out var handler) + var entry = EntryOf(http); + + return boot.Entries.CallSessions.ContainsKey(entry) ? handler(http) - : NotRoutedAsync(http, pattern, EntryRegistry.UnknownEntryMessage(entry, handlers.Keys)); + : UnknownEntryAsync(http, EntryRegistry.UnknownEntryMessage(entry, boot.Entries.Entries)); } private static async Task NotRoutedAsync(HttpContext http, string pattern, string reason) @@ -70,14 +89,23 @@ private static async Task NotRoutedAsync(HttpContext http, string pattern, strin CallRouteLog.RouteNotMapped(logger, pattern, reason); - http.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; + await WriteProblemAsync(http, StatusCodes.Status503ServiceUnavailable, "This host routes no inbound call.", reason, pattern) + .ConfigureAwait(false); + } + + private static Task UnknownEntryAsync(HttpContext http, string reason) + => WriteProblemAsync(http, StatusCodes.Status404NotFound, "No entry answers on this route.", reason, http.Request.Path); + + private static async Task WriteProblemAsync(HttpContext http, int status, string title, string detail, string instance) + { + http.Response.StatusCode = status; await http.Response.WriteAsJsonAsync(new ProblemDetails { - Status = StatusCodes.Status503ServiceUnavailable, - Title = "This host routes no inbound call.", - Detail = reason, - Instance = pattern, + Status = status, + Title = title, + Detail = detail, + Instance = instance, }, http.RequestAborted).ConfigureAwait(false); } } diff --git a/src/AgentCore.AspNetCore/Call/CallSeams.cs b/src/AgentCore.AspNetCore/Call/CallSeams.cs index d63b11c2..5ed11643 100644 --- a/src/AgentCore.AspNetCore/Call/CallSeams.cs +++ b/src/AgentCore.AspNetCore/Call/CallSeams.cs @@ -3,19 +3,6 @@ namespace AgentCore.AspNetCore.Call; /// The names the call seam uses in every failure it raises. -/// -/// -/// One constant, because the guard at startup and the route extension both select the same -/// adapter and must fail with the same pointer when they cannot. -/// -/// -/// It is : spec §11's Added table does not list it, and D15 makes every -/// public member permanent. Both callers live in this assembly, and an outside implementer of -/// selects nothing — -/// -/// does that for it. -/// -/// internal static class CallSeams { /// The providers.call seam. diff --git a/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs b/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs index f0f8afc1..a1624595 100644 --- a/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs +++ b/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs @@ -9,9 +9,12 @@ namespace AgentCore.AspNetCore.Call; /// public interface ICallTransportAdapter : ICallAdapter { - /// Builds the handler one entry answers a call with. + /// Builds the handler the call route answers every entry with. /// The providers.call block, including its limits. - /// The entry key the handler answers on. - /// The delegate the entry's call route runs. - RequestDelegate CreateHandler(CallProviderConfiguration configuration, string entryName); + /// + /// The delegate the call route runs. The URL names the entry, and the route has already + /// refused one the document does not declare; the handler reads it with + /// . + /// + RequestDelegate CreateHandler(CallProviderConfiguration configuration); } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index 33d4d7f5..a2be427a 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -10,11 +10,8 @@ using AgentCore.Application.Secrets; using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tools.Registry; -using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.DependencyInjection.Startup; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -96,8 +93,8 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers, /// Gets the blob store, or when the document names none. internal IBlobStore? Blobs => Started.Blobs; - /// Gets what each entry's call route runs, keyed by entry name, or when no call routes here. - internal IReadOnlyDictionary? CallHandlers => Started.CallHandlers; + /// Gets what the call route runs, or when no call routes here. + internal RequestDelegate? CallHandler => Started.CallHandler; /// Gets why no call routes here, or when calls route. internal string? CallUnroutable => Started.CallUnroutable; @@ -267,48 +264,8 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) knowledge, seams.Call, seams.Speech, - seams.Handlers, + seams.Handler, seams.Unroutable); - - ValidateMappedEntries(configuration); - } - - /// Refuses a mapped route that names an entry the document does not declare. - /// The loaded document. It carries the declared entries. - /// A route names an unknown entry. - private void ValidateMappedEntries(AgentCoreConfiguration configuration) - { - var sources = _services?.GetService>(); - if (sources is null) - { - return; - } - - List failures = []; - foreach (var endpoint in sources.SelectMany(source => source.Endpoints)) - { - if (endpoint.Metadata.GetMetadata() is not { } mapped) - { - continue; - } - - if (!configuration.Entries.ContainsKey(mapped.Entry)) - { - failures.Add(new ConfigurationError - { - Pointer = "/entries", - Message = - $"Map{mapped.Surface} names an unknown entry. " - + EntryRegistry.UnknownEntryMessage(mapped.Entry, configuration.Entries.Keys), - Check = ConfigurationCheck.ReferenceResolution, - }); - } - } - - if (failures.Count > 0) - { - throw new ConfigurationLoadException(failures); - } } /// @@ -377,7 +334,7 @@ private sealed record BootState( IKnowledgeRetrievalPort? Knowledge, IReadOnlyList? CallAdapters, IReadOnlyList? SpeechAdapters, - IReadOnlyDictionary? CallHandlers, + RequestDelegate? CallHandler, string? CallUnroutable); } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs index d8957467..e6008eca 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs @@ -17,28 +17,28 @@ namespace AgentCore.AspNetCore.DependencyInjection.Startup; /// carries text, so it is itself both and there is nothing to build. The list goes in the container /// beside the document so that a vendor which does need constructing has somewhere to be found. /// -/// -/// What each MapCall route runs, keyed by entry name, or when this +/// +/// What the MapCall route runs for every entry, or when this /// document routes no inbound call — the host registered no transport, wrote no /// providers.call block, or named a vendor this process dials out to, which has no inbound URL. /// /// -/// Why is , in the words a deployer can act on, or +/// Why is , in the words a deployer can act on, or /// when calls route. /// internal readonly record struct CallSeamAdapters( IReadOnlyList? Call, IReadOnlyList? Speech, - IReadOnlyDictionary? Handlers, + RequestDelegate? Handler, string? Unroutable); /// The two provider blocks a call arrives on: providers.call and providers.speech. internal static class CallSeamStartup { - /// Checks the two blocks agree, and hands back the vendor lists and one handler per entry to register. - /// The loaded document. It carries both provider blocks and the entries. + /// Checks the two blocks agree, and hands back the vendor lists and the handler to register. + /// The loaded document. It carries both provider blocks. /// The options the host filled. It carries the registered vendors. - /// The two lists and the per-entry handlers, each one or when the host registered none. + /// The two lists and the handler, each one or when the host registered none. internal static CallSeamAdapters Build( AgentCoreConfiguration configuration, AgentCoreOptions options) @@ -78,13 +78,7 @@ internal static CallSeamAdapters Build( $"'{selectedCall.Kind}' is a vendor this process dials out to, so it answers no inbound route"); } - Dictionary handlers = new(StringComparer.Ordinal); - foreach (var entryName in configuration.Entries.Keys) - { - handlers[entryName] = transport.CreateHandler(callEntry, entryName); - } - - return new CallSeamAdapters(callAdapters, options.Speech, handlers, null); + return new CallSeamAdapters(callAdapters, options.Speech, transport.CreateHandler(callEntry), null); } /// Refuses a configuration that turned the call seam on and named no transport. diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index 56aa3bd5..f7dbf5d5 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -1,11 +1,8 @@ -using System.Globalization; using System.Text.Json; -using System.Text.Json.Nodes; using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Harness; -using AgentCore.Application.Tools; -using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.DependencyInjection; +using AgentCore.AspNetCore.DependencyInjection.Startup; using AgentCore.AspNetCore.Sessions; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Hosting.OpenAI; @@ -18,13 +15,16 @@ namespace AgentCore.AspNetCore.Endpoints; /// -/// The Responses path: an OpenAI-compatible POST /v1/responses over the turn loop, +/// The Responses path: an OpenAI-compatible POST /v1/{entry}/responses over the turn loop, /// with the call continuing across requests through the session store. /// public static class ResponsesEndpointRouteBuilderExtensions { - /// The route this endpoint answers on when the host names none. - public const string DefaultPattern = "/v1/responses"; + /// The route parameter that names the entry, as {entry} in a pattern. + public const string EntryRouteParameter = "entry"; + + /// The route every entry answers on when the host names none. + public const string DefaultPattern = "/v1/{" + EntryRouteParameter + "}/responses"; /// The answer header that reports the stage the machine holds. public const string StageHeaderName = "X-AgentCore-Stage"; @@ -38,33 +38,38 @@ public static class ResponsesEndpointRouteBuilderExtensions /// The OpenAI error type every refused request reports. private const string InvalidRequestError = "invalid_request_error"; - /// Maps the endpoint for one entry on . + /// Maps every entry on , with the URL naming the entry. /// The route builder of the host. - /// The entry key this route answers on. /// The mapped endpoint, so a host adds its own conventions. - public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder endpoints, string entry) - => endpoints.MapResponses(DefaultPattern, entry); + public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder endpoints) + => endpoints.MapResponses(DefaultPattern); - /// Maps the endpoint for one entry on one route. + /// Maps every entry on one route, with the URL naming the entry. /// The route builder of the host. - /// The route to answer on. - /// The entry key this route answers on. + /// The route to answer on. It must carry the {entry} parameter. /// The mapped endpoint, so a host adds its own conventions. - public static IEndpointConventionBuilder MapResponses( - this IEndpointRouteBuilder endpoints, string pattern, string entry) + /// carries no {entry}. + public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder endpoints, string pattern) { ArgumentNullException.ThrowIfNull(endpoints); ArgumentException.ThrowIfNullOrEmpty(pattern); - ArgumentException.ThrowIfNullOrEmpty(entry); - return endpoints.MapPost(pattern, (HttpContext http) => HandleAsync(http, entry)) - .WithMetadata(new AgentCoreEntryMetadata(entry, "Responses")); + if (!pattern.Contains("{" + EntryRouteParameter + "}", StringComparison.Ordinal)) + { + throw new ArgumentException( + $"The pattern '{pattern}' carries no {{{EntryRouteParameter}}} parameter, so no URL can name " + + "an entry.", + nameof(pattern)); + } + + return endpoints.MapPost(pattern, HandleAsync); } /// Runs one turn of one call, and files the session under the ids the answer carries. - private static async Task HandleAsync(HttpContext http, string entry) + private static async Task HandleAsync(HttpContext http) { var cancellationToken = http.RequestAborted; + var entry = http.Request.RouteValues[EntryRouteParameter] as string ?? string.Empty; JsonElement body; try @@ -121,17 +126,13 @@ await ResponsesRequestReader.WriteErrorAsync( conversationId = ResponsesRequestReader.ReadConversationId(body); } - AgentCoreAgent agent; - try - { - agent = http.RequestServices.GetRequiredService().Entries.ForAgent(entry); - } - catch (InvalidOperationException failure) + var entries = http.RequestServices.GetRequiredService().Entries; + if (!entries.Agents.TryGetValue(entry, out var agent)) { await ResponsesRequestReader.WriteErrorAsync( http, - StatusCodes.Status503ServiceUnavailable, - failure.Message, + StatusCodes.Status404NotFound, + EntryRegistry.UnknownEntryMessage(entry, entries.Entries), InvalidRequestError, "unknown_entry", cancellationToken).ConfigureAwait(false); @@ -316,7 +317,7 @@ await ResponsesTurnStream.WriteAsync(http, agent, sessions, session, call, input } else { - await WriteTurnAsync(http, agent, sessions, session, call, input, origin, responseId, conversationId, cancellationToken) + await ResponsesTurnReply.WriteAsync(http, agent, sessions, session, call, input, origin, responseId, conversationId, cancellationToken) .ConfigureAwait(false); } } @@ -333,77 +334,4 @@ await ResponsesRequestReader.WriteErrorAsync( cancellationToken).ConfigureAwait(false); } } - - /// Runs one turn and answers the whole reply, filed under its ids. - private static async Task WriteTurnAsync( - HttpContext http, - AgentCoreAgent agent, - AgentCoreAgentSessionStore sessions, - AgentSession session, - CallSession call, - ChatMessage input, - CallTurnOrigin? origin, - string responseId, - string? conversationId, - CancellationToken cancellationToken) - { - var turn = await call - .RunTurnMessageAtOriginAsync(input, origin, cancellationToken) - .ConfigureAwait(false); - - await SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) - .ConfigureAwait(false); - - var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, turn.ReplyText)) - { - AgentId = agent.Id, - ResponseId = responseId, - CreatedAt = turn.EndedAt, - }; - - var rendered = OpenAIResponses.WriteResponse(response, responseId, conversationId); - - // The render is a closed JsonElement, so the turn facts go on as JSON: the object - // the framework wrote, with the metadata member replaced by ours beside its own. - - var node = JsonNode.Parse(rendered.GetRawText())!.AsObject(); - JsonObject metadata = node["metadata"]?.AsObject() ?? []; - - foreach (var (name, value) in ResponsesAgentCore.TurnMetadata(call, turn)) - { - metadata[name] = value; - } - - node["metadata"] = metadata; - - http.Response.StatusCode = StatusCodes.Status200OK; - http.Response.Headers[StageHeaderName] = turn.StageAfter; - - await http.Response - .WriteAsJsonAsync(node, cancellationToken) - .ConfigureAwait(false); - } - - /// Files the session the turn just advanced, under every id that names it now. - /// - /// A conversation id is stable across turns and a response id changes each one, - /// so a turn that carried a conversation is filed under both: the next turn may - /// continue by either pointer. A chain turn without a conversation files under - /// its new response id alone. - /// - internal static async Task SaveAsync( - AgentCoreAgentSessionStore sessions, - AIAgent agent, - AgentSession session, - string responseId, - string? conversationId, - CancellationToken cancellationToken) - { - if (conversationId is not null) - { - await sessions.SaveSessionAsync(agent, conversationId, session, cancellationToken).ConfigureAwait(false); - } - - await sessions.SaveSessionAsync(agent, responseId, session, cancellationToken).ConfigureAwait(false); - } } diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesSessionFiling.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesSessionFiling.cs new file mode 100644 index 00000000..268fd0f7 --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesSessionFiling.cs @@ -0,0 +1,25 @@ +using AgentCore.AspNetCore.Sessions; +using Microsoft.Agents.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// Files a session the Responses path just advanced, under every id that names it. +internal static class ResponsesSessionFiling +{ + /// Files the session the turn just advanced, under every id that names it now. + internal static async Task SaveAsync( + AgentCoreAgentSessionStore sessions, + AIAgent agent, + AgentSession session, + string responseId, + string? conversationId, + CancellationToken cancellationToken) + { + if (conversationId is not null) + { + await sessions.SaveSessionAsync(agent, conversationId, session, cancellationToken).ConfigureAwait(false); + } + + await sessions.SaveSessionAsync(agent, responseId, session, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs new file mode 100644 index 00000000..91913b7b --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs @@ -0,0 +1,63 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Runtime; +using AgentCore.AspNetCore.Sessions; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.Hosting.OpenAI; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// The whole-reply branch of the Responses path: one turn, one JSON answer. +internal static class ResponsesTurnReply +{ + /// Runs one turn and answers the whole reply, filed under its ids. + internal static async Task WriteAsync( + HttpContext http, + AgentCoreAgent agent, + AgentCoreAgentSessionStore sessions, + AgentSession session, + CallSession call, + ChatMessage input, + CallTurnOrigin? origin, + string responseId, + string? conversationId, + CancellationToken cancellationToken) + { + var turn = await call + .RunTurnMessageAtOriginAsync(input, origin, cancellationToken) + .ConfigureAwait(false); + + await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) + .ConfigureAwait(false); + + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, turn.ReplyText)) + { + AgentId = agent.Id, + ResponseId = responseId, + CreatedAt = turn.EndedAt, + }; + + var rendered = OpenAIResponses.WriteResponse(response, responseId, conversationId); + + // The render is a closed JsonElement, so the turn facts go on as JSON: the object + // the framework wrote, with the metadata member replaced by ours beside its own. + + var node = JsonNode.Parse(rendered.GetRawText())!.AsObject(); + JsonObject metadata = node["metadata"]?.AsObject() ?? []; + + foreach (var (name, value) in ResponsesAgentCore.TurnMetadata(call, turn)) + { + metadata[name] = value; + } + + node["metadata"] = metadata; + + http.Response.StatusCode = StatusCodes.Status200OK; + http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = turn.StageAfter; + + await http.Response + .WriteAsJsonAsync(node, cancellationToken) + .ConfigureAwait(false); + } +} diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs index fbb4e0d2..74a52022 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs @@ -61,7 +61,7 @@ internal static async Task WriteAsync( await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); } - await ResponsesEndpointRouteBuilderExtensions.SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) + await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) .ConfigureAwait(false); } diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 9a12690f..c5df04e9 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -1,7 +1,7 @@ #nullable enable AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions AgentCore.AspNetCore.Call.ICallTransportAdapter -AgentCore.AspNetCore.Call.ICallTransportAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! configuration, string! entryName) -> Microsoft.AspNetCore.Http.RequestDelegate! +AgentCore.AspNetCore.Call.ICallTransportAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! configuration) -> Microsoft.AspNetCore.Http.RequestDelegate! AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.AgentCoreHttpClients(System.Net.Http.HttpMessageHandler? primaryHandler = null, Microsoft.Extensions.Logging.ILoggerFactory? loggers = null) -> void AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.CreateClient(string! name) -> System.Net.Http.HttpClient! @@ -56,25 +56,28 @@ override AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.GetSessionAsyn override AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.SaveSessionAsync(Microsoft.Agents.AI.AIAgent! agent, string! sessionStoreId, Microsoft.Agents.AI.AgentSession! session, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.CarriesText.get -> bool -AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! configuration, string! entryName) -> Microsoft.AspNetCore.Http.RequestDelegate! +AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! configuration) -> Microsoft.AspNetCore.Http.RequestDelegate! AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.Kind.get -> string! AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.TelnyxRelayCallAdapter() -> void AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter.Kind.get -> string! AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter.TelnyxRelaySpeechAdapter() -> void -const AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.DefaultPattern = "/v1/call" -> string! +const AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.DefaultPattern = "/v1/{entry}/call" -> string! +const AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.EntryRouteParameter = "entry" -> string! const AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.MaxAttempts = 3 -> int const AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.PipelineName = "agentcore-http" -> string! -const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.DefaultPattern = "/v1/responses" -> string! +const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.DefaultPattern = "/v1/{entry}/responses" -> string! +const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.EntryRouteParameter = "entry" -> string! const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.StageHeaderName = "X-AgentCore-Stage" -> string! const AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.TelnyxRelayKind = "telnyx-relay" -> string! const AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter.TelnyxRelayKind = "telnyx-relay" -> string! -static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! entry) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! -static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern, string! entry) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! +static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.EntryOf(Microsoft.AspNetCore.Http.HttpContext! http) -> string! +static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! +static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! static AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions.AddAgentCore(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions.AddAgentCoreWebSockets(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! -static AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.MapResponses(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! entry) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! -static AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.MapResponses(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern, string! entry) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! +static AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.MapResponses(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! +static AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.MapResponses(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.ConnectionLifetime -> System.TimeSpan static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.FirstRetryDelay -> System.TimeSpan static readonly AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.RequestDeadline -> System.TimeSpan diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs index eed925c9..fbc22198 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs @@ -41,13 +41,11 @@ public sealed class TelnyxRelayCallAdapter : ICallTransportAdapter public bool CarriesText => true; /// - public RequestDelegate CreateHandler(CallProviderConfiguration configuration, string entryName) + public RequestDelegate CreateHandler(CallProviderConfiguration configuration) { ArgumentNullException.ThrowIfNull(configuration); - ArgumentException.ThrowIfNullOrEmpty(entryName); var options = BuildOptions(configuration); - options.EntryName = entryName; return http => TelnyxRelayEndpointRouteBuilderExtensions.HandleAsync(http, options); } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs index 7764da1d..1e0d8dc3 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs @@ -60,8 +60,11 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort { private readonly TelnyxRelayOptions _options; + private readonly ILogger _logger; + private readonly Channel _outbound; + private readonly CancellationTokenSource _cancellation; // The same token every loop reads, captured once. Read off the field and never off @@ -69,8 +72,11 @@ internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort // its way out, and a disposed source's Token getter throws, while the struct captured here goes // on answering "already cancelled" for as long as anyone holds it. private readonly CancellationToken _connectionToken; + private readonly IHostApplicationLifetime _lifetime; + private readonly ConnectionTaskObserver _observer; + private readonly JsonWebSocketPump _pump; // The last of the two barge-in gates, in this connection's own vocabulary. SpeakAsync stamps @@ -95,20 +101,23 @@ internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort // volatile for the same reason _session is: the read loop assigns it when the setup frame // arrives, and teardown reads it from another task to find the last turn. private volatile CallTurnArbiter? _arbiter; + private bool _loggedPromptBeforeSetup; + private bool _loggedMalformedInterrupt; + private bool _loggedSecondSetup; - /// Reads this socket's entry session store, resolving it once from the registry. - /// The store for the entry the handler stamped into the options. + /// Reads this socket's entry session store, resolved once from the URL's entry. + /// The store for the entry the URL named. private ICallSessions EntrySessions() => _entrySessions - ?? throw new InvalidOperationException( - $"The entry '{_options.EntryName}' is not declared, so this socket names no session store."); + ?? throw new InvalidOperationException("This socket resolved no session store."); private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOptions options, ILogger logger) { _options = options; + _logger = logger; // A dropped socket ends this call, and so does the host shutting down. Both stop the read @@ -116,9 +125,11 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt // reads. IHostApplicationLifetime is resolved here, from the request's own provider, and // never at MapTelnyxRelay time: nothing is bound to it until a call actually arrives. _lifetime = http.RequestServices.GetRequiredService(); + _cancellation = CancellationTokenSource.CreateLinkedTokenSource( http.RequestAborted, _lifetime.ApplicationStopping); + _connectionToken = _cancellation.Token; // AddAgentCore registers this from options.TimeProvider, or TimeProvider.System when the @@ -184,7 +195,7 @@ public static Task RunAsync(HttpContext http, WebSocket socket, TelnyxRelayOptio TelnyxRelayConnection connection = new(http, socket, options, logger); connection._entrySessions = http.RequestServices .GetRequiredService() - .Entries.ForSessions(options.EntryName); + .Entries.ForSessions(CallEndpointRouteBuilderExtensions.EntryOf(http)); return connection.RunAsync(); } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs index e7440c75..88077c5c 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; -using AgentCore.AspNetCore.Call; namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; @@ -19,7 +18,7 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// Nothing here decides whether this transport is in use. The composition root reads /// providers.call while the host starts, picks the one transport it names, and asks it for a /// handler through ; -/// +/// /// owns only the route string. This type maps whatever it is handed, and it is /// so that is the only thing that /// hands it anything, apart from the test host, through InternalsVisibleTo: a host names its @@ -40,13 +39,12 @@ internal static class TelnyxRelayEndpointRouteBuilderExtensions /// reaches this value. It is kept because the relay suite maps its host through /// directly and needs one route string both sides agree on. /// - public const string DefaultPattern = "/v1/telnyx/relay"; + public const string DefaultPattern = "/v1/{" + Call.CallEndpointRouteBuilderExtensions.EntryRouteParameter + "}/telnyx/relay"; - /// Maps the socket for one entry on one route, with the limits the host chose. + /// Maps the socket on one route, with the limits the host chose. /// The route builder of the host. - /// The route to answer on. + /// The route to answer on. It must carry the {entry} parameter. /// What the endpoint may do, and for how long. - /// The entry key this route answers on. /// The mapped endpoint, so a host adds its own conventions. /// /// The options are not checked here. is what @@ -60,20 +58,15 @@ internal static class TelnyxRelayEndpointRouteBuilderExtensions public static IEndpointConventionBuilder MapTelnyxRelay( this IEndpointRouteBuilder endpoints, string pattern, - TelnyxRelayOptions options, - string entry) + TelnyxRelayOptions options) { ArgumentNullException.ThrowIfNull(endpoints); ArgumentException.ThrowIfNullOrEmpty(pattern); ArgumentNullException.ThrowIfNull(options); - ArgumentException.ThrowIfNullOrEmpty(entry); - - options.EntryName = entry; // Map, and not MapGet. An HTTP/2 WebSocket arrives as CONNECT rather than GET, and MapGet // would answer 405 to it. - return endpoints.Map(pattern, (HttpContext http) => HandleAsync(http, options)) - .WithMetadata(new AgentCoreEntryMetadata(entry, "TelnyxRelay")); + return endpoints.Map(pattern, (HttpContext http) => HandleAsync(http, options)); } internal static async Task HandleAsync(HttpContext http, TelnyxRelayOptions options) diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs index 708f04e5..5992eec0 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs @@ -9,9 +9,6 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// internal sealed class TelnyxRelayOptions { - /// Gets or sets the entry key this socket answers on. - public string EntryName { get; set; } = string.Empty; - /// Gets or sets the largest inbound frame the endpoint accepts, in bytes. /// /// The WebSocket middleware turns the request timeout off once it accepts, so nothing else diff --git a/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs b/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs index 80f7db8a..2130a943 100644 --- a/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs +++ b/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs @@ -16,27 +16,28 @@ public static class AgentCoreHostEndpointExtensions /// Installs the WebSocket middleware and maps health, the Responses endpoint, and the call socket. /// The application to map on. /// - /// The route the OpenAI-compatible Responses endpoint answers on, or for + /// The route the OpenAI-compatible Responses endpoint answers on, with {entry} naming + /// the entry, or for /// . /// - /// The entry key the Responses route answers on. - /// The entry key the call route answers on. + /// + /// The route the call socket answers on, with {entry} naming the entry, or + /// for . + /// /// The same application, so a host chains its calls. /// is . public static WebApplication MapAgentCoreHost( - this WebApplication app, string? responsesPattern = null, string responsesEntry = "main", string callEntry = "main") + this WebApplication app, string? responsesPattern = null, string? callPattern = null) { ArgumentNullException.ThrowIfNull(app); - ArgumentException.ThrowIfNullOrEmpty(responsesEntry); - ArgumentException.ThrowIfNullOrEmpty(callEntry); app.MapGet(HealthPattern, () => Results.Ok("ok")); app.UseWebSockets(); - app.MapResponses(responsesPattern ?? ResponsesEndpointRouteBuilderExtensions.DefaultPattern, responsesEntry); + app.MapResponses(responsesPattern ?? ResponsesEndpointRouteBuilderExtensions.DefaultPattern); - app.MapCall(callEntry); + app.MapCall(callPattern ?? CallEndpointRouteBuilderExtensions.DefaultPattern); return app; } diff --git a/src/AgentCore.Hosting/PublicAPI.Unshipped.txt b/src/AgentCore.Hosting/PublicAPI.Unshipped.txt index d16b7fd9..4d3e4ad2 100644 --- a/src/AgentCore.Hosting/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Hosting/PublicAPI.Unshipped.txt @@ -7,4 +7,4 @@ const AgentCore.Hosting.AgentCoreHostBuilderExtensions.DefaultConfigurationPath const AgentCore.Hosting.AgentCoreHostBuilderExtensions.McpHttpClientName = "agentcore.mcp" -> string! const AgentCore.Hosting.AgentCoreHostEndpointExtensions.HealthPattern = "/health" -> string! static AgentCore.Hosting.AgentCoreHostBuilderExtensions.AddAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplicationBuilder! builder, System.Action? configure = null) -> Microsoft.AspNetCore.Builder.WebApplicationBuilder! -static AgentCore.Hosting.AgentCoreHostEndpointExtensions.MapAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplication! app, string? responsesPattern = null, string! responsesEntry = "main", string! callEntry = "main") -> Microsoft.AspNetCore.Builder.WebApplication! +static AgentCore.Hosting.AgentCoreHostEndpointExtensions.MapAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplication! app, string? responsesPattern = null, string? callPattern = null) -> Microsoft.AspNetCore.Builder.WebApplication! diff --git a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs index a89f0e66..21821ef6 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs @@ -162,7 +162,7 @@ internal static class ExampleDocument - { kind: openai, model: gpt-5.4-nano, as: fill } # the extractor, chosen on null discipline - { kind: openai, model: gpt-4.1, as: judge } # evaluation only, chosen on judgement - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false, codeExecute: false } - call: { kind: telnyx-relay } # the pipe: who carries the call and owns /v1/call + call: { kind: telnyx-relay } # the pipe: who carries the call and owns /v1/{entry}/call speech: # the ears and the mouth, named one role at a time stt: { kind: telnyx-relay } # recognition. Bundled here, so it matches call tts: { kind: telnyx-relay } # synthesis. Bundled here, so it matches call diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs b/tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs index be6a9227..0739e800 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs @@ -45,7 +45,7 @@ public void TheTransportTheDocumentNamesIsAskedForItsHandler() var seams = Build(callKind: "bundled-fake", transport); - Assert.NotNull(seams.Handlers?["main"]); + Assert.NotNull(seams.Handler); // The block handed over is the providers.call entry of this document, not null and not some // empty stand-in. The kind is what proves which entry it is. @@ -75,7 +75,7 @@ public void ADialOutVendorRoutesNothingAndSaysWhy() // Section 12 asks this case to route nothing AND say so. A route that vanishes in silence is // how a deployment loses every call to a 404 with nothing to read. - Assert.Null(seams.Handlers); + Assert.Null(seams.Handler); Assert.NotNull(seams.Unroutable); Assert.Contains("dial-out-fake", seams.Unroutable, StringComparison.Ordinal); } @@ -86,7 +86,7 @@ public void AHostThatRegisteredNoTransportRoutesNothingAndSaysWhy() var seams = CallSeamStartup.Build( ConfigurationLoader.LoadYaml(Document("bundled-fake")), new AgentCoreOptions()); - Assert.Null(seams.Handlers); + Assert.Null(seams.Handler); Assert.NotNull(seams.Unroutable); Assert.Contains("no call adapter", seams.Unroutable, StringComparison.Ordinal); } @@ -99,11 +99,11 @@ public async Task AHostWithNoAgentCoreRegistrationAnswersTheRouteWithAReason() builder.WebHost.UseUrls("http://127.0.0.1:0"); await using var app = builder.Build(); - app.MapCall("/v1/call", "main"); + app.MapCall(); await app.StartAsync(TestContext.Current.CancellationToken); using HttpClient client = new() { BaseAddress = new Uri(Address(app)) }; - var response = await client.GetAsync("/v1/call", TestContext.Current.CancellationToken); + var response = await client.GetAsync("/v1/main/call", TestContext.Current.CancellationToken); // A readable refusal, and not the 404 a route that mapped nothing would have produced. Assert.Equal(System.Net.HttpStatusCode.ServiceUnavailable, response.StatusCode); @@ -116,7 +116,18 @@ await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken), [Fact] public void TheDefaultPatternIsVendorNeutral() { - Assert.Equal("/v1/call", CallEndpointRouteBuilderExtensions.DefaultPattern); + Assert.Equal("/v1/{entry}/call", CallEndpointRouteBuilderExtensions.DefaultPattern); + } + + [Fact] + public void ARouteWithNoEntryParameterIsRefused() + { + var builder = WebApplication.CreateSlimBuilder(); + using var app = builder.Build(); + + var failure = Assert.Throws(() => app.MapCall("/v1/call")); + + Assert.Contains("{entry}", failure.Message, StringComparison.Ordinal); } // --------------------------------------------------------------------------------------------- @@ -188,7 +199,7 @@ private sealed class FakeTransport(string kind) : ICallTransportAdapter public CallProviderConfiguration? Configuration { get; private set; } - public RequestDelegate CreateHandler(CallProviderConfiguration configuration, string entryName) + public RequestDelegate CreateHandler(CallProviderConfiguration configuration) { Configuration = configuration; return _ => Task.CompletedTask; diff --git a/tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs b/tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs index 87c29bb1..cd5577f2 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs @@ -42,7 +42,7 @@ public async Task APlainGetToTheVendorNeutralRoute_ReachesTheRelayHandler() reply, options => options.UseCall(new TelnyxRelayCallAdapter())); - var answer = await host.GetAsync(CallEndpointRouteBuilderExtensions.DefaultPattern); + var answer = await host.GetAsync(TelnyxRelayHost.MainCall); // 404 would mean MapCall mapped nothing, and every call to this deployment would be lost // with nothing to read. 400 is the relay's own HandleAsync refusing a request that is not a diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs index 89fe8db1..2c529543 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs @@ -3,6 +3,7 @@ using System.Text; using System.Threading.Channels; using AgentCore.Application.Configuration.Parsing; +using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.Vendors.TelnyxRelay; using Microsoft.AspNetCore.Http; @@ -379,8 +380,9 @@ public static async Task StartAsync( } DefaultHttpContext http = new() { RequestServices = provider }; + http.Request.RouteValues[CallEndpointRouteBuilderExtensions.EntryRouteParameter] = "main"; - TelnyxRelayOptions options = new() { EntryName = "main" }; + TelnyxRelayOptions options = new(); relay?.Invoke(options); FakeWebSocket socket = new(); diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs index adda85f1..f37ab025 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs @@ -57,7 +57,7 @@ public static async Task StartAsync( }); var app = builder.Build(); - app.MapResponses("main"); + app.MapResponses(); await app.StartAsync(); var address = app.Services @@ -77,7 +77,7 @@ public static async Task StartAsync( /// The answer. public async Task PostAsync(string json, IReadOnlyDictionary? headers = null) { - using HttpRequestMessage request = new(HttpMethod.Post, ResponsesEndpointRouteBuilderExtensions.DefaultPattern) + using HttpRequestMessage request = new(HttpMethod.Post, "/v1/main/responses") { Content = new StringContent(json, Encoding.UTF8, "application/json"), }; diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs index 3e1f8d7a..c1384eb0 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs @@ -28,6 +28,12 @@ namespace AgentCore.AspNetCore.Tests.Fakes; /// internal sealed class TelnyxRelayHost : IAsyncDisposable { + /// The vendor-neutral call route, with the document's one entry filled in. + public const string MainCall = "/v1/main/call"; + + /// The relay's own route, with the document's one entry filled in. + public const string MainRelay = "/v1/main/telnyx/relay"; + private readonly WebApplication _app; private readonly Uri _socketAddress; private readonly HttpClient _client; @@ -92,7 +98,7 @@ public static Task StartAsync( /// transport the seam is meant to pick. /// /// Anything a test adds to the logging pipeline. - /// The started host, answering on CallEndpointRouteBuilderExtensions.DefaultPattern. + /// The started host, answering on . /// /// maps the relay through the internal MapTelnyxRelay and so /// bypasses the seam entirely, which is right for the several dozen frame-level tests that use @@ -167,15 +173,15 @@ private static async Task StartCoreAsync( { // The vendor-neutral seam picks the transport out of providers.call and the adapter the // test registered. Nothing here names a route or a vendor. - route = CallEndpointRouteBuilderExtensions.DefaultPattern; - app.MapCall("main"); + route = MainCall; + app.MapCall(); } else { - route = TelnyxRelayEndpointRouteBuilderExtensions.DefaultPattern; + route = MainRelay; var relayOptions = new TelnyxRelayOptions(); relay?.Invoke(relayOptions); - app.MapTelnyxRelay(route, relayOptions, "main"); + app.MapTelnyxRelay(TelnyxRelayEndpointRouteBuilderExtensions.DefaultPattern, relayOptions); } await app.StartAsync(); diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs index a1b7dbaf..1d5adbea 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs @@ -23,7 +23,7 @@ public async Task APlainGet_IsRefused() using FragmentingChatClient reply = new("hello"); await using var host = await TelnyxRelayHost.StartAsync(TelnyxRelayTurnTests.PolicyYaml, reply); - var answer = await host.GetAsync(TelnyxRelayEndpointRouteBuilderExtensions.DefaultPattern); + var answer = await host.GetAsync(TelnyxRelayHost.MainRelay); Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); } @@ -40,7 +40,7 @@ public async Task AHostThatForgotUseWebSockets_FailsWithAMessageThatNamesTheFix( TelnyxRelayTurnTests.PolicyYaml, reply); - var answer = await host.GetAsync(TelnyxRelayEndpointRouteBuilderExtensions.DefaultPattern); + var answer = await host.GetAsync(TelnyxRelayHost.MainRelay); Assert.Equal(HttpStatusCode.InternalServerError, answer.StatusCode); Assert.Contains("UseWebSockets", host.LastError, StringComparison.Ordinal); diff --git a/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs b/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs index 51225b41..8a64c09d 100644 --- a/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs +++ b/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs @@ -339,6 +339,9 @@ public async Task HealthAnswersOnTheMappedRoute() Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); } + /// The default Responses route, with the document's one entry filled in. + private const string MainResponses = "/v1/main/responses"; + [Fact] public async Task ResponsesAnswersOnTheDefaultRoute() { @@ -347,26 +350,63 @@ public async Task ResponsesAnswersOnTheDefaultRoute() // No user message is a caller mistake this endpoint names, and naming it proves the route // reached the endpoint rather than the 404 handler. - var response = await PostEmptyAsync(client, ResponsesEndpointRouteBuilderExtensions.DefaultPattern); + var response = await PostEmptyAsync(client, MainResponses); Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode); } + [Fact] + public async Task ResponsesRefusesAnEntryTheDocumentDoesNotDeclare() + { + await using var app = await StartMappedAsync(); + using HttpClient client = new() { BaseAddress = Address(app) }; + + var response = await PostEmptyAsync(client, "/v1/nobody/responses"); + + Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode); + var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + Assert.Contains("\"code\":\"unknown_entry\"", body); + Assert.Contains("Valid entries: main", body); + } + [Fact] public async Task ResponsesMovesWhenTheHostNamesAnotherRoute() { // A host that mounts a second Responses surface of its own needs this one out of the // way, and it must actually leave the default route behind when it moves. - const string Moved = "/agentcore/v1/responses"; - await using var app = await StartMappedAsync(Moved); + await using var app = await StartMappedAsync("/agentcore/v1/{entry}/responses"); using HttpClient client = new() { BaseAddress = Address(app) }; Assert.Equal( System.Net.HttpStatusCode.BadRequest, - (await PostEmptyAsync(client, Moved)).StatusCode); + (await PostEmptyAsync(client, "/agentcore/v1/main/responses")).StatusCode); Assert.Equal( System.Net.HttpStatusCode.NotFound, - (await PostEmptyAsync(client, ResponsesEndpointRouteBuilderExtensions.DefaultPattern)).StatusCode); + (await PostEmptyAsync(client, MainResponses)).StatusCode); + } + + [Fact] + public async Task CallRefusesAnEntryTheDocumentDoesNotDeclare() + { + await using var app = await StartMappedAsync(); + using HttpClient client = new() { BaseAddress = Address(app) }; + + var response = await client.GetAsync("/v1/nobody/call", TestContext.Current.CancellationToken); + + Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode); + Assert.Contains( + "Valid entries: main", + await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task ResponsesRefusesARouteWithNoEntryParameter() + { + await using var app = await BuildAsync(); + + var failure = Assert.Throws(() => app.MapAgentCoreHost("/v1/responses")); + + Assert.Contains("{entry}", failure.Message); } // --------------------------------------------------------------------------------------------- From e494667554a4a27742979a09a0fcaa6901469ef6 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 18 Sep 2026 13:15:47 -0600 Subject: [PATCH 16/35] feat: Update ChatCallTitler to include system message and improve transcript handling in tests --- .../Calls/ChatCallTitler.cs | 25 ++++++++++++++-- .../Calls/ChatCallTitlerTests.cs | 30 ++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/AgentCore.Application/Calls/ChatCallTitler.cs b/src/AgentCore.Application/Calls/ChatCallTitler.cs index 4d7e21df..6a8ba70d 100644 --- a/src/AgentCore.Application/Calls/ChatCallTitler.cs +++ b/src/AgentCore.Application/Calls/ChatCallTitler.cs @@ -15,9 +15,12 @@ public sealed class ChatCallTitler(ICallStore calls, IChatClient client) : ICall // charged for. The cap holds for a caller's messages too, which arrive unbounded. private const int MaxMessages = 6; + // A system message private const string Instruction = - "Write a title for this conversation. Six words at most. No quotation marks, no final stop. " - + "Reply with the title alone."; + "You name conversations. The user message holds a transcript, one line per turn. " + + "Write a title for it: the topic the person raised, six words at most, " + + "no quotation marks, no final stop. When the transcript raises no topic yet, " + + "use the person's own first words as the title. Reply with the title alone."; /// public IAsyncEnumerable GenerateAsync( @@ -93,7 +96,10 @@ private async IAsyncEnumerable NameAsync( [EnumeratorCancellation] CancellationToken cancellationToken) { List prompt = - [.. messages.Take(MaxMessages), new ChatMessage(ChatRole.User, Instruction)]; + [ + new ChatMessage(ChatRole.System, Instruction), + new ChatMessage(ChatRole.User, Transcript(messages.Take(MaxMessages))), + ]; StringBuilder title = new(); @@ -119,4 +125,17 @@ private async IAsyncEnumerable NameAsync( await calls.RenameAsync(callId, whole, cancellationToken).ConfigureAwait(false); } } + + /// Folds the messages into one text, one role: words line per message. + private static string Transcript(IEnumerable messages) + { + StringBuilder text = new(); + + foreach (var message in messages) + { + text.Append(message.Role.Value).Append(": ").AppendLine(message.Text); + } + + return text.ToString(); + } } diff --git a/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs b/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs index a2e6817d..1d3f2e1a 100644 --- a/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs @@ -144,10 +144,32 @@ public async Task GenerateFromAsync_MoreMessagesThanTheCap_SendsOnlyTheFirstSix( await CollectAsync(titler.GenerateFromAsync("c1", many, Token)); // Assert - // The titler appends the instruction as the last message; everything before it is the caller's. - Assert.Equal( - ["m0", "m1", "m2", "m3", "m4", "m5"], - client.Seen.SkipLast(1).Select(message => message.Text)); + // The instruction is the system message; the caller's words are folded into the one user message. + var transcript = Assert.Single(client.Seen, message => message.Role == ChatRole.User).Text; + Assert.Equal("user: m0\nuser: m1\nuser: m2\nuser: m3\nuser: m4\nuser: m5\n", transcript.ReplaceLineEndings("\n")); + } + + [Fact] + public async Task GenerateFromAsync_Always_SendsTheInstructionAsTheSystemMessageAndTheWordsAsTheUser() + { + // Arrange + InMemoryCallStore calls = new(); + await calls.CreateAsync("c1", Token); + StubChatClient client = new("A squeaky belt"); + ChatCallTitler titler = new(calls, client); + + // Act + await CollectAsync(titler.GenerateFromAsync("c1", Said("my belt squeaks"), Token)); + + // Assert + Assert.Collection( + client.Seen, + message => Assert.Equal(ChatRole.System, message.Role), + message => + { + Assert.Equal(ChatRole.User, message.Role); + Assert.Equal("user: my belt squeaks", message.Text.Trim()); + }); } private static List Said(string words) => [new ChatMessage(ChatRole.User, words)]; From 74f759052a94810e05eac018873eb365c7e8820f Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 18 Sep 2026 16:26:30 -0600 Subject: [PATCH 17/35] feat(tools): replace code.execute with file.publish and add shell env options --- config/example.yaml | 25 +- .../Blobs/BlobMediaTypes.cs | 40 ++++ src/AgentCore.Application/Blobs/BlobPolicy.cs | 12 +- .../Calls/CallRepository.cs | 8 +- .../Compilation/AgentCaptureCompiler.cs | 48 ---- .../Compilation/AgentCompilationContext.cs | 14 +- .../AgentContextProviderCompiler.cs | 5 +- .../Compilation/AgentHarnessProviders.cs | 76 +----- .../Compilation/AgentShellOptionsCompiler.cs | 126 ++++++++++ .../Compilation/AgentToolCompiler.cs | 2 +- .../Compilation/ConfigurationCompiler.cs | 3 +- .../Schema/AgentShellConfiguration.cs | 22 ++ .../Schema/LlmProviderConfiguration.cs | 6 - .../Schema/agentcore-v1.schema.json | 33 ++- src/AgentCore.Application/Diagnostics/Log.cs | 26 +- .../PublicAPI.Unshipped.txt | 34 ++- .../AuditingFunctionInvokingChatClient.cs | 22 +- .../Runtime/CallSession/CallTurn.cs | 1 + .../Runtime/CallSession/CallTurnRunner.cs | 2 + .../Runtime/Harness/BackgroundChildAgent.cs | 29 ++- .../Runtime/Harness/BlobOwnerKey.cs | 5 +- .../Runtime/Harness/CallShellOptions.cs | 18 +- .../Runtime/Harness/CallShells.cs | 68 +++++- .../Harness/HostedFileCaptureProvider.cs | 167 ------------- .../Runtime/Turn/TurnAttachments.cs | 98 ++++++++ .../Runtime/Turn/TurnFiles.cs | 22 ++ .../Runtime/Turn/TurnRenders.cs | 88 +------ .../Runtime/Turn/TurnSources.cs | 96 +------- .../Runtime/TurnInvocation.cs | 3 + .../Secrets/ResolvedSecrets.cs | 18 ++ .../Tools/Builtin/BuiltinToolNames.cs | 4 +- .../Tools/Builtin/BuiltinToolOptions.cs | 7 +- .../Tools/Builtin/BuiltinToolSource.cs | 2 +- .../Builtin/CodeExecuteToolDefinition.cs | 20 -- .../Tools/Builtin/FilePublishTool.cs | 182 ++++++++++++++ .../Builtin/FilePublishToolDefinition.cs | 41 ++++ .../Tools/Builtin/IBuiltinToolDefinition.cs | 13 +- .../Transcript/FileContent.cs | 19 +- .../DependencyInjection/AgentCoreBoot.cs | 15 +- .../Startup/CompilationStartup.cs | 9 +- .../Startup/ToolRegistryStartup.cs | 11 +- .../Endpoints/ResponsesContracts.cs | 7 +- .../Endpoints/ResponsesTurnStream.cs | 4 +- .../Endpoints/TurnStreamFiles.cs | 9 +- .../Blobs/S3/S3BlobStore.cs | 14 +- .../Llm/OpenAI/OpenAiChatClientAdapter.cs | 3 +- .../Llm/OpenAI/OpenAiSandboxFilesClient.cs | 98 -------- .../Blobs/BlobPolicyTests.cs | 16 ++ .../Blobs/BlobStoreFactoryTests.cs | 16 +- .../Compilation/HostedWebSearchDropTests.cs | 28 --- .../Compilation/ShellOptionsCompilerTests.cs | 96 ++++++++ .../Configuration/ConfigurationLoaderTests.cs | 4 +- .../Configuration/ExampleDocument.cs | 28 ++- .../Fakes/ScriptedHostedFileClient.cs | 80 ------- .../Harness/BackgroundChildAgentTests.cs | 32 +++ .../Runtime/Harness/CallShellsTests.cs | 30 +++ .../Harness/HostedFileCaptureProviderTests.cs | 224 ------------------ .../Runtime/Turn/TurnFilesTests.cs | 79 ++++++ .../Secrets/ResolvedSecretsTests.cs | 28 +++ .../Tools/BuiltinToolTests.cs | 15 +- .../Tools/CodeExecuteToolDefinitionTests.cs | 37 --- .../Tools/FilePublishBackgroundChildTests.cs | 74 ++++++ .../Tools/FilePublishToolDefinitionTests.cs | 202 ++++++++++++++++ .../Transcript/FileContentTests.cs | 8 +- .../ToolRegistryStartupTests.cs | 2 + .../Endpoints/FileWireTests.cs | 201 ++++++++++++++++ .../Endpoints/TurnStreamFilesTests.cs | 4 +- .../Fakes/FakeBlobStoreAdapter.cs | 65 +++++ .../Fakes/ResponsesHost.cs | 3 + .../Blobs/S3/S3BlobStoreLinkTests.cs | 20 +- .../Llm/OpenAiReasoningEffortTests.cs | 26 +- .../Llm/OpenAiSandboxFilesClientTests.cs | 154 ------------ 72 files changed, 1769 insertions(+), 1278 deletions(-) create mode 100644 src/AgentCore.Application/Blobs/BlobMediaTypes.cs delete mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs delete mode 100644 src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs create mode 100644 src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs create mode 100644 src/AgentCore.Application/Runtime/Turn/TurnFiles.cs delete mode 100644 src/AgentCore.Application/Tools/Builtin/CodeExecuteToolDefinition.cs create mode 100644 src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs create mode 100644 src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs delete mode 100644 src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs create mode 100644 tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs delete mode 100644 tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs delete mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Turn/TurnFilesTests.cs delete mode 100644 tests/AgentCore.Application.Tests/Tools/CodeExecuteToolDefinitionTests.cs create mode 100644 tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs create mode 100644 tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Fakes/FakeBlobStoreAdapter.cs delete mode 100644 tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs diff --git a/config/example.yaml b/config/example.yaml index 0d77c40e..89fc5424 100644 --- a/config/example.yaml +++ b/config/example.yaml @@ -189,10 +189,15 @@ tools: # kind: builtin. These are markers, not code. Each tells the model provider it may run a hosted # tool. A provider that does not run it ignores it. AgentToolCompiler drops the marker for a - # model vetoed with webSearch: false or codeExecute: false (see 8. providers). That is a - # warning at compile time, never a boot failure. + # model vetoed with webSearch: false (see 8. providers). That is a warning at compile time, + # never a boot failure. - { id: search, kind: builtin, uses: web.search } - - { id: python, kind: builtin, uses: code.execute } + + # kind: builtin, a plain function. The model calls it when a file in the call's workspace is a + # deliverable: the file is copied into providers.blobs (see 8. providers), owned by the call, + # and the person gets a link. Files not published are lost when the call ends. Needs + # providers.blobs and options.UseWorkspace(...) on the host; missing either fails the boot. + - { id: publish, kind: builtin, uses: file.publish } # kind: binding, typed form. Not used in this example. The host registered # options.Bind("CloseCase", (string caseId, string reason) => ...) @@ -290,7 +295,7 @@ agents: - { id: closer, instructions: "", tools: [] } # Internal. Everything on. scoped: false searches every product on purpose. - - { id: analyst, instructions: "", tools: [ lookup_order, create_case, search, python ], + - { id: analyst, instructions: "", tools: [ lookup_order, create_case, search, publish ], knowledge: { mode: tool, limit: 8, citations: true, scoped: false } } # Customer facing. Tools yes, citations no. Sets two keys and inherits limit: 5. @@ -363,14 +368,14 @@ entries: # This section binds adapters to ports. It never changes agent shape. providers: # The models. as: is the name every model: { ref: ... } in this file points at. - # webSearch: false and codeExecute: false are vetoes, not defaults. Omitted or true both leave - # the choice to the vendor's adapter. cheap is the least capable model, so vetoing both there - # costs nothing and stops a future hosted tool from running on it by accident. + # webSearch: false is a veto, not a default. Omitted or true both leave the choice to the + # vendor's adapter. cheap is the least capable model, so vetoing it there costs nothing and + # stops a future hosted tool from running on it by accident. llm: - { kind: openai, model: gpt-4.1-mini, as: reply } # the voice path, chosen on latency - { kind: openai, model: gpt-5.4-nano, as: fill } # the extractor, chosen on null discipline - { kind: openai, model: gpt-4.1, as: judge } # evaluation only, chosen on judgement - - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false, codeExecute: false } + - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false } # Three voice planes. They are not duplicates. # call the media pipe. It carries the audio and owns the route /v1/{entry}/call. @@ -394,6 +399,10 @@ providers: # model's own width. embeddings: { kind: openai, model: text-embedding-3-small } + # Where a file the model publishes (file.publish) is kept after the call, owned by the call id. + # Any S3-compatible store. Reads the s3-access-key and s3-secret-key secrets. + blobs: { kind: s3, endpoint: https://s3.us-east-005.backblazeb2.com, bucket: agentcore-files, region: us-east-005 } + # ------------------------------------------------------------------------------------------- # 8.1 knowledge: the collection this deployment reads # diff --git a/src/AgentCore.Application/Blobs/BlobMediaTypes.cs b/src/AgentCore.Application/Blobs/BlobMediaTypes.cs new file mode 100644 index 00000000..f5859a34 --- /dev/null +++ b/src/AgentCore.Application/Blobs/BlobMediaTypes.cs @@ -0,0 +1,40 @@ +namespace AgentCore.Application.Blobs; + +/// The media type a file name implies, one entry per . +internal static class BlobMediaTypes +{ + /// The type for a name whose extension is not listed. A browser saves it rather than showing it. + public const string Fallback = "application/octet-stream"; + + private static readonly Dictionary ByExtension = new(StringComparer.OrdinalIgnoreCase) + { + ["png"] = "image/png", + ["jpg"] = "image/jpeg", + ["jpeg"] = "image/jpeg", + ["gif"] = "image/gif", + ["webp"] = "image/webp", + ["pdf"] = "application/pdf", + ["csv"] = "text/csv", + ["txt"] = "text/plain", + ["md"] = "text/markdown", + ["json"] = "application/json", + ["zip"] = "application/zip", + ["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation", + }; + + /// Reads the media type off a file name's extension. + /// The file name. + /// The IANA media type, or when the extension is not listed. + public static string Of(string name) + { + ArgumentNullException.ThrowIfNull(name); + + var extension = Path.GetExtension(name).TrimStart('.'); + + return extension.Length > 0 && ByExtension.TryGetValue(extension, out var mediaType) + ? mediaType + : Fallback; + } +} diff --git a/src/AgentCore.Application/Blobs/BlobPolicy.cs b/src/AgentCore.Application/Blobs/BlobPolicy.cs index 8545eb6f..4339d589 100644 --- a/src/AgentCore.Application/Blobs/BlobPolicy.cs +++ b/src/AgentCore.Application/Blobs/BlobPolicy.cs @@ -8,9 +8,15 @@ public sealed class BlobPolicy /// The cap a sandbox file must fit under. 10 MB. public const long DefaultMaxBytes = 10L * 1024 * 1024; - /// The extensions stored by default: png, pdf, csv. - public static readonly IReadOnlySet DefaultExtensions = - new HashSet(StringComparer.OrdinalIgnoreCase) { "png", "pdf", "csv" }; + /// + /// The extensions stored by default: images, PDF, plain data and Office files. Never + /// html, svg or xml: a presigned link serves those as a live page from + /// the bucket, so a model-written file could pose as one of the operator's own. + /// + public static readonly IReadOnlySet DefaultExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "png", "jpg", "jpeg", "gif", "webp", "pdf", "csv", "txt", "md", "json", "zip", "xlsx", "docx", "pptx", + }; /// The policy the harness uses when the document names none. public static BlobPolicy Default { get; } = new(DefaultMaxBytes, DefaultExtensions); diff --git a/src/AgentCore.Application/Calls/CallRepository.cs b/src/AgentCore.Application/Calls/CallRepository.cs index 13277b95..b73accf2 100644 --- a/src/AgentCore.Application/Calls/CallRepository.cs +++ b/src/AgentCore.Application/Calls/CallRepository.cs @@ -7,8 +7,8 @@ namespace AgentCore.Application.Calls; /// -/// Everything a host or a consumer does with a stored call: its row, its words, and the files its -/// sandbox wrote. The one door; the stores behind it are adapters nobody else needs to name. +/// Everything a host or a consumer does with a stored call: its row, its words, and the files it +/// published. The one door; the stores behind it are adapters nobody else needs to name. /// public sealed class CallRepository : ICallStore { @@ -18,7 +18,7 @@ public sealed class CallRepository : ICallStore /// Makes the repository over the stores the document opened. /// The store the rows and words live in. - /// The store the sandbox files live in, or when the document names none. + /// The store the published files live in, or when the document names none. public CallRepository(ICallStore calls, IBlobStore? blobs) { ArgumentNullException.ThrowIfNull(calls); @@ -33,7 +33,7 @@ public CallRepository(ICallStore calls, IBlobStore? blobs) /// The adapter the rows live in. For a host checking which vendor it opened; go through the repository for everything else. public ICallStore Store => _calls; - /// Links every sandbox file the messages carry and the capture kept, each name once, in first-seen order. + /// Links every published file the messages carry and the store kept, each name once, in first-seen order. /// The call that owns the files. /// The messages to read the references off: the stored transcript, or one turn's updates. /// Cancels the signing. diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs deleted file mode 100644 index 5a18eaa1..00000000 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCaptureCompiler.cs +++ /dev/null @@ -1,48 +0,0 @@ -#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. - -using AgentCore.Application.Blobs; -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime.Harness; -using Microsoft.Extensions.AI; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; - -namespace AgentCore.Application.Configuration.Compilation; - -/// -/// The provider that keeps what an agent's sandbox wrote. It is added when three things hold: the -/// agent runs a hosted code tool, its vendor can download what the sandbox wrote, and the document -/// opened a blob store. The code.execute tool is the switch; no yaml on the agent names this. -/// -internal static class AgentCaptureCompiler -{ - /// Builds the capture provider, or nothing when there is nothing to capture. - /// The agents.defaults section, or . - /// The agent being compiled. - /// The compile-time seams, including the blob store and the chat clients. - /// This agent's compiled tools, or when it advertises none. - public static HostedFileCaptureProvider? Build( - AgentDefaults? defaults, - AgentConfiguration item, - AgentCompilationContext context, - IReadOnlyList? tools) - { - if (context.Blobs is not { } blobs || tools?.Any(static tool => tool is HostedCodeInterpreterTool) != true) - { - return null; - } - - var files = context.ChatClients.GetChatClient(item.Model ?? defaults?.Model).GetService(); - - if (files is null) - { - return null; - } - - return new HostedFileCaptureProvider( - files, - blobs, - BlobPolicy.Default, - context.Loggers?.CreateLogger() ?? NullLogger.Instance); - } -} diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs index 91ce598c..1d70fca4 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Evaluation; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; +using AgentCore.Application.Secrets; using AgentCore.Application.Skills; using AgentCore.Application.Tools.Registry; using Microsoft.Extensions.Logging; @@ -53,13 +54,6 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// public IKnowledgeRetrievalPort? Knowledge { get; init; } - /// - /// Gets or sets the store a sandbox file is kept in after the run, or - /// when the document names no providers.blobs. With it null, a code.execute agent - /// captures nothing. - /// - public IBlobStore? Blobs { get; init; } - /// /// Gets or sets the skills every agent's skills: list is drawn from, or /// when the host bound no skills folder. @@ -87,4 +81,10 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// when the host bound no workspace root. /// public string? WorkspaceRoot { get; init; } + + /// + /// Gets or sets the set a shell: block's env: resolves its ${secret:name} + /// references against, or to treat every such reference as unresolved. + /// + public ResolvedSecrets? Secrets { get; init; } } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index f5a73a24..a36d00ef 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -32,8 +32,7 @@ public static List Build( ResolvedClarification clarification, KnowledgeScopeConfiguration? scope, Func resolve, - ICollection? background = null, - IReadOnlyList? tools = null) + ICollection? background = null) { List providers = [new TurnContextProvider()]; @@ -74,7 +73,7 @@ public static List Build( #pragma warning restore MAAI001 } - AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background, tools); + AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background); if (AgentKnowledge.Compose(defaults, item) is not { } composed) { diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 283d3f38..17bf41c5 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -1,10 +1,8 @@ -using System.Text.RegularExpressions; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; -using Microsoft.Agents.AI.Tools.Shell; using Microsoft.Extensions.AI; namespace AgentCore.Application.Configuration.Compilation; @@ -67,7 +65,6 @@ internal static class AgentHarnessProviders /// This agent's JSON pointer, for a memory:, files:, shell:, or background: failure. /// Resolves an agents.items id to its compiled agent, or when undeclared. /// Collects the built background providers, so the call can release their sessions when it ends. - /// This agent's compiled tools, or when it advertises none. public static void Add( List providers, AgentDefaults? defaults, @@ -75,8 +72,7 @@ public static void Add( AgentCompilationContext context, string pointer, Func resolve, - ICollection? background = null, - IReadOnlyList? tools = null) + ICollection? background = null) { var harness = AgentHarness.Compose(defaults, item); @@ -107,7 +103,7 @@ public static void Add( if (item.Shell is { } shell) { - var options = BuildShellOptions(item, shell, context, pointer); + var options = AgentShellOptionsCompiler.Build(item, shell, context, pointer); providers.Add(new CallShellProvider(options)); providers.Add(new CallShellEnvironmentProvider(options)); } @@ -118,11 +114,6 @@ public static void Add( providers.Add(provider); background?.Add(provider); } - - if (AgentCaptureCompiler.Build(defaults, item, context, tools) is { } capture) - { - providers.Add(capture); - } } #pragma warning restore MAAI001 @@ -295,69 +286,6 @@ private static CallFilesProvider BuildFilesProvider( #pragma warning restore MAAI001 - private static CallShellOptions BuildShellOptions( - AgentConfiguration item, - ShellConfiguration shell, - AgentCompilationContext context, string pointer) - { - if (context.WorkspaceRoot is null) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "shell"), - $"the agent '{item.Id}' declares a shell: block and this host bound no workspace " - + "root, so the shell has no working directory. Call options.UseWorkspace(...) with " - + "the folder, or remove the shell: block."); - } - - var policy = shell.Policy is { } declared ? BuildPolicy(item, declared, pointer) : null; - - var timeout = shell.TimeoutSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : (TimeSpan?)null; - - return new CallShellOptions(shell.Kind, policy, timeout); - } - - private static ShellPolicy BuildPolicy( - AgentConfiguration item, - ShellPolicyConfiguration policy, - string pointer) - { - // ShellPolicy treats a supplied-but-empty allow list as deny-all (it denies any command that - // matches none of the allow patterns, and an empty list matches nothing), so an agent that - // declares no allow: must reach the executor with allowList: null, not an empty collection. - var allow = policy.Allow.Count == 0 ? null : policy.Allow; - - try - { - return new ShellPolicy(denyList: policy.Deny, allowList: allow); - } - catch (ArgumentException exception) - { - // ShellPolicy compiles every pattern into a Regex eagerly in its own constructor, so a - // bad pattern in either list throws here, at compile time, rather than at the model's - // first command. - var bad = policy.Deny.Concat(allow ?? []) - .FirstOrDefault(pattern => !IsValidRegex(pattern)); - - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "shell"), "policy"), - $"the agent '{item.Id}' declares a shell: policy whose pattern '{bad}' is not a " - + $"valid regex: {exception.Message}"); - } - } - - private static bool IsValidRegex(string pattern) - { - try - { - _ = new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); - return true; - } - catch (ArgumentException) - { - return false; - } - } - #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. /// diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs new file mode 100644 index 00000000..19154d57 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs @@ -0,0 +1,126 @@ +using System.Text.RegularExpressions; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Secrets; +using Microsoft.Agents.AI.Tools.Shell; + +namespace AgentCore.Application.Configuration.Compilation; + +/// Compiles one agent's shell: block into . +internal static class AgentShellOptionsCompiler +{ + /// Builds this agent's shell options from its declared shell: block. + /// The agent being compiled. + /// The declared block. + /// The compile-time seams, including the bound workspace root and resolved secrets. + /// This agent's JSON pointer. + /// + /// The block names no workspace root, a Docker-only key under kind: local, or a policy + /// pattern that is not a valid regex. + /// + internal static CallShellOptions Build( + AgentConfiguration item, + ShellConfiguration shell, + AgentCompilationContext context, + string pointer) + { + if (context.WorkspaceRoot is null) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "shell"), + $"the agent '{item.Id}' declares a shell: block and this host bound no workspace " + + "root, so the shell has no working directory. Call options.UseWorkspace(...) with " + + "the folder, or remove the shell: block."); + } + + if (shell.Kind == ShellKind.Local) + { + RejectDockerOnlyKey(item, pointer, "image", shell.Image is not null); + RejectDockerOnlyKey(item, pointer, "network", shell.Network is not null); + RejectDockerOnlyKey(item, pointer, "memoryMb", shell.MemoryMb is not null); + } + + var policy = shell.Policy is { } declared ? BuildPolicy(item, declared, pointer) : null; + + var timeout = shell.TimeoutSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : (TimeSpan?)null; + + var secrets = context.Secrets ?? ResolvedSecrets.Empty; + var env = shell.Env.Count == 0 + ? null + : shell.Env.ToDictionary( + static entry => entry.Key, + entry => secrets.Format(entry.Value), + StringComparer.Ordinal); + + var maxOutputBytes = shell.MaxOutputKb is { } maxOutputKb ? maxOutputKb * 1024 : (int?)null; + + var memoryBytes = shell.MemoryMb is { } memoryMb ? (long)memoryMb * 1024 * 1024 : (long?)null; + + return new CallShellOptions( + shell.Kind, + policy, + timeout, + env, + maxOutputBytes, + shell.Image, + shell.Network, + memoryBytes); + } + + /// Fails compilation when a Docker-only shell: key appears under kind: local. + private static void RejectDockerOnlyKey(AgentConfiguration item, string pointer, string key, bool present) + { + if (!present) + { + return; + } + + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "shell"), + $"the agent '{item.Id}' declares a shell: {key}: and kind: local, but {key}: only applies to " + + "kind: docker. Remove it, or set kind: docker."); + } + + private static ShellPolicy BuildPolicy( + AgentConfiguration item, + ShellPolicyConfiguration policy, + string pointer) + { + // ShellPolicy treats a supplied-but-empty allow list as deny-all (it denies any command that + // matches none of the allow patterns, and an empty list matches nothing), so an agent that + // declares no allow: must reach the executor with allowList: null, not an empty collection. + var allow = policy.Allow.Count == 0 ? null : policy.Allow; + + try + { + return new ShellPolicy(denyList: policy.Deny, allowList: allow); + } + catch (ArgumentException exception) + { + // ShellPolicy compiles every pattern into a Regex eagerly in its own constructor, so a + // bad pattern in either list throws here, at compile time, rather than at the model's + // first command. + var bad = policy.Deny.Concat(allow ?? []) + .FirstOrDefault(pattern => !IsValidRegex(pattern)); + + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "shell"), "policy"), + $"the agent '{item.Id}' declares a shell: policy whose pattern '{bad}' is not a " + + $"valid regex: {exception.Message}"); + } + } + + private static bool IsValidRegex(string pattern) + { + try + { + _ = new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); + return true; + } + catch (ArgumentException) + { + return false; + } + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs index a987955f..ba866f98 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs @@ -82,7 +82,7 @@ private static void Add( ModelReference? model, AgentCompilationContext context) { - if (tool is HostedWebSearchTool or HostedCodeInterpreterTool) + if (tool is HostedWebSearchTool) { if (context.ChatClients.ResolveHostedTool(tool, model) is not { } resolved) { diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index fbdaa224..c39e92c4 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -294,8 +294,7 @@ private static (Dictionary Agents, IReadOnlySet Harness clarification, configuration.Providers?.Knowledge?.Scope, Resolve, - backgroundProviders, - compiledTools); + backgroundProviders); harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); harnessStateKeys.UnionWith(AgentApproval.StateKeysFor(section.Defaults, item, compiledTools)); diff --git a/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs index 9f76730f..01c6efde 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs @@ -1,3 +1,6 @@ +using System.Collections.ObjectModel; +using AgentCore.Application.Configuration.Parsing; + namespace AgentCore.Application.Configuration.Schema; /// The executors a shell: block may name. @@ -37,4 +40,23 @@ public sealed record ShellConfiguration /// Gets how long one command may run, or for the executor default. public int? TimeoutSeconds { get; init; } + + /// + /// Gets the environment passed to the executor, on top of the one the executor kind already + /// supplies. A value may hold ${secret:name} references. + /// + public IReadOnlyDictionary Env { get; init; } + = ReadOnlyDictionary.Empty; + + /// Gets the per-stream output cap, in KiB, or for the executor default. + public int? MaxOutputKb { get; init; } + + /// Gets the container image. only. + public string? Image { get; init; } + + /// Gets the Docker network mode. only. + public string? Network { get; init; } + + /// Gets the container memory limit, in MB. only. + public int? MemoryMb { get; init; } } \ No newline at end of file diff --git a/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs index 886f077a..46e4da97 100644 --- a/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs @@ -25,10 +25,4 @@ public sealed record LlmProviderConfiguration /// vendor's adapter decide. /// public bool? WebSearch { get; init; } - - /// - /// Gets whether this entry may run hosted code execution, or to let the - /// vendor's adapter decide. - /// - public bool? CodeExecute { get; init; } } diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index dba4d385..29096570 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -920,6 +920,33 @@ "timeoutSeconds": { "type": "integer", "minimum": 1 + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The environment passed to the executor, on top of what the executor kind already supplies. A value may hold ${secret:name}." + }, + "maxOutputKb": { + "type": "integer", + "minimum": 1, + "description": "The per-stream output cap, in KiB." + }, + "image": { + "type": "string", + "minLength": 1, + "description": "kind: docker. The container image." + }, + "network": { + "type": "string", + "minLength": 1, + "description": "kind: docker. The Docker network mode." + }, + "memoryMb": { + "type": "integer", + "minimum": 1, + "description": "kind: docker. The container memory limit, in MB." } } }, @@ -1224,7 +1251,7 @@ }, "blobs": { "$ref": "#/$defs/blobProvider", - "description": "Where a file the vendor's sandbox wrote is kept after the run, such as s3. A document that names none keeps no sandbox file." + "description": "Where a file the agent produces is kept after the run, such as s3. A document that names none keeps no such file." } } }, @@ -1291,10 +1318,6 @@ "webSearch": { "type": "boolean", "description": "Whether this entry may run a hosted web search. An opt-out: omitted or true lets the vendor's adapter decide, false vetoes it even on a model the adapter thinks is capable." - }, - "codeExecute": { - "type": "boolean", - "description": "Whether this entry may run hosted code execution. An opt-out: omitted or true lets the vendor's adapter decide, false vetoes it even on a model the adapter thinks is capable." } } }, diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index cd6e1e82..b488445b 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -281,35 +281,35 @@ public static partial void KnowledgeScopeComposed( Message = "Could not release the background agent sessions of the call '{CallId}'.")] public static partial void BackgroundReleaseFailed(ILogger logger, string callId, Exception exception); - /// A sandbox file could not be kept: the run had no call to own it. - /// The logger of the provider. - /// The agent whose run produced the file. + /// A workspace file could not be published: the run had no call to own it. + /// The logger of the tool. + /// The tool the model called. [LoggerMessage( EventId = 23, Level = LogLevel.Warning, - Message = "A sandbox file of the agent '{Agent}' was not kept: the run has no call id. " + Message = "A file published through '{Tool}' was not kept: the run has no call id. " + "Files are kept only for a run through a CallSession, or a background child of one.")] - public static partial void SandboxFileHasNoOwner(ILogger logger, string agent); + public static partial void SandboxFileHasNoOwner(ILogger logger, string tool); - /// A sandbox file was refused by name or by policy, and the reply went out without it. - /// The logger of the provider. + /// A workspace file was refused by name or by policy, and the model was told why. + /// The logger of the tool. /// The call that would have owned the file. - /// The name the sandbox gave the file. + /// The file's name. /// Why it was refused. [LoggerMessage( EventId = 24, Level = LogLevel.Warning, - Message = "The sandbox file '{Name}' of call {CallId} was not kept: {Reason}.")] + Message = "The file '{Name}' of call {CallId} was not published: {Reason}.")] public static partial void SandboxFileRefused(ILogger logger, string callId, string name, string reason); - /// A sandbox file could not be downloaded or stored, and the reply went out without it. - /// The logger of the provider. + /// A workspace file could not be read or stored, and the model was told so. + /// The logger of the tool. /// The call that would have owned the file. - /// The name the sandbox gave the file. + /// The file's name. /// The cause. [LoggerMessage( EventId = 25, Level = LogLevel.Warning, - Message = "The sandbox file '{Name}' of call {CallId} could not be kept.")] + Message = "The file '{Name}' of call {CallId} could not be published.")] public static partial void SandboxFileCaptureFailed(ILogger logger, string callId, string name, Exception exception); } diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 7de2bc0b..932aead6 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -700,8 +700,6 @@ AgentCore.Application.Configuration.Schema.LlmProviderConfiguration AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.$() -> AgentCore.Application.Configuration.Schema.LlmProviderConfiguration! AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.As.get -> string! AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.As.init -> void -AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.CodeExecute.get -> bool? -AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.CodeExecute.init -> void AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.Equals(AgentCore.Application.Configuration.Schema.LlmProviderConfiguration? other) -> bool AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.Kind.get -> string! AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.Kind.init -> void @@ -1391,11 +1389,19 @@ AgentCore.Application.Tools.Binding.ToolBindingRegistry.TryGetMethod(string! nam AgentCore.Application.Tools.Builtin.BuiltinToolNames AgentCore.Application.Tools.Builtin.BuiltinToolPorts AgentCore.Application.Tools.Builtin.BuiltinToolPorts.$() -> AgentCore.Application.Tools.Builtin.BuiltinToolPorts! -AgentCore.Application.Tools.Builtin.BuiltinToolPorts.BuiltinToolPorts(AgentCore.Application.Ports.IChatClientFactory? ChatClients) -> void AgentCore.Application.Tools.Builtin.BuiltinToolPorts.ChatClients.get -> AgentCore.Application.Ports.IChatClientFactory? AgentCore.Application.Tools.Builtin.BuiltinToolPorts.ChatClients.init -> void -AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Deconstruct(out AgentCore.Application.Ports.IChatClientFactory? ChatClients) -> void AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Equals(AgentCore.Application.Tools.Builtin.BuiltinToolPorts? other) -> bool +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.BuiltinToolPorts(AgentCore.Application.Ports.IChatClientFactory? ChatClients, AgentCore.Application.Ports.IBlobStore? Blobs = null, AgentCore.Application.Blobs.BlobPolicy? BlobPolicy = null, string? WorkspaceRoot = null, Microsoft.Extensions.Logging.ILoggerFactory? Loggers = null) -> void +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Deconstruct(out AgentCore.Application.Ports.IChatClientFactory? ChatClients, out AgentCore.Application.Ports.IBlobStore? Blobs, out AgentCore.Application.Blobs.BlobPolicy? BlobPolicy, out string? WorkspaceRoot, out Microsoft.Extensions.Logging.ILoggerFactory? Loggers) -> void +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Blobs.get -> AgentCore.Application.Ports.IBlobStore? +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Blobs.init -> void +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.BlobPolicy.get -> AgentCore.Application.Blobs.BlobPolicy? +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.BlobPolicy.init -> void +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.WorkspaceRoot.get -> string? +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.WorkspaceRoot.init -> void +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Loggers.get -> Microsoft.Extensions.Logging.ILoggerFactory? +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Loggers.init -> void AgentCore.Application.Tools.Builtin.BuiltinToolSource AgentCore.Application.Tools.Builtin.BuiltinToolSource.BuiltinToolSource(AgentCore.Application.Tools.Builtin.BuiltinToolPorts! ports) -> void AgentCore.Application.Tools.Builtin.BuiltinToolSource.ProvideAsync(AgentCore.Application.Tools.Registry.ToolSourceContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> @@ -1562,8 +1568,8 @@ const AgentCore.Application.Secrets.KnownSecrets.QdrantApiKeyVariable = "QDRANT_ const AgentCore.Application.State.StateExtractor.SchemaName = "agentcore_state" -> string! const AgentCore.Application.State.UnfilledSlotReminder.CloseTag = "" -> string! const AgentCore.Application.State.UnfilledSlotReminder.OpenTag = "" -> string! -const AgentCore.Application.Tools.Builtin.BuiltinToolNames.CodeExecute = "code.execute" -> string! const AgentCore.Application.Tools.Builtin.BuiltinToolNames.WebSearch = "web.search" -> string! +const AgentCore.Application.Tools.Builtin.BuiltinToolNames.FilePublish = "file.publish" -> string! const AgentCore.Application.Tools.ToolErrorResult.ErrorProperty = "error" -> string! const AgentCore.Application.Tools.ToolErrorResult.MessageProperty = "message" -> string! const AgentCore.Application.Tools.ToolErrorResult.ToolProperty = "tool" -> string! @@ -2198,8 +2204,6 @@ static AgentCore.Application.Configuration.Schema.BlobProviderConfiguration.oper static readonly AgentCore.Application.Secrets.KnownSecrets.S3AccessKeyId -> AgentCore.Application.Secrets.SecretName! static readonly AgentCore.Application.Secrets.KnownSecrets.S3SecretAccessKey -> AgentCore.Application.Secrets.SecretName! AgentCore.Application.Blobs.BlobStoreFactory -AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Blobs.get -> AgentCore.Application.Ports.IBlobStore? -AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Blobs.init -> void AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Blobs.get -> AgentCore.Application.Configuration.Schema.BlobProviderConfiguration? AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Blobs.init -> void static AgentCore.Application.Blobs.BlobStoreFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask @@ -2259,8 +2263,8 @@ AgentCore.Application.Transcript.FileContent.MediaType.set -> void AgentCore.Application.Transcript.FileContent.Name.get -> string! AgentCore.Application.Transcript.FileContent.Name.set -> void AgentCore.Application.Transcript.FileContent.FileContent() -> void -AgentCore.Application.Transcript.FileContent.Scope.get -> string? -AgentCore.Application.Transcript.FileContent.Scope.set -> void +AgentCore.Application.Transcript.FileContent.Title.get -> string? +AgentCore.Application.Transcript.FileContent.Title.set -> void AgentCore.Application.Configuration.Compilation.ResolvedHarness.Clock.get -> bool AgentCore.Application.Configuration.Compilation.ResolvedHarness.Clock.init -> void AgentCore.Application.Configuration.Compilation.ResolvedHarness.BaseInstructions.get -> bool @@ -2279,3 +2283,15 @@ static AgentCore.Application.Configuration.Compilation.AgentInstructions.Base.ge AgentCore.Application.Runtime.Harness.CallerTimeZone static AgentCore.Application.Runtime.Harness.CallerTimeZone.Parse(string? id) -> System.TimeZoneInfo? static AgentCore.Application.Runtime.Harness.CallerTimeZone.Set(Microsoft.Agents.AI.AgentSession! session, System.TimeZoneInfo! zone) -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.Env.get -> System.Collections.Generic.IReadOnlyDictionary! +AgentCore.Application.Configuration.Schema.ShellConfiguration.Env.init -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.MaxOutputKb.get -> int? +AgentCore.Application.Configuration.Schema.ShellConfiguration.MaxOutputKb.init -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.Image.get -> string? +AgentCore.Application.Configuration.Schema.ShellConfiguration.Image.init -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.Network.get -> string? +AgentCore.Application.Configuration.Schema.ShellConfiguration.Network.init -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.MemoryMb.get -> int? +AgentCore.Application.Configuration.Schema.ShellConfiguration.MemoryMb.init -> void +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Secrets.get -> AgentCore.Application.Secrets.ResolvedSecrets? +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Secrets.init -> void diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index b4200859..4d222801 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -38,7 +38,11 @@ internal sealed class AuditingFunctionInvokingChatClient : FunctionInvokingChatC private readonly ConcurrentDictionary _drains = new(StringComparer.Ordinal); private sealed record Drain( - TurnRenders? Renders, TurnSources? Sources, Action? OnToolFailure, bool Nested); + TurnRenders? Renders, + TurnSources? Sources, + TurnFiles? Files, + Action? OnToolFailure, + bool Nested); /// Creates the client. /// The model this loop sends its rounds to. @@ -91,18 +95,23 @@ internal void Release(IReadOnlyList callIds) // Snapshot the turn once per tool call and file it in the call's arguments, so tools // declare what they need as parameters. context.Arguments[TurnInvocation.ArgumentsKey] = invocation; - _drains[callId] = new Drain(invocation.Renders, invocation.Sources, invocation.OnToolFailure, nested); + _drains[callId] = new Drain( + invocation.Renders, invocation.Sources, invocation.Files, invocation.OnToolFailure, nested); invocation.Results?.NoteCall(callId, Release); } using var outerCall = invocation?.Renders is { } renders && !nested ? renders.BeginOuterCall(invocation.OuterCallId ?? callId) : null; - + using var outerSources = invocation?.Sources is { } sources && !nested ? sources.BeginOuterCall(invocation.OuterCallId ?? callId) : null; + using var outerFiles = invocation?.Files is { } files && !nested + ? files.BeginOuterCall(invocation.OuterCallId ?? callId) + : null; + try { var result = await base.InvokeFunctionAsync(context, cancellationToken).ConfigureAwait(false); @@ -179,7 +188,7 @@ private static bool IsCallerCancellation(Exception failure, CancellationToken ca /// /// Builds the messages the model reads, reports every tool it could not find, and attaches - /// whatever this turn drew or cited to the tool-result message it belongs to. + /// whatever this turn drew, cited, or published to the tool-result message it belongs to. /// protected override IList CreateResponseMessages(ReadOnlySpan results) { @@ -207,6 +216,11 @@ protected override IList CreateResponseMessages(ReadOnlySpan _session.Events.RaiseToolFailure(turn.Index, failure), Tools = _delegatedTools?.Tools, ToolsFor = _delegatedTools?.ToolId, diff --git a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs index 3f12125a..a253135d 100644 --- a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs +++ b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs @@ -1,10 +1,11 @@ +using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; namespace AgentCore.Application.Runtime.Harness; /// -/// Wraps one background: child so every session it gets knows which call started it, and -/// which zone the person on that call is in. +/// Wraps one background: child so every session it gets knows which call started it, +/// which zone the person on that call is in, and which workspace and shells that call owns. /// /// /// BackgroundAgentsProvider creates the child session inside the parent's tool call, before @@ -34,6 +35,30 @@ protected override async ValueTask CreateSessionCoreAsync(Cancella CallerTimeZone.Stamp(session, zone); } + if (turn is not null) + { + TurnRegistry.Set(session, Shared(turn)); + } + return session; } + + /// + /// The part of the parent's turn a child may share: the call, its workspace folder, and its + /// shells, so files: and shell: on the child work on the same disk. Every drain, + /// screen, tool list, and clarification stays with the parent; a child's publish reports a + /// link in its result instead. + /// + private static TurnInvocation Shared(TurnInvocation parent) + => new() + { + CallId = parent.CallId, + TurnIndex = parent.TurnIndex, + Stage = parent.Stage, + Workspace = parent.Workspace, + Shells = parent.Shells, + Knowledge = parent.Knowledge, + TimeZone = parent.TimeZone, + Nested = true, + }; } diff --git a/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs b/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs index 14f487e4..ba1fc48b 100644 --- a/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs +++ b/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs @@ -7,8 +7,9 @@ namespace AgentCore.Application.Runtime.Harness; /// /// A parent run has a turn filed in TurnRegistry, so its providers read the call id there. /// A child session has no turn: the framework starts it with fresh, empty state and null run -/// options. stamps this key when the session is created, and -/// reads it back when the turn lookup finds nothing. +/// options. stamps this key when the session is created, so the +/// file.publish tool a background child calls can still find the call that owns the file +/// when the turn lookup finds nothing. /// internal static class BlobOwnerKey { diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs b/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs index 33e92661..2d8e4397 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs @@ -10,4 +10,20 @@ namespace AgentCore.Application.Runtime.Harness; /// Where the shell runs. /// The command filter, or for none. /// How long one command may run, or for the executor default. -internal sealed record CallShellOptions(ShellKind Kind, ShellPolicy? Policy, TimeSpan? Timeout); +/// +/// The environment to add on top of the one the executor kind already supplies, with every +/// ${secret:name} reference already resolved. or empty for none. +/// +/// The per-stream output cap, or for the executor default. +/// The container image. only. +/// The Docker network mode. only. +/// The container memory limit. only. +internal sealed record CallShellOptions( + ShellKind Kind, + ShellPolicy? Policy, + TimeSpan? Timeout, + IReadOnlyDictionary? Env = null, + int? MaxOutputBytes = null, + string? Image = null, + string? Network = null, + long? MemoryBytes = null); diff --git a/src/AgentCore.Application/Runtime/Harness/CallShells.cs b/src/AgentCore.Application/Runtime/Harness/CallShells.cs index 14ba74d1..9f7bee8a 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShells.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShells.cs @@ -1,3 +1,4 @@ +using System.Collections.ObjectModel; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Diagnostics; using Microsoft.Agents.AI.Tools.Shell; @@ -118,6 +119,15 @@ private static async Task ProbeAsync( return await prober.RefreshAsync(cancellationToken).ConfigureAwait(false); } + /// + /// The host variables copied into a executor's clean environment, + /// on top of whatever the executor already preserves on its own. LANG missing breaks locale-aware + /// tools (encoding, sorting); TMPDIR missing sends scratch writes to a directory a sandboxed host + /// may not grant. PATH and HOME are listed too, so this allowlist does not depend on the + /// executor's own choice of what it preserves. + /// + private static readonly string[] CleanEnvironmentAllowlist = ["PATH", "HOME", "LANG", "TMPDIR"]; + private ShellExecutor Create(CallShellOptions options) { switch (options.Kind) @@ -129,6 +139,8 @@ private ShellExecutor Create(CallShellOptions options) Mode = ShellMode.Persistent, ConfineWorkingDirectory = true, AcknowledgeUnsafe = true, + CleanEnvironment = true, + Environment = BuildLocalEnvironment(options.Env), Policy = options.Policy, }; if (options.Timeout is { } localTimeout) @@ -136,16 +148,22 @@ private ShellExecutor Create(CallShellOptions options) localOptions.Timeout = localTimeout; } + if (options.MaxOutputBytes is { } localMaxOutputBytes) + { + localOptions.MaxOutputBytes = localMaxOutputBytes; + } + return new LocalShellExecutor(localOptions); case ShellKind.Docker: // MountReadonly is false because the workspace is this call's own scratch folder, // and files: already writes to it. Every other Docker default (network none, - // read-only root, nobody user, pids limit) stays. + // read-only root, nobody user, pids limit) stays unless the shell: block overrides it. DockerShellExecutorOptions dockerOptions = new() { HostWorkdir = _workspace, MountReadonly = false, + Environment = options.Env ?? ReadOnlyDictionary.Empty, Policy = options.Policy, }; if (options.Timeout is { } dockerTimeout) @@ -153,6 +171,26 @@ private ShellExecutor Create(CallShellOptions options) dockerOptions.Timeout = dockerTimeout; } + if (options.MaxOutputBytes is { } dockerMaxOutputBytes) + { + dockerOptions.MaxOutputBytes = dockerMaxOutputBytes; + } + + if (options.Image is { } image) + { + dockerOptions.Image = image; + } + + if (options.Network is { } network) + { + dockerOptions.Network = network; + } + + if (options.MemoryBytes is { } memoryBytes) + { + dockerOptions.MemoryBytes = memoryBytes; + } + return new DockerShellExecutor(dockerOptions); default: @@ -160,6 +198,34 @@ private ShellExecutor Create(CallShellOptions options) } } + /// + /// Builds a executor's environment: the agent's declared + /// shell.env, then backfilled from this process's + /// own environment for whatever shell.env did not already set. + /// + private static Dictionary BuildLocalEnvironment(IReadOnlyDictionary? declared) + { + Dictionary environment = new(StringComparer.Ordinal); + + if (declared is not null) + { + foreach (var (key, value) in declared) + { + environment[key] = value; + } + } + + foreach (var name in CleanEnvironmentAllowlist) + { + if (!environment.ContainsKey(name) && Environment.GetEnvironmentVariable(name) is { } value) + { + environment[name] = value; + } + } + + return environment; + } + /// /// Disposes every executor this call started. Idempotent, and never throws out: a failed /// dispose is logged at Warning through instead. A second diff --git a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs b/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs deleted file mode 100644 index e97e71b6..00000000 --- a/src/AgentCore.Application/Runtime/Harness/HostedFileCaptureProvider.cs +++ /dev/null @@ -1,167 +0,0 @@ -#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. - -using AgentCore.Application.Transcript; -using AgentCore.Application.Blobs; -using AgentCore.Application.Diagnostics; -using AgentCore.Application.Ports; -using AgentCore.Application.Runtime.Turn; -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; -using Microsoft.Extensions.Logging; - -namespace AgentCore.Application.Runtime.Harness; - -/// -/// Copies every file the vendor's sandbox wrote during a run into the call's blob store, and -/// writes what it kept onto the file's . -/// -internal sealed class HostedFileCaptureProvider : AIContextProvider -{ - private const string Instructions = - "When you produce a file (a chart, a PDF, a CSV), save it under /mnt/data with a short plain " - + "file name, and refer to it in your reply as sandbox:/mnt/data/."; - - private readonly IHostedFileClient _files; - - private readonly IBlobStore _blobs; - - private readonly BlobPolicy _policy; - - private readonly ILogger _logger; - - /// Creates the provider for one agent. - /// The vendor's downloader, taken off the agent's chat client. - /// The store providers.blobs opened. - /// The cap and the allowlist. - /// Where a file that could not be kept is reported. - public HostedFileCaptureProvider(IHostedFileClient files, IBlobStore blobs, BlobPolicy policy, ILogger logger) - { - ArgumentNullException.ThrowIfNull(files); - ArgumentNullException.ThrowIfNull(blobs); - ArgumentNullException.ThrowIfNull(policy); - ArgumentNullException.ThrowIfNull(logger); - - _files = files; - _blobs = blobs; - _policy = policy; - _logger = logger; - } - - /// - protected override ValueTask ProvideAIContextAsync(InvokingContext context, CancellationToken cancellationToken = default) - => new(new AIContext { Instructions = Instructions }); - - /// - protected override async ValueTask InvokedCoreAsync(InvokedContext context, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(context); - - List? found = null; - - foreach (var message in context.ResponseMessages ?? []) - { - foreach (var file in message.Contents.OfType()) - { - (found ??= []).Add(file); - } - } - - if (found is null) - { - return; - } - - if (OwnerOf(context.Session) is not { } callId) - { - Log.SandboxFileHasNoOwner(_logger, context.Agent.Name ?? context.Agent.Id); - return; - } - - foreach (var file in found) - { - await KeepAsync(callId, file, cancellationToken).ConfigureAwait(false); - } - } - - /// The call that owns this run's files: the filed turn, or the stamp a child session carries. - private static string? OwnerOf(AgentSession? session) - { - if (TurnRegistry.For(session)?.CallId is { } fromTurn) - { - return fromTurn; - } - - return session is not null && session.StateBag.TryGetValue(BlobOwnerKey.Value, out var stamped) - ? stamped - : null; - } - - // Kept stays false on every path that does not store the file, so a refusal writes nothing. - private async ValueTask KeepAsync(string callId, FileContent file, CancellationToken cancellationToken) - { - var name = file.Name; - - if (!BlobName.IsSafe(name)) - { - Log.SandboxFileRefused(_logger, callId, name, "the name is not a plain file name"); - return; - } - - try - { - await using var download = await _files - .DownloadAsync(file.FileId, new HostedFileClientOptions { Scope = file.Scope }, cancellationToken) - .ConfigureAwait(false); - - // The download stream rarely knows its length, and the policy needs one: read up to one - // byte past the cap, so an oversized file is refused without buffering all of it. - using MemoryStream buffer = new(); - await CopyCappedAsync(download, buffer, _policy.MaxBytes + 1, cancellationToken).ConfigureAwait(false); - - if (_policy.WhyRefused(name, buffer.Length) is { } reason) - { - Log.SandboxFileRefused(_logger, callId, name, reason); - return; - } - - buffer.Position = 0; - - var mediaType = download.MediaType ?? file.MediaType; - - var kept = await _blobs - .PutAsync(new BlobWrite(callId, name, mediaType, buffer, buffer.Length), cancellationToken) - .ConfigureAwait(false); - - // The reply is committed to the transcript after this provider runs, so what is written - // here is what every later read links from. No read ever asks the store whether the - // file exists. - file.MediaType = kept.MediaType; - file.Length = kept.Length; - file.Kept = true; - } - catch (Exception exception) when (exception is not OperationCanceledException) - { - Log.SandboxFileCaptureFailed(_logger, callId, name, exception); - } - } - - private static async ValueTask CopyCappedAsync(Stream source, Stream target, long cap, CancellationToken cancellationToken) - { - var chunk = new byte[81920]; - long copied = 0; - - while (copied < cap) - { - var wanted = (int)Math.Min(chunk.Length, cap - copied); - var read = await source.ReadAsync(chunk.AsMemory(0, wanted), cancellationToken).ConfigureAwait(false); - - if (read == 0) - { - return; - } - - await target.WriteAsync(chunk.AsMemory(0, read), cancellationToken).ConfigureAwait(false); - copied += read; - } - } -} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs b/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs new file mode 100644 index 00000000..952b256f --- /dev/null +++ b/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs @@ -0,0 +1,98 @@ +namespace AgentCore.Application.Runtime.Turn; + +/// +/// What a turn's tools have produced for the caller and not yet attached to a message, filed under +/// the outermost tool call that produced it. +/// +/// +/// The invoking client opens the outermost tool call around its invocation and takes what was filed +/// under it when it builds the tool-result message. Nested calls keep filing under the outer call; +/// outside any turn there is none, and a publish is discarded. +/// +/// The content one publish files. +internal abstract class TurnAttachments +{ + private readonly Lock _gate = new(); + + private readonly Dictionary> _byCallId = new(StringComparer.Ordinal); + + private string? _outerCallId; + + /// Gets the id of the outermost tool call now running, or outside one. + protected string? OuterCallId => _outerCallId; + + /// Opens one outermost tool call as the key publishes file under. + /// The id of the outermost tool call now running. + /// The scope. Disposing it puts back the key that was open before. + internal IDisposable BeginOuterCall(string callId) + { + ArgumentNullException.ThrowIfNull(callId); + + string? previous; + lock (_gate) + { + previous = _outerCallId; + _outerCallId = callId; + } + + return new OuterCallScope(this, previous); + } + + /// Takes what was filed under one outer tool call, in publish order. + /// The call whose content to take. + /// What that call filed, or empty. + internal IReadOnlyList TakeFor(string callId) + { + ArgumentNullException.ThrowIfNull(callId); + + lock (_gate) + { + return _byCallId.Remove(callId, out var filed) ? filed : []; + } + } + + /// Files one content under a call. A later publish of the same thing wins, in the place the earlier one took, so publish order is kept. + /// The outer call to file under. + /// What to file. + /// Whether an already filed content is the same thing as . + protected void Attach(string callId, TContent content, Predicate sameAs) + { + lock (_gate) + { + if (!_byCallId.TryGetValue(callId, out var filed)) + { + filed = []; + _byCallId[callId] = filed; + } + + var index = filed.FindIndex(sameAs); + if (index >= 0) + { + filed[index] = content; + } + else + { + filed.Add(content); + } + } + } + + private sealed class OuterCallScope(TurnAttachments owner, string? previous) : IDisposable + { + private bool _closed; + + public void Dispose() + { + if (_closed) + { + return; + } + + _closed = true; + lock (owner._gate) + { + owner._outerCallId = previous; + } + } + } +} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnFiles.cs b/src/AgentCore.Application/Runtime/Turn/TurnFiles.cs new file mode 100644 index 00000000..1a427723 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Turn/TurnFiles.cs @@ -0,0 +1,22 @@ +using AgentCore.Application.Transcript; + +namespace AgentCore.Application.Runtime.Turn; + +/// What a turn has published to the caller's file store and not yet attached to a message. +internal sealed class TurnFiles : TurnAttachments +{ + /// Files one published file under the outermost tool call, or drops it outside a turn. + /// The file the store kept. + public void Publish(FileContent file) + { + ArgumentNullException.ThrowIfNull(file); + + if (OuterCallId is not { } callId) + { + return; + } + + // The same name published twice is one blob: the store replaced the bytes. + Attach(callId, file, existing => string.Equals(existing.Name, file.Name, StringComparison.Ordinal)); + } +} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs b/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs index 1a64cae3..8bf22a1e 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs @@ -5,62 +5,8 @@ namespace AgentCore.Application.Runtime.Turn; /// What a turn has drawn and not yet attached to a message. -internal sealed class TurnRenders : IRenderPort +internal sealed class TurnRenders : TurnAttachments, IRenderPort { - private readonly Lock _gate = new(); - - private readonly Dictionary> _byCallId = new(StringComparer.Ordinal); - - // The outermost tool call publishes file under, pushed by the invoking client around the - // outermost invocation. Nested calls keep filing under the outer call; outside a turn there - // is none, and publishes are discarded, exactly as before. - private string? _outerCallId; - - /// Opens one outermost tool call as the key publishes file under. - /// The id of the outermost tool call now running. - /// The scope. Disposing it puts back the key that was open before. - internal IDisposable BeginOuterCall(string callId) - { - ArgumentNullException.ThrowIfNull(callId); - - string? previous; - lock (_gate) - { - previous = _outerCallId; - _outerCallId = callId; - } - - return new OuterCallScope(this, previous); - } - - /// One open outer call. Disposing it puts back what was open before. - private sealed class OuterCallScope : IDisposable - { - private readonly TurnRenders _renders; - private readonly string? _previous; - private bool _closed; - - public OuterCallScope(TurnRenders renders, string? previous) - { - _renders = renders; - _previous = previous; - } - - public void Dispose() - { - if (_closed) - { - return; - } - - _closed = true; - lock (_renders._gate) - { - _renders._outerCallId = _previous; - } - } - } - /// public void Publish(string name, string renderId, object data, bool transient = false) { @@ -68,7 +14,7 @@ public void Publish(string name, string renderId, object data, bool transient = ArgumentNullException.ThrowIfNull(renderId); ArgumentNullException.ThrowIfNull(data); - if (transient || _outerCallId is not { } callId) + if (transient || OuterCallId is not { } callId) { return; } @@ -76,34 +22,6 @@ public void Publish(string name, string renderId, object data, bool transient = var element = JsonSerializer.SerializeToElement(data, data.GetType(), TranscriptJson.Options); var content = new RenderContent { Name = name, RenderId = renderId, Data = element }; - lock (_gate) - { - if (!_byCallId.TryGetValue(callId, out var drawn)) - { - drawn = []; - _byCallId[callId] = drawn; - } - - var index = drawn.FindIndex(existing => string.Equals(existing.RenderId, renderId, StringComparison.Ordinal)); - if (index >= 0) - { - drawn[index] = content; - } - else - { - drawn.Add(content); - } - } - } - - /// Takes what was drawn under one outer tool call, in publish order. - internal IReadOnlyList TakeFor(string callId) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_gate) - { - return _byCallId.Remove(callId, out var drawn) ? drawn : []; - } + Attach(callId, content, existing => string.Equals(existing.RenderId, renderId, StringComparison.Ordinal)); } } diff --git a/src/AgentCore.Application/Runtime/Turn/TurnSources.cs b/src/AgentCore.Application/Runtime/Turn/TurnSources.cs index 1235fb9e..3747a7d1 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnSources.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnSources.cs @@ -5,108 +5,22 @@ namespace AgentCore.Application.Runtime.Turn; /// What a turn has cited and not yet attached to a message. -internal sealed class TurnSources : ISourcePort +internal sealed class TurnSources : TurnAttachments, ISourcePort { - private readonly Lock _gate = new(); - - private readonly Dictionary> _byCallId = new(StringComparer.Ordinal); - - // The outermost tool call publishes file under, pushed by the invoking client around the - // outermost invocation. Nested calls keep filing under the outer call; outside a turn there - // is none, and publishes are discarded, exactly as before. - private string? _outerCallId; - - /// Opens one outermost tool call as the key publishes file under. - /// The id of the outermost tool call now running. - /// The scope. Disposing it puts back the key that was open before. - internal IDisposable BeginOuterCall(string callId) - { - ArgumentNullException.ThrowIfNull(callId); - - string? previous; - lock (_gate) - { - previous = _outerCallId; - _outerCallId = callId; - } - - return new OuterCallScope(this, previous); - } - - /// One open outer call. Disposing it puts back what was open before. - private sealed class OuterCallScope : IDisposable - { - private readonly TurnSources _sources; - private readonly string? _previous; - private bool _closed; - - public OuterCallScope(TurnSources sources, string? previous) - { - _sources = sources; - _previous = previous; - } - - public void Dispose() - { - if (_closed) - { - return; - } - - _closed = true; - lock (_sources._gate) - { - _sources._outerCallId = _previous; - } - } - } - /// public void Publish(SourceReference source) { ArgumentNullException.ThrowIfNull(source); - if (_outerCallId is not { } callId) + if (OuterCallId is not { } callId) { return; } var content = new SourceContent { Source = source, CallId = callId }; - lock (_gate) - { - if (!_byCallId.TryGetValue(callId, out var cited)) - { - cited = []; - _byCallId[callId] = cited; - } - - // Two searches in one turn can return the same card. The later publish wins, in the - // place the earlier one took, so the order the turn cited things in is kept. - var index = cited.FindIndex(existing => - string.Equals(existing.Source.SourceId, source.SourceId, StringComparison.Ordinal)); - - if (index >= 0) - { - cited[index] = content; - } - else - { - cited.Add(content); - } - } - } - - /// Takes what was cited under one outer tool call, in publish order. - /// The call whose sources to take. - /// What that call cited, or empty. - internal IReadOnlyList TakeFor(string callId) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_gate) - { - return _byCallId.Remove(callId, out var cited) ? cited : []; - } + // Two searches in one turn can return the same card. + Attach(callId, content, existing => + string.Equals(existing.Source.SourceId, source.SourceId, StringComparison.Ordinal)); } } diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs index 113b1f6c..a7901438 100644 --- a/src/AgentCore.Application/Runtime/TurnInvocation.cs +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -60,6 +60,9 @@ internal sealed record TurnInvocation /// Gets what the turn's tools answer into. Never on a loop-built turn. public TurnResults? Results { get; init; } + /// Gets what the turn publishes files into. Never on a loop-built turn. + public TurnFiles? Files { get; init; } + /// Gets the tools a delegated run of this call is offered, or for none. public IReadOnlyList? Tools { get; init; } diff --git a/src/AgentCore.Application/Secrets/ResolvedSecrets.cs b/src/AgentCore.Application/Secrets/ResolvedSecrets.cs index e04071c5..f0a10ebb 100644 --- a/src/AgentCore.Application/Secrets/ResolvedSecrets.cs +++ b/src/AgentCore.Application/Secrets/ResolvedSecrets.cs @@ -139,6 +139,24 @@ public override string ToString() yield return reference; } } + + for (var index = 0; index < configuration.Agents.Items.Count; index++) + { + if (configuration.Agents.Items[index].Shell is not { } shell) + { + continue; + } + + var env = ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer("/agents/items", index), "shell"), + "env"); + + foreach (var reference in In(shell.Env, env)) + { + yield return reference; + } + } } /// Yields every entry of one string map that references a secret. diff --git a/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs b/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs index 8c1fe52f..1616ed4b 100644 --- a/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs +++ b/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs @@ -6,6 +6,6 @@ public static class BuiltinToolNames /// Lets the model provider run a web search of its own. public const string WebSearch = "web.search"; - /// Lets the model provider run code of its own in a hosted sandbox. - public const string CodeExecute = "code.execute"; + /// Hands one file from the call's workspace to the person, through the blob store. + public const string FilePublish = "file.publish"; } diff --git a/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs b/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs index b11fc342..3c7b3f91 100644 --- a/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs +++ b/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs @@ -1,20 +1,23 @@ using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Tools.Binding; using Microsoft.Extensions.AI; namespace AgentCore.Application.Tools.Builtin; /// -/// What every built-in hands , and the two rules they all share. +/// What every built-in hands , and the rules they all share. /// internal static class BuiltinToolOptions { /// Builds the options every built-in is created with. /// The declaration the document holds. - /// The options. + /// The options: the declared id as the name, the resolved description, no result schema, + /// and the turn bound from the call rather than filled by the model. internal static AIFunctionFactoryOptions Options(ToolConfiguration tool) => new() { Name = tool.Id, Description = tool.Description ?? string.Empty, ExcludeResultSchema = true, + ConfigureParameterBinding = ToolParameterBindings.For, }; } diff --git a/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs b/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs index 7b011cdb..e23de14e 100644 --- a/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs +++ b/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs @@ -14,7 +14,7 @@ public sealed class BuiltinToolSource : IToolSource new IBuiltinToolDefinition[] { new WebSearchToolDefinition(), - new CodeExecuteToolDefinition(), + new FilePublishToolDefinition(), }.ToDictionary(definition => definition.Name, StringComparer.Ordinal); private readonly BuiltinToolPorts _ports; diff --git a/src/AgentCore.Application/Tools/Builtin/CodeExecuteToolDefinition.cs b/src/AgentCore.Application/Tools/Builtin/CodeExecuteToolDefinition.cs deleted file mode 100644 index 6f7be400..00000000 --- a/src/AgentCore.Application/Tools/Builtin/CodeExecuteToolDefinition.cs +++ /dev/null @@ -1,20 +0,0 @@ -using AgentCore.Application.Configuration.Schema; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Tools.Builtin; - -/// -/// The uses: code.execute builtin: one . -/// -internal sealed class CodeExecuteToolDefinition : IBuiltinToolDefinition -{ - /// - public string Name => BuiltinToolNames.CodeExecute; - - /// - public string DefaultDescription => - "Writes and runs Python code in the model provider's hosted sandbox."; - - /// - public AITool Build(ToolConfiguration tool, BuiltinToolPorts ports) => new HostedCodeInterpreterTool(); -} diff --git a/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs b/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs new file mode 100644 index 00000000..ed1c7d89 --- /dev/null +++ b/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs @@ -0,0 +1,182 @@ +using System.ComponentModel; +using System.Text.Json.Nodes; +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Diagnostics; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Transcript; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Tools.Builtin; + +/// +/// Copies one file out of the running call's workspace into the blob store, owned by the call, and +/// files a on the turn so the card reaches the person. +/// +/// +/// A background child runs with no turn, so it has no drain to file the card on: its blob is still +/// stored under the parent call, and the link goes back to the child in the result alone. +/// +internal sealed class FilePublishTool +{ + private readonly IBlobStore _blobs; + + private readonly BlobPolicy _policy; + + private readonly string _workspaceRoot; + + private readonly ILogger _logger; + + private readonly ToolConfiguration _tool; + + /// Creates the tool. + /// The declaration the document holds. Its id is the name the model calls. + /// The store providers.blobs opened. + /// The cap and the allowlist. + /// The root every call's folder sits under. + /// Where a refused file is reported. + public FilePublishTool(ToolConfiguration tool, IBlobStore blobs, BlobPolicy policy, string workspaceRoot, ILogger logger) + { + ArgumentNullException.ThrowIfNull(tool); + ArgumentNullException.ThrowIfNull(blobs); + ArgumentNullException.ThrowIfNull(policy); + ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot); + ArgumentNullException.ThrowIfNull(logger); + + _tool = tool; + _blobs = blobs; + _policy = policy; + _workspaceRoot = workspaceRoot; + _logger = logger; + } + + /// Builds the function the model calls, named after the declaration. + /// The function. + public AIFunction AsAIFunction() => AIFunctionFactory.Create(PublishAsync, BuiltinToolOptions.Options(_tool)); + + private async ValueTask PublishAsync( + [Description("The file's path, relative to the workspace.")] string path, + [Description("A short label for the person, such as 'Sales by month'.")] string? title = null, + TurnInvocation? turn = null, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(path)) + { + return Failed("path is required: the file's path, relative to the workspace."); + } + + if (OwnerOf(turn) is not { } owner) + { + Log.SandboxFileHasNoOwner(_logger, _tool.Id); + return Failed("no call is running, so there is nobody to hand the file to."); + } + + var (callId, workspace) = owner; + + if (ResolveInside(workspace, path) is not { } full) + { + return Failed($"'{path}' is not inside the workspace. Give a path relative to the workspace, without '..'."); + } + + if (!File.Exists(full)) + { + return Failed($"there is no file at '{path}' in the workspace."); + } + + var name = Path.GetFileName(full); + var length = new FileInfo(full).Length; + + if (!BlobName.IsSafe(name)) + { + Log.SandboxFileRefused(_logger, callId, name, "the name is not a plain file name"); + return Failed($"'{name}' is not a plain file name. Rename the file and publish it again."); + } + + if (_policy.WhyRefused(name, length) is { } reason) + { + Log.SandboxFileRefused(_logger, callId, name, reason); + return Failed($"'{name}' was refused: {reason}. Allowed extensions: {string.Join(", ", _policy.AllowedExtensions)}; " + + $"largest file: {_policy.MaxBytes} bytes."); + } + + BlobRef blob; + Uri? url; + + try + { + await using var content = File.OpenRead(full); + + blob = await _blobs + .PutAsync(new BlobWrite(callId, name, BlobMediaTypes.Of(name), content, length), cancellationToken) + .ConfigureAwait(false); + + url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + Log.SandboxFileCaptureFailed(_logger, callId, name, exception); + return Failed($"'{name}' could not be stored: {exception.Message}"); + } + + turn?.Files?.Publish(new FileContent + { + Name = blob.Name, + FileId = path, + Title = string.IsNullOrWhiteSpace(title) ? null : title.Trim(), + MediaType = blob.MediaType, + Length = blob.Length, + Kept = true, + }); + + return new JsonObject + { + ["name"] = blob.Name, + ["mediaType"] = blob.MediaType, + ["length"] = blob.Length, + ["url"] = url?.ToString(), + }; + } + + /// + /// The call that owns the file and its folder: the filed turn, or for a background child the + /// stamp its session carries and the folder that call id names under the root. + /// + private (string CallId, string Workspace)? OwnerOf(TurnInvocation? turn) + { + if (turn is { CallId: { } fromTurn }) + { + return turn.Workspace is { } workspace ? (fromTurn, workspace) : null; + } + + var session = AIAgent.CurrentRunContext?.Session; + + return session is not null + && session.StateBag.TryGetValue(BlobOwnerKey.Value, out var stamped) + && stamped is not null + ? (stamped, Path.Combine(_workspaceRoot, stamped)) + : null; + } + + /// Resolves a model-written path under the workspace, or nothing when it escapes. + private static string? ResolveInside(string workspace, string path) + { + if (Path.IsPathRooted(path)) + { + return null; + } + + var root = Path.GetFullPath(workspace); + var rootWithSeparator = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar; + var full = Path.GetFullPath(Path.Combine(root, path)); + + return full.StartsWith(rootWithSeparator, StringComparison.Ordinal) && full.Length > rootWithSeparator.Length + ? full + : null; + } + + private JsonObject Failed(string message) => ToolErrorResult.Create(_tool.Id, message); +} diff --git a/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs b/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs new file mode 100644 index 00000000..47aa499a --- /dev/null +++ b/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs @@ -0,0 +1,41 @@ +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Schema; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace AgentCore.Application.Tools.Builtin; + +/// +/// The uses: file.publish builtin: one over the blob store. +/// +internal sealed class FilePublishToolDefinition : IBuiltinToolDefinition +{ + /// + public string Name => BuiltinToolNames.FilePublish; + + /// + public string DefaultDescription => + "Hands one file from the workspace to the person and returns a link to it. " + + "A file that is not published is lost when the call ends."; + + /// + public AITool Build(ToolConfiguration tool, BuiltinToolPorts ports) + { + ArgumentNullException.ThrowIfNull(tool); + ArgumentNullException.ThrowIfNull(ports); + + var blobs = ports.Blobs ?? throw BuiltinToolSource.Unbound(tool, Name, "providers.blobs"); + + var root = ports.WorkspaceRoot ?? throw BuiltinToolSource.Unbound( + tool, Name, "the workspace root (options.UseWorkspace(...))"); + + return new FilePublishTool( + tool, + blobs, + ports.BlobPolicy ?? BlobPolicy.Default, + root, + ports.Loggers?.CreateLogger() ?? NullLogger.Instance) + .AsAIFunction(); + } +} diff --git a/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs b/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs index 28402ed6..d1d940cf 100644 --- a/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs +++ b/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs @@ -1,13 +1,24 @@ +using AgentCore.Application.Blobs; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; namespace AgentCore.Application.Tools.Builtin; /// The adapters a built-in may need. A built-in uses none or more of them. /// The factory the tool runs on, or when the host bound none. -public sealed record BuiltinToolPorts(IChatClientFactory? ChatClients); +/// The store providers.blobs opened, or when the document names none. +/// The cap and the allowlist a published file must pass, or for . +/// The root options.UseWorkspace(...) bound, or when the host bound none. +/// Where a built-in takes its logger from, or to log nothing. +public sealed record BuiltinToolPorts( + IChatClientFactory? ChatClients, + IBlobStore? Blobs = null, + BlobPolicy? BlobPolicy = null, + string? WorkspaceRoot = null, + ILoggerFactory? Loggers = null); /// What every uses: name AgentCore ships has, whatever kind of thing it builds. internal interface IToolDefinition diff --git a/src/AgentCore.Application/Transcript/FileContent.cs b/src/AgentCore.Application/Transcript/FileContent.cs index 49a2ab4d..8b193367 100644 --- a/src/AgentCore.Application/Transcript/FileContent.cs +++ b/src/AgentCore.Application/Transcript/FileContent.cs @@ -4,28 +4,25 @@ namespace AgentCore.Application.Transcript; /// /// A file the reply produced, carried by the message that produced it. This is the only shape a -/// reader sees: where the file came from, and how the vendor reported it, is AgentCore's business. +/// reader sees: where the file came from is AgentCore's business. /// public sealed class FileContent : AIContent { - /// The name the model gave the file. It is the name the store keeps it under. + /// The file name. It is the name the store keeps it under. public required string Name { get; set; } - /// The vendor's id for the file. What the capture downloads by. + /// Where the file came from: the workspace-relative path the model published. public required string FileId { get; set; } - /// The vendor's container the file sits in, or when the vendor has none. - public string? Scope { get; set; } + /// A short label the model gave the file for the person, or . + public string? Title { get; set; } - /// The IANA media type. The vendor's guess until the capture keeps the file, then the store's. + /// The IANA media type the store holds the file under. public string MediaType { get; set; } = "application/octet-stream"; - /// How many bytes the store holds. Zero until the capture keeps the file. + /// How many bytes the store holds. public long Length { get; set; } - /// - /// Whether the store holds the file. until the capture keeps it, and - /// for good when the policy refused it, the download failed, or no capture ran at all. - /// + /// Whether the store holds the file. A reader links only what is kept. public bool Kept { get; set; } } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index a2be427a..abcfae5a 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -196,8 +196,13 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) .BuildAsync(_options, startup, cancellationToken) .ConfigureAwait(false)); + // Opened before the tools: file.publish reads the store at build time. + var blobs = Track(await BlobStartup + .OpenAsync(configuration, _options, cancellationToken) + .ConfigureAwait(false)); + var tools = await ToolRegistryStartup - .BuildAsync(this, _options, startup, chatClients, configuration, cancellationToken) + .BuildAsync(this, _options, startup, chatClients, blobs, _loggers, configuration, cancellationToken) .ConfigureAwait(false); ConfigurationValidator.ValidateToolReferences(configuration, tools.ServedIds); @@ -218,10 +223,6 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) .OpenAsync(configuration, _options, _loggers, cancellationToken) .ConfigureAwait(false)); - var blobs = Track(await BlobStartup - .OpenAsync(configuration, _options, cancellationToken) - .ConfigureAwait(false)); - CallRepository calls = new(store, blobs); var evaluators = await EvaluationStartup @@ -234,14 +235,14 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) chatClients, tools.Registry, calls, - blobs, evaluators, knowledge, skills, KnowledgeCitationFormatterFactory.Resolve(configuration, _options.KnowledgeCitations), _loggers, _options.WorkspaceRoot, - _options.TimeProvider) + _options.TimeProvider, + secrets) .ConfigureAwait(false); var seams = CallSeamStartup.Build(configuration, _options); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs index 296cfca4..0aef3b6f 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Evaluation; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; +using AgentCore.Application.Secrets; using AgentCore.Application.Skills; using AgentCore.Application.Tools.Registry; using Microsoft.Extensions.Logging; @@ -30,7 +31,6 @@ internal static class CompilationStartup /// The factory step 3c built, which the compile table asks for every agent and for the extractor. /// The registry step 4 built. /// The store every call's row and every word of it is kept in. - /// The store step 4d opened, or when the document names no blob vendor. /// /// The registry the moderator comes out of. R3 puts moderation in the chat pipeline of every /// compiled agent, so it is bound here rather than on the session factory. @@ -41,6 +41,7 @@ internal static class CompilationStartup /// The factory the guard evaluator and the knowledge provider take their loggers from. /// The root options.UseWorkspace(...) bound, or . /// The clock the host bound, or for the system clock. + /// The set a shell: block's env: resolves its ${secret:name} references against. /// The compiled entries, and the seams that made them. /// An entry does not compile. internal static ValueTask CompileAsync( @@ -48,14 +49,14 @@ internal static ValueTask CompileAsync( IChatClientFactory chatClients, ToolRegistry tools, ICallStore calls, - IBlobStore? blobs, EvaluatorRegistry evaluators, IKnowledgeRetrievalPort? knowledge, SkillCatalog? skills, IKnowledgeCitationFormatter citations, ILoggerFactory loggers, string? workspaceRoot = null, - TimeProvider? clock = null) + TimeProvider? clock = null, + ResolvedSecrets? secrets = null) { GuardEvaluator guards = new(configuration.Guards, loggers.CreateLogger()); CompiledAgentRegistry registry = new(); @@ -68,13 +69,13 @@ internal static ValueTask CompileAsync( Guards = guards, Moderation = PromptModerator.FromRegistry(evaluators), CallStore = calls, - Blobs = blobs, Knowledge = knowledge, Skills = skills, Citations = citations, Loggers = loggers, WorkspaceRoot = workspaceRoot, Clock = clock, + Secrets = secrets, }); return ValueTask.FromResult(new CompiledGraph(chatClients, guards, registry, entries)); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs index 5f4b6be4..67b1080c 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Registry; +using Microsoft.Extensions.Logging; namespace AgentCore.AspNetCore.DependencyInjection.Startup; @@ -27,6 +28,8 @@ internal static class ToolRegistryStartup /// The options the host filled. /// The loaded document and the resolved secrets. /// The factory a shipped agent runs on. Step 3c fails the boot rather than returning none. + /// The store step 4d opened, or when the document names none. + /// The factory a built-in takes its logger from. /// The loaded document. /// Cancels the discovery. /// The registry, and the served-ids union decision 15's reference pass reads. @@ -40,12 +43,18 @@ internal static async ValueTask BuildAsync( AgentCoreOptions options, AgentCoreStartup startup, IChatClientFactory chatClients, + IBlobStore? blobs, + ILoggerFactory loggers, AgentCoreConfiguration configuration, CancellationToken cancellationToken) { List sources = [ - new BuiltinToolSource(new BuiltinToolPorts(chatClients)), + new BuiltinToolSource(new BuiltinToolPorts( + chatClients, + blobs, + WorkspaceRoot: options.WorkspaceRoot, + Loggers: loggers)), new BindingToolSource(options.Bindings), ]; diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs index 99def8e8..431d083d 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs @@ -205,12 +205,15 @@ internal sealed record SourcePayload public required string Origin { get; init; } } -/// One file the sandbox wrote and the store kept, as the browser reads it. +/// One file the model published from the workspace and the store kept, as the browser reads it. internal sealed record FilePayload { - /// Gets the file name, as the model wrote it under /mnt/data. + /// Gets the file name the store keeps it under. public required string Name { get; init; } + /// Gets the label the model gave it for the person, or . + public string? Title { get; init; } + /// Gets the IANA media type, such as image/png. public required string MediaType { get; init; } diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs index 74a52022..3ef41c27 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs @@ -101,8 +101,8 @@ private static async IAsyncEnumerable StreamAgentUpdatesAsy if (dialect) { - // The enumeration above ends only after the run's providers have finished, and the - // capture provider is one of them: by here the bytes are in the store or never will be. + // The enumeration above ends only after the run has finished, and the publish tool ran + // inside it: by here the bytes are in the store or never will be. var calls = http.RequestServices.GetRequiredService(); await foreach (var part in files.ResolveAsync(calls, call.CallId, cancellationToken).ConfigureAwait(false)) diff --git a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs index 8543b353..7a4735e2 100644 --- a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs @@ -6,13 +6,13 @@ namespace AgentCore.AspNetCore.Endpoints; /// -/// The sandbox files one turn surfaced, linked for the browser once the turn is over. +/// The files one turn published, linked for the browser once the turn is over. /// internal sealed class TurnStreamFiles { - private readonly List _files = []; + private readonly List _files = []; - /// Notes every sandbox file one update carries. + /// Notes every published file one update carries. /// One update of the stream. internal void Note(ChatResponseUpdate update) { @@ -35,7 +35,7 @@ internal async IAsyncEnumerable ResolveAsync( } var links = await calls - .LinkFilesAsync(callId, [new ChatMessage(ChatRole.Assistant, _files)], cancellationToken) + .LinkFilesAsync(callId, [new ChatMessage(ChatRole.Assistant, [.. _files])], cancellationToken) .ConfigureAwait(false); foreach (var (blob, url) in links) @@ -43,6 +43,7 @@ internal async IAsyncEnumerable ResolveAsync( yield return new TurnStreamFile(new FilePayload { Name = blob.Name, + Title = _files.LastOrDefault(file => string.Equals(file.Name, blob.Name, StringComparison.Ordinal))?.Title, MediaType = blob.MediaType, Length = blob.Length, Url = url?.ToString(), diff --git a/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs index d78f14de..8d3b1f9d 100644 --- a/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs +++ b/src/AgentCore.Infrastructure/Blobs/S3/S3BlobStore.cs @@ -100,11 +100,6 @@ public async ValueTask PutAsync(BlobWrite write, CancellationToken canc } /// - /// - /// A presigned GET. Only host is signed: a browser sends no other header the bucket - /// could check. The media type and disposition ride as response overrides, which the - /// signature covers, so the link cannot be bent into serving the bytes another way. - /// public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(blob); @@ -114,7 +109,7 @@ public async ValueTask PutAsync(BlobWrite write, CancellationToken canc BucketName = _bucket, Key = KeyOf(blob.OwnerId, blob.Name), Verb = HttpVerb.GET, - Protocol = Protocol.HTTPS, + Protocol = LinkProtocol(), Expires = DateTime.UtcNow.Add(lifetime), ResponseHeaderOverrides = { @@ -159,6 +154,13 @@ public async ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken canc /// public void Dispose() => _client.Dispose(); + /// The endpoint's scheme, or https when the client was given a region and no URL. + private Protocol LinkProtocol() + => Uri.TryCreate(_client.Config.ServiceURL, UriKind.Absolute, out var endpoint) + && string.Equals(endpoint.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) + ? Protocol.HTTP + : Protocol.HTTPS; + private async ValueTask DeleteBatchAsync(List batch, CancellationToken cancellationToken) { if (batch.Count == 0) diff --git a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs index 742c5319..3a42ed5b 100644 --- a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs +++ b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs @@ -48,7 +48,7 @@ await secrets var client = _client.GetResponsesClient().AsIChatClient(entry.Model); - return new OpenAiSandboxFilesClient(WithResponseDefaults(client, entry.ReasoningEffort), _client); + return WithResponseDefaults(client, entry.ReasoningEffort); } /// @@ -60,7 +60,6 @@ await secrets return marker switch { HostedWebSearchTool when entry.WebSearch != false => marker, - HostedCodeInterpreterTool when entry.CodeExecute != false => marker, _ => null, }; } diff --git a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs deleted file mode 100644 index a11c7e0b..00000000 --- a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiSandboxFilesClient.cs +++ /dev/null @@ -1,98 +0,0 @@ -#pragma warning disable OPENAI001 -#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. - -using AgentCore.Application.Transcript; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.AI; -using OpenAI; -using OpenAI.Responses; - -namespace AgentCore.Infrastructure.Llm.OpenAI; - -/// -/// Surfaces every file the OpenAI sandbox wrote as one flat on the -/// reply. OpenAI reports a file only as a citation on the text, and Microsoft.Extensions.AI keeps it -/// there, so this is the one place that knows the vendor's shape. -/// -internal sealed class OpenAiSandboxFilesClient : DelegatingChatClient -{ - private readonly IHostedFileClient _files; - - public OpenAiSandboxFilesClient(IChatClient inner, OpenAIClient openAi) - : base(inner) - { - ArgumentNullException.ThrowIfNull(openAi); - - _files = openAi.AsIHostedFileClient(); - } - - /// - public override object? GetService(Type serviceType, object? serviceKey = null) - => serviceKey is null && serviceType == typeof(IHostedFileClient) - ? _files - : base.GetService(serviceType, serviceKey); - - /// - public override async Task GetResponseAsync( - IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) - { - var response = await base.GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false); - - foreach (var message in response.Messages) - { - Surface(message.Contents); - } - - return response; - } - - /// - public override async IAsyncEnumerable GetStreamingResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) - { - await foreach (var update in base.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false)) - { - Surface(update.Contents); - yield return update; - } - } - - /// Appends one for every container-file citation in the list. - private static void Surface(IList contents) - { - List? found = null; - - foreach (var content in contents) - { - if (content is not TextContent { Annotations: { } annotations }) - { - continue; - } - - foreach (var annotation in annotations) - { - if (annotation.RawRepresentation is ContainerFileCitationMessageAnnotation raw) - { - (found ??= []).Add(new FileContent - { - Name = raw.Filename ?? raw.FileId, - FileId = raw.FileId, - Scope = raw.ContainerId, - }); - } - } - } - - if (found is null) - { - return; - } - - foreach (var file in found) - { - contents.Add(file); - } - } -} diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs index 8dbcda5c..64c7a94f 100644 --- a/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs +++ b/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs @@ -11,6 +11,9 @@ public sealed class BlobPolicyTests [InlineData("report.PDF", 1)] [InlineData("rows.csv", 0)] [InlineData("big.png", 10L * 1024 * 1024)] + [InlineData("report.md", 518)] + [InlineData("units.xlsx", 4_096)] + [InlineData("bundle.zip", 4_096)] public void WhyRefused_AllowedExtensionUnderCap_ReturnsNull(string name, long length) { // Act @@ -34,6 +37,7 @@ public void WhyRefused_OneByteOverCap_NamesTheSize() [Theory] [InlineData("page.html")] [InlineData("logo.svg")] + [InlineData("feed.xml")] [InlineData("run.exe")] [InlineData("chart.png.js")] public void WhyRefused_ExtensionOffTheList_NamesTheExtension(string name) @@ -89,4 +93,16 @@ public void Constructor_ZeroCap_Throws() // Act & Assert Assert.Throws(() => new BlobPolicy(0, ["png"])); } + + [Fact] + public void DefaultExtensions_EachHasAMediaType() + { + // Act + var untyped = BlobPolicy.DefaultExtensions + .Where(extension => BlobMediaTypes.Of("file." + extension) == BlobMediaTypes.Fallback) + .ToList(); + + // Assert + Assert.Empty(untyped); + } } diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs index f1e163c8..49659c2d 100644 --- a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs @@ -78,16 +78,14 @@ public void LoadYaml_AnUnknownKeyUnderBlobs_IsRejectedBySchema() () => ConfigurationLoader.LoadYaml(Document("kind: s3", "path: /tmp"))); } - private const string KnowledgeLine = Configuration.ExampleDocument.LastProviderLine; - - /// Builds the section 8.1 document with one blobs block written into it. + /// Builds the section 8.1 document with its blobs block replaced by these entries, or taken out. private static string Document(params string[] entries) - => entries.Length == 0 - ? Configuration.ExampleDocument.Yaml - : Configuration.ExampleDocument.Yaml.Replace( - KnowledgeLine, - KnowledgeLine + "\n blobs:\n" + string.Join("\n", entries.Select(entry => " " + entry)), - StringComparison.Ordinal); + => Configuration.ExampleDocument.Yaml.Replace( + Configuration.ExampleDocument.BlobsLine, + entries.Length == 0 + ? string.Empty + : " blobs:\n" + string.Join("\n", entries.Select(entry => " " + entry)), + StringComparison.Ordinal); /// An adapter that opens nothing and records what it was handed. private sealed class FakeBlobStoreAdapter(string kind) : IBlobStoreAdapter diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs index 46b1913c..f4b823d1 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs @@ -17,7 +17,6 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; public sealed class HostedWebSearchDropTests { private const string SearchToolId = BuiltinToolNames.WebSearch; - private const string CodeToolId = BuiltinToolNames.CodeExecute; [Fact] public void Compile_CapableModel_KeepsTheTool() @@ -27,30 +26,6 @@ public void Compile_CapableModel_KeepsTheTool() Assert.Single(tools.OfType()); } - [Fact] - public void Compile_CodeExecuteOnCapableVendor_KeepsTheTool() - { - var tools = BuildAgentTools( - "reply", - model: null, - CodeTool(), - new ScreeningChatClientFactory(new HostedCodeInterpreterTool())); - - Assert.Single(tools.OfType()); - } - - [Fact] - public void Compile_CodeExecuteOnIncapableVendor_DropsTheTool() - { - var tools = BuildAgentTools( - "reply", - model: null, - CodeTool(), - new ScreeningChatClientFactory(new HostedWebSearchTool())); - - Assert.Empty(tools.OfType()); - } - [Fact] public void Compile_TunedMarker_ReachesTheModel() { @@ -161,9 +136,6 @@ public async Task Compile_TwoAgentsOnDifferentModels_ThroughTheRealCompiler_Only private static ToolConfiguration SearchTool() => new() { Id = SearchToolId, Kind = ToolKind.Builtin, Uses = BuiltinToolNames.WebSearch }; - private static ToolConfiguration CodeTool() - => new() { Id = CodeToolId, Kind = ToolKind.Builtin, Uses = BuiltinToolNames.CodeExecute }; - private static List Tools(string agent, bool capable) => BuildAgentTools(agent, model: null, SearchTool(), new ScreeningChatClientFactory(Marker(capable))); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs new file mode 100644 index 00000000..ddcaabb7 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs @@ -0,0 +1,96 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Secrets; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using Xunit; + +namespace AgentCore.Application.Tests.Configuration.Compilation; + +/// +/// The new shell: keys: env: (with ${secret:name}), maxOutputKb:, and the +/// Docker-only keys refused under kind: local. +/// +public sealed class ShellOptionsCompilerTests +{ + [Fact] + public void Load_ShellEnvWithASecretReference_BindsTheReferenceAndLeavesAPlainValueAlone() + { + var configuration = ConfigurationLoader.LoadYaml(""" + apiVersion: agentcore/v1 + agents: + items: + - id: only + instructions: "run commands" + shell: { kind: local, env: { CUSTSERVICE_DSN: "${secret:custservice-dsn}", PYTHONUNBUFFERED: "1" } } + entries: + main: + agent: only + """); + + var shell = Assert.Single(configuration.Agents!.Items).Shell; + Assert.NotNull(shell); + Assert.True(shell!.Env["CUSTSERVICE_DSN"].HasSecretReferences); + Assert.Equal("custservice-dsn", Assert.Single(shell.Env["CUSTSERVICE_DSN"].References).Name); + Assert.False(shell.Env["PYTHONUNBUFFERED"].HasSecretReferences); + } + + [Fact] + public void Build_ShellEnvAndMaxOutputKb_ResolveIntoTheCallShellOptions() + { + var root = Path.Combine(Path.GetTempPath(), "agentcore-shell-env-secret-" + Guid.NewGuid().ToString("N")); + var item = new AgentConfiguration { Id = "only" }; + var shell = new ShellConfiguration + { + Kind = ShellKind.Local, + MaxOutputKb = 64, + Env = new Dictionary(StringComparer.Ordinal) + { + ["CUSTSERVICE_DSN"] = SecretTemplate.Parse("${secret:custservice-dsn}"), + ["PYTHONUNBUFFERED"] = SecretTemplate.Parse("1"), + }, + }; + + var context = new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))) + { + WorkspaceRoot = root, + Secrets = ResolvedSecrets.Create([new KeyValuePair("custservice-dsn", "postgres://x")]), + }; + + var options = AgentShellOptionsCompiler.Build(item, shell, context, "/agents/items/0"); + + Assert.Equal("postgres://x", options.Env!["CUSTSERVICE_DSN"]); + Assert.Equal("1", options.Env!["PYTHONUNBUFFERED"]); + Assert.Equal(64 * 1024, options.MaxOutputBytes); + } + + [Fact] + public void Compile_ShellWithADockerOnlyKeyUnderKindLocal_FailsNamingTheAgentAndTheKey() + { + var document = ConfigurationLoader.LoadYaml(""" + apiVersion: agentcore/v1 + agents: + items: + - id: only + instructions: "run commands" + shell: { kind: local, image: "ghcr.io/x/y:1.0" } + entries: + main: + agent: only + """); + + var root = Path.Combine(Path.GetTempPath(), "agentcore-shell-docker-only-" + Guid.NewGuid().ToString("N")); + + var failure = Assert.Throws(() => ConfigurationCompiler.CompileAll( + document, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))) + { + WorkspaceRoot = root, + })["main"]); + + Assert.Equal("/agents/items/0/shell", failure.Pointer); + Assert.Contains("'only'", failure.Message, StringComparison.Ordinal); + Assert.Contains("image:", failure.Message, StringComparison.Ordinal); + } +} diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs index 5afa83e4..b2dd8e18 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs @@ -80,8 +80,9 @@ public void Example_BindsEveryToolKind() Assert.Equal(ToolKind.Builtin, Example.Tools[2].Kind); Assert.Equal("web.search", Example.Tools[2].Uses); + Assert.Equal(ToolKind.Builtin, Example.Tools[3].Kind); - Assert.Equal("code.execute", Example.Tools[3].Uses); + Assert.Equal("file.publish", Example.Tools[3].Uses); } [Fact] @@ -153,7 +154,6 @@ public void Example_BindsProviders() Assert.Equal("judge", Example.Providers.Llm[2].As); Assert.Equal("cheap", Example.Providers.Llm[3].As); Assert.Equal(false, Example.Providers.Llm[3].WebSearch); - Assert.Equal(false, Example.Providers.Llm[3].CodeExecute); Assert.Equal("telnyx-relay", Example.Providers.Speech!.Stt.Kind); Assert.Equal("telnyx", Example.Providers.Telephony!.Kind); Assert.Equal("qdrant", Example.Providers.Knowledge!.Kind); diff --git a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs index 21821ef6..df3092e3 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs @@ -31,6 +31,12 @@ internal static class ExampleDocument /// public const string LastProviderLine = " citation: source-locator"; + /// + /// The one-line providers.blobs entry, for a test that takes it out or swaps its own in. + /// + public const string BlobsLine = + " blobs: { kind: s3, endpoint: https://s3.us-east-005.backblazeb2.com, bucket: agentcore-files, region: us-east-005 }"; + /// The section 8.1 document as YAML. public const string Yaml = """ @@ -107,7 +113,7 @@ internal static class ExampleDocument properties: { summary: { type: string } } required: [ summary ] - { id: search, kind: builtin, uses: web.search } - - { id: python, kind: builtin, uses: code.execute } + - { id: publish, kind: builtin, uses: file.publish } agents: defaults: model: { ref: reply, temperature: 0.3 } @@ -121,7 +127,7 @@ internal static class ExampleDocument - { id: resolver, instructions: "", tools: [] } - { id: escalator, instructions: "", tools: [ create_case ] } - { id: closer, instructions: "", tools: [] } - - { id: analyst, instructions: "", tools: [ lookup_order, create_case, search, python ], + - { id: analyst, instructions: "", tools: [ lookup_order, create_case, search, publish ], knowledge: { mode: tool, limit: 8, citations: true, scoped: false } } - { id: webchat, instructions: "", tools: [ lookup_order ], knowledge: { mode: tool, citations: false } } @@ -161,7 +167,7 @@ internal static class ExampleDocument - { kind: openai, model: gpt-4.1-mini, as: reply } # the voice path, chosen on latency - { kind: openai, model: gpt-5.4-nano, as: fill } # the extractor, chosen on null discipline - { kind: openai, model: gpt-4.1, as: judge } # evaluation only, chosen on judgement - - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false, codeExecute: false } + - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false } call: { kind: telnyx-relay } # the pipe: who carries the call and owns /v1/{entry}/call speech: # the ears and the mouth, named one role at a time stt: { kind: telnyx-relay } # recognition. Bundled here, so it matches call @@ -169,6 +175,7 @@ internal static class ExampleDocument telephony: { kind: telnyx } # dial, transfer, hang up. Not the pipe — that is call moderation: { kind: openai } # reads what the CALLER said, before the model runs embeddings: { kind: openai, model: text-embedding-3-small } + blobs: { kind: s3, endpoint: https://s3.us-east-005.backblazeb2.com, bucket: agentcore-files, region: us-east-005 } knowledge: kind: qdrant endpoint: https://qdrant.example.com:6334 @@ -416,9 +423,9 @@ internal static class ExampleDocument "uses": "web.search" }, { - "id": "python", + "id": "publish", "kind": "builtin", - "uses": "code.execute" + "uses": "file.publish" } ], "agents": { @@ -479,7 +486,7 @@ internal static class ExampleDocument "lookup_order", "create_case", "search", - "python" + "publish" ], "knowledge": { "mode": "tool", @@ -591,8 +598,7 @@ internal static class ExampleDocument "kind": "openai", "model": "gpt-4.1-nano", "as": "cheap", - "webSearch": false, - "codeExecute": false + "webSearch": false } ], "call": { @@ -616,6 +622,12 @@ internal static class ExampleDocument "kind": "openai", "model": "text-embedding-3-small" }, + "blobs": { + "kind": "s3", + "endpoint": "https://s3.us-east-005.backblazeb2.com", + "bucket": "agentcore-files", + "region": "us-east-005" + }, "knowledge": { "kind": "qdrant", "endpoint": "https://qdrant.example.com:6334", diff --git a/tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs b/tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs deleted file mode 100644 index 0452967e..00000000 --- a/tests/AgentCore.Application.Tests/Fakes/ScriptedHostedFileClient.cs +++ /dev/null @@ -1,80 +0,0 @@ -#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. - -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Tests.Fakes; - -/// An that serves fixed bytes per file id, and records each download's scope. -internal sealed class ScriptedHostedFileClient : IHostedFileClient -{ - private readonly Dictionary _files = new(StringComparer.Ordinal); - - /// Gets the scope each download asked for, keyed by file id. - public Dictionary ScopesAsked { get; } = new(StringComparer.Ordinal); - - public ScriptedHostedFileClient Serve(string fileId, byte[] bytes, string? mediaType = null) - { - _files[fileId] = (bytes, mediaType); - return this; - } - - public Task DownloadAsync(string fileId, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) - { - ScopesAsked[fileId] = options?.Scope; - - return _files.TryGetValue(fileId, out var file) - ? Task.FromResult(new FixedDownload(file.Bytes, file.MediaType)) - : throw new InvalidOperationException($"No such file '{fileId}'."); - } - - public Task UploadAsync(Stream content, string? mediaType = null, string? fileName = null, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - public Task GetFileInfoAsync(string fileId, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - public IAsyncEnumerable ListFilesAsync(HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - public Task DeleteAsync(string fileId, HostedFileClientOptions? options = null, CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - public object? GetService(Type serviceType, object? serviceKey = null) => null; - - public void Dispose() - { - } - - private sealed class FixedDownload(byte[] bytes, string? mediaType) : HostedFileDownloadStream - { - private readonly MemoryStream _inner = new(bytes); - - public override string? MediaType => mediaType; - - public override bool CanRead => true; - - public override bool CanSeek => false; - - public override long Length => throw new NotSupportedException(); - - public override long Position - { - get => throw new NotSupportedException(); - set => throw new NotSupportedException(); - } - - public override void Flush() - { - } - - public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count); - - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); - - protected override void Dispose(bool disposing) - { - _inner.Dispose(); - base.Dispose(disposing); - } - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs index 86dce9fe..657ea6bd 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using Microsoft.Agents.AI; using Xunit; @@ -58,6 +59,37 @@ public async Task CreateSessionAsync_InsideAParentRunWithAZone_StampsTheZoneOnTh Assert.Equal("Asia/Taipei", stamped); } + [Fact] + public async Task CreateSessionAsync_InsideTheParentsRun_FilesTheParentsWorkspaceOnTheChild() + { + // Arrange + var token = TestContext.Current.CancellationToken; + BackgroundChildAgent child = new(new ChatClientAgent(new ScriptedChatClient("child"))); + SessionCreatingProvider creating = new(child); + ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); + var renders = new TurnRenders(); + var turn = new TurnInvocation + { + CallId = "call-9", + TurnIndex = 0, + Stage = "s", + Workspace = "/work/call-9", + Renders = renders, + }; + + // Act + await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); + + // Assert + Assert.NotNull(creating.Created); + var filed = TurnRegistry.For(creating.Created); + Assert.NotNull(filed); + Assert.Equal("/work/call-9", filed.Workspace); + Assert.Equal("call-9", filed.CallId); + Assert.True(filed.Nested); + Assert.Null(filed.Renders); + } + [Fact] public async Task CreateSessionAsync_OutsideAnyRun_StampsNothing() { diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs index 7f549b2d..89907a68 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs @@ -139,6 +139,36 @@ public async Task Get_AfterDispose_ThrowsObjectDisposedException() () => shells.Get(new CallShellOptions(ShellKind.Local, Policy: null, Timeout: null))); } + [Fact] + public async Task Get_Local_CleanEnvironment_DropsTheHostsCanaryButKeepsPathAndADeclaredEnvVar() + { + Environment.SetEnvironmentVariable("AGENTCORE_TEST_CANARY", "leaked"); + try + { + await using CallShells shells = new(_workspace, logger: null); + CallShellOptions options = new( + ShellKind.Local, + Policy: null, + Timeout: null, + Env: new Dictionary { ["PROBE_OK"] = "yes" }); + + var canary = await shells.Get(options).RunAsync( + "echo \"c=$AGENTCORE_TEST_CANARY\"", TestContext.Current.CancellationToken); + Assert.Equal("c=", canary.Stdout.Trim()); + + var declared = await shells.Get(options).RunAsync( + "echo $PROBE_OK", TestContext.Current.CancellationToken); + Assert.Equal("yes", declared.Stdout.Trim()); + + var path = await shells.Get(options).RunAsync("ls / >/dev/null && echo ok", TestContext.Current.CancellationToken); + Assert.Equal("ok", path.Stdout.Trim()); + } + finally + { + Environment.SetEnvironmentVariable("AGENTCORE_TEST_CANARY", null); + } + } + [Fact] public async Task Get_Docker_ReturnsADockerShellExecutor_WithNoDockerNeeded() { diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs deleted file mode 100644 index 4f8c5324..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/HostedFileCaptureProviderTests.cs +++ /dev/null @@ -1,224 +0,0 @@ -#pragma warning disable MAAI001 // The context constructors are evaluation-only in Microsoft.Agents.AI 1.21.0. - -using AgentCore.Application.Transcript; -using AgentCore.Application.Blobs; -using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Harness; -using AgentCore.Application.Runtime.Turn; -using AgentCore.Application.Tests.Fakes; -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; -using Microsoft.Extensions.Logging.Abstractions; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime.Harness; - -/// -/// After a run: every sandbox file the vendor surfaced is downloaded and stored under the call, and -/// the content it rode in on says what was kept. -/// -public sealed class HostedFileCaptureProviderTests -{ - private static readonly byte[] Png = [0x89, (byte)'P', (byte)'N', (byte)'G', 1, 2, 3]; - - [Fact] - public async Task InvokedAsync_FileOnTheMessage_StoresItUnderTheCallAndTheName() - { - // Arrange - var files = new ScriptedHostedFileClient().Serve("cfile_1", Png, "image/png"); - RecordingBlobStore blobs = new(); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(File("cfile_1", "chart.png", "cntr_1")); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - var stored = Assert.Single(blobs.Blobs); - Assert.Equal(("call-7", "chart.png"), stored.Key); - Assert.Equal("image/png", stored.Value.MediaType); - Assert.Equal(Png, stored.Value.Bytes); - Assert.Equal("cntr_1", files.ScopesAsked["cfile_1"]); - } - - [Fact] - public async Task InvokedAsync_FileKept_WritesWhatWasStoredOntoTheContent() - { - // Arrange: the vendor names no media type; the download does. - var files = new ScriptedHostedFileClient().Serve("cfile_1", Png, "image/png"); - RecordingBlobStore blobs = new(); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var file = File("cfile_1", "chart.png"); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(file)), TestContext.Current.CancellationToken); - - // Assert: a later read links from the content alone. - Assert.True(file.Kept); - Assert.Equal("image/png", file.MediaType); - Assert.Equal(Png.Length, file.Length); - } - - [Fact] - public async Task InvokedAsync_FileRefused_LeavesTheContentNotKept() - { - // Arrange: a 100-byte cap, a 300-byte file. - var files = new ScriptedHostedFileClient().Serve("cfile_6", new byte[300], "image/png"); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var file = File("cfile_6", "big.png"); - var provider = new HostedFileCaptureProvider(files, new RecordingBlobStore(), new BlobPolicy(100, ["png"]), NullLogger.Instance); - - // Act - await provider.InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], Reply(file)), TestContext.Current.CancellationToken); - - // Assert - Assert.False(file.Kept); - } - - [Fact] - public async Task InvokedAsync_ChildSessionWithTheOwnerStamp_StoresUnderThatCall() - { - // Arrange: no turn filed, only the stamp BackgroundChildAgent leaves. - var files = new ScriptedHostedFileClient().Serve("cfile_3", Png, "image/png"); - RecordingBlobStore blobs = new(); - var agent = Agent(); - var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - session.StateBag.SetValue(BlobOwnerKey.Value, "call-child"); - var response = Reply(File("cfile_3", "rows.csv")); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - Assert.True(blobs.Blobs.ContainsKey(("call-child", "rows.csv"))); - } - - [Fact] - public async Task InvokedAsync_NoOwnerAtAll_StoresNothingAndDoesNotThrow() - { - // Arrange - var files = new ScriptedHostedFileClient().Serve("cfile_4", Png, "image/png"); - RecordingBlobStore blobs = new(); - var agent = Agent(); - var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - var response = Reply(File("cfile_4", "chart.png")); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - Assert.Empty(blobs.Blobs); - } - - [Theory] - [InlineData("../etc/passwd")] - [InlineData("page.html")] - public async Task InvokedAsync_UnsafeNameOrDisallowedExtension_IsRefusedNotStored(string name) - { - // Arrange - var files = new ScriptedHostedFileClient().Serve("cfile_5", Png, "image/png"); - RecordingBlobStore blobs = new(); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(File("cfile_5", name)); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - Assert.Empty(blobs.Blobs); - } - - [Fact] - public async Task InvokedAsync_FileOverTheCap_IsRefusedWithoutBufferingAllOfIt() - { - // Arrange: a 100-byte cap, a 300-byte file. - var files = new ScriptedHostedFileClient().Serve("cfile_6", new byte[300], "image/png"); - RecordingBlobStore blobs = new(); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(File("cfile_6", "big.png")); - var provider = new HostedFileCaptureProvider(files, blobs, new BlobPolicy(100, ["png"]), NullLogger.Instance); - - // Act - await provider.InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - Assert.Empty(blobs.Blobs); - } - - [Fact] - public async Task InvokedAsync_DownloadThrows_StoresNothingAndDoesNotThrow() - { - // Arrange: the client knows no such file. - ScriptedHostedFileClient files = new(); - RecordingBlobStore blobs = new(); - var (agent, session) = await AgentWithFiledTurn("call-7"); - var response = Reply(File("cfile_missing", "chart.png")); - - // Act - await Provider(files, blobs).InvokedAsync(new AIContextProvider.InvokedContext(agent, session, [], response), TestContext.Current.CancellationToken); - - // Assert - Assert.Empty(blobs.Blobs); - } - - [Fact] - public async Task InvokingAsync_TellsTheModelWhereToSaveAndHowToLink() - { - // Arrange - var agent = Agent(); - var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - - // Act - var context = await Provider(new ScriptedHostedFileClient(), new RecordingBlobStore()) - .InvokingAsync(new AIContextProvider.InvokingContext(agent, session, new AIContext()), TestContext.Current.CancellationToken); - - // Assert - Assert.Contains("/mnt/data", context.Instructions, StringComparison.Ordinal); - Assert.Contains("sandbox:/mnt/data/", context.Instructions, StringComparison.Ordinal); - } - - [Fact] - public async Task InvokingAsync_KeepsWhatTheEarlierProvidersBuilt() - { - // Arrange - var agent = Agent(); - var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - var tool = AIFunctionFactory.Create(() => "ok", "count_orders"); - ChatMessage asked = new(ChatRole.User, "How many orders?"); - AIContext incoming = new() - { - Instructions = "You answer the Spirit agent.", - Messages = [asked], - Tools = [tool], - }; - - // Act - var context = await Provider(new ScriptedHostedFileClient(), new RecordingBlobStore()) - .InvokingAsync(new AIContextProvider.InvokingContext(agent, session, incoming), TestContext.Current.CancellationToken); - - // Assert - Assert.Contains("You answer the Spirit agent.", context.Instructions, StringComparison.Ordinal); - Assert.Contains("/mnt/data", context.Instructions, StringComparison.Ordinal); - Assert.Same(asked, Assert.Single(context.Messages!)); - Assert.Same(tool, Assert.Single(context.Tools!)); - } - - private static HostedFileCaptureProvider Provider(ScriptedHostedFileClient files, RecordingBlobStore blobs) - => new(files, blobs, BlobPolicy.Default, NullLogger.Instance); - - private static ChatClientAgent Agent() => new ChatClientAgent(new ScriptedChatClient("ok")); - - private static async Task<(AIAgent Agent, AgentSession Session)> AgentWithFiledTurn(string callId) - { - var agent = Agent(); - var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - TurnRegistry.Set(session, new TurnInvocation { CallId = callId, TurnIndex = 0, Stage = "s" }); - return (agent, session); - } - - private static FileContent File(string fileId, string name, string? scope = null) - => new() { Name = name, FileId = fileId, Scope = scope }; - - private static List Reply(params AIContent[] contents) - => [new ChatMessage(ChatRole.Assistant, [new TextContent("see sandbox:/mnt/data/x"), .. contents])]; -} diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnFilesTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnFilesTests.cs new file mode 100644 index 00000000..ff90fa9c --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnFilesTests.cs @@ -0,0 +1,79 @@ +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Transcript; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime.Turn; + +/// +/// What a turn has published and not yet attached to a message. Keyed by the outer tool call, like +/// the render and source collectors, because the message a file card belongs on is the result of +/// the call that published it. +/// +public sealed class TurnFilesTests +{ + [Fact] + public void Publish_UnderACall_IsTakenByThatCallOnce() + { + TurnFiles files = new(); + + using (files.BeginOuterCall("call-1")) + { + files.Publish(Card("rows.csv", 8)); + } + + var taken = files.TakeFor("call-1"); + + Assert.Equal("rows.csv", Assert.Single(taken).Name); + Assert.Empty(files.TakeFor("call-1")); + } + + [Fact] + public void Publish_WithNoCallOpen_IsDropped() + { + TurnFiles files = new(); + + files.Publish(Card("rows.csv", 8)); + + Assert.Empty(files.TakeFor("rows.csv")); + } + + [Fact] + public void Publish_TheSameNameTwice_KeepsTheLaterFactsInTheFirstPlace() + { + TurnFiles files = new(); + + using (files.BeginOuterCall("call-1")) + { + files.Publish(Card("rows.csv", 8)); + files.Publish(Card("chart.png", 3)); + files.Publish(Card("rows.csv", 16)); + } + + var taken = files.TakeFor("call-1"); + + Assert.Equal(["rows.csv", "chart.png"], taken.Select(card => card.Name)); + Assert.Equal(16, taken[0].Length); + } + + [Fact] + public void Publish_InsideANestedCall_FilesUnderTheOuterCall() + { + TurnFiles files = new(); + + using (files.BeginOuterCall("outer")) + { + using (files.BeginOuterCall("inner")) + { + files.Publish(Card("rows.csv", 8)); + } + + files.Publish(Card("chart.png", 3)); + } + + Assert.Single(files.TakeFor("inner")); + Assert.Single(files.TakeFor("outer")); + } + + private static FileContent Card(string name, long length) + => new() { Name = name, FileId = name, MediaType = "text/csv", Length = length, Kept = true }; +} diff --git a/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs b/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs index 0cb7cb23..d7665beb 100644 --- a/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs +++ b/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs @@ -41,6 +41,34 @@ public async Task TheWorkedExample_ResolvesItsOneSecret() Assert.Equal("Bearer " + ApiKeyValue, secrets.Format(header)); } + [Fact] + public async Task AShellEnvValue_IsResolved_LikeAnMcpEnvValue() + { + const string document = """ + apiVersion: agentcore/v1 + agents: + items: + - id: worker + instructions: "ok" + shell: + kind: local + env: { DB_PASSWORD: "${secret:db-password}", DB_HOST: "localhost" } + entries: + main: + agent: worker + """; + + MapSecretResolver resolver = new MapSecretResolver().With("db-password", "hunter2"); + + var secrets = await ResolvedSecrets.ResolveAsync( + ConfigurationLoader.LoadYaml(document), + resolver, + TestContext.Current.CancellationToken); + + Assert.Equal(["db-password"], secrets.Names); + Assert.Equal(["db-password"], resolver.Asked); + } + [Fact] public async Task OneName_ReadsTheResolverOnce_HoweverManyToolsReferenceIt() { diff --git a/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs b/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs index 93d983cf..9fcdf149 100644 --- a/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs @@ -15,11 +15,10 @@ namespace AgentCore.Application.Tests.Tools; /// The first tool kind of section 8.1: kind: builtin, which AgentCore ships. /// /// -/// The shipped example holds two built-ins: web.search and code.execute, markers -/// that build one HostedWebSearchTool and one HostedCodeInterpreterTool and run no -/// code of their own — see HostedWebSearchDropTests for what reaches a compiled agent. They -/// call nothing, so the call path, the section 8.7 error-result shape, description resolution, and -/// cancellation that a plain built-in which actually runs would exercise stay untested until one ships. +/// The shipped example holds two built-ins: web.search, a marker that builds one +/// HostedWebSearchTool and runs no code of its own — see HostedWebSearchDropTests for +/// what reaches a compiled agent — and file.publish, a plain function whose call path is +/// covered in FilePublishToolDefinitionTests. /// public sealed class BuiltinToolTests { @@ -81,8 +80,10 @@ public async Task AUsesNameAgentCoreDoesNotShip_FailsTheBoot() /// Builds one declared tool through , synchronously. private sealed class BuiltinFactory { - private readonly BuiltinToolSource _source = - new(new BuiltinToolPorts(new RecordingChatClientFactory())); + private readonly BuiltinToolSource _source = new(new BuiltinToolPorts( + new RecordingChatClientFactory(), + new RecordingBlobStore(), + WorkspaceRoot: Path.Combine(Path.GetTempPath(), "agentcore-builtin-tests"))); public AITool? Create(ToolConfiguration tool) { diff --git a/tests/AgentCore.Application.Tests/Tools/CodeExecuteToolDefinitionTests.cs b/tests/AgentCore.Application.Tests/Tools/CodeExecuteToolDefinitionTests.cs deleted file mode 100644 index e3899806..00000000 --- a/tests/AgentCore.Application.Tests/Tools/CodeExecuteToolDefinitionTests.cs +++ /dev/null @@ -1,37 +0,0 @@ -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Tools.Builtin; -using Microsoft.Extensions.AI; -using Xunit; - -namespace AgentCore.Application.Tests.Tools; - -/// The uses: code.execute builtin, which builds a marker and nothing else. -public sealed class CodeExecuteToolDefinitionTests -{ - [Fact] - public void Name_IsTheDocumentedUsesValue() - { - Assert.Equal("code.execute", BuiltinToolNames.CodeExecute); - } - - [Fact] - public void Build_ProducesAHostedCodeInterpreterTool() - { - var tool = new CodeExecuteToolDefinition().Build( - new ToolConfiguration { Id = "python", Kind = ToolKind.Builtin, Uses = BuiltinToolNames.CodeExecute }, - new BuiltinToolPorts(ChatClients: null)); - - Assert.IsType(tool); - } - - [Fact] - public void Build_NeedsNoPorts() - { - // The marker carries no behaviour, so an unbound chat client factory is not a failure here. - var exception = Record.Exception(() => new CodeExecuteToolDefinition().Build( - new ToolConfiguration { Id = "python", Kind = ToolKind.Builtin, Uses = BuiltinToolNames.CodeExecute }, - new BuiltinToolPorts(ChatClients: null))); - - Assert.Null(exception); - } -} diff --git a/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs b/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs new file mode 100644 index 00000000..0a9d1813 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs @@ -0,0 +1,74 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools; +using AgentCore.Application.Tools.Builtin; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Tools; + +/// +/// A background child runs with no turn, so file.publish finds the owning call on the stamp +/// its session carries and stores the file under the parent call. +/// +/// +/// The child session is created inside the parent's run, the way BackgroundAgentsProvider +/// creates it, so stamps it. The child then runs on that session +/// with null run options, which is what the provider passes it. +/// +public sealed class FilePublishBackgroundChildTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-publish-child-" + Guid.NewGuid().ToString("N")); + + public FilePublishBackgroundChildTests() => Directory.CreateDirectory(Path.Combine(_root, "call-9")); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Fact] + public async Task AChildThatPublishes_StoresTheFileUnderTheParentCall() + { + // Arrange + var token = TestContext.Current.CancellationToken; + File.WriteAllText(Path.Combine(_root, "call-9", "rows.csv"), "a,b"); + RecordingBlobStore blobs = new(); + + var publish = new FilePublishToolDefinition().Build( + new ToolConfiguration { Id = "publish", Kind = ToolKind.Builtin, Uses = BuiltinToolNames.FilePublish }, + new BuiltinToolPorts(ChatClients: null, Blobs: blobs, WorkspaceRoot: _root)); + + ToolCallingChatClient childModel = new( + "published", + new Dictionary(StringComparer.Ordinal) { ["path"] = "rows.csv" }); + + BackgroundChildAgent child = new(new ChatClientAgent(childModel, new ChatClientAgentOptions { ChatOptions = new ChatOptions { Tools = [publish] } })); + SessionCreatingProvider creating = new(child); + ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); + var turn = new TurnInvocation { CallId = "call-9", TurnIndex = 0, Stage = "s", Workspace = Path.Combine(_root, "call-9") }; + + await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); + + // Act: the child runs on its stamped session with no run options, as the provider runs it. + await child.RunAsync("publish the rows", creating.Created!, options: null, token); + + // Assert + Assert.Equal(["publish"], childModel.Called); + var result = Assert.Single(childModel.ToolResults); + Assert.Contains("https://blobs.test/call-9/rows.csv", result, StringComparison.Ordinal); + Assert.DoesNotContain(ToolErrorResult.ErrorProperty + "\":true", result, StringComparison.Ordinal); + Assert.Single(blobs.Blobs.Keys, key => key == ("call-9", "rows.csv")); + } + + private sealed class SessionCreatingProvider(AIAgent child) : AIContextProvider + { + public AgentSession? Created { get; private set; } + + protected override async ValueTask InvokingCoreAsync(InvokingContext context, CancellationToken cancellationToken = default) + { + Created = await child.CreateSessionAsync(cancellationToken); + return new AIContext(); + } + } +} diff --git a/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs b/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs new file mode 100644 index 00000000..6f25b173 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs @@ -0,0 +1,202 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools; +using AgentCore.Application.Tools.Builtin; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Tools; + +/// +/// The uses: file.publish builtin: what it refuses, and what it stores, links, and files on +/// the turn when it accepts. +/// +public sealed class FilePublishToolDefinitionTests : IDisposable +{ + private static readonly ToolConfiguration Declared = + new() { Id = "publish", Kind = ToolKind.Builtin, Uses = BuiltinToolNames.FilePublish, Description = "Publish a file." }; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-publish-" + Guid.NewGuid().ToString("N")); + + private readonly RecordingBlobStore _blobs = new(); + + public FilePublishToolDefinitionTests() => Directory.CreateDirectory(Path.Combine(_root, "call-1")); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Fact] + public void Name_IsTheDocumentedUsesValue() + { + Assert.Equal("file.publish", BuiltinToolNames.FilePublish); + } + + [Fact] + public void Build_NoBlobStore_FailsTheLoadNamingTheToolAndThePort() + { + var failure = Assert.Throws(() => new FilePublishToolDefinition().Build( + Declared, new BuiltinToolPorts(ChatClients: null, Blobs: null, WorkspaceRoot: _root))); + + Assert.Contains("'publish'", failure.Message, StringComparison.Ordinal); + Assert.Contains("providers.blobs", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Build_NoWorkspaceRoot_FailsTheLoadNamingUseWorkspace() + { + var failure = Assert.Throws(() => new FilePublishToolDefinition().Build( + Declared, new BuiltinToolPorts(ChatClients: null, Blobs: _blobs, WorkspaceRoot: null))); + + Assert.Contains("'publish'", failure.Message, StringComparison.Ordinal); + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Build_NamesTheFunctionAfterTheDeclaredIdAndHidesTheTurnFromTheModel() + { + var function = Assert.IsType(Build(), exactMatch: false); + + Assert.Equal("publish", function.Name); + Assert.Equal("Publish a file.", function.Description); + + var properties = function.JsonSchema.GetProperty("properties"); + Assert.True(properties.TryGetProperty("path", out _)); + Assert.True(properties.TryGetProperty("title", out _)); + Assert.False(properties.TryGetProperty("turn", out _)); + Assert.Contains("path", function.JsonSchema.GetProperty("required").EnumerateArray().Select(e => e.GetString())); + } + + [Theory] + [InlineData("../secret.csv")] + [InlineData("out/../../secret.csv")] + [InlineData("/etc/passwd")] + public async Task Publish_APathOutsideTheWorkspace_IsRefusedWithAToolError(string path) + { + File.WriteAllText(Path.Combine(_root, "secret.csv"), "a,b"); + + var result = await PublishAsync(path); + + Assert.True(ToolErrorResult.IsError(result)); + Assert.Equal("publish", result["tool"]!.GetValue()); + Assert.Contains("inside the workspace", result["message"]!.GetValue(), StringComparison.Ordinal); + Assert.Empty(_blobs.Blobs); + } + + [Fact] + public async Task Publish_AFileThatIsNotThere_IsRefusedWithAToolError() + { + var result = await PublishAsync("missing.csv"); + + Assert.True(ToolErrorResult.IsError(result)); + Assert.Contains("missing.csv", result["message"]!.GetValue(), StringComparison.Ordinal); + } + + [Fact] + public async Task Publish_AnExtensionThePolicyRefuses_IsRefusedWithTheReason() + { + File.WriteAllText(Path.Combine(_root, "call-1", "notes.exe"), "x"); + + var result = await PublishAsync("notes.exe"); + + Assert.True(ToolErrorResult.IsError(result)); + Assert.Contains("extension 'exe' is not allowed", result["message"]!.GetValue(), StringComparison.Ordinal); + Assert.Empty(_blobs.Blobs); + } + + [Fact] + public async Task Publish_AFileOverTheCap_IsRefusedWithTheReason() + { + File.WriteAllBytes(Path.Combine(_root, "call-1", "big.csv"), new byte[64]); + + var result = await PublishAsync("big.csv", policy: new BlobPolicy(32, ["csv"])); + + Assert.True(ToolErrorResult.IsError(result)); + Assert.Contains("size 64 is outside 0..32 bytes", result["message"]!.GetValue(), StringComparison.Ordinal); + } + + [Fact] + public async Task Publish_AGoodFile_StoresItUnderTheCallLinksItAndFilesTheCardOnTheTurn() + { + File.WriteAllText(Path.Combine(_root, "call-1", "rows.csv"), "a,b\n1,2\n"); + TurnFiles files = new(); + using var outer = files.BeginOuterCall("tc_1"); + + var result = await PublishAsync("rows.csv", title: "Sales by month", files: files); + + Assert.False(ToolErrorResult.IsError(result)); + Assert.Equal("rows.csv", result["name"]!.GetValue()); + Assert.Equal("text/csv", result["mediaType"]!.GetValue()); + Assert.Equal(8, result["length"]!.GetValue()); + Assert.Equal("https://blobs.test/call-1/rows.csv?ttl=900", result["url"]!.GetValue()); + + var (mediaType, bytes) = _blobs.Blobs[("call-1", "rows.csv")]; + Assert.Equal("text/csv", mediaType); + Assert.Equal("a,b\n1,2\n", System.Text.Encoding.UTF8.GetString(bytes)); + + var card = Assert.Single(files.TakeFor("tc_1")); + Assert.Equal("rows.csv", card.Name); + Assert.Equal("rows.csv", card.FileId); + Assert.Equal("Sales by month", card.Title); + Assert.Equal("text/csv", card.MediaType); + Assert.Equal(8, card.Length); + Assert.True(card.Kept); + } + + [Fact] + public async Task Publish_AFileInASubfolder_IsStoredUnderItsOwnName() + { + Directory.CreateDirectory(Path.Combine(_root, "call-1", "out")); + File.WriteAllBytes(Path.Combine(_root, "call-1", "out", "chart.png"), [1, 2, 3]); + + var result = await PublishAsync("out/chart.png"); + + Assert.Equal("chart.png", result["name"]!.GetValue()); + Assert.Equal("image/png", result["mediaType"]!.GetValue()); + Assert.True(_blobs.Blobs.ContainsKey(("call-1", "chart.png"))); + } + + [Fact] + public async Task Publish_OutsideAnyTurn_IsRefusedWithAToolError() + { + File.WriteAllText(Path.Combine(_root, "call-1", "rows.csv"), "a"); + + var result = await PublishAsync("rows.csv", turn: false); + + Assert.True(ToolErrorResult.IsError(result)); + Assert.Contains("no call is running", result["message"]!.GetValue(), StringComparison.Ordinal); + } + + private AITool Build(BlobPolicy? policy = null) + => new FilePublishToolDefinition().Build( + Declared, new BuiltinToolPorts(ChatClients: null, Blobs: _blobs, BlobPolicy: policy, WorkspaceRoot: _root)); + + private async Task PublishAsync( + string path, string? title = null, BlobPolicy? policy = null, TurnFiles? files = null, bool turn = true) + { + var function = (AIFunction)Build(policy); + + Dictionary arguments = new(StringComparer.Ordinal) { ["path"] = path, ["title"] = title }; + + if (turn) + { + arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation + { + CallId = "call-1", + TurnIndex = 0, + Stage = string.Empty, + Workspace = Path.Combine(_root, "call-1"), + Files = files, + }; + } + + var result = await function.InvokeAsync(new AIFunctionArguments(arguments), TestContext.Current.CancellationToken); + + return Assert.IsType(ToolResultJson.ToNode(result)); + } +} diff --git a/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs b/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs index 392e2de7..39fd6538 100644 --- a/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/FileContentTests.cs @@ -12,12 +12,12 @@ public sealed class FileContentTests [Fact] public void Kept_SurvivesTheTranscriptEncoder() { - // Arrange: what the capture wrote, stored, read back. + // Arrange: what the publish tool wrote, stored, read back. FileContent file = new() { Name = "chart.png", - FileId = "cfile_1", - Scope = "cntr_1", + FileId = "out/chart.png", + Title = "Sales by month", MediaType = "image/png", Length = 48213, Kept = true, @@ -30,7 +30,7 @@ public void Kept_SurvivesTheTranscriptEncoder() // Assert var read = Assert.Single(restored.Contents.OfType()); - Assert.Equal(("chart.png", "cfile_1", "cntr_1", "image/png", 48213L, true), (read.Name, read.FileId, read.Scope, read.MediaType, read.Length, read.Kept)); + Assert.Equal(("chart.png", "out/chart.png", "Sales by month", "image/png", 48213L, true), (read.Name, read.FileId, read.Title, read.MediaType, read.Length, read.Kept)); Assert.Contains("\"agentcore.file\"", json, StringComparison.Ordinal); } } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs index 5e9115b3..273a32bd 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs @@ -147,6 +147,8 @@ private static ValueTask BuildAsync( options, startup, new RoutingChatClientFactory(new FragmentingChatClient("hello")), + blobs: null, + NullLoggerFactory.Instance, configuration, TestContext.Current.CancellationToken); } diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs new file mode 100644 index 00000000..4570f4af --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs @@ -0,0 +1,201 @@ +using System.Runtime.CompilerServices; +using System.Text.Json; +using AgentCore.Application.Calls; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.AspNetCore.Tests.Fakes; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.Endpoints; + +/// +/// The whole wire a published file travels: the model calls file.publish on a file in the +/// call's workspace, the blob store keeps it under the call, the browser gets one +/// agentcore_file part with the link, and the transcript links the same file on a later read. +/// +public sealed class FileWireTests : IDisposable +{ + private const string CallId = "call-pub-1"; + + private const string Yaml = + """ + apiVersion: agentcore/v1 + tools: + - { id: publish, kind: builtin, uses: file.publish } + agents: + defaults: + model: { ref: reply } + items: + - { id: analyst, instructions: "hand over the report", tools: [ publish ] } + entries: + main: + agent: analyst + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + blobs: { kind: fake } + """; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-filewire-" + Guid.NewGuid().ToString("N")); + + public FileWireTests() => Directory.CreateDirectory(Path.Combine(_root, CallId)); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [Fact] + public async Task AToolThatPublishes_ReachesTheBrowserAsAFilePartAndTheTranscriptLinksItLater() + { + File.WriteAllText(Path.Combine(_root, CallId, "report.csv"), "month,sales\njan,10\n"); + FakeBlobStoreAdapter blobs = new(); + + await using var host = await ResponsesHost.StartAsync( + Yaml, + new PublishingChatClient(), + configure: options => options.UseWorkspace(_root).UseBlobStores(blobs)); + + using var response = await host.PostAsync( + $$"""{ "stream": true, "conversation": "{{CallId}}", "input": "send me the report", "agentcore": { "message_id": "m1" } }"""); + var events = await ResponsesHost.ReadEventsAsync(response); + + var files = events + .Select(text => JsonDocument.Parse(text).RootElement) + .Where(chunk => chunk.TryGetProperty("agentcore_file", out var file) && file.ValueKind != JsonValueKind.Null) + .Select(chunk => chunk.GetProperty("agentcore_file")) + .ToList(); + + var file = Assert.Single(files); + Assert.Equal("report.csv", file.GetProperty("name").GetString()); + Assert.Equal("Quarterly report", file.GetProperty("title").GetString()); + Assert.Equal("text/csv", file.GetProperty("media_type").GetString()); + Assert.Equal(19, file.GetProperty("length").GetInt64()); + Assert.Equal($"https://blobs.test/{CallId}/report.csv?ttl=900", file.GetProperty("url").GetString()); + + // The bytes are in the store, owned by the call. + var (mediaType, bytes) = blobs.Store.Blobs[(CallId, "report.csv")]; + Assert.Equal("text/csv", mediaType); + Assert.Equal("month,sales\njan,10\n", System.Text.Encoding.UTF8.GetString(bytes)); + + // The model read the link back in its tool result. + var toolResult = events + .Select(text => JsonDocument.Parse(text).RootElement) + .Where(chunk => chunk.TryGetProperty("agentcore_tool", out var tool) + && tool.GetProperty("phase").GetString() == "result") + .Select(chunk => chunk.GetProperty("agentcore_tool")) + .Single(); + Assert.False(toolResult.GetProperty("failed").GetBoolean()); + Assert.Equal($"https://blobs.test/{CallId}/report.csv?ttl=900", toolResult.GetProperty("result").GetProperty("url").GetString()); + + // And a later read of the transcript links the same file again. + var calls = host.Services.GetRequiredService(); + var stored = await calls.ReadAsync(CallId, TestContext.Current.CancellationToken); + var links = await calls.LinkFilesAsync(CallId, stored.Select(row => row.Content), TestContext.Current.CancellationToken); + + var link = Assert.Single(links); + Assert.Equal((CallId, "report.csv", "text/csv", 19L), (link.Blob.OwnerId, link.Blob.Name, link.Blob.MediaType, link.Blob.Length)); + Assert.Equal($"https://blobs.test/{CallId}/report.csv?ttl=900", link.Url?.ToString()); + } + + [Fact] + public async Task AToolThatPublishesAMissingFile_TellsTheModelAndWritesNoFilePart() + { + FakeBlobStoreAdapter blobs = new(); + + await using var host = await ResponsesHost.StartAsync( + Yaml, + new PublishingChatClient(), + configure: options => options.UseWorkspace(_root).UseBlobStores(blobs)); + + using var response = await host.PostAsync( + $$"""{ "stream": true, "conversation": "{{CallId}}", "input": "send me the report", "agentcore": { "message_id": "m1" } }"""); + var events = await ResponsesHost.ReadEventsAsync(response); + + Assert.DoesNotContain(events, text => text.Contains("agentcore_file", StringComparison.Ordinal)); + + var toolResult = events + .Select(text => JsonDocument.Parse(text).RootElement) + .Where(chunk => chunk.TryGetProperty("agentcore_tool", out var tool) + && tool.GetProperty("phase").GetString() == "result") + .Select(chunk => chunk.GetProperty("agentcore_tool")) + .Single(); + Assert.True(toolResult.GetProperty("failed").GetBoolean()); + Assert.Contains("report.csv", toolResult.GetProperty("result").GetProperty("message").GetString(), StringComparison.Ordinal); + Assert.Empty(blobs.Store.Blobs); + } + + [Fact] + public async Task APublishToolWithNoBlobStore_FailsTheStartNamingTheToolAndThePort() + { + var yaml = Yaml.Replace("blobs: { kind: fake }", string.Empty, StringComparison.Ordinal); + + var failure = await Assert.ThrowsAsync(() => ResponsesHost.StartAsync( + yaml, + new PublishingChatClient(), + configure: options => options.UseWorkspace(_root))); + + Assert.Contains("'publish'", failure.Message, StringComparison.Ordinal); + Assert.Contains("providers.blobs", failure.Message, StringComparison.Ordinal); + } + + /// Calls the publish tool it is offered, once, on the report, then answers in words. + private sealed class PublishingChatClient : IChatClient + { + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.Yield(); + + var alreadyPublished = messages.Any(message => message.Contents.OfType().Any()); + + if (!alreadyPublished && options?.Tools?.OfType().FirstOrDefault(tool => tool.Name == "publish") is { } publish) + { + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent( + "call_1", + publish.Name, + new Dictionary(StringComparer.Ordinal) + { + ["path"] = "report.csv", + ["title"] = "Quarterly report", + })]); + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, "here is the report."); + } + + public async Task GetResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + CancellationToken cancellationToken = default) + { + List updates = []; + await foreach (var update in GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false)) + { + updates.Add(update); + } + + return updates.ToChatResponse(); + } + + public object? GetService(Type serviceType, object? serviceKey = null) + => serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; + + public void Dispose() + { + } + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs index ce6c3ba4..bf1e3685 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs @@ -9,13 +9,13 @@ namespace AgentCore.AspNetCore.Tests.Endpoints; -/// Which sandbox files reach the browser as a part, and with what link. +/// Which published files reach the browser as a part, and with what link. public sealed class TurnStreamFilesTests { private static ChatResponseUpdate UpdateWith(params AIContent[] contents) => new(ChatRole.Assistant, contents); - /// A file the capture provider kept, as it writes onto the content before the stream ends. + /// A file the publish tool kept, as it files it on the turn before the stream ends. private static FileContent Kept(string name, string mediaType, long length) => new() { Name = name, FileId = "cfile_" + name, MediaType = mediaType, Length = length, Kept = true }; diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeBlobStoreAdapter.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeBlobStoreAdapter.cs new file mode 100644 index 00000000..13ca16c4 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeBlobStoreAdapter.cs @@ -0,0 +1,65 @@ +using AgentCore.Application.Blobs; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; + +namespace AgentCore.AspNetCore.Tests.Fakes; + +/// A providers.blobs vendor that opens one in-memory store, so a test reads what a turn published. +internal sealed class FakeBlobStoreAdapter(string kind = "fake") : IBlobStoreAdapter +{ + public string Kind => kind; + + /// Gets the one store every open hands over. + public FakeBlobStore Store { get; } = new(); + + public ValueTask OpenAsync( + BlobProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default) + => ValueTask.FromResult(Store); +} + +/// An in-memory whose links name the owner and the blob, so a test can read them off a URL. +internal sealed class FakeBlobStore : IBlobStore +{ + private readonly Dictionary<(string Owner, string Name), (string MediaType, byte[] Bytes)> _blobs = []; + + /// Gets every blob stored, keyed by owner and name. + public IReadOnlyDictionary<(string Owner, string Name), (string MediaType, byte[] Bytes)> Blobs => _blobs; + + public async ValueTask PutAsync(BlobWrite write, CancellationToken cancellationToken = default) + { + using MemoryStream copy = new(); + await write.Content.CopyToAsync(copy, cancellationToken); + lock (_blobs) + { + _blobs[(write.OwnerId, write.Name)] = (write.MediaType, copy.ToArray()); + } + + return new BlobRef(write.OwnerId, write.Name, write.MediaType, write.Length); + } + + public ValueTask OpenReadAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => ValueTask.FromResult(_blobs.TryGetValue((ownerId, name), out var blob) + ? new BlobRead(blob.MediaType, blob.Bytes.Length, new MemoryStream(blob.Bytes)) + : null); + + public ValueTask StatAsync(string ownerId, string name, CancellationToken cancellationToken = default) + => ValueTask.FromResult(_blobs.TryGetValue((ownerId, name), out var blob) + ? new BlobRef(ownerId, name, blob.MediaType, blob.Bytes.Length) + : null); + + public ValueTask LinkAsync(BlobRef blob, TimeSpan lifetime, CancellationToken cancellationToken = default) + => ValueTask.FromResult(new Uri($"https://blobs.test/{blob.OwnerId}/{blob.Name}?ttl={(int)lifetime.TotalSeconds}")); + + public ValueTask DeleteByOwnerAsync(string ownerId, CancellationToken cancellationToken = default) + { + lock (_blobs) + { + foreach (var key in _blobs.Keys.Where(key => key.Owner == ownerId).ToList()) + { + _blobs.Remove(key); + } + } + + return ValueTask.CompletedTask; + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs index f37ab025..86533023 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs @@ -37,6 +37,9 @@ private ResponsesHost(WebApplication app, HttpClient client) /// Gets the client that speaks to the host. public HttpClient Client { get; } + /// Gets the started host's services, for a test that reads what a turn stored. + public IServiceProvider Services => _app.Services; + /// Starts one host over one document. /// The document, as YAML. /// The model behind every name the routing factory does not hold. diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs index 5b9155b9..8bda1461 100644 --- a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs @@ -14,18 +14,34 @@ namespace AgentCore.Infrastructure.Tests.Blobs.S3; /// public sealed class S3BlobStoreLinkTests { - private static S3BlobStore Open() + private static S3BlobStore Open(string endpoint = "https://s3.us-east-005.backblazeb2.com") => new( new AmazonS3Client( new BasicAWSCredentials("fakeKeyId", "fakeSecret"), new AmazonS3Config { - ServiceURL = "https://s3.us-east-005.backblazeb2.com", + ServiceURL = endpoint, AuthenticationRegion = "us-east-005", ForcePathStyle = true, }), "SpiritAI"); + [Fact] + public async Task LinkAsync_PlainHttpEndpoint_LinksOverHttp() + { + // Arrange + using var store = Open("http://localhost:59000"); + + // Act + var url = await store.LinkAsync(new BlobRef("call-1", "rows.csv", "text/csv", 8), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); + + // Assert + Assert.NotNull(url); + Assert.Equal("http", url.Scheme); + Assert.Equal("localhost", url.Host); + Assert.Equal(59000, url.Port); + } + [Fact] public async Task LinkAsync_SignsHostOnly_AndCarriesTheResponseOverrides() { diff --git a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs index 78bb03c4..eb59c6cc 100644 --- a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs @@ -163,7 +163,7 @@ public void ResolveHostedWebSearch_WithoutAVeto_ResolvesTheMarker() var adapter = new OpenAiChatClientAdapter(); HostedWebSearchTool marker = new(); - Assert.Same(marker, adapter.ResolveHostedTool(marker, Entry(webSearch: null, codeExecute: null))); + Assert.Same(marker, adapter.ResolveHostedTool(marker, Entry(webSearch: null))); } [Fact] @@ -171,24 +171,7 @@ public void ResolveHostedSearch_WithAVeto_AnswersNull() { var adapter = new OpenAiChatClientAdapter(); - Assert.Null(adapter.ResolveHostedTool(new HostedWebSearchTool(), Entry(webSearch: false, codeExecute: null))); - } - - [Fact] - public void ResolveHostedCodeExecution_WithoutAVeto_ResolvesTheMarker() - { - var adapter = new OpenAiChatClientAdapter(); - HostedCodeInterpreterTool marker = new(); - - Assert.Same(marker, adapter.ResolveHostedTool(marker, Entry(webSearch: null, codeExecute: null))); - } - - [Fact] - public void ResolveHostedCodeExecution_WithAVeto_AnswersNull() - { - var adapter = new OpenAiChatClientAdapter(); - - Assert.Null(adapter.ResolveHostedTool(new HostedCodeInterpreterTool(), Entry(webSearch: null, codeExecute: false))); + Assert.Null(adapter.ResolveHostedTool(new HostedWebSearchTool(), Entry(webSearch: false))); } [Fact] @@ -196,16 +179,15 @@ public void ResolveHostedTool_ForAnUnknownMarker_AnswersNull() { var adapter = new OpenAiChatClientAdapter(); - Assert.Null(adapter.ResolveHostedTool(new HostedMcpServerTool("s", "https://example.com"), Entry(webSearch: null, codeExecute: null))); + Assert.Null(adapter.ResolveHostedTool(new HostedMcpServerTool("s", "https://example.com"), Entry(webSearch: null))); } - private static LlmProviderConfiguration Entry(bool? webSearch, bool? codeExecute) => new() + private static LlmProviderConfiguration Entry(bool? webSearch) => new() { Kind = OpenAiChatClientAdapter.ProviderKind, Model = "m", As = "reply", WebSearch = webSearch, - CodeExecute = codeExecute, }; } diff --git a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs deleted file mode 100644 index a73d9e04..00000000 --- a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiSandboxFilesClientTests.cs +++ /dev/null @@ -1,154 +0,0 @@ -#pragma warning disable OPENAI001 -#pragma warning disable MEAI001 // IHostedFileClient is evaluation-only in Microsoft.Extensions.AI 10.10.0. - -using AgentCore.Application.Transcript; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Runtime.CompilerServices; -using AgentCore.Application.Blobs; -using AgentCore.Infrastructure.Llm.OpenAI; -using Microsoft.Extensions.AI; -using OpenAI; -using OpenAI.Responses; -using Xunit; - -namespace AgentCore.Infrastructure.Tests.Llm; - -/// -/// The vendor middleware that turns a container_file_citation into a . -/// -/// -/// The wire shape is the OpenAI API reference's container_file_citation object. The -/// Microsoft.Extensions.AI.OpenAI adapter maps it to a and keeps -/// the SDK object on ; the container id lives only there. -/// -public sealed class OpenAiSandboxFilesClientTests -{ - private const string CitationJson = """ - { - "type": "container_file_citation", - "container_id": "cntr_68c8f1a2b3c4d5e6f7a8b9c0", - "file_id": "cfile_68c8f1a2b3c4d5e6f7a8b9c1", - "filename": "chart.png", - "start_index": 42, - "end_index": 71 - } - """; - - private static readonly OpenAIClient OpenAi = new(new ApiKeyCredential("sk-test")); - - [Fact] - public async Task GetResponseAsync_ContainerFileCitation_AddsOneFileContent() - { - // Arrange - var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [CitedText()]))); - using var client = new OpenAiSandboxFilesClient(inner, OpenAi); - - // Act - var response = await client.GetResponseAsync("draw", cancellationToken: TestContext.Current.CancellationToken); - - // Assert - var file = Assert.Single(response.Messages[0].Contents.OfType()); - Assert.Equal("cfile_68c8f1a2b3c4d5e6f7a8b9c1", file.FileId); - Assert.Equal("cntr_68c8f1a2b3c4d5e6f7a8b9c0", file.Scope); - Assert.Equal("chart.png", file.Name); - Assert.False(file.Kept); - Assert.Equal("Here is your chart: [Download](sandbox:/mnt/data/chart.png)", response.Text); - } - - [Fact] - public async Task GetStreamingResponseAsync_ContainerFileCitation_AddsItToThatUpdate() - { - // Arrange - var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [CitedText()]))); - using var client = new OpenAiSandboxFilesClient(inner, OpenAi); - - // Act - var files = new List(); - await foreach (var update in client.GetStreamingResponseAsync("draw", cancellationToken: TestContext.Current.CancellationToken)) - { - files.AddRange(update.Contents.OfType()); - } - - // Assert - Assert.Equal("cfile_68c8f1a2b3c4d5e6f7a8b9c1", Assert.Single(files).FileId); - } - - [Fact] - public async Task GetResponseAsync_CitationWithoutTheRawObject_AddsNothing() - { - // Arrange: a citation from some other source (a vector-store file, say) carries no container. - TextContent text = new("see [1]") - { - Annotations = [new CitationAnnotation { FileId = "file-abc", Title = "notes.txt" }], - }; - var inner = new ScriptedChatClient(new ChatResponse(new ChatMessage(ChatRole.Assistant, [text]))); - using var client = new OpenAiSandboxFilesClient(inner, OpenAi); - - // Act - var response = await client.GetResponseAsync("cite", cancellationToken: TestContext.Current.CancellationToken); - - // Assert - Assert.Empty(response.Messages[0].Contents.OfType()); - } - - [Fact] - public void GetService_IHostedFileClient_AnswersThroughTheWrappersAbove() - { - // Arrange: the same wrappers the composite and the harness put above the vendor client. - using var client = new OpenAiSandboxFilesClient(new ScriptedChatClient(new ChatResponse()), OpenAi) - .AsBuilder() - .ConfigureOptions(options => options.Temperature ??= 0.2f) - .UseFunctionInvocation() - .Build(); - - // Act & Assert - Assert.NotNull(client.GetService()); - } - - [Fact] - public void GetService_IHostedFileClient_TheVendorClientAloneAnswersNothing() - { - // The reason the middleware exists. - using var vendor = OpenAi.GetResponsesClient().AsIChatClient("gpt-x"); - - Assert.Null(vendor.GetService()); - } - - private static TextContent CitedText() - { - var raw = ModelReaderWriter.Read(BinaryData.FromString(CitationJson))!; - - return new TextContent("Here is your chart: [Download](sandbox:/mnt/data/chart.png)") - { - Annotations = [new CitationAnnotation { FileId = raw.FileId, Title = raw.Filename, RawRepresentation = raw }], - }; - } - - /// An inner client that answers one fixed response, whole or as one update per message. - private sealed class ScriptedChatClient(ChatResponse response) : IChatClient - { - public Task GetResponseAsync( - IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) - => Task.FromResult(response); - - public async IAsyncEnumerable GetStreamingResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) - { - foreach (var message in response.Messages) - { - yield return new ChatResponseUpdate(message.Role, [.. message.Contents]); - } - - await Task.CompletedTask; - } - - public object? GetService(Type serviceType, object? serviceKey = null) => null; - - public void Dispose() - { - } - } -} From 44b9b441e88d3fedaeffdc73edeb466ccfefa008 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 18 Sep 2026 16:29:46 -0600 Subject: [PATCH 18/35] feat(blobs): add support for TSV file type in BlobPolicy and tests --- src/AgentCore.Application/Blobs/BlobMediaTypes.cs | 1 + src/AgentCore.Application/Blobs/BlobPolicy.cs | 2 +- tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/AgentCore.Application/Blobs/BlobMediaTypes.cs b/src/AgentCore.Application/Blobs/BlobMediaTypes.cs index f5859a34..f77bf70f 100644 --- a/src/AgentCore.Application/Blobs/BlobMediaTypes.cs +++ b/src/AgentCore.Application/Blobs/BlobMediaTypes.cs @@ -15,6 +15,7 @@ internal static class BlobMediaTypes ["webp"] = "image/webp", ["pdf"] = "application/pdf", ["csv"] = "text/csv", + ["tsv"] = "text/tab-separated-values", ["txt"] = "text/plain", ["md"] = "text/markdown", ["json"] = "application/json", diff --git a/src/AgentCore.Application/Blobs/BlobPolicy.cs b/src/AgentCore.Application/Blobs/BlobPolicy.cs index 4339d589..c3bde263 100644 --- a/src/AgentCore.Application/Blobs/BlobPolicy.cs +++ b/src/AgentCore.Application/Blobs/BlobPolicy.cs @@ -15,7 +15,7 @@ public sealed class BlobPolicy /// public static readonly IReadOnlySet DefaultExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { - "png", "jpg", "jpeg", "gif", "webp", "pdf", "csv", "txt", "md", "json", "zip", "xlsx", "docx", "pptx", + "png", "jpg", "jpeg", "gif", "webp", "pdf", "csv", "tsv", "txt", "md", "json", "zip", "xlsx", "docx", "pptx", }; /// The policy the harness uses when the document names none. diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs index 64c7a94f..f77528b5 100644 --- a/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs +++ b/tests/AgentCore.Application.Tests/Blobs/BlobPolicyTests.cs @@ -10,6 +10,7 @@ public sealed class BlobPolicyTests [InlineData("chart.png", 15_769)] [InlineData("report.PDF", 1)] [InlineData("rows.csv", 0)] + [InlineData("rows.tsv", 0)] [InlineData("big.png", 10L * 1024 * 1024)] [InlineData("report.md", 518)] [InlineData("units.xlsx", 4_096)] From e340c4384d0efba7fa21366353862b9ee48df949 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 18 Sep 2026 23:27:56 -0600 Subject: [PATCH 19/35] refactor: update conversation-related terminology --- README.md | 6 +- config/example.yaml | 26 +- ...server.cs => AuditConversationObserver.cs} | 26 +- .../Audit/AuditSinkFactory.cs | 2 +- .../Audit/Memory/InMemoryAuditSink.cs | 14 +- .../Audit/QueuedAuditSink.cs | 16 +- .../Blobs/BlobStoreFactory.cs | 2 +- src/AgentCore.Application/Blobs/BlobWrite.cs | 2 +- src/AgentCore.Application/Blobs/FileLink.cs | 2 +- .../Calls/CallChannelContext.cs | 10 - src/AgentCore.Application/Calls/CallRecord.cs | 35 - .../Calls/CallRepository.cs | 182 ---- src/AgentCore.Application/Calls/CallStatus.cs | 11 - .../Calls/Memory/InMemoryCallStore.cs | 425 -------- .../Compilation/AgentApproval.cs | 2 +- .../Compilation/AgentBackgroundCompiler.cs | 2 +- .../Compilation/AgentCompilationContext.cs | 4 +- .../AgentContextProviderCompiler.cs | 2 +- .../Compilation/AgentDelegationTool.cs | 2 +- .../Compilation/AgentHarnessProviders.cs | 38 +- .../Compilation/AgentInstructions.cs | 2 +- .../Compilation/AgentShellOptionsCompiler.cs | 6 +- .../Compilation/CompiledAgent.cs | 16 +- .../Compilation/ConfigurationCompiler.cs | 14 +- .../Compilation/GraphGuardGate.cs | 6 +- .../Schema/AgentMemoryConfiguration.cs | 6 +- .../Schema/AgentShellConfiguration.cs | 4 +- .../Schema/AgentsConfiguration.cs | 4 +- ...s => ConversationProviderConfiguration.cs} | 8 +- .../Schema/ExtractorConfiguration.cs | 2 +- .../Schema/PolicyConfiguration.cs | 4 +- .../Schema/ProvidersConfiguration.cs | 8 +- .../Schema/ReservedStateSlots.cs | 8 +- .../Schema/TitlerConfiguration.cs | 6 +- .../Schema/agentcore-v1.schema.json | 26 +- .../Validation/DelegationCycleCheck.cs | 2 +- .../Validation/GuardEvaluator.cs | 12 +- .../Validation/IGuardEvaluator.cs | 2 +- .../Validation/KnowledgeScopeCheck.cs | 8 +- .../Validation/ReasoningTemperatureCheck.cs | 2 +- .../Configuration/Validation/StateDomain.cs | 4 +- .../Validation/ValidationErrors.cs | 4 +- .../ChatConversationTitler.cs} | 46 +- .../ConversationChannel.cs} | 12 +- .../ConversationChannelContext.cs | 10 + .../ConversationClarificationState.cs} | 6 +- .../ConversationCursor.cs} | 22 +- .../ConversationInput.cs} | 12 +- .../ConversationPage.cs} | 6 +- .../Conversation/ConversationRecord.cs | 35 + .../ConversationSessionState.cs} | 22 +- .../ConversationSpeechPairing.cs} | 42 +- .../ConversationStateJson.cs} | 6 +- .../Conversation/ConversationStatus.cs | 11 + .../ConversationStoreFactory.cs} | 20 +- .../Conversation/Conversations.cs | 199 ++++ .../Memory/InMemoryConversationStore.cs | 425 ++++++++ .../Conversation/StoredConversation.cs | 16 + .../Diagnostics/AgentCoreTelemetry.cs | 8 +- src/AgentCore.Application/Diagnostics/Log.cs | 138 +-- ...rver.cs => LoggingConversationObserver.cs} | 82 +- ...er.cs => TelemetryConversationObserver.cs} | 30 +- .../Diagnostics/TelemetrySessionFactory.cs | 2 +- .../CompositeEmbeddingGeneratorFactory.cs | 2 +- .../Evaluation/ModerationEvaluatorFactory.cs | 2 +- .../Evaluation/ModerationVerdict.cs | 2 +- .../Evaluation/PromptModerator.cs | 12 +- .../CompositeKnowledgeStoreFactory.cs | 2 +- .../Knowledge/KnowledgeAuditRecord.cs | 2 +- .../Knowledge/KnowledgeCancellation.cs | 2 +- .../Knowledge/KnowledgeNotices.cs | 2 +- .../Knowledge/KnowledgePrefetchProvider.cs | 4 +- .../Knowledge/KnowledgeProbe.cs | 4 +- .../Knowledge/KnowledgeProviderFactory.cs | 2 +- .../Knowledge/StateKnowledgeScope.cs | 6 +- .../Llm/CompositeChatClientFactory.cs | 2 +- .../Policy/StagePolicy.cs | 4 +- .../Ports/ICallChannelFactory.cs | 13 - .../Ports/ICallSessionFactory.cs | 13 - .../Ports/ICallSessions.cs | 46 - .../Ports/ICallTitler.cs | 23 - ...CallAdapter.cs => IConversationAdapter.cs} | 8 +- .../Ports/IConversationChannelFactory.cs | 13 + ...InputPort.cs => IConversationInputPort.cs} | 26 +- ...llObserver.cs => IConversationObserver.cs} | 28 +- ...tputPort.cs => IConversationOutputPort.cs} | 10 +- .../Ports/IConversationPort.cs | 20 +- .../Ports/IConversationSessionFactory.cs | 13 + ...try.cs => IConversationSessionRegistry.cs} | 4 +- .../Ports/IConversationSessions.cs | 46 + .../{ICallStore.cs => IConversationStore.cs} | 142 +-- ...dapter.cs => IConversationStoreAdapter.cs} | 8 +- .../Ports/IConversationTitler.cs | 23 + .../Ports/IConversations.cs | 66 ++ .../Ports/IModerationAdapter.cs | 4 +- .../Ports/IRenderPort.cs | 2 +- .../Ports/ISourcePort.cs | 2 +- .../Ports/ISpeechAdapter.cs | 18 +- .../Ports/ITelemetryAdapter.cs | 2 +- .../Providers/VendorAdapterSelector.cs | 8 +- .../Providers/VendorSeam.cs | 6 +- .../PublicAPI.Unshipped.txt | 921 +++++++++--------- .../Runtime/AgentCoreAgent.cs | 156 +-- .../Runtime/CallEventKinds.cs | 53 - .../Runtime/Clarifications.cs | 24 +- .../{CallEvent.cs => ConversationEvent.cs} | 12 +- ...ventChain.cs => ConversationEventChain.cs} | 70 +- ...lEventKind.cs => ConversationEventKind.cs} | 14 +- .../Runtime/ConversationEventKinds.cs | 53 + ...eys.cs => ConversationEventPayloadKeys.cs} | 4 +- ...r.cs => ConversationObserverDispatcher.cs} | 72 +- ...lObservers.cs => ConversationObservers.cs} | 30 +- ...{CallSession.cs => ConversationSession.cs} | 150 +-- .../ConversationInterruptionTracker.cs} | 12 +- .../ConversationSessionLifetime.cs} | 38 +- .../ConversationSessionStateStore.cs} | 42 +- .../ConversationTranscriptLedger.cs} | 64 +- .../ConversationTurn.cs} | 4 +- .../ConversationTurnCommit.cs} | 18 +- .../ConversationTurnCompletion.cs} | 50 +- .../ConversationTurnRunner.cs} | 62 +- .../ConversationTurnStream.cs} | 12 +- .../ConversationTurnWriters.cs} | 14 +- .../ReplyOutcome.cs | 0 .../TranscriptEntry.cs | 0 ...ctory.cs => ConversationSessionFactory.cs} | 30 +- ...urnOrigin.cs => ConversationTurnOrigin.cs} | 6 +- ...lWorkspace.cs => ConversationWorkspace.cs} | 40 +- .../Runtime/FallbackAgent.cs | 8 +- .../Runtime/Harness/BackgroundChildAgent.cs | 12 +- .../Harness/BackgroundSessionRelease.cs | 14 +- .../Runtime/Harness/BlobOwnerKey.cs | 8 +- .../Runtime/Harness/CallerTimeZone.cs | 12 +- ...ovider.cs => ConversationFilesProvider.cs} | 12 +- ...> ConversationShellEnvironmentProvider.cs} | 14 +- ...Options.cs => ConversationShellOptions.cs} | 4 +- ...ovider.cs => ConversationShellProvider.cs} | 10 +- .../{CallShells.cs => ConversationShells.cs} | 42 +- .../Runtime/Harness/HarnessSessionState.cs | 2 +- .../Runtime/Harness/PendingApprovalQueue.cs | 24 +- .../Runtime/ModerationAgent.cs | 4 +- .../Runtime/ToolCallScopes.cs | 10 +- .../Runtime/Turn/TurnMessages.cs | 6 +- .../Runtime/TurnDisposition.cs | 2 +- .../Runtime/TurnInvocation.cs | 20 +- .../Scripting/ScriptRequest.cs | 2 +- .../Secrets/KnownSecrets.cs | 2 +- .../Secrets/SecretResolutionException.cs | 4 +- .../Secrets/SecretResolverExtensions.cs | 2 +- ...ons.cs => InMemoryConversationSessions.cs} | 62 +- .../Skills/SkillsProviderFactory.cs | 2 +- .../State/ConstStateWriter.cs | 4 +- .../State/CounterStateWriter.cs | 2 +- .../State/StateDocument.cs | 14 +- .../State/StateExtractionResult.cs | 4 +- .../State/StateExtractor.cs | 22 +- .../State/ToolStateWriter.cs | 2 +- .../State/UnfilledSlotReminder.cs | 4 +- .../Tools/Binding/ToolBindingRegistry.cs | 4 +- .../Tools/Binding/ToolParameterBindings.cs | 2 +- .../Tools/Builtin/BuiltinToolNames.cs | 2 +- .../Tools/Builtin/BuiltinToolOptions.cs | 2 +- .../Tools/Builtin/FilePublishTool.cs | 24 +- .../Builtin/FilePublishToolDefinition.cs | 2 +- .../Tools/DeclaredTool.cs | 4 +- .../Tools/Registry/ToolRegistration.cs | 2 +- .../Tools/Registry/ToolRegistryBuilder.cs | 4 +- .../Tools/ToolCallScope.cs | 10 +- .../AgentCoreChatHistoryProvider.cs | 136 +-- ...{CallMessage.cs => ConversationMessage.cs} | 12 +- ...geDraft.cs => ConversationMessageDraft.cs} | 8 +- ...essageIds.cs => ConversationMessageIds.cs} | 2 +- ...ranscript.cs => ConversationTranscript.cs} | 60 +- .../Transcript/TranscriptMarks.cs | 6 +- src/AgentCore.AspNetCore/Call/.editorconfig | 8 - src/AgentCore.AspNetCore/Call/CallSeams.cs | 11 - .../Call/ICallTransportAdapter.cs | 20 - .../ConnectionTaskObserver.cs | 24 +- ...ersationEndpointRouteBuilderExtensions.cs} | 20 +- .../ConversationRouteLog.cs} | 20 +- .../Conversation/ConversationSeams.cs | 11 + .../ConversationTurnArbiter.cs} | 92 +- .../IConversationTransportAdapter.cs | 20 + .../JsonWebSocketPump.cs | 34 +- .../DependencyInjection/AgentCoreBoot.cs | 48 +- .../AgentCoreBootService.cs | 2 +- .../DependencyInjection/AgentCoreOptions.cs | 82 +- .../AgentCoreServiceCollectionExtensions.cs | 33 +- .../Startup/ChatClientStartup.cs | 2 +- .../Startup/CompilationStartup.cs | 10 +- ...mStartup.cs => ConversationSeamStartup.cs} | 72 +- ...artup.cs => ConversationSessionStartup.cs} | 30 +- ...{CallStartup.cs => ConversationStartup.cs} | 22 +- .../Startup/EntryRegistry.cs | 26 +- .../Startup/ToolRegistryStartup.cs | 2 +- .../DependencyInjection/StartupLog.cs | 10 +- .../Endpoints/ResponsesContracts.cs | 14 +- .../Endpoints/ResponsesEndpoints.cs | 44 +- .../Endpoints/ResponsesTurnReply.cs | 8 +- .../Endpoints/ResponsesTurnStream.cs | 22 +- .../Endpoints/TurnStreamFiles.cs | 14 +- .../PublicAPI.Unshipped.txt | 38 +- .../Sessions/AgentCoreAgentSessionStore.cs | 22 +- ...eeper.cs => ConversationSessionSweeper.cs} | 14 +- .../TelnyxRelay/TelnyxRelayConnection.cs | 252 ++--- .../TelnyxRelay/TelnyxRelayContracts.cs | 18 +- ...r.cs => TelnyxRelayConversationAdapter.cs} | 28 +- ... TelnyxRelayConversationChannelFactory.cs} | 24 +- .../TelnyxRelay/TelnyxRelayEndpoints.cs | 22 +- .../TelnyxRelay/TelnyxRelayFrameReader.cs | 10 +- .../Vendors/TelnyxRelay/TelnyxRelayJson.cs | 2 +- .../Vendors/TelnyxRelay/TelnyxRelayLog.cs | 172 ++-- .../Vendors/TelnyxRelay/TelnyxRelayOptions.cs | 12 +- .../TelnyxRelay/TelnyxRelaySpeechAdapter.cs | 4 +- src/AgentCore.Domain/Audit/AuditEvent.cs | 14 +- src/AgentCore.Domain/Audit/AuditEventKind.cs | 10 +- src/AgentCore.Domain/Audit/AuditEventKinds.cs | 8 +- .../Audit/AuditEventVocabulary.cs | 18 +- src/AgentCore.Domain/Audit/AuditHash.cs | 2 +- .../Audit/AuditPayloadKeys.cs | 2 +- ...lEndReason.cs => ConversationEndReason.cs} | 28 +- ...ndReasons.cs => ConversationEndReasons.cs} | 30 +- src/AgentCore.Domain/Audit/ToolFailureKind.cs | 4 +- .../Audit/ToolFailureKinds.cs | 4 +- src/AgentCore.Domain/PublicAPI.Unshipped.txt | 32 +- src/AgentCore.Domain/TurnResult.cs | 12 +- .../AgentCore.Hosting.csproj | 2 +- .../AgentCoreHostBuilderExtensions.cs | 14 +- .../AgentCoreHostEndpointExtensions.cs | 18 +- src/AgentCore.Hosting/PublicAPI.Unshipped.txt | 2 +- .../AgentCore.Infrastructure.csproj | 2 +- .../Audit/Postgres/PostgresAuditSink.cs | 32 +- .../Calls/Postgres/PostgresCallRows.cs | 66 -- .../Postgres/PostgresConversationRows.cs | 66 ++ .../Postgres/PostgresConversationStore.cs} | 156 +-- .../PostgresConversationStoreAdapter.cs} | 12 +- .../Postgres/PostgresConversationStoreSql.cs} | 106 +- .../PostgresConversationVerification.cs} | 18 +- .../Postgres/Migrations/001_agentcore.sql | 100 +- .../Postgres/PostgresDataSourceFactory.cs | 2 +- .../Database/Postgres/PostgresSchema.cs | 2 +- .../VectorData/Qdrant/IQdrantSearchChannel.cs | 6 +- .../VectorData/Qdrant/QdrantSearchChannel.cs | 4 +- .../PublicAPI.Unshipped.txt | 10 +- .../Grafana/GrafanaOtlpTelemetryAdapter.cs | 2 +- .../Tools/HttpToolSource.cs | 2 +- .../Tools/Mcp/McpLog.cs | 6 +- .../Tools/Mcp/McpServerSession.cs | 28 +- .../Tools/Mcp/McpTool.cs | 2 +- .../Tools/McpToolSource.cs | 2 +- .../Audit/AuditCallObserverTests.cs | 249 ----- .../Audit/AuditConversationObserverTests.cs | 249 +++++ .../Audit/AuditSinkFactoryTests.cs | 6 +- ...ts.cs => ConversationSessionAuditTests.cs} | 196 ++-- ... => ConversationSessionModerationTests.cs} | 68 +- .../Audit/QueuedAuditSinkTests.cs | 8 +- .../Blobs/BlobStoreFactoryTests.cs | 2 +- .../Calls/CallCursorTests.cs | 52 - .../Compilation/AgentToolTests.cs | 4 +- .../ClarificationWiringBindingTests.cs | 6 +- .../Compilation/CompactionCompilationTests.cs | 2 +- .../CompiledAgentConcurrencyTests.cs | 18 +- .../Compilation/CompiledAgentRunTests.cs | 2 +- .../ConfigurationCompilerModelFacingTests.cs | 2 +- .../Compilation/FilesCompilationTests.cs | 42 +- .../Compilation/GraphNoMatchTests.cs | 32 +- .../Compilation/GuardedGraphEdgeTests.cs | 40 +- .../Compilation/HarnessCompilationTests.cs | 4 +- .../KnowledgeProviderBindingTests.cs | 2 +- .../KnowledgeProviderSchemaTests.cs | 8 +- .../Compilation/LoopCompilationTests.cs | 2 +- .../Compilation/MemoryCompilationTests.cs | 64 +- .../Compilation/ShellOptionsCompilerTests.cs | 2 +- .../Configuration/ConfigurationBinderTests.cs | 18 +- .../Configuration/ConfigurationLoaderTests.cs | 16 +- .../ConfigurationSchemaValidatorTests.cs | 10 +- ...emaTests.cs => ConversationSchemaTests.cs} | 52 +- .../Configuration/ExampleDocument.cs | 10 +- .../Configuration/FacetResolveSchemaTests.cs | 2 +- .../Configuration/McpConfigurationTests.cs | 2 +- .../Validation/ConfigurationValidatorTests.cs | 14 +- .../Validation/GuardEvaluatorTests.cs | 2 +- .../ReasoningTemperatureCheckTests.cs | 6 +- .../{Calls => Conversation}/.editorconfig | 0 .../ChatConversationTitlerTests.cs} | 94 +- .../ConversationChannelTests.cs} | 16 +- .../Conversation/ConversationCursorTests.cs | 52 + .../ConversationSessionStateTests.cs} | 28 +- .../ConversationSpeechPairingTests.cs} | 54 +- .../ConversationStoreFactoryTests.cs} | 64 +- .../ConversationsTests.cs} | 101 +- .../DelegatingConversationStoreTests.cs} | 30 +- .../InMemoryConversationStoreTests.cs} | 112 +-- ...MemoryConversationStoreTranscriptTests.cs} | 72 +- .../InMemoryConversationStoreAppendTests.cs} | 46 +- .../Diagnostics/DiagnosticsFakes.cs | 2 +- .../Diagnostics/LibraryOpenTelemetryTests.cs | 54 +- ...cs => LoggingConversationObserverTests.cs} | 86 +- ... => TelemetryConversationObserverTests.cs} | 54 +- .../Diagnostics/TelemetrySeamTests.cs | 2 +- .../Diagnostics/TurnObservabilityTests.cs | 84 +- ...CompositeEmbeddingGeneratorFactoryTests.cs | 6 +- .../Evaluation/Fakes/RecordingEvaluator.cs | 2 +- .../Evaluation/PromptModeratorTests.cs | 4 +- .../Fakes/RecordingCallStore.cs | 107 -- .../Fakes/RecordingChatClientAdapter.cs | 6 +- .../Fakes/RecordingConversationStore.cs | 107 ++ .../Fakes/ShellScriptedClient.cs | 2 +- .../Fakes/ThrowingCallStore.cs | 29 - .../Fakes/ThrowingConversationStore.cs | 29 + .../Fakes/ToolCallingChatClient.cs | 4 +- .../CompositeKnowledgeStoreFactoryTests.cs | 10 +- .../Knowledge/FacetFilterTests.cs | 2 +- .../Knowledge/KnowledgeAuditRecordTests.cs | 2 +- .../KnowledgeCitationFormatterFactoryTests.cs | 2 +- .../Knowledge/KnowledgeProbeTests.cs | 30 +- .../KnowledgeProviderFactoryTests.cs | 22 +- .../Llm/CompositeChatClientFactoryTests.cs | 16 +- ...nSet.cs => ConversationPolicyGoldenSet.cs} | 74 +- ...ts.cs => GoldenConversationReplayTests.cs} | 42 +- .../Policy/StagePolicyTests.cs | 2 +- .../Ports/VendorAdapterTests.cs | 2 +- .../Providers/VendorAdapterSelectorTests.cs | 2 +- .../Runtime/AgentCoreAgentSessionTests.cs | 166 ++-- .../Runtime/AgentCoreAgentTestSupport.cs | 20 +- .../Runtime/AgentCoreAgentTests.cs | 32 +- .../Runtime/AgentSessionAcrossAgentsTests.cs | 10 +- ...ctionInvokingChatClientErrorPolicyTests.cs | 10 +- ...ingFunctionInvokingChatClientStripTests.cs | 12 +- .../Runtime/CallEventKindsTests.cs | 79 -- .../Runtime/CappedToolCallFormatterTests.cs | 12 +- .../Runtime/ClarificationsTests.cs | 10 +- .../Runtime/CompactionStrategyFactoryTests.cs | 8 +- .../Runtime/ConversationEventKindsTests.cs | 79 ++ ...=> ConversationObserverDispatcherTests.cs} | 146 +-- ...Tests.cs => ConversationObserversTests.cs} | 36 +- ...cs => ConversationSessionApprovalTests.cs} | 10 +- ...sts.cs => ConversationSessionEditTests.cs} | 54 +- ...ersationSessionFactoryModelFacingTests.cs} | 10 +- ... => ConversationSessionGraphReplyTests.cs} | 38 +- ...> ConversationSessionInterruptionTests.cs} | 102 +- ...ts.cs => ConversationSessionProbeTests.cs} | 16 +- ...onTests.cs => ConversationSessionTests.cs} | 106 +- ...s => ConversationSessionWorkspaceTests.cs} | 42 +- ...Tests.cs => ConversationWorkspaceTests.cs} | 32 +- .../Runtime/DelegatedToolsTests.cs | 26 +- .../Harness/BackgroundChildAgentTests.cs | 18 +- ...s.cs => ConversationFilesProviderTests.cs} | 14 +- ... => ConversationSessionBackgroundTests.cs} | 20 +- ... => ConversationSessionGraphStateTests.cs} | 46 +- ... ConversationSessionProviderStateTests.cs} | 60 +- ...ts.cs => ConversationSessionShellTests.cs} | 62 +- ...llsTests.cs => ConversationShellsTests.cs} | 68 +- .../Harness/HarnessSessionStateTests.cs | 2 +- ...geScopeThroughConversationSessionTests.cs} | 38 +- .../Runtime/RuntimeFakes.cs | 22 +- .../Runtime/Turn/TurnContextProviderTests.cs | 18 +- .../Runtime/Turn/TurnResultsTests.cs | 4 +- .../Runtime/TurnPipelineTests.cs | 56 +- .../Runtime/TurnScreenTests.cs | 16 +- .../Secrets/ResolvedSecretsTests.cs | 4 +- .../Secrets/SecretResolverExtensionsTests.cs | 2 +- ...sTests.cs => ConversationSessionsTests.cs} | 84 +- .../Skills/SkillsProviderFactoryTests.cs | 2 +- .../State/StateDocumentTests.cs | 12 +- .../State/StateExtractorTests.cs | 4 +- .../State/StateWriterTests.cs | 4 +- .../State/ToolResultPathTests.cs | 2 +- .../Tools/BindingToolTests.cs | 2 +- .../Tools/BuiltinToolTests.cs | 2 +- .../Tools/DeclaredToolTests.cs | 2 +- .../Tools/FilePublishBackgroundChildTests.cs | 16 +- .../Tools/FilePublishToolDefinitionTests.cs | 28 +- .../Tools/TimeLimitedToolTests.cs | 2 +- .../Tools/ToolCallScopeTests.cs | 18 +- .../Tools/TypedBindingToolTests.cs | 12 +- ...AgentCoreChatHistoryProviderTestSupport.cs | 40 +- .../AgentCoreChatHistoryProviderTests.cs | 44 +- ...entCoreChatHistoryProviderTruncateTests.cs | 34 +- .../Transcript/CallSessionResumeTests.cs | 103 -- .../CompiledHistoryProviderTests.cs | 22 +- ...onversationSessionConversationRowTests.cs} | 32 +- ...onversationSessionGraphTranscriptTests.cs} | 34 +- ... ConversationSessionOutsideAppendTests.cs} | 54 +- ...> ConversationSessionResumeTestSupport.cs} | 40 +- .../ConversationSessionResumeTests.cs | 103 ++ ...> ConversationSessionStateRestoreTests.cs} | 140 +-- ...> ConversationSessionStoreFailureTests.cs} | 68 +- ... => ConversationSessionTranscriptTests.cs} | 54 +- ....cs => ConversationTranscriptEditTests.cs} | 36 +- ...ests.cs => ConversationTranscriptTests.cs} | 30 +- .../Transcript/InnerAgentTranscriptTests.cs | 10 +- .../Transcript/TranscriptJsonTests.cs | 4 +- .../AgentCore.AspNetCore.Tests/.editorconfig | 8 +- .../ConversationChannelShapeTests.cs} | 22 +- .../ConversationInputPortTests.cs} | 38 +- .../ConversationOptionsFromDocumentTests.cs} | 32 +- .../ConversationRegistrationTests.cs} | 70 +- .../ConversationRouteSelectionTests.cs} | 70 +- .../ConversationTurnArbiterTests.cs} | 36 +- ...yxRelayThroughTheConversationSeamTests.cs} | 24 +- .../DependencyInjection/AddAgentCoreTests.cs | 262 ++--- .../AgentCoreHttpClientsTests.cs | 2 +- .../KnowledgeScopeArgumentOrderTests.cs | 4 +- .../DependencyInjection/StartedHostFixture.cs | 4 +- .../WorkspaceStartupTests.cs | 22 +- .../OpenAiEmbeddingGeneratorAdapterTests.cs | 2 +- .../Endpoints/ApprovalWireTests.cs | 10 +- .../Endpoints/FileWireTests.cs | 36 +- .../Endpoints/ResponsesTests.cs | 18 +- .../Endpoints/SourceWireTests.cs | 24 +- .../Endpoints/TimeZoneHeaderTests.cs | 2 +- .../Endpoints/ToolWireTests.cs | 18 +- .../Endpoints/TurnStreamFilesTests.cs | 18 +- ...eCallInput.cs => FakeConversationInput.cs} | 20 +- ...allOutput.cs => FakeConversationOutput.cs} | 2 +- .../Fakes/FakeRelayClient.cs | 4 +- .../Fakes/FakeWebSocket.cs | 12 +- .../Fakes/HostFakes.cs | 8 +- .../Fakes/RelayFrames.cs | 8 +- .../Fakes/TelnyxRelayHost.cs | 60 +- .../OpenAI/OpenAiChatClientAdapterTests.cs | 2 +- ...s.cs => ConversationSessionsRelayTests.cs} | 42 +- .../TelnyxRelay/TelnyxRelayBargeInTests.cs | 48 +- ....cs => TelnyxRelayConversationEndTests.cs} | 256 ++--- .../TelnyxRelay/TelnyxRelayEndpointTests.cs | 46 +- .../TelnyxRelay/TelnyxRelayFrameCostTests.cs | 38 +- .../TelnyxRelayFrameReaderTests.cs | 16 +- .../TelnyxRelay/TelnyxRelayTurnTests.cs | 66 +- .../TelnyxRelay/TelnyxRelayWriteLoopTests.cs | 10 +- .../Audit/AuditEventVocabularyTests.cs | 66 +- .../AgentCore.Domain.Tests/TurnResultTests.cs | 8 +- tests/AgentCore.Evals/DatasetFixture.cs | 2 +- .../AgentCoreHostTests.cs | 48 +- .../ConfigurationSecretResolverTests.cs | 4 +- .../Postgres/PostgresAuditSinkAdapterTests.cs | 4 +- .../Audit/Postgres/PostgresAuditSinkTests.cs | 66 +- .../Blobs/S3/S3BlobStoreLinkTests.cs | 10 +- .../Postgres/ContinuationStoreTests.cs | 12 +- .../ConversationThreadSchemaTests.cs} | 58 +- .../PostgresConversationListTests.cs} | 88 +- .../PostgresConversationPrincipalTests.cs} | 34 +- .../PostgresConversationStoreAppendTests.cs} | 48 +- .../PostgresConversationStoreSweepTests.cs} | 60 +- .../PostgresConversationStoreTests.cs} | 78 +- ...PostgresConversationStoreTruncateTests.cs} | 42 +- .../PostgresConversationStoreWordsTests.cs} | 108 +- .../Database/Postgres/PostgresDatabaseTest.cs | 2 +- .../Database/Postgres/PostgresSchemaTests.cs | 66 +- .../OpenAiModerationEvaluatorTests.cs | 4 +- .../Qdrant/AmbiguityIntegrationTests.cs | 26 +- .../Qdrant/QdrantKnowledgeAdapterTests.cs | 8 +- .../Qdrant/QdrantKnowledgeStoreTests.cs | 2 +- .../VectorData/Qdrant/QdrantServer.cs | 2 +- .../Llm/OpenAiReasoningEffortTests.cs | 4 +- .../ToolSeamTests.cs | 4 +- .../Tools/Fakes/ControllableMcpServer.cs | 4 +- .../Tools/HttpToolSourceTests.cs | 2 +- .../Tools/McpServerSessionTests.cs | 10 +- .../Tools/McpToolSourceTests.cs | 2 +- .../DelegatingCallStore.cs | 118 --- .../DelegatingConversationStore.cs | 118 +++ ...llStore.cs => ParkingConversationStore.cs} | 16 +- .../RecordingChatClientFactory.cs | 4 +- tests/AgentCore.TestSupport/SkillFolder.cs | 6 +- 465 files changed, 7625 insertions(+), 7467 deletions(-) rename src/AgentCore.Application/Audit/{AuditCallObserver.cs => AuditConversationObserver.cs} (61%) delete mode 100644 src/AgentCore.Application/Calls/CallChannelContext.cs delete mode 100644 src/AgentCore.Application/Calls/CallRecord.cs delete mode 100644 src/AgentCore.Application/Calls/CallRepository.cs delete mode 100644 src/AgentCore.Application/Calls/CallStatus.cs delete mode 100644 src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs rename src/AgentCore.Application/Configuration/Schema/{CallProviderConfiguration.cs => ConversationProviderConfiguration.cs} (64%) rename src/AgentCore.Application/{Calls/ChatCallTitler.cs => Conversation/ChatConversationTitler.cs} (65%) rename src/AgentCore.Application/{Calls/CallChannel.cs => Conversation/ConversationChannel.cs} (87%) create mode 100644 src/AgentCore.Application/Conversation/ConversationChannelContext.cs rename src/AgentCore.Application/{Calls/CallClarificationState.cs => Conversation/ConversationClarificationState.cs} (68%) rename src/AgentCore.Application/{Calls/CallCursor.cs => Conversation/ConversationCursor.cs} (72%) rename src/AgentCore.Application/{Calls/CallInput.cs => Conversation/ConversationInput.cs} (88%) rename src/AgentCore.Application/{Calls/CallPage.cs => Conversation/ConversationPage.cs} (52%) create mode 100644 src/AgentCore.Application/Conversation/ConversationRecord.cs rename src/AgentCore.Application/{Calls/CallSessionState.cs => Conversation/ConversationSessionState.cs} (70%) rename src/AgentCore.Application/{Calls/CallSpeechPairing.cs => Conversation/ConversationSpeechPairing.cs} (66%) rename src/AgentCore.Application/{Calls/CallStateJson.cs => Conversation/ConversationStateJson.cs} (66%) create mode 100644 src/AgentCore.Application/Conversation/ConversationStatus.cs rename src/AgentCore.Application/{Calls/CallStoreFactory.cs => Conversation/ConversationStoreFactory.cs} (69%) create mode 100644 src/AgentCore.Application/Conversation/Conversations.cs create mode 100644 src/AgentCore.Application/Conversation/Memory/InMemoryConversationStore.cs create mode 100644 src/AgentCore.Application/Conversation/StoredConversation.cs rename src/AgentCore.Application/Diagnostics/{LoggingCallObserver.cs => LoggingConversationObserver.cs} (55%) rename src/AgentCore.Application/Diagnostics/{TelemetryCallObserver.cs => TelemetryConversationObserver.cs} (67%) delete mode 100644 src/AgentCore.Application/Ports/ICallChannelFactory.cs delete mode 100644 src/AgentCore.Application/Ports/ICallSessionFactory.cs delete mode 100644 src/AgentCore.Application/Ports/ICallSessions.cs delete mode 100644 src/AgentCore.Application/Ports/ICallTitler.cs rename src/AgentCore.Application/Ports/{ICallAdapter.cs => IConversationAdapter.cs} (81%) create mode 100644 src/AgentCore.Application/Ports/IConversationChannelFactory.cs rename src/AgentCore.Application/Ports/{ICallInputPort.cs => IConversationInputPort.cs} (73%) rename src/AgentCore.Application/Ports/{ICallObserver.cs => IConversationObserver.cs} (56%) rename src/AgentCore.Application/Ports/{ICallOutputPort.cs => IConversationOutputPort.cs} (84%) create mode 100644 src/AgentCore.Application/Ports/IConversationSessionFactory.cs rename src/AgentCore.Application/Ports/{ICallSessionRegistry.cs => IConversationSessionRegistry.cs} (84%) create mode 100644 src/AgentCore.Application/Ports/IConversationSessions.cs rename src/AgentCore.Application/Ports/{ICallStore.cs => IConversationStore.cs} (56%) rename src/AgentCore.Application/Ports/{ICallStoreAdapter.cs => IConversationStoreAdapter.cs} (63%) create mode 100644 src/AgentCore.Application/Ports/IConversationTitler.cs create mode 100644 src/AgentCore.Application/Ports/IConversations.cs delete mode 100644 src/AgentCore.Application/Runtime/CallEventKinds.cs rename src/AgentCore.Application/Runtime/{CallEvent.cs => ConversationEvent.cs} (75%) rename src/AgentCore.Application/Runtime/{CallEventChain.cs => ConversationEventChain.cs} (77%) rename src/AgentCore.Application/Runtime/{CallEventKind.cs => ConversationEventKind.cs} (76%) create mode 100644 src/AgentCore.Application/Runtime/ConversationEventKinds.cs rename src/AgentCore.Application/Runtime/{CallEventPayloadKeys.cs => ConversationEventPayloadKeys.cs} (66%) rename src/AgentCore.Application/Runtime/{CallObserverDispatcher.cs => ConversationObserverDispatcher.cs} (73%) rename src/AgentCore.Application/Runtime/{CallObservers.cs => ConversationObservers.cs} (76%) rename src/AgentCore.Application/Runtime/{CallSession.cs => ConversationSession.cs} (72%) rename src/AgentCore.Application/Runtime/{CallSession/CallInterruptionTracker.cs => ConversationSession/ConversationInterruptionTracker.cs} (94%) rename src/AgentCore.Application/Runtime/{CallSession/CallSessionLifetime.cs => ConversationSession/ConversationSessionLifetime.cs} (54%) rename src/AgentCore.Application/Runtime/{CallSession/CallSessionStateStore.cs => ConversationSession/ConversationSessionStateStore.cs} (80%) rename src/AgentCore.Application/Runtime/{CallSession/CallTranscriptLedger.cs => ConversationSession/ConversationTranscriptLedger.cs} (70%) rename src/AgentCore.Application/Runtime/{CallSession/CallTurn.cs => ConversationSession/ConversationTurn.cs} (84%) rename src/AgentCore.Application/Runtime/{CallSession/CallTurnCommit.cs => ConversationSession/ConversationTurnCommit.cs} (88%) rename src/AgentCore.Application/Runtime/{CallSession/CallTurnCompletion.cs => ConversationSession/ConversationTurnCompletion.cs} (89%) rename src/AgentCore.Application/Runtime/{CallSession/CallTurnRunner.cs => ConversationSession/ConversationTurnRunner.cs} (81%) rename src/AgentCore.Application/Runtime/{CallSession/CallTurnStream.cs => ConversationSession/ConversationTurnStream.cs} (95%) rename src/AgentCore.Application/Runtime/{CallSession/CallTurnWriters.cs => ConversationSession/ConversationTurnWriters.cs} (85%) rename src/AgentCore.Application/Runtime/{CallSession => ConversationSession}/ReplyOutcome.cs (100%) rename src/AgentCore.Application/Runtime/{CallSession => ConversationSession}/TranscriptEntry.cs (100%) rename src/AgentCore.Application/Runtime/{CallSessionFactory.cs => ConversationSessionFactory.cs} (73%) rename src/AgentCore.Application/Runtime/{CallTurnOrigin.cs => ConversationTurnOrigin.cs} (78%) rename src/AgentCore.Application/Runtime/{CallWorkspace.cs => ConversationWorkspace.cs} (60%) rename src/AgentCore.Application/Runtime/Harness/{CallFilesProvider.cs => ConversationFilesProvider.cs} (80%) rename src/AgentCore.Application/Runtime/Harness/{CallShellEnvironmentProvider.cs => ConversationShellEnvironmentProvider.cs} (69%) rename src/AgentCore.Application/Runtime/Harness/{CallShellOptions.cs => ConversationShellOptions.cs} (90%) rename src/AgentCore.Application/Runtime/Harness/{CallShellProvider.cs => ConversationShellProvider.cs} (69%) rename src/AgentCore.Application/Runtime/Harness/{CallShells.cs => ConversationShells.cs} (81%) rename src/AgentCore.Application/Sessions/Memory/{InMemoryCallSessions.cs => InMemoryConversationSessions.cs} (65%) rename src/AgentCore.Application/Transcript/{CallMessage.cs => ConversationMessage.cs} (66%) rename src/AgentCore.Application/Transcript/{CallMessageDraft.cs => ConversationMessageDraft.cs} (50%) rename src/AgentCore.Application/Transcript/{CallMessageIds.cs => ConversationMessageIds.cs} (85%) rename src/AgentCore.Application/Transcript/{CallTranscript.cs => ConversationTranscript.cs} (76%) delete mode 100644 src/AgentCore.AspNetCore/Call/.editorconfig delete mode 100644 src/AgentCore.AspNetCore/Call/CallSeams.cs delete mode 100644 src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs rename src/AgentCore.AspNetCore/{Call => Conversation}/ConnectionTaskObserver.cs (90%) rename src/AgentCore.AspNetCore/{Call/CallEndpointRouteBuilderExtensions.cs => Conversation/ConversationEndpointRouteBuilderExtensions.cs} (85%) rename src/AgentCore.AspNetCore/{Call/CallRouteLog.cs => Conversation/ConversationRouteLog.cs} (61%) create mode 100644 src/AgentCore.AspNetCore/Conversation/ConversationSeams.cs rename src/AgentCore.AspNetCore/{Call/CallTurnArbiter.cs => Conversation/ConversationTurnArbiter.cs} (84%) create mode 100644 src/AgentCore.AspNetCore/Conversation/IConversationTransportAdapter.cs rename src/AgentCore.AspNetCore/{Call => Conversation}/JsonWebSocketPump.cs (95%) rename src/AgentCore.AspNetCore/DependencyInjection/Startup/{CallSeamStartup.cs => ConversationSeamStartup.cs} (59%) rename src/AgentCore.AspNetCore/DependencyInjection/Startup/{CallSessionStartup.cs => ConversationSessionStartup.cs} (73%) rename src/AgentCore.AspNetCore/DependencyInjection/Startup/{CallStartup.cs => ConversationStartup.cs} (59%) rename src/AgentCore.AspNetCore/Sessions/{CallSessionSweeper.cs => ConversationSessionSweeper.cs} (83%) rename src/AgentCore.AspNetCore/Vendors/TelnyxRelay/{TelnyxRelayCallAdapter.cs => TelnyxRelayConversationAdapter.cs} (81%) rename src/AgentCore.AspNetCore/Vendors/TelnyxRelay/{TelnyxRelayCallChannelFactory.cs => TelnyxRelayConversationChannelFactory.cs} (68%) rename src/AgentCore.Domain/Audit/{CallEndReason.cs => ConversationEndReason.cs} (70%) rename src/AgentCore.Domain/Audit/{CallEndReasons.cs => ConversationEndReasons.cs} (58%) delete mode 100644 src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs create mode 100644 src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationRows.cs rename src/AgentCore.Infrastructure/{Calls/Postgres/PostgresCallStore.cs => Conversation/Postgres/PostgresConversationStore.cs} (69%) rename src/AgentCore.Infrastructure/{Calls/Postgres/PostgresCallStoreAdapter.cs => Conversation/Postgres/PostgresConversationStoreAdapter.cs} (65%) rename src/AgentCore.Infrastructure/{Calls/Postgres/PostgresCallStoreSql.cs => Conversation/Postgres/PostgresConversationStoreSql.cs} (56%) rename src/AgentCore.Infrastructure/{Calls/Postgres/PostgresCallVerification.cs => Conversation/Postgres/PostgresConversationVerification.cs} (67%) delete mode 100644 tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs create mode 100644 tests/AgentCore.Application.Tests/Audit/AuditConversationObserverTests.cs rename tests/AgentCore.Application.Tests/Audit/{CallSessionAuditTests.cs => ConversationSessionAuditTests.cs} (77%) rename tests/AgentCore.Application.Tests/Audit/{CallSessionModerationTests.cs => ConversationSessionModerationTests.cs} (87%) delete mode 100644 tests/AgentCore.Application.Tests/Calls/CallCursorTests.cs rename tests/AgentCore.Application.Tests/Configuration/{CallSchemaTests.cs => ConversationSchemaTests.cs} (78%) rename tests/AgentCore.Application.Tests/{Calls => Conversation}/.editorconfig (100%) rename tests/AgentCore.Application.Tests/{Calls/ChatCallTitlerTests.cs => Conversation/ChatConversationTitlerTests.cs} (59%) rename tests/AgentCore.Application.Tests/{Calls/CallChannelTests.cs => Conversation/ConversationChannelTests.cs} (76%) create mode 100644 tests/AgentCore.Application.Tests/Conversation/ConversationCursorTests.cs rename tests/AgentCore.Application.Tests/{Calls/CallSessionStateTests.cs => Conversation/ConversationSessionStateTests.cs} (72%) rename tests/AgentCore.Application.Tests/{Calls/CallSpeechPairingTests.cs => Conversation/ConversationSpeechPairingTests.cs} (64%) rename tests/AgentCore.Application.Tests/{Calls/CallStoreFactoryTests.cs => Conversation/ConversationStoreFactoryTests.cs} (63%) rename tests/AgentCore.Application.Tests/{Calls/CallRepositoryTests.cs => Conversation/ConversationsTests.cs} (50%) rename tests/AgentCore.Application.Tests/{Calls/DelegatingCallStoreTests.cs => Conversation/DelegatingConversationStoreTests.cs} (50%) rename tests/AgentCore.Application.Tests/{Calls/InMemoryCallStoreTests.cs => Conversation/InMemoryConversationStoreTests.cs} (64%) rename tests/AgentCore.Application.Tests/{Calls/InMemoryCallStoreTranscriptTests.cs => Conversation/InMemoryConversationStoreTranscriptTests.cs} (56%) rename tests/AgentCore.Application.Tests/{Calls/Memory/InMemoryCallStoreAppendTests.cs => Conversation/Memory/InMemoryConversationStoreAppendTests.cs} (76%) rename tests/AgentCore.Application.Tests/Diagnostics/{LoggingCallObserverTests.cs => LoggingConversationObserverTests.cs} (61%) rename tests/AgentCore.Application.Tests/Diagnostics/{TelemetryCallObserverTests.cs => TelemetryConversationObserverTests.cs} (67%) delete mode 100644 tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs create mode 100644 tests/AgentCore.Application.Tests/Fakes/RecordingConversationStore.cs delete mode 100644 tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs create mode 100644 tests/AgentCore.Application.Tests/Fakes/ThrowingConversationStore.cs rename tests/AgentCore.Application.Tests/Policy/{CallPolicyGoldenSet.cs => ConversationPolicyGoldenSet.cs} (79%) rename tests/AgentCore.Application.Tests/Policy/{GoldenCallReplayTests.cs => GoldenConversationReplayTests.cs} (52%) delete mode 100644 tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/ConversationEventKindsTests.cs rename tests/AgentCore.Application.Tests/Runtime/{CallObserverDispatcherTests.cs => ConversationObserverDispatcherTests.cs} (61%) rename tests/AgentCore.Application.Tests/Runtime/{CallObserversTests.cs => ConversationObserversTests.cs} (56%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionApprovalTests.cs => ConversationSessionApprovalTests.cs} (94%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionEditTests.cs => ConversationSessionEditTests.cs} (73%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionFactoryModelFacingTests.cs => ConversationSessionFactoryModelFacingTests.cs} (88%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionGraphReplyTests.cs => ConversationSessionGraphReplyTests.cs} (87%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionInterruptionTests.cs => ConversationSessionInterruptionTests.cs} (92%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionProbeTests.cs => ConversationSessionProbeTests.cs} (93%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionTests.cs => ConversationSessionTests.cs} (92%) rename tests/AgentCore.Application.Tests/Runtime/{CallSessionWorkspaceTests.cs => ConversationSessionWorkspaceTests.cs} (79%) rename tests/AgentCore.Application.Tests/Runtime/{CallWorkspaceTests.cs => ConversationWorkspaceTests.cs} (61%) rename tests/AgentCore.Application.Tests/Runtime/Harness/{CallFilesProviderTests.cs => ConversationFilesProviderTests.cs} (85%) rename tests/AgentCore.Application.Tests/Runtime/Harness/{CallSessionBackgroundTests.cs => ConversationSessionBackgroundTests.cs} (87%) rename tests/AgentCore.Application.Tests/Runtime/Harness/{CallSessionGraphStateTests.cs => ConversationSessionGraphStateTests.cs} (79%) rename tests/AgentCore.Application.Tests/Runtime/Harness/{CallSessionProviderStateTests.cs => ConversationSessionProviderStateTests.cs} (79%) rename tests/AgentCore.Application.Tests/Runtime/Harness/{CallSessionShellTests.cs => ConversationSessionShellTests.cs} (80%) rename tests/AgentCore.Application.Tests/Runtime/Harness/{CallShellsTests.cs => ConversationShellsTests.cs} (71%) rename tests/AgentCore.Application.Tests/Runtime/{KnowledgeScopeThroughCallSessionTests.cs => KnowledgeScopeThroughConversationSessionTests.cs} (86%) rename tests/AgentCore.Application.Tests/Sessions/{CallSessionsTests.cs => ConversationSessionsTests.cs} (62%) delete mode 100644 tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs rename tests/AgentCore.Application.Tests/Transcript/{CallSessionCallRowTests.cs => ConversationSessionConversationRowTests.cs} (65%) rename tests/AgentCore.Application.Tests/Transcript/{CallSessionGraphTranscriptTests.cs => ConversationSessionGraphTranscriptTests.cs} (89%) rename tests/AgentCore.Application.Tests/Transcript/{CallSessionOutsideAppendTests.cs => ConversationSessionOutsideAppendTests.cs} (79%) rename tests/AgentCore.Application.Tests/Transcript/{CallSessionResumeTestSupport.cs => ConversationSessionResumeTestSupport.cs} (77%) create mode 100644 tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTests.cs rename tests/AgentCore.Application.Tests/Transcript/{CallSessionStateRestoreTests.cs => ConversationSessionStateRestoreTests.cs} (69%) rename tests/AgentCore.Application.Tests/Transcript/{CallSessionStoreFailureTests.cs => ConversationSessionStoreFailureTests.cs} (74%) rename tests/AgentCore.Application.Tests/Transcript/{CallSessionTranscriptTests.cs => ConversationSessionTranscriptTests.cs} (89%) rename tests/AgentCore.Application.Tests/Transcript/{CallTranscriptEditTests.cs => ConversationTranscriptEditTests.cs} (71%) rename tests/AgentCore.Application.Tests/Transcript/{CallTranscriptTests.cs => ConversationTranscriptTests.cs} (83%) rename tests/AgentCore.AspNetCore.Tests/{Call/CallChannelShapeTests.cs => Conversation/ConversationChannelShapeTests.cs} (59%) rename tests/AgentCore.AspNetCore.Tests/{Call/CallInputPortTests.cs => Conversation/ConversationInputPortTests.cs} (61%) rename tests/AgentCore.AspNetCore.Tests/{Call/CallOptionsFromDocumentTests.cs => Conversation/ConversationOptionsFromDocumentTests.cs} (70%) rename tests/AgentCore.AspNetCore.Tests/{Call/CallRegistrationTests.cs => Conversation/ConversationRegistrationTests.cs} (74%) rename tests/AgentCore.AspNetCore.Tests/{Call/CallRouteSelectionTests.cs => Conversation/ConversationRouteSelectionTests.cs} (70%) rename tests/AgentCore.AspNetCore.Tests/{Call/CallTurnArbiterTests.cs => Conversation/ConversationTurnArbiterTests.cs} (89%) rename tests/AgentCore.AspNetCore.Tests/{Call/TelnyxRelayThroughTheCallSeamTests.cs => Conversation/TelnyxRelayThroughTheConversationSeamTests.cs} (65%) rename tests/AgentCore.AspNetCore.Tests/Fakes/{FakeCallInput.cs => FakeConversationInput.cs} (75%) rename tests/AgentCore.AspNetCore.Tests/Fakes/{FakeCallOutput.cs => FakeConversationOutput.cs} (95%) rename tests/AgentCore.AspNetCore.Tests/Sessions/{CallSessionsRelayTests.cs => ConversationSessionsRelayTests.cs} (56%) rename tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/{TelnyxRelayCallEndTests.cs => TelnyxRelayConversationEndTests.cs} (68%) rename tests/AgentCore.Infrastructure.Tests/{Calls => Conversation}/Postgres/ContinuationStoreTests.cs (80%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/CallThreadSchemaTests.cs => Conversation/Postgres/ConversationThreadSchemaTests.cs} (51%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallListTests.cs => Conversation/Postgres/PostgresConversationListTests.cs} (59%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallPrincipalTests.cs => Conversation/Postgres/PostgresConversationPrincipalTests.cs} (73%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallStoreAppendTests.cs => Conversation/Postgres/PostgresConversationStoreAppendTests.cs} (77%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallStoreSweepTests.cs => Conversation/Postgres/PostgresConversationStoreSweepTests.cs} (58%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallStoreTests.cs => Conversation/Postgres/PostgresConversationStoreTests.cs} (67%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallStoreTruncateTests.cs => Conversation/Postgres/PostgresConversationStoreTruncateTests.cs} (65%) rename tests/AgentCore.Infrastructure.Tests/{Calls/Postgres/PostgresCallStoreWordsTests.cs => Conversation/Postgres/PostgresConversationStoreWordsTests.cs} (79%) delete mode 100644 tests/AgentCore.TestSupport/DelegatingCallStore.cs create mode 100644 tests/AgentCore.TestSupport/DelegatingConversationStore.cs rename tests/AgentCore.TestSupport/{ParkingCallStore.cs => ParkingConversationStore.cs} (72%) diff --git a/README.md b/README.md index d27856e3..b8a9509b 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ policy: providers: llm: - { kind: openai, model: gpt-5.6-luna, as: reply } - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -54,8 +54,8 @@ app.MapAgentCoreHost(); app.Run(); ``` -`AddAgentCoreHost` loads the document (`config/example.yaml` unless `AgentCore__ConfigurationPath` names another) and binds every vendor seam. `MapAgentCoreHost` serves the health check, the OpenAI-compatible Responses endpoint, and the call socket. -Every entry under `entries:` answers on `POST /v1/{entry}/responses` and on the call socket at `/v1/{entry}/call`. +`AddAgentCoreHost` loads the document (`config/example.yaml` unless `AgentCore__ConfigurationPath` names another) and binds every vendor seam. `MapAgentCoreHost` serves the health check, the OpenAI-compatible Responses endpoint, and the conversation socket. +Every entry under `entries:` answers on `POST /v1/{entry}/responses` and on the conversation socket at `/v1/{entry}/call`. An OpenAI SDK reaches one entry through its base URL alone: `base_url = https://host/v1/phone`. A document it cannot find is a startup failure, never a silent default. diff --git a/config/example.yaml b/config/example.yaml index 89fc5424..365c85ab 100644 --- a/config/example.yaml +++ b/config/example.yaml @@ -21,7 +21,7 @@ # 5. tools what an agent may call # 6. agents models, prompts, knowledge, compaction # 7. entries what a caller reaches: a stage machine or one agent -# 8. providers adapters: llm, call, speech, telephony, moderation, embeddings, knowledge, +# 8. providers adapters: llm, conversation, speech, telephony, moderation, embeddings, knowledge, # telemetry # 9. evaluation the judge that scores finished turns @@ -36,7 +36,7 @@ apiVersion: agentcore/v1 # What the caller hears when a turn fails. Two failures reach it: a run that returns no text # after 40 tool rounds, and a tool that fails four times in a row. Every entry speaks this line. # An entry may override it with its own fallbackReply: (see 7. entries). -# Optional. Default: the value shown. Blank is a load error, because blank is silence on a call. +# Optional. Default: the value shown. Blank is a load error, because blank is silence on a conversation. fallbackReply: "I am sorry. I could not finish that. Please say it again." # What the caller hears when moderation flags their input and the agent refuses the turn. @@ -56,7 +56,7 @@ refusalReply: "I am sorry. I cannot help with that request." # counter it adds one whenever its increment: rule is true # # Three slots are reserved, always present, and read-only: stage, turnIndex, and -# callDurationSeconds. A rule may read them. Do not declare them here. +# conversationDurationSeconds. A rule may read them. Do not declare them here. state: # writer: extractor. Nullable on the wire. A null leaves the slot at its previous value. callerAskedForHuman: { type: boolean, default: false, writer: extractor } @@ -193,9 +193,9 @@ tools: # never a boot failure. - { id: search, kind: builtin, uses: web.search } - # kind: builtin, a plain function. The model calls it when a file in the call's workspace is a - # deliverable: the file is copied into providers.blobs (see 8. providers), owned by the call, - # and the person gets a link. Files not published are lost when the call ends. Needs + # kind: builtin, a plain function. The model calls it when a file in the conversation's workspace is a + # deliverable: the file is copied into providers.blobs (see 8. providers), owned by the conversation, + # and the person gets a link. Files not published are lost when the conversation ends. Needs # providers.blobs and options.UseWorkspace(...) on the host; missing either fails the boot. - { id: publish, kind: builtin, uses: file.publish } @@ -270,8 +270,8 @@ agents: knowledge: { mode: prefetch, limit: 5, citations: false } # Bounds the conversation an agent carries. Every strategy is deterministic: the same messages - # give the same result. There is no summarization on purpose. A resumed call rebuilds from - # the replayed words, and a model-written summary would give one call two histories. + # give the same result. There is no summarization on purpose. A resumed conversation rebuilds from + # the replayed words, and a model-written summary would give one conversation two histories. # strategy truncate | sliding_window | tool_result | context_window # tool_result folds old function-tool groups into one short line each. # context_window folds first, then truncates whole groups. @@ -378,14 +378,14 @@ providers: - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false } # Three voice planes. They are not duplicates. - # call the media pipe. It carries the audio and owns the route /v1/{entry}/call. + # conversation the media pipe. It carries the audio and owns the route /v1/{entry}/call. # speech recognition (stt) and synthesis (tts), one role at a time. # telephony call control: dial, transfer, hang up. It must outlive any one media leg, # because a warm transfer creates a second leg. - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: - stt: { kind: telnyx-relay } # bundled with the relay, so it matches call - tts: { kind: telnyx-relay } # bundled with the relay, so it matches call + stt: { kind: telnyx-relay } # bundled with the relay, so it matches conversation + tts: { kind: telnyx-relay } # bundled with the relay, so it matches conversation telephony: { kind: telnyx } # Reads what the CALLER said, before the model runs. A flagged turn never reaches the model and @@ -399,7 +399,7 @@ providers: # model's own width. embeddings: { kind: openai, model: text-embedding-3-small } - # Where a file the model publishes (file.publish) is kept after the call, owned by the call id. + # Where a file the model publishes (file.publish) is kept after the conversation, owned by the conversation id. # Any S3-compatible store. Reads the s3-access-key and s3-secret-key secrets. blobs: { kind: s3, endpoint: https://s3.us-east-005.backblazeb2.com, bucket: agentcore-files, region: us-east-005 } diff --git a/src/AgentCore.Application/Audit/AuditCallObserver.cs b/src/AgentCore.Application/Audit/AuditConversationObserver.cs similarity index 61% rename from src/AgentCore.Application/Audit/AuditCallObserver.cs rename to src/AgentCore.Application/Audit/AuditConversationObserver.cs index 24ab618c..89cc0bff 100644 --- a/src/AgentCore.Application/Audit/AuditCallObserver.cs +++ b/src/AgentCore.Application/Audit/AuditConversationObserver.cs @@ -7,14 +7,14 @@ namespace AgentCore.Application.Audit; /// /// Turns the durable facts of a call into the append-only chain of D23. /// -internal sealed class AuditCallObserver : ICallObserver +internal sealed class AuditConversationObserver : IConversationObserver { private readonly IAuditSinkPort _sink; /// Creates the observer that writes the chain. /// Where the rows go. /// is . - public AuditCallObserver(IAuditSinkPort sink) + public AuditConversationObserver(IAuditSinkPort sink) { ArgumentNullException.ThrowIfNull(sink); @@ -22,37 +22,37 @@ public AuditCallObserver(IAuditSinkPort sink) } /// - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { - ArgumentNullException.ThrowIfNull(callEvent); + ArgumentNullException.ThrowIfNull(conversationEvent); // A diagnostic-only fact took no identity, so there is no row to write and nothing to report. - if (callEvent.EventId is not { } eventId) + if (conversationEvent.EventId is not { } eventId) { return ValueTask.CompletedTask; } // The two enums are not interchangeable, and a value outside the closed set is dropped rather // than thrown over: the turn loop pairs an identity with a stored kind, so this is unreachable - // for any event the session raises, and audit is a record of the call and never a part of it. - if (!CallEventKinds.TryGetAuditKind(callEvent.Kind, out AuditEventKind kind)) + // for any event the session raises, and audit is a record of the conversation and never a part of it. + if (!ConversationEventKinds.TryGetAuditKind(conversationEvent.Kind, out AuditEventKind kind)) { return ValueTask.CompletedTask; } AuditEvent auditEvent = new() { - CallId = callEvent.CallId, + ConversationId = conversationEvent.ConversationId, EventId = eventId, Kind = kind, - OccurredAt = callEvent.OccurredAt, - TurnIndex = callEvent.TurnIndex, - AmendsEventId = callEvent.AmendsEventId, - Payload = callEvent.Payload, + OccurredAt = conversationEvent.OccurredAt, + TurnIndex = conversationEvent.TurnIndex, + AmendsEventId = conversationEvent.AmendsEventId, + Payload = conversationEvent.Payload, }; // The token of the run belongs to the dispatcher, which passes CancellationToken.None: the - // enqueue belongs to the record of the call, not to a turn the caller may have cancelled. + // enqueue belongs to the record of the conversation, not to a turn the caller may have cancelled. return _sink.AppendAsync(auditEvent, cancellationToken); } } diff --git a/src/AgentCore.Application/Audit/AuditSinkFactory.cs b/src/AgentCore.Application/Audit/AuditSinkFactory.cs index 303a5244..553bf8a1 100644 --- a/src/AgentCore.Application/Audit/AuditSinkFactory.cs +++ b/src/AgentCore.Application/Audit/AuditSinkFactory.cs @@ -14,7 +14,7 @@ public static class AuditSinkFactory /// The built-in kind, and the one a document that names no provider gets. public const string MemoryKind = "memory"; - /// What this seam calls itself, so the shared selector writes its failures. + /// What this seam conversations itself, so the shared selector writes its failures. private static readonly VendorSeam Seam = new("providers.audit", "/providers/audit/kind", "options.UseAuditSinks(...)", "sinks"); diff --git a/src/AgentCore.Application/Audit/Memory/InMemoryAuditSink.cs b/src/AgentCore.Application/Audit/Memory/InMemoryAuditSink.cs index a2e4bf69..b14b2def 100644 --- a/src/AgentCore.Application/Audit/Memory/InMemoryAuditSink.cs +++ b/src/AgentCore.Application/Audit/Memory/InMemoryAuditSink.cs @@ -25,18 +25,18 @@ public IReadOnlyList Events } /// - /// Reads back the events of one call, oldest first. + /// Reads back the events of one conversation, oldest first. /// - /// The id of the call. - /// The events of that call, in the order they arrived. - /// is . - public IReadOnlyList EventsOf(string callId) + /// The id of the conversation. + /// The events of that conversation, in the order they arrived. + /// is . + public IReadOnlyList EventsOf(string conversationId) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); lock (_gate) { - return [.. _events.Where(item => string.Equals(item.CallId, callId, StringComparison.Ordinal))]; + return [.. _events.Where(item => string.Equals(item.ConversationId, conversationId, StringComparison.Ordinal))]; } } diff --git a/src/AgentCore.Application/Audit/QueuedAuditSink.cs b/src/AgentCore.Application/Audit/QueuedAuditSink.cs index ad2d0738..ea5c8cc2 100644 --- a/src/AgentCore.Application/Audit/QueuedAuditSink.cs +++ b/src/AgentCore.Application/Audit/QueuedAuditSink.cs @@ -15,7 +15,7 @@ public sealed class QueuedAuditSink : IAuditSinkPort, IAsyncDisposable, IDisposa /// The number of events the queue holds before it starts dropping. public const int DefaultCapacity = 10_000; - /// The most events the writer hands the store in one call. + /// The most events the writer hands the store in one conversation. public const int DefaultBatchSize = 100; /// How long waits for the drain before it gives up. @@ -199,7 +199,7 @@ private async Task AppendBatchAsync(List batch) { await _inner.AppendManyAsync([.. batch], _stopping.Token).ConfigureAwait(false); } -#pragma warning disable CA1031 // The store is a record of the call and never a part of it. +#pragma warning disable CA1031 // The store is a record of the conversation and never a part of it. catch (Exception exception) #pragma warning restore CA1031 { @@ -219,9 +219,9 @@ private void Report(AuditEvent auditEvent) { try { - Log.AuditQueueFull(_logger, auditEvent.CallId, auditEvent.EventId); + Log.AuditQueueFull(_logger, auditEvent.ConversationId, auditEvent.EventId); } -#pragma warning disable CA1031 // A logger that refuses the report is still not a part of the call. +#pragma warning disable CA1031 // A logger that refuses the report is still not a part of the conversation. catch (Exception) #pragma warning restore CA1031 { @@ -236,15 +236,15 @@ private void Report(List batch, Exception exception) { try { - // One line for the batch and not one for each event. The store refused the call, so the - // fault is one fault, and the first event names the call an operator goes looking at. + // One line for the batch and not one for each event. The store refused the conversation, so the + // fault is one fault, and the first event names the conversation an operator goes looking at. Log.AuditAppendFailed( _logger, - batch[0].CallId, + batch[0].ConversationId, AuditEventKinds.ToToken(batch[0].Kind), exception); } -#pragma warning disable CA1031 // A logger that refuses the report is still not a part of the call. +#pragma warning disable CA1031 // A logger that refuses the report is still not a part of the conversation. catch (Exception) #pragma warning restore CA1031 { diff --git a/src/AgentCore.Application/Blobs/BlobStoreFactory.cs b/src/AgentCore.Application/Blobs/BlobStoreFactory.cs index 8d870b4e..a8dc9283 100644 --- a/src/AgentCore.Application/Blobs/BlobStoreFactory.cs +++ b/src/AgentCore.Application/Blobs/BlobStoreFactory.cs @@ -10,7 +10,7 @@ namespace AgentCore.Application.Blobs; /// public static class BlobStoreFactory { - /// What this seam calls itself, so the shared selector writes its failures. + /// What this seam conversations itself, so the shared selector writes its failures. private static readonly VendorSeam Seam = new("providers.blobs", "/providers/blobs/kind", "options.UseBlobStores(...)", "stores"); diff --git a/src/AgentCore.Application/Blobs/BlobWrite.cs b/src/AgentCore.Application/Blobs/BlobWrite.cs index 3f3436a8..ca8f03d9 100644 --- a/src/AgentCore.Application/Blobs/BlobWrite.cs +++ b/src/AgentCore.Application/Blobs/BlobWrite.cs @@ -1,7 +1,7 @@ namespace AgentCore.Application.Blobs; /// One blob to store. -/// Who writes it. The call id today. +/// Who writes it. The conversation id today. /// The name it is stored under. Must pass . /// The IANA media type, such as image/png. /// The bytes. Read once, from its current position. The caller disposes it. diff --git a/src/AgentCore.Application/Blobs/FileLink.cs b/src/AgentCore.Application/Blobs/FileLink.cs index 54219318..519e529e 100644 --- a/src/AgentCore.Application/Blobs/FileLink.cs +++ b/src/AgentCore.Application/Blobs/FileLink.cs @@ -1,6 +1,6 @@ namespace AgentCore.Application.Blobs; -/// One file a call's sandbox wrote and the store kept. +/// One file a conversation's sandbox wrote and the store kept. /// The file's facts. /// Where a browser fetches it from, or when the store has no web door. public sealed record FileLink(BlobRef Blob, Uri? Url); diff --git a/src/AgentCore.Application/Calls/CallChannelContext.cs b/src/AgentCore.Application/Calls/CallChannelContext.cs deleted file mode 100644 index e863df44..00000000 --- a/src/AgentCore.Application/Calls/CallChannelContext.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AgentCore.Application.Calls; - -/// What one call needs to open its channel. -/// The AgentCore call id, which the channel must not invent for itself. -/// Per-call values the host attached, or . -/// -/// This carries no vendor field and no wire frame, so D8 holds: a factory learns what the call is -/// without the core learning what the vendor is. -/// -public sealed record CallChannelContext(string CallId, IReadOnlyDictionary? CustomParameters); diff --git a/src/AgentCore.Application/Calls/CallRecord.cs b/src/AgentCore.Application/Calls/CallRecord.cs deleted file mode 100644 index 9065706e..00000000 --- a/src/AgentCore.Application/Calls/CallRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Text.Json; - -namespace AgentCore.Application.Calls; - -/// One call, apart from its words. It is one row of store 0. -/// The call this describes. It is the join to stores 1 and 3. -/// What to show in a list, or until one is made. -/// Whether the call is still listed as usual. -/// A consumer's own id for the call, or . -/// A consumer's own fields, or . -/// When the call row was made. UTC. -/// -/// When store 1 last wrote a word of this call, or when it holds none. UTC. -/// Derived at read time; store 0 keeps no such column. -/// -/// -/// What the session of this call held, or for a call that has run no turn -/// under a build that writes it. Read by GetAsync and CreateAsync only: a listing does -/// not need it and does not pay for it. -/// -/// -/// The ordinal the call's next appended row takes. Read by GetAsync and CreateAsync -/// only, on the same terms as : a listing leaves it at its default 0 rather -/// than paying to read it. -/// -public sealed record CallRecord( - string CallId, - string? Title, - CallStatus Status, - string? ExternalId, - JsonElement? Custom, - DateTimeOffset CreatedAt, - DateTimeOffset? LastMessageAt, - CallSessionState? State = null, - int NextOrdinal = 0); diff --git a/src/AgentCore.Application/Calls/CallRepository.cs b/src/AgentCore.Application/Calls/CallRepository.cs deleted file mode 100644 index b73accf2..00000000 --- a/src/AgentCore.Application/Calls/CallRepository.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Text.Json; -using AgentCore.Application.Blobs; -using AgentCore.Application.Ports; -using AgentCore.Application.Transcript; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Calls; - -/// -/// Everything a host or a consumer does with a stored call: its row, its words, and the files it -/// published. The one door; the stores behind it are adapters nobody else needs to name. -/// -public sealed class CallRepository : ICallStore -{ - private readonly ICallStore _calls; - - private readonly IBlobStore? _blobs; - - /// Makes the repository over the stores the document opened. - /// The store the rows and words live in. - /// The store the published files live in, or when the document names none. - public CallRepository(ICallStore calls, IBlobStore? blobs) - { - ArgumentNullException.ThrowIfNull(calls); - - _calls = calls; - _blobs = blobs; - } - - /// Whether the document named a blob store, so a call can have files at all. - public bool KeepsFiles => _blobs is not null; - - /// The adapter the rows live in. For a host checking which vendor it opened; go through the repository for everything else. - public ICallStore Store => _calls; - - /// Links every published file the messages carry and the store kept, each name once, in first-seen order. - /// The call that owns the files. - /// The messages to read the references off: the stored transcript, or one turn's updates. - /// Cancels the signing. - /// One link per kept file. - public async Task> LinkFilesAsync( - string callId, - IEnumerable messages, - CancellationToken cancellationToken = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(callId); - ArgumentNullException.ThrowIfNull(messages); - - if (_blobs is null) - { - return []; - } - - List kept = []; - - foreach (var file in messages.SelectMany(message => message.Contents).OfType()) - { - if (!file.Kept || !BlobName.IsSafe(file.Name)) - { - continue; - } - - BlobRef blob = new(callId, file.Name, file.MediaType, file.Length); - var at = kept.FindIndex(known => string.Equals(known.Name, blob.Name, StringComparison.Ordinal)); - - if (at >= 0) - { - kept[at] = blob; - } - else - { - kept.Add(blob); - } - } - - List links = []; - - foreach (var blob in kept) - { - var url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); - links.Add(new FileLink(blob, url)); - } - - return links; - } - - /// - public async ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default) - { - if (_blobs is not null) - { - await _blobs.DeleteByOwnerAsync(callId, cancellationToken).ConfigureAwait(false); - } - - await _calls.DeleteAsync(callId, cancellationToken).ConfigureAwait(false); - } - - /// - public ValueTask CreateAsync(string callId, CancellationToken cancellationToken = default) - => _calls.CreateAsync(callId, cancellationToken); - - /// - public ValueTask GetAsync(string callId, CancellationToken cancellationToken = default) - => _calls.GetAsync(callId, cancellationToken); - - /// - public ValueTask ListAsync( - string principalKey, - string? after, - int limit, - CallStatus? status = null, - CancellationToken cancellationToken = default) - => _calls.ListAsync(principalKey, after, limit, status, cancellationToken); - - /// - public ValueTask RenameAsync(string callId, string title, CancellationToken cancellationToken = default) - => _calls.RenameAsync(callId, title, cancellationToken); - - /// - public ValueTask SetStatusAsync(string callId, CallStatus status, CancellationToken cancellationToken = default) - => _calls.SetStatusAsync(callId, status, cancellationToken); - - /// - public ValueTask SetCustomAsync(string callId, JsonElement? custom, CancellationToken cancellationToken = default) - => _calls.SetCustomAsync(callId, custom, cancellationToken); - - /// - public ValueTask SetExternalIdAsync(string callId, string? externalId, CancellationToken cancellationToken = default) - => _calls.SetExternalIdAsync(callId, externalId, cancellationToken); - - /// - public ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - => _calls.AppendAsync(callId, messages, state, cancellationToken); - - /// - public ValueTask AppendMessageAsync(string callId, ChatMessage message, CancellationToken cancellationToken = default) - => _calls.AppendMessageAsync(callId, message, cancellationToken); - - /// - public ValueTask RewriteAsync(string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) - => _calls.RewriteAsync(callId, messageId, content, cancellationToken); - - /// - public ValueTask> ReadAsync(string callId, CancellationToken cancellationToken = default) - => _calls.ReadAsync(callId, cancellationToken); - - /// - public ValueTask TruncateAsync(string callId, int fromOrdinal, CancellationToken cancellationToken = default) - => _calls.TruncateAsync(callId, fromOrdinal, cancellationToken); - - /// - public ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) - => _calls.EraseAsync(callId, cancellationToken); - - /// - public ValueTask SweepAsync(TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) - => _calls.SweepAsync(retention, batchSize, cancellationToken); - - /// - public ValueTask AttachPrincipalAsync(string callId, string principalKey, string role, CancellationToken cancellationToken = default) - => _calls.AttachPrincipalAsync(callId, principalKey, role, cancellationToken); - - /// - public ValueTask DetachPrincipalAsync(string callId, string principalKey, CancellationToken cancellationToken = default) - => _calls.DetachPrincipalAsync(callId, principalKey, cancellationToken); - - /// - public ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) - => _calls.SaveContinuationAsync(continuationId, envelope, cancellationToken); - - /// - public ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default) - => _calls.GetContinuationAsync(continuationId, cancellationToken); - - /// - public ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default) - => _calls.DeleteContinuationAsync(continuationId, cancellationToken); -} diff --git a/src/AgentCore.Application/Calls/CallStatus.cs b/src/AgentCore.Application/Calls/CallStatus.cs deleted file mode 100644 index 33c99ec6..00000000 --- a/src/AgentCore.Application/Calls/CallStatus.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace AgentCore.Application.Calls; - -/// Whether a call still belongs in a caller's list. -public enum CallStatus -{ - /// Listed as usual. - Regular, - - /// Kept, but out of the way. - Archived, -} diff --git a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs deleted file mode 100644 index 7590d1f2..00000000 --- a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs +++ /dev/null @@ -1,425 +0,0 @@ -using System.Text.Json; -using AgentCore.Application.Ports; -using AgentCore.Application.Transcript; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Calls.Memory; - -/// The store backing that keeps every row in this process: a call, and its words. -public sealed class InMemoryCallStore : ICallStore -{ - private readonly Lock _lock = new(); - - private readonly Dictionary _calls = []; - - private readonly Dictionary<(string CallId, int Ordinal), CallMessage> _rows = []; - - /// The resume blob of each call, beside the row rather than on it. - private readonly Dictionary _state = []; - - /// The next free ordinal of each call. Never rewound, even when its words are. - private readonly Dictionary _nextOrdinal = []; - - private readonly HashSet<(string CallId, string PrincipalKey)> _claims = []; - - /// One serialized agent session per continuation id, beside the calls. - private readonly Dictionary _continuations = []; - - private readonly TimeProvider _time; - - /// Creates the store. - /// Where created_at comes from, or for the system clock. - public InMemoryCallStore(TimeProvider? timeProvider = null) => _time = timeProvider ?? TimeProvider.System; - - /// - public ValueTask CreateAsync(string callId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_lock) - { - if (!_calls.TryGetValue(callId, out var existing)) - { - var now = _time.GetUtcNow(); - existing = new CallRecord(callId, null, CallStatus.Regular, null, null, now, null); - _calls[callId] = existing; - } - - return ValueTask.FromResult(existing with - { - State = _state.GetValueOrDefault(callId), - NextOrdinal = _nextOrdinal.GetValueOrDefault(callId), - }); - } - } - - /// - public ValueTask GetAsync(string callId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_lock) - { - var call = _calls.GetValueOrDefault(callId); - - return ValueTask.FromResult(call is null - ? null - : call with - { - State = _state.GetValueOrDefault(callId), - NextOrdinal = _nextOrdinal.GetValueOrDefault(callId), - }); - } - } - - /// - public ValueTask ListAsync( - string principalKey, - string? after, - int limit, - CallStatus? status = null, - CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(principalKey); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limit); - - var hasCursor = CallCursor.TryDecode(after, out var sortAt, out var cursorId); - - lock (_lock) - { - var ordered = _claims - .Where(claim => claim.PrincipalKey == principalKey) - .Select(claim => _calls.GetValueOrDefault(claim.CallId)) - .OfType() - .Where(call => status is null || call.Status == status) - .Where(call => !hasCursor - || SortValue(call) < sortAt - || (SortValue(call) == sortAt - && string.CompareOrdinal(call.CallId, cursorId) < 0)) - .OrderByDescending(SortValue) - .ThenByDescending(call => call.CallId, StringComparer.Ordinal) - .Take(limit) - .ToList(); - - var next = ordered.Count == limit - ? CallCursor.Encode(SortValue(ordered[^1]), ordered[^1].CallId) - : null; - - return ValueTask.FromResult(new CallPage(ordered, next)); - } - } - - /// - public ValueTask RenameAsync(string callId, string title, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - ArgumentNullException.ThrowIfNull(title); - - return Amend(callId, call => call with { Title = title }); - } - - /// - public ValueTask SetStatusAsync(string callId, CallStatus status, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - return Amend(callId, call => call with { Status = status }); - } - - /// - public ValueTask SetCustomAsync( - string callId, JsonElement? custom, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - return Amend(callId, call => call with { Custom = custom?.Clone() }); - } - - /// - public ValueTask SetExternalIdAsync( - string callId, string? externalId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - return Amend(callId, call => call with { ExternalId = externalId }); - } - - /// - public ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - _calls.Remove(callId); - - _claims.RemoveWhere(claim => claim.CallId == callId); - - _state.Remove(callId); - - _nextOrdinal.Remove(callId); - - _continuations.Remove(callId); - - RemoveWords(callId); - - return default; - } - - /// - public ValueTask SweepAsync( - TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) - { - ArgumentOutOfRangeException.ThrowIfLessThan(retention, TimeSpan.Zero); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(batchSize); - - lock (_lock) - { - var cutoff = _time.GetUtcNow() - retention; - - // SortValue is the clock ListAsync ranks by, so a call is swept exactly when it has - // fallen off the end of the list. - // - // batchSize is read for its guard and then ignored. It exists to keep one transaction - // short in a durable backing, and this store has no transaction; honouring it here would - // only make the caller loop for the same answer. - var going = _calls.Values - .Where(call => SortValue(call) < cutoff) - .Select(call => call.CallId) - .ToList(); - - foreach (var callId in going) - { - _calls.Remove(callId); - - _claims.RemoveWhere(claim => claim.CallId == callId); - - _state.Remove(callId); - - _nextOrdinal.Remove(callId); - - _continuations.Remove(callId); - - RemoveWords(callId); - } - - return ValueTask.FromResult(going.Count); - } - } - - /// - public ValueTask AttachPrincipalAsync( - string callId, string principalKey, string role, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - ArgumentNullException.ThrowIfNull(principalKey); - ArgumentNullException.ThrowIfNull(role); - - lock (_lock) - { - _claims.Add((callId, principalKey)); - } - - return default; - } - - /// - public ValueTask DetachPrincipalAsync( - string callId, string principalKey, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - ArgumentNullException.ThrowIfNull(principalKey); - - lock (_lock) - { - _claims.Remove((callId, principalKey)); - } - - return default; - } - - /// - public ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - ArgumentNullException.ThrowIfNull(messages); - - if (messages.Count == 0) - { - return ValueTask.FromResult>([]); - } - - lock (_lock) - { - if (!_calls.TryGetValue(callId, out var call)) - { - throw new InvalidOperationException($"Store 0 holds no call '{callId}' to append words to."); - } - - var fallbackTurnIndex = _state.GetValueOrDefault(callId)?.NextTurnIndex ?? 0; - var first = _nextOrdinal.GetValueOrDefault(callId); - - var rows = new List(messages.Count); - for (var index = 0; index < messages.Count; index++) - { - var draft = messages[index]; - CallMessage row = new( - callId, first + index, draft.TurnIndex ?? fallbackTurnIndex, draft.Content, draft.MessageId); - - rows.Add(row); - _rows.Add((row.CallId, row.Ordinal), row); - } - - _nextOrdinal[callId] = first + messages.Count; - - var now = _time.GetUtcNow(); - _calls[callId] = call with { LastMessageAt = now }; - - if (state is not null) - { - _state[callId] = state; - } - - return ValueTask.FromResult>(rows); - } - } - - /// - public ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - ArgumentException.ThrowIfNullOrEmpty(messageId); - ArgumentNullException.ThrowIfNull(content); - - lock (_lock) - { - foreach (var pair in _rows) - { - if (pair.Key.CallId != callId || pair.Value.MessageId != messageId) - { - continue; - } - - _rows[pair.Key] = pair.Value with { Content = content }; - break; - } - } - - return default; - } - - /// - public ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_lock) - { - IReadOnlyList rows = - [.. _rows.Values.Where(row => row.CallId == callId).OrderBy(row => row.Ordinal)]; - - return ValueTask.FromResult(rows); - } - } - - /// - public ValueTask TruncateAsync( - string callId, int fromOrdinal, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_lock) - { - var going = _rows.Keys - .Where(key => string.Equals(key.CallId, callId, StringComparison.Ordinal) - && key.Ordinal >= fromOrdinal) - .ToList(); - - foreach (var key in going) - { - _rows.Remove(key); - } - - return ValueTask.FromResult(going.Count); - } - } - - /// - public ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - lock (_lock) - { - return ValueTask.FromResult(RemoveWords(callId)); - } - } - - /// - public ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(continuationId); - - lock (_lock) - { - _continuations[continuationId] = envelope.Clone(); - } - - return default; - } - - /// - public ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(continuationId); - - lock (_lock) - { - return ValueTask.FromResult( - _continuations.TryGetValue(continuationId, out var envelope) ? envelope : null); - } - } - - /// - public ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(continuationId); - - lock (_lock) - { - _continuations.Remove(continuationId); - } - - return default; - } - - private static DateTimeOffset SortValue(CallRecord call) => call.LastMessageAt ?? call.CreatedAt; - - private int RemoveWords(string callId) - { - var going = _rows.Keys.Where(key => key.CallId == callId).ToList(); - foreach (var key in going) - { - _rows.Remove(key); - } - - return going.Count; - } - - private ValueTask Amend(string callId, Func amend) - { - lock (_lock) - { - if (_calls.TryGetValue(callId, out var call)) - { - _calls[callId] = amend(call); - } - } - - return default; - } -} diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs index 0d26529f..e7503505 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs @@ -31,7 +31,7 @@ public static IReadOnlyList Compose(AgentDefaults? defaults, AgentConfig /// The called tool's name. /// /// An ordinal prefix match for a trailing-* pattern, else an ordinal exact match. A - /// * anywhere else is literal, so it matches nothing a document can call. + /// * anywhere else is literal, so it matches nothing a document can conversation. /// public static bool Matches(string pattern, string toolName) { diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs index 89cf260d..e705035d 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentBackgroundCompiler.cs @@ -9,7 +9,7 @@ namespace AgentCore.Application.Configuration.Compilation; /// /// The provider behind one agent's background: list: its children, each wrapped so a child -/// session knows which call started it. +/// session knows which conversation started it. /// internal static class AgentBackgroundCompiler { diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs index 1d70fca4..f4787b48 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs @@ -35,7 +35,7 @@ public AgentCompilationContext(IChatClientFactory chatClients) public ToolRegistry? Tools { get; init; } /// - /// Gets or sets the evaluator a guarded graph edge calls. + /// Gets or sets the evaluator a guarded graph edge conversations. /// public IGuardEvaluator? Guards { get; init; } @@ -47,7 +47,7 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// /// Gets or sets the backing store of store 1, or for memory. /// - public ICallStore? CallStore { get; init; } + public IConversationStore? ConversationStore { get; init; } /// /// Gets or sets the store every agent's knowledge: block reads through. diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index a36d00ef..bb40f203 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -85,7 +85,7 @@ public static List Build( throw ConfigurationCompiler.Fail( ConfigurationError.AppendPointer(pointer, "knowledge"), $"the agent '{item.Id}' declares a knowledge: block and this host registered no " - + "knowledge vendor, so there is no store to read. Call " + + "knowledge vendor, so there is no store to read. Conversation " + "options.UseKnowledgeStores(...) with an adapter that serves " + $"{nameof(IKnowledgeRetrievalPort)}, or remove the knowledge: block."); } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs index 5912c115..19c7b12a 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs @@ -9,7 +9,7 @@ namespace AgentCore.Application.Configuration.Compilation; /// -/// Turns one declaration into the function the outer agent calls. +/// Turns one declaration into the function the outer agent conversations. /// internal static class AgentDelegationTool { diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 17bf41c5..580dffdc 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -17,14 +17,14 @@ internal static class AgentHarnessProviders /// /// MAF's default , with its persistence claim /// replaced: the default tells the model these files "persist beyond the current conversation", - /// which is false here — FileMemoryProvider's working folder is the call's workspace, - /// deleted at EndCall. Every other sentence, including how to use the tools, is unchanged. + /// which is false here — FileMemoryProvider's working folder is the conversation's workspace, + /// deleted at EndConversation. Every other sentence, including how to use the tools, is unchanged. /// private const string MemoryInstructions = "## File Based Memory\n" + "You have access to a file-based memory system via the `file_memory_*` tools for storing and retrieving information across interactions.\n" - + "These files act as your working memory for this call: they live in this call's workspace and are deleted when the call ends,\n" - + "so anything you write now stays available for the rest of this call, but not after it ends.\n" + + "These files act as your working memory for this conversation: they live in this conversation's workspace and are deleted when the conversation ends,\n" + + "so anything you write now stays available for the rest of this conversation, but not after it ends.\n" + "Use these tools to store plans, memories, processing results, or downloaded data.\n\n" + "- Use descriptive file names (e.g., \"projectarchitecture.md\", \"userpreferences.md\").\n" + "- Include a description when writing a file to help with future discovery.\n" @@ -37,14 +37,14 @@ internal static class AgentHarnessProviders /// /// MAF's default , with its persistence claim /// replaced: the default tells the model these files "persist beyond the current session" and - /// "may be shared across sessions or agents", which is false here — CallFilesProvider - /// resolves to the call's workspace, deleted at EndCall. Every other sentence, including + /// "may be shared across sessions or agents", which is false here — ConversationFilesProvider + /// resolves to the conversation's workspace, deleted at EndConversation. Every other sentence, including /// how to use the tools, is unchanged. /// private const string FilesInstructions = "## File Access\n" + "You have access to a shared file storage area via the `file_access_*` tools for reading, writing, and managing files.\n" - + "These files live in this call's workspace: they exist only for the duration of this call and are deleted when the call ends.\n" + + "These files live in this conversation's workspace: they exist only for the duration of this conversation and are deleted when the conversation ends.\n" + "Use these tools to read input data provided by the user, write output artifacts, and manage any files the user has asked you to work with.\n\n" + "- Never delete or overwrite existing files unless the user has explicitly asked you to do so.\n" + "- Files may be organized into subdirectories. Use `file_access_ls` to explore the tree level by level,\n" @@ -64,7 +64,7 @@ internal static class AgentHarnessProviders /// The compile-time seams, including the bound workspace root. /// This agent's JSON pointer, for a memory:, files:, shell:, or background: failure. /// Resolves an agents.items id to its compiled agent, or when undeclared. - /// Collects the built background providers, so the call can release their sessions when it ends. + /// Collects the built background providers, so the conversation can release their sessions when it ends. public static void Add( List providers, AgentDefaults? defaults, @@ -104,8 +104,8 @@ public static void Add( if (item.Shell is { } shell) { var options = AgentShellOptionsCompiler.Build(item, shell, context, pointer); - providers.Add(new CallShellProvider(options)); - providers.Add(new CallShellEnvironmentProvider(options)); + providers.Add(new ConversationShellProvider(options)); + providers.Add(new ConversationShellEnvironmentProvider(options)); } if (item.Background.Count > 0) @@ -246,7 +246,7 @@ private static FileMemoryProvider BuildMemoryProvider( catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { // FileSystemAgentFileStore's constructor creates the root eagerly, and this compiles - // before CallSessionStartup's own guarded create — so a bad root fails here first, and + // before ConversationSessionStartup's own guarded create — so a bad root fails here first, and // must fail with the same named cause an operator gets from that later guard. throw ConfigurationCompiler.Fail( ConfigurationError.AppendPointer(pointer, "memory"), @@ -258,7 +258,7 @@ private static FileMemoryProvider BuildMemoryProvider( #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. - private static CallFilesProvider BuildFilesProvider( + private static ConversationFilesProvider BuildFilesProvider( AgentConfiguration item, AgentFilesConfiguration files, AgentCompilationContext context, @@ -273,7 +273,7 @@ private static CallFilesProvider BuildFilesProvider( + "the folder, or remove the files: block."); } - return new CallFilesProvider( + return new ConversationFilesProvider( context.WorkspaceRoot, new FileAccessProviderOptions { @@ -290,20 +290,20 @@ private static CallFilesProvider BuildFilesProvider( /// /// Builds the state a new session starts with: its working - /// folder set to the id of the call running the turn, so it reads and writes under - /// <root>/<callId>/ — the folder the host creates and deletes with the call. + /// folder set to the id of the conversation running the turn, so it reads and writes under + /// <root>/<conversationId>/ — the folder the host creates and deletes with the conversation. /// private static FileMemoryState InitializeWorkingFolder(AgentSession? session) { - if (TurnRegistry.For(session)?.CallId is not { } callId) + if (TurnRegistry.For(session)?.ConversationId is not { } conversationId) { throw new InvalidOperationException( - "A memory: block's FileMemoryProvider needs the running call's id, and no turn is " + "A memory: block's FileMemoryProvider needs the running conversation's id, and no turn is " + "filed for this session. The provider's working folder is bound only while " - + "a turn runs through a CallSession. Run the agent through a CallSession."); + + "a turn runs through a ConversationSession. Run the agent through a ConversationSession."); } - return new FileMemoryState { WorkingFolder = callId }; + return new FileMemoryState { WorkingFolder = conversationId }; } #pragma warning restore MAAI001 diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs index 7a351a6f..92d0610b 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentInstructions.cs @@ -24,7 +24,7 @@ public static class AgentInstructions + "- Explain your reasoning and thought process as you work through tasks.\n" + "- Explain what you learned and what you are going to do next between tool calls, so the user can follow along with your thought process.\n" + "- Avoid making more than 4 tool calls in a row without explaining what you are doing.\n" - + "- If a tool call fails or returns unexpected results, adapt your approach rather than repeating the same call.\n" + + "- If a tool call fails or returns unexpected results, adapt your approach rather than repeating the same conversation.\n" + "- When you have completed the task, present a clear and concise summary of what you did and what you found.\n" + "\n" + "Resolve what you can from what you know and what you are given. Ask only for what you " diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs index 19154d57..7edb3cf2 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentShellOptionsCompiler.cs @@ -7,7 +7,7 @@ namespace AgentCore.Application.Configuration.Compilation; -/// Compiles one agent's shell: block into . +/// Compiles one agent's shell: block into . internal static class AgentShellOptionsCompiler { /// Builds this agent's shell options from its declared shell: block. @@ -19,7 +19,7 @@ internal static class AgentShellOptionsCompiler /// The block names no workspace root, a Docker-only key under kind: local, or a policy /// pattern that is not a valid regex. /// - internal static CallShellOptions Build( + internal static ConversationShellOptions Build( AgentConfiguration item, ShellConfiguration shell, AgentCompilationContext context, @@ -57,7 +57,7 @@ internal static CallShellOptions Build( var memoryBytes = shell.MemoryMb is { } memoryMb ? (long)memoryMb * 1024 * 1024 : (long?)null; - return new CallShellOptions( + return new ConversationShellOptions( shell.Kind, policy, timeout, diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs index b3218c15..8661c426 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs @@ -26,7 +26,7 @@ internal CompiledAgent( string fallbackReply, string refusalReply, CompileTableRow row, - ICallStore calls, + IConversationStore conversations, AIAgent entry, Dictionary byAgentId, Dictionary agentIdByStage, @@ -48,7 +48,7 @@ internal CompiledAgent( Shape = row.Shape; SessionCarriesHistory = row.SessionCarriesHistory; Agent = entry; - CallStore = calls; + ConversationStore = conversations; SpokenBy = spokenBy; History = history; HarnessStateKeys = harnessStateKeys; @@ -104,22 +104,22 @@ internal CompiledAgent( internal IReadOnlySet? SpokenBy { get; } /// - /// Gets store 1 of every call this agent answers. + /// Gets store 1 of every conversation this agent answers. /// internal AgentCoreChatHistoryProvider History { get; } - /// Gets the store this agent's calls and every word of them are kept in. - internal ICallStore CallStore { get; } + /// Gets the store this agent's conversations and every word of them are kept in. + internal IConversationStore ConversationStore { get; } /// /// Gets the union of every harness provider's state keys, over every agent this document /// compiled — never the history provider's key. Empty when the document names no harness - /// switch. This is what a call's Providers keeps beside its stage and its slots. + /// switch. This is what a conversation's Providers keeps beside its stage and its slots. /// internal IReadOnlySet HarnessStateKeys { get; } #pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. /// - /// Gets every background provider this document compiled, over every agent. The call releases + /// Gets every background provider this document compiled, over every agent. The conversation releases /// each one's session when it ends, so children still running cannot outlive it. /// internal IReadOnlyList BackgroundProviders { get; } @@ -167,7 +167,7 @@ internal CompiledAgent( return agentId.Length == 0 ? null : _turnByAgentId[agentId]; } - /// Builds one stage machine for one call. + /// Builds one stage machine for one conversation. /// The evaluator that runs each exit guard. /// The machine, in the initial stage. public StagePolicy CreatePolicy(IGuardEvaluator guards) diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index c39e92c4..17a4eb7c 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Evaluation; @@ -68,7 +68,7 @@ internal static CompileTableRow SelectEntryRow(EntryConfiguration entry, string throw Fail( entryPointer, "the entry holds two of agent:, policy:, and graph:. The section 8.2 compile table " - + "takes exactly one: agent: for one agent answering directly, policy: for a call that " + + "takes exactly one: agent: for one agent answering directly, policy: for a conversation that " + "walks stages, and graph: for a run that needs checkpointing, a request port, or a " + "parallel fan-out with a join."); } @@ -133,9 +133,9 @@ public static IReadOnlyDictionary CompileAll( ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(context); - ICallStore calls = context.CallStore ?? new InMemoryCallStore(); + IConversationStore conversations = context.ConversationStore ?? new InMemoryConversationStore(); - AgentCoreChatHistoryProvider history = new(calls); + AgentCoreChatHistoryProvider history = new(conversations); Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders)> built = new(StringComparer.Ordinal); @@ -168,7 +168,7 @@ public static IReadOnlyDictionary CompileAll( fallbackReply, refusalReply, row, - calls, + conversations, entryAgent, shared.Agents, stages, @@ -209,7 +209,7 @@ private static AIAgent WithTurnDisposition( /// The loaded document. /// The seams the document names. /// Store 1, or to leave the framework default in place. - /// The agents keyed by id, the union of every harness provider's state keys, and every background provider for the call-end release. + /// The agents keyed by id, the union of every harness provider's state keys, and every background provider for the conversation-end release. private static (Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders) BuildAgents( AgentCoreConfiguration configuration, AgentCompilationContext context, @@ -278,7 +278,7 @@ private static (Dictionary Agents, IReadOnlySet Harness pointer, $"the agent '{id}' delegates back to itself through a kind: agent tool: " + $"{string.Join(" -> ", path)} -> {id}. Check 8 of section 8.5 rejects a delegation " - + "cycle, because the call would never return."); + + "cycle, because the conversation would never return."); } path.Add(id); diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs b/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs index f3b60a04..f58b1f7a 100644 --- a/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs +++ b/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs @@ -9,9 +9,9 @@ internal static class GraphGuardGate { /// The reason a gate reports when the run carries no state. internal const string NoStateMessage = - "A guarded graph edge asked for the state of the running call, and the run carries none. " - + "Row 4 of the section 8.2 compile table reads the state of one call, and the graph-state " - + "wrapper files it from the turn before the run starts. Run the graph through a CallSession, " + "A guarded graph edge asked for the state of the running conversation, and the run carries none. " + + "Row 4 of the section 8.2 compile table reads the state of one conversation, and the graph-state " + + "wrapper files it from the turn before the run starts. Run the graph through a ConversationSession, " + "which files the turn on the run's session. This throws and does not answer false, because " + "a guarded edge that quietly became unconditional is the silent graph failure section 8.2 " + "refuses to ship."; diff --git a/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs index 4b9247a1..cb50f4d5 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs @@ -4,15 +4,15 @@ namespace AgentCore.Application.Configuration.Schema; public enum AgentFileStoreKind { /// - /// The host-created per-call directory: AgentCoreOptions.WorkspaceRoot/<callId>/, - /// created with the call and deleted with it. The one store no process decides for a caller. + /// The host-created per-conversation directory: AgentCoreOptions.WorkspaceRoot/<conversationId>/, + /// created with the conversation and deleted with it. The one store no process decides for a caller. /// Workspace, } /// /// One agent's memory: block: the file_memory_* tools over a store. The provider -/// keeps its working folder in the session state (§3.5), so a resumed call reads the same files. +/// keeps its working folder in the session state (§3.5), so a resumed conversation reads the same files. /// public sealed record AgentMemoryConfiguration { diff --git a/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs index 01c6efde..289d6be1 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs @@ -26,11 +26,11 @@ public sealed record ShellPolicyConfiguration public IReadOnlyList Allow { get; init; } = []; } -/// One agent's shell: block: one executor per call, removed with it (§4.4). +/// One agent's shell: block: one executor per conversation, removed with it (§4.4). public sealed record ShellConfiguration { /// - /// Gets the executor kind. Deliberately required: where a shell runs is the consumer's call, so + /// Gets the executor kind. Deliberately required: where a shell runs is the consumer's conversation, so /// no default exists here (§4.5.1). /// public required ShellKind Kind { get; init; } diff --git a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs index 4455decb..5d0e5fab 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs @@ -87,7 +87,7 @@ public sealed record AgentConfiguration /// Gets the model of this agent, or to inherit the default. public ModelReference? Model { get; init; } - /// Gets the ids of the tools this agent may call. + /// Gets the ids of the tools this agent may conversation. public IReadOnlyList Tools { get; init; } = []; /// Gets the names of the skills this agent may load. @@ -119,7 +119,7 @@ public sealed record AgentConfiguration /// /// Gets this agent's shell: block, or for none. One executor per - /// call, never a process singleton. + /// conversation, never a process singleton. /// public ShellConfiguration? Shell { get; init; } diff --git a/src/AgentCore.Application/Configuration/Schema/CallProviderConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ConversationProviderConfiguration.cs similarity index 64% rename from src/AgentCore.Application/Configuration/Schema/CallProviderConfiguration.cs rename to src/AgentCore.Application/Configuration/Schema/ConversationProviderConfiguration.cs index 3c5fd6df..e22d06e4 100644 --- a/src/AgentCore.Application/Configuration/Schema/CallProviderConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/ConversationProviderConfiguration.cs @@ -1,14 +1,14 @@ namespace AgentCore.Application.Configuration.Schema; /// -/// The vendor that carries the call, and the limits of the socket it opens. +/// The vendor that carries the conversation, and the limits of the socket it opens. /// -public sealed record CallProviderConfiguration +public sealed record ConversationProviderConfiguration { - /// Gets the vendor that carries the call, such as telnyx-relay. + /// Gets the vendor that carries the conversation, such as telnyx-relay. public required string Kind { get; init; } - /// Gets how long the socket waits with no inbound frame before ending the call, or null for the adapter's default. + /// Gets how long the socket waits with no inbound frame before ending the conversation, or null for the adapter's default. public int? IdleTimeoutSeconds { get; init; } /// Gets how long teardown gives a stuck task before moving on, or null for the adapter's default. diff --git a/src/AgentCore.Application/Configuration/Schema/ExtractorConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ExtractorConfiguration.cs index c553d7b7..9c14e609 100644 --- a/src/AgentCore.Application/Configuration/Schema/ExtractorConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/ExtractorConfiguration.cs @@ -8,7 +8,7 @@ public enum ExtractorTrigger } /// -/// A pointer to one entry of providers.llm, with the call settings that go with it. +/// A pointer to one entry of providers.llm, with the conversation settings that go with it. /// public sealed record ModelReference { diff --git a/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs index 06b678b8..dd9bbbd3 100644 --- a/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs @@ -33,7 +33,7 @@ public sealed record StageConfiguration /// Gets the id of the agent that speaks in this stage, or . public string? Agent { get; init; } - /// Gets whether the stage ends the call. A terminal stage needs no exit. + /// Gets whether the stage ends the conversation. A terminal stage needs no exit. public bool Terminal { get; init; } /// Gets what the stage does when no exit guard is true. @@ -48,7 +48,7 @@ public sealed record StageConfiguration /// public sealed record PolicyConfiguration { - /// Gets the id of the stage the call starts in. + /// Gets the id of the stage the conversation starts in. public required string Initial { get; init; } /// Gets the declared stages, in document order. diff --git a/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs index 16d7d55a..2de0cfc6 100644 --- a/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs @@ -342,8 +342,8 @@ public sealed record ProvidersConfiguration /// Gets the language models, in document order. public IReadOnlyList Llm { get; init; } = []; - /// Gets the vendor that carries the call and owns its inbound route, or . - public CallProviderConfiguration? Call { get; init; } + /// Gets the vendor that carries the conversation and owns its inbound route, or . + public ConversationProviderConfiguration? Conversation { get; init; } /// Gets the two speech roles, or . public SpeechProviderConfiguration? Speech { get; init; } @@ -366,8 +366,8 @@ public sealed record ProvidersConfiguration /// Gets the audit sink provider, or for the in-process default. public VendorProviderConfiguration? Audit { get; init; } - /// Gets the call store provider, or for the in-process default. - public VendorProviderConfiguration? Calls { get; init; } + /// Gets the conversation store provider, or for the in-process default. + public VendorProviderConfiguration? Conversations { get; init; } /// /// Gets the blob store provider, or when a sandbox file is never kept. diff --git a/src/AgentCore.Application/Configuration/Schema/ReservedStateSlots.cs b/src/AgentCore.Application/Configuration/Schema/ReservedStateSlots.cs index fbfce486..06b88ce4 100644 --- a/src/AgentCore.Application/Configuration/Schema/ReservedStateSlots.cs +++ b/src/AgentCore.Application/Configuration/Schema/ReservedStateSlots.cs @@ -14,11 +14,11 @@ public static class ReservedStateSlots /// The zero-based index of the current turn. public const string TurnIndex = "turnIndex"; - /// The seconds the call has run. - public const string CallDurationSeconds = "callDurationSeconds"; + /// The seconds the conversation has run. + public const string ConversationDurationSeconds = "conversationDurationSeconds"; /// Gets every reserved slot name. - public static IReadOnlyList All { get; } = [Stage, TurnIndex, CallDurationSeconds]; + public static IReadOnlyList All { get; } = [Stage, TurnIndex, ConversationDurationSeconds]; /// Reports whether a name is reserved. /// The slot name to test. @@ -26,5 +26,5 @@ public static class ReservedStateSlots public static bool Contains(string name) => string.Equals(name, Stage, StringComparison.Ordinal) || string.Equals(name, TurnIndex, StringComparison.Ordinal) - || string.Equals(name, CallDurationSeconds, StringComparison.Ordinal); + || string.Equals(name, ConversationDurationSeconds, StringComparison.Ordinal); } diff --git a/src/AgentCore.Application/Configuration/Schema/TitlerConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/TitlerConfiguration.cs index 66ae0b5b..952c3056 100644 --- a/src/AgentCore.Application/Configuration/Schema/TitlerConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/TitlerConfiguration.cs @@ -1,15 +1,15 @@ namespace AgentCore.Application.Configuration.Schema; /// -/// The call titler. It names a call from the first few messages of the call itself. +/// The conversation titler. It names a conversation from the first few messages of the conversation itself. /// /// -/// The titler never speaks to the caller and writes nothing but the call's name. The block is +/// The titler never speaks to the caller and writes nothing but the conversation's name. The block is /// optional: a document that declares none leaves the titler on whichever providers.llm /// entry the factory defaults to. /// public sealed record TitlerConfiguration { - /// Gets the model the titler calls. + /// Gets the model the titler conversations. public required ModelReference Model { get; init; } } diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index 29096570..aad758cf 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -265,7 +265,7 @@ }, "titler": { "type": "object", - "description": "The model that names a call from its first few messages. The key is optional, and a document that omits it leaves the titler on the default providers.llm entry.", + "description": "The model that names a conversation from its first few messages. The key is optional, and a document that omits it leaves the titler on the default providers.llm entry.", "required": [ "model" ], @@ -759,7 +759,7 @@ }, "shell": { "$ref": "#/$defs/shell", - "description": "One shell executor per call." + "description": "One shell executor per conversation." }, "approval": { "$ref": "#/$defs/approval", @@ -789,7 +789,7 @@ }, "compaction": { "type": ["object", "null"], - "description": "Decision 3: no strategy here calls a model. A resumed call rebuilds a new session and re-derives from the replayed words, so a strategy that called a model would give one call two histories.", + "description": "Decision 3: no strategy here calls a model. A resumed conversation rebuilds a new session and re-derives from the replayed words, so a strategy that called a model would give one conversation two histories.", "additionalProperties": false, "properties": { "strategy": { @@ -818,7 +818,7 @@ "enum": [ "workspace" ], - "description": "The host-created per-call directory, deleted with the call. The only store today." + "description": "The host-created per-conversation directory, deleted with the conversation. The only store today." }, "approval": { "type": "object", @@ -956,7 +956,7 @@ "docker", "local" ], - "description": "Where a shell runs is the consumer's call, so the document names one: there is no default." + "description": "Where a shell runs is the consumer's conversation, so the document names one: there is no default." }, "shellPattern": { "type": "string", @@ -1205,7 +1205,7 @@ "providers": { "type": "object", "required": [ - "call", + "conversation", "speech" ], "additionalProperties": false, @@ -1217,8 +1217,8 @@ "$ref": "#/$defs/llmProvider" } }, - "call": { - "$ref": "#/$defs/callProvider" + "conversation": { + "$ref": "#/$defs/conversationProvider" }, "speech": { "$ref": "#/$defs/speechProvider" @@ -1245,9 +1245,9 @@ "$ref": "#/$defs/vendorProvider", "description": "Where the D23 audit chain is written, such as memory. A document that names none uses the in-process memory sink, which is not durable." }, - "calls": { + "conversations": { "$ref": "#/$defs/vendorProvider", - "description": "Where a call is kept: its row, and the words of it. A document that names none uses the in-process memory store, which is not durable and holds no retention window." + "description": "Where a conversation is kept: its row, and the words of it. A document that names none uses the in-process memory store, which is not durable and holds no retention window." }, "blobs": { "$ref": "#/$defs/blobProvider", @@ -1351,9 +1351,9 @@ } } }, - "callProvider": { + "conversationProvider": { "type": "object", - "description": "The media plane: who carries the call and owns its inbound route. Not providers.speech, which is recognition and synthesis, and not providers.telephony, which is call control.", + "description": "The media plane: who carries the conversation and owns its inbound route. Not providers.speech, which is recognition and synthesis, and not providers.telephony, which is conversation control.", "required": [ "kind" ], @@ -1367,7 +1367,7 @@ "type": "integer", "minimum": -1, "maximum": 4294967, - "description": "How long the socket waits with no inbound frame before ending the call. -1 means never." + "description": "How long the socket waits with no inbound frame before ending the conversation. -1 means never." }, "closeTimeoutSeconds": { "type": "integer", diff --git a/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs b/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs index 1b997020..5652ef19 100644 --- a/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/DelegationCycleCheck.cs @@ -102,7 +102,7 @@ private static ConfigurationError CycleError(Edge edge, string cycle) // The compiler prints the same chain in the same 'first -> second -> first' form, and // gives the same reason. The two messages agree rather than compete. Message = $"this tool runs the agent '{edge.Target}', and that closes the delegation cycle " - + $"{cycle}. The call would never return.", + + $"{cycle}. The conversation would never return.", Check = ConfigurationCheck.DelegationCycles, }; } diff --git a/src/AgentCore.Application/Configuration/Validation/GuardEvaluator.cs b/src/AgentCore.Application/Configuration/Validation/GuardEvaluator.cs index 3dafc189..865adb5d 100644 --- a/src/AgentCore.Application/Configuration/Validation/GuardEvaluator.cs +++ b/src/AgentCore.Application/Configuration/Validation/GuardEvaluator.cs @@ -28,13 +28,13 @@ namespace AgentCore.Application.Configuration.Validation; /// A guard is static configuration, so each rule of the guards: table deserializes exactly /// once, when this type is constructed. A rule that arrives inline deserializes once for each node, /// and the result is held by node identity. That removes the per-turn parse, which matters because a -/// guard runs on every turn of every call. +/// guard runs on every turn of every conversation. /// /// /// Section 8.7 fixes the failure behaviour: JsonLogic throws when a value cannot convert, and /// check 4 cannot see every such case. This type catches the failure, reports it once for each guard, /// treats the guard as false, and continues. It never propagates, because a failed guard must not -/// drop a call. A rule that fails to deserialize follows the same path: the constructor holds the +/// drop a conversation. A rule that fails to deserialize follows the same path: the constructor holds the /// cause, names the guard, and reports it once, so a malformed rule never kills the process at /// startup and never hides which guard is at fault. /// @@ -66,7 +66,7 @@ public GuardEvaluator(IReadOnlyDictionary guards) /// The logger the failure of each distinct guard is written to. /// /// This is the binding section 8.7 asks for: a guard that throws is logged once, treated as - /// false, and the call continues. The composition root uses it, so the report reaches a host + /// false, and the conversation continues. The composition root uses it, so the report reaches a host /// without the host writing the handler. /// /// is . @@ -188,7 +188,7 @@ public static JsonObject BuildData(IReadOnlyDictionary state) return data; } - /// Turns one logger into the handler the failure path calls. + /// Turns one logger into the handler the failure path conversations. /// The logger. /// The handler. /// is . @@ -229,7 +229,7 @@ private static CompiledGuard Compile(JsonNode? rule) { return new CompiledGuard(JsonSerializer.Deserialize(rule), null); } -#pragma warning disable CA1031 // Section 8.7: a rule that will not parse is false, and the call continues. +#pragma warning disable CA1031 // Section 8.7: a rule that will not parse is false, and the conversation continues. catch (Exception exception) #pragma warning restore CA1031 { @@ -250,7 +250,7 @@ private bool Apply(CompiledGuard compiled, IReadOnlyDictionary /// Section 8.7 fixes the run-time failure behaviour: a guard that throws is possible and is not a /// defect. An implementation logs the failure once and returns . It never -/// propagates the exception, because a failed guard must not drop a call. +/// propagates the exception, because a failed guard must not drop a conversation. /// /// /// An implementation resolves a named guard through the guards: table that it receives when it diff --git a/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs b/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs index 8ea49804..6ec16e0a 100644 --- a/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/KnowledgeScopeCheck.cs @@ -26,7 +26,7 @@ public static void Run(AgentCoreConfiguration configuration, List 0 }) diff --git a/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs b/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs index 01f4d707..fbdb40b7 100644 --- a/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs @@ -16,7 +16,7 @@ namespace AgentCore.Application.Configuration.Validation; /// pointer at the key the author has to change. /// /// -/// The check reads the document only. A caller that sets a temperature on its own call options in +/// The check reads the document only. A caller that sets a temperature on its own conversation options in /// code can still send one the entry forbids, because no configuration check can see that. /// /// diff --git a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs index a7c4972f..d76e2cee 100644 --- a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs +++ b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs @@ -215,7 +215,7 @@ public static string Describe(IReadOnlyDictionary state) List points = [.. members.Select(static member => (JsonNode?)member.DeepClone())]; // A slot with no default reads as null until a writer fills it, and that is a state the - // guards run in. Without this point check 5 analyses a domain the call never starts in. + // guards run in. Without this point check 5 analyses a domain the conversation never starts in. if (slot.Default is null) { points.Add(null); @@ -241,7 +241,7 @@ private static StateSlotConfiguration ReservedSlot(string name) Writer = StateWriter.Const, Default = JsonValue.Create(0), }, - ReservedStateSlots.CallDurationSeconds => new StateSlotConfiguration + ReservedStateSlots.ConversationDurationSeconds => new StateSlotConfiguration { Type = StateSlotType.Number, Writer = StateWriter.Const, diff --git a/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs b/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs index 8554cc68..ae75e94a 100644 --- a/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs +++ b/src/AgentCore.Application/Configuration/Validation/ValidationErrors.cs @@ -9,7 +9,7 @@ internal static class ValidationErrors /// /// The longest interval, in seconds, that every timer these values reach will accept. /// CancellationTokenSource.CancelAfter, Task.WaitAsync and PeriodicTimer each - /// throw above milliseconds, from a call site that carries no pointer + /// throw above milliseconds, from a conversation site that carries no pointer /// into the document. /// public const int MaxIntervalSeconds = int.MaxValue / 1000; @@ -41,7 +41,7 @@ public static ConfigurationError WellFormedness(string pointer, string message) /// One or more sentences saying what the range protects. /// Collects the refusal. /// - /// Both bounds go through one call so a field cannot be given a floor and left without a ceiling: + /// Both bounds go through one conversation so a field cannot be given a floor and left without a ceiling: /// every ceiling here stands between a document and a raw throw out of a timer at boot or mid-turn. /// public static void CheckRange( diff --git a/src/AgentCore.Application/Calls/ChatCallTitler.cs b/src/AgentCore.Application/Conversation/ChatConversationTitler.cs similarity index 65% rename from src/AgentCore.Application/Calls/ChatCallTitler.cs rename to src/AgentCore.Application/Conversation/ChatConversationTitler.cs index 6a8ba70d..fd53e76e 100644 --- a/src/AgentCore.Application/Calls/ChatCallTitler.cs +++ b/src/AgentCore.Application/Conversation/ChatConversationTitler.cs @@ -3,15 +3,15 @@ using AgentCore.Application.Ports; using Microsoft.Extensions.AI; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// The titler that asks the configured chat client. -/// The store, where the words are read and the finished title goes. +/// The store, where the words are read and the finished title goes. /// The model that writes it. -public sealed class ChatCallTitler(ICallStore calls, IChatClient client) : ICallTitler +public sealed class ChatConversationTitler(IConversationStore conversations, IChatClient client) : IConversationTitler { // Messages and not turns: one turn writes several when tools are called. A six-word title does - // not improve for having read the whole call, and the whole call is what the prompt would be + // not improve for having read the whole conversation, and the whole conversation is what the prompt would be // charged for. The cap holds for a caller's messages too, which arrive unbounded. private const int MaxMessages = 6; @@ -24,25 +24,25 @@ public sealed class ChatCallTitler(ICallStore calls, IChatClient client) : ICall /// public IAsyncEnumerable GenerateAsync( - string callId, CancellationToken cancellationToken = default) + string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); - return GenerateCoreAsync(callId, cancellationToken); + return GenerateCoreAsync(conversationId, cancellationToken); } - /// Reads the call's messages and streams the title writes. + /// Reads the conversation's messages and streams the title writes. private async IAsyncEnumerable GenerateCoreAsync( - string callId, [EnumeratorCancellation] CancellationToken cancellationToken) + string conversationId, [EnumeratorCancellation] CancellationToken cancellationToken) { - var rows = await calls.ReadAsync(callId, cancellationToken).ConfigureAwait(false); + var rows = await conversations.ReadAsync(conversationId, cancellationToken).ConfigureAwait(false); if (rows.Count == 0) { yield break; } - await foreach (var piece in NameAsync(callId, rows.Select(row => row.Content), cancellationToken) + await foreach (var piece in NameAsync(conversationId, rows.Select(row => row.Content), cancellationToken) .ConfigureAwait(false)) { yield return piece; @@ -51,19 +51,19 @@ private async IAsyncEnumerable GenerateCoreAsync( /// public IAsyncEnumerable GenerateFromAsync( - string callId, + string conversationId, IReadOnlyList messages, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); ArgumentNullException.ThrowIfNull(messages); - return GenerateFromCoreAsync(callId, messages, cancellationToken); + return GenerateFromCoreAsync(conversationId, messages, cancellationToken); } - /// Streams the title of caller-supplied messages once the call proves to exist. + /// Streams the title of caller-supplied messages once the conversation proves to exist. private async IAsyncEnumerable GenerateFromCoreAsync( - string callId, + string conversationId, IReadOnlyList messages, [EnumeratorCancellation] CancellationToken cancellationToken) { @@ -72,26 +72,26 @@ private async IAsyncEnumerable GenerateFromCoreAsync( yield break; } - // Nothing else on this path touches the call, and RenameAsync on a missing one is a silent + // Nothing else on this path touches the conversation, and RenameAsync on a missing one is a silent // no-op in both stores. Without this the model runs and its answer is dropped. - if (await calls.GetAsync(callId, cancellationToken).ConfigureAwait(false) is null) + if (await conversations.GetAsync(conversationId, cancellationToken).ConfigureAwait(false) is null) { yield break; } - await foreach (var piece in NameAsync(callId, messages, cancellationToken).ConfigureAwait(false)) + await foreach (var piece in NameAsync(conversationId, messages, cancellationToken).ConfigureAwait(false)) { yield return piece; } } - /// Asks the model for a name, streams it, and writes the finished one to the call. - /// The call the finished title belongs to. + /// Asks the model for a name, streams it, and writes the finished one to the conversation. + /// The conversation the finished title belongs to. /// The messages to name. The instruction is added here, not by the caller. /// Stops the generation, leaving the title as it was. /// The title in pieces, in order. private async IAsyncEnumerable NameAsync( - string callId, + string conversationId, IEnumerable messages, [EnumeratorCancellation] CancellationToken cancellationToken) { @@ -122,7 +122,7 @@ private async IAsyncEnumerable NameAsync( if (whole.Length > 0) { - await calls.RenameAsync(callId, whole, cancellationToken).ConfigureAwait(false); + await conversations.RenameAsync(conversationId, whole, cancellationToken).ConfigureAwait(false); } } diff --git a/src/AgentCore.Application/Calls/CallChannel.cs b/src/AgentCore.Application/Conversation/ConversationChannel.cs similarity index 87% rename from src/AgentCore.Application/Calls/CallChannel.cs rename to src/AgentCore.Application/Conversation/ConversationChannel.cs index 104d6384..18086196 100644 --- a/src/AgentCore.Application/Calls/CallChannel.cs +++ b/src/AgentCore.Application/Conversation/ConversationChannel.cs @@ -1,9 +1,9 @@ using AgentCore.Application.Ports; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// -/// The two halves of one call, opened together and disposed together. +/// The two halves of one conversation, opened together and disposed together. /// /// /// @@ -35,14 +35,14 @@ namespace AgentCore.Application.Calls; /// boundary and are marked experimental — and computes for itself what the bundled vendor /// reported for free: bytes written minus the transport's own queue, counted from the first /// audibly played sound, mapped back to the words the model wrote — measured, never estimated. -/// The settled answer still arrives as a on the input stream, and -/// every settle path after carries a two-second +/// The settled answer still arrives as a on the input stream, and +/// every settle path after carries a two-second /// deadline, after which the reply counts as fully heard. Sections 2, 6, and 11 of the design /// record the argument. /// /// /// caller ─audio─▶ [ STT client ] ─text─▶ split input port ─┐ -/// ├─ CallChannel ─▶ agent +/// ├─ ConversationChannel ─▶ agent /// caller ◀─audio─ [ TTS client ] ◀─text─ split output port ─┘ /// │ /// [ playback clock ] @@ -50,7 +50,7 @@ namespace AgentCore.Application.Calls; /// /// What the caller does. /// What the agent says. -public sealed record CallChannel(ICallInputPort Input, ICallOutputPort Output) : IAsyncDisposable +public sealed record ConversationChannel(IConversationInputPort Input, IConversationOutputPort Output) : IAsyncDisposable { private bool _disposed; diff --git a/src/AgentCore.Application/Conversation/ConversationChannelContext.cs b/src/AgentCore.Application/Conversation/ConversationChannelContext.cs new file mode 100644 index 00000000..8435ecaa --- /dev/null +++ b/src/AgentCore.Application/Conversation/ConversationChannelContext.cs @@ -0,0 +1,10 @@ +namespace AgentCore.Application.Conversation; + +/// What one conversation needs to open its channel. +/// The AgentCore conversation id, which the channel must not invent for itself. +/// Per-conversation values the host attached, or . +/// +/// This carries no vendor field and no wire frame, so D8 holds: a factory learns what the conversation is +/// without the core learning what the vendor is. +/// +public sealed record ConversationChannelContext(string ConversationId, IReadOnlyDictionary? CustomParameters); diff --git a/src/AgentCore.Application/Calls/CallClarificationState.cs b/src/AgentCore.Application/Conversation/ConversationClarificationState.cs similarity index 68% rename from src/AgentCore.Application/Calls/CallClarificationState.cs rename to src/AgentCore.Application/Conversation/ConversationClarificationState.cs index 54ff3588..6e394a96 100644 --- a/src/AgentCore.Application/Calls/CallClarificationState.cs +++ b/src/AgentCore.Application/Conversation/ConversationClarificationState.cs @@ -1,12 +1,12 @@ -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// What one slot's knowledge probe has already spent of its ask budget (§8). /// -/// Carried on so a caller who drops and reconnects mid-call is not +/// Carried on so a caller who drops and reconnects mid-conversation is not /// asked the same clarification a second maxAsks times. What was last named to the caller is /// deliberately absent: it belongs to a turn the reconnected caller is no longer in. /// -public sealed record CallClarificationState +public sealed record ConversationClarificationState { /// Gets how many times the knowledge probe has offered this slot (§8, K22). public int ProbeAsks { get; init; } diff --git a/src/AgentCore.Application/Calls/CallCursor.cs b/src/AgentCore.Application/Conversation/ConversationCursor.cs similarity index 72% rename from src/AgentCore.Application/Calls/CallCursor.cs rename to src/AgentCore.Application/Conversation/ConversationCursor.cs index 280204ec..5359f48a 100644 --- a/src/AgentCore.Application/Calls/CallCursor.cs +++ b/src/AgentCore.Application/Conversation/ConversationCursor.cs @@ -2,27 +2,27 @@ using System.Globalization; using System.Text; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// /// The place in a listing that a page ended, as one opaque string. /// -public static class CallCursor +public static class ConversationCursor { private const char Separator = '|'; /// Encodes where a page ended. /// The last row's sort time. - /// The last row's call id. + /// The last row's conversation id. /// A string the caller hands back unread. - /// The call id is . - public static string Encode(DateTimeOffset sortAt, string callId) + /// The conversation id is . + public static string Encode(DateTimeOffset sortAt, string conversationId) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); var plain = string.Create( CultureInfo.InvariantCulture, - $"{sortAt.UtcTicks}{Separator}{callId}"); + $"{sortAt.UtcTicks}{Separator}{conversationId}"); return Convert.ToBase64String(Encoding.UTF8.GetBytes(plain)); } @@ -30,13 +30,13 @@ public static string Encode(DateTimeOffset sortAt, string callId) /// Reads a cursor this class wrote. /// The value a caller handed back, which may be anything at all. /// The sort time it held, or . - /// The call id it held, or an empty string. + /// The conversation id it held, or an empty string. /// when the value was a cursor. - public static bool TryDecode(string? cursor, out DateTimeOffset sortAt, out string callId) + public static bool TryDecode(string? cursor, out DateTimeOffset sortAt, out string conversationId) { sortAt = default; - callId = string.Empty; + conversationId = string.Empty; if (string.IsNullOrEmpty(cursor)) { @@ -66,7 +66,7 @@ public static bool TryDecode(string? cursor, out DateTimeOffset sortAt, out stri } sortAt = new DateTimeOffset(ticks, TimeSpan.Zero); - callId = plain[(split + 1)..]; + conversationId = plain[(split + 1)..]; return true; } diff --git a/src/AgentCore.Application/Calls/CallInput.cs b/src/AgentCore.Application/Conversation/ConversationInput.cs similarity index 88% rename from src/AgentCore.Application/Calls/CallInput.cs rename to src/AgentCore.Application/Conversation/ConversationInput.cs index 5121e606..0965fa65 100644 --- a/src/AgentCore.Application/Calls/CallInput.cs +++ b/src/AgentCore.Application/Conversation/ConversationInput.cs @@ -1,4 +1,4 @@ -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// /// One thing the caller did, in the order it happened. @@ -14,9 +14,9 @@ namespace AgentCore.Application.Calls; /// this assembly can add a case, and a consumer's switch over the three below is exhaustive. /// /// -public abstract record CallInput +public abstract record ConversationInput { - private protected CallInput() + private protected ConversationInput() { } @@ -27,11 +27,11 @@ private protected CallInput() /// marks the end of the turn. is an interim /// transcript, and a recognizer sends many of those for one sentence. /// - public sealed record Utterance(string Text, string Language, bool IsFinal) : CallInput; + public sealed record Utterance(string Text, string Language, bool IsFinal) : ConversationInput; /// The caller pressed one key. /// The key. A keypad carries card numbers and PINs, so no log line may hold it. - public sealed record Keypress(string Key) : CallInput; + public sealed record Keypress(string Key) : ConversationInput; /// The caller cut the reply off. /// @@ -43,5 +43,5 @@ public sealed record Keypress(string Key) : CallInput; /// How much of the reply played. Measured, never estimated: D28 forbids the estimator that /// would otherwise stand here, and item 6c of section 11 asks for the same. /// - public sealed record Barge(string HeardText, TimeSpan PlayedDuration) : CallInput; + public sealed record Barge(string HeardText, TimeSpan PlayedDuration) : ConversationInput; } diff --git a/src/AgentCore.Application/Calls/CallPage.cs b/src/AgentCore.Application/Conversation/ConversationPage.cs similarity index 52% rename from src/AgentCore.Application/Calls/CallPage.cs rename to src/AgentCore.Application/Conversation/ConversationPage.cs index f8796d7c..46fc12c0 100644 --- a/src/AgentCore.Application/Calls/CallPage.cs +++ b/src/AgentCore.Application/Conversation/ConversationPage.cs @@ -1,9 +1,9 @@ -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// One page of a listing. -/// The page's rows, most recently active first. +/// The page's rows, most recently active first. /// /// What to pass as after for the following page, or when this page was /// the last. A full page always carries one; a short page never does. /// -public sealed record CallPage(IReadOnlyList Calls, string? NextCursor); +public sealed record ConversationPage(IReadOnlyList Conversations, string? NextCursor); diff --git a/src/AgentCore.Application/Conversation/ConversationRecord.cs b/src/AgentCore.Application/Conversation/ConversationRecord.cs new file mode 100644 index 00000000..b00053b6 --- /dev/null +++ b/src/AgentCore.Application/Conversation/ConversationRecord.cs @@ -0,0 +1,35 @@ +using System.Text.Json; + +namespace AgentCore.Application.Conversation; + +/// One conversation, apart from its words. It is one row of store 0. +/// The conversation this describes. It is the join to stores 1 and 3. +/// What to show in a list, or until one is made. +/// Whether the conversation is still listed as usual. +/// A consumer's own id for the conversation, or . +/// A consumer's own fields, or . +/// When the conversation row was made. UTC. +/// +/// When store 1 last wrote a word of this conversation, or when it holds none. UTC. +/// Derived at read time; store 0 keeps no such column. +/// +/// +/// What the session of this conversation held, or for a conversation that has run no turn +/// under a build that writes it. Read by GetAsync and CreateAsync only: a listing does +/// not need it and does not pay for it. +/// +/// +/// The ordinal the conversation's next appended row takes. Read by GetAsync and CreateAsync +/// only, on the same terms as : a listing leaves it at its default 0 rather +/// than paying to read it. +/// +public sealed record ConversationRecord( + string ConversationId, + string? Title, + ConversationStatus Status, + string? ExternalId, + JsonElement? Custom, + DateTimeOffset CreatedAt, + DateTimeOffset? LastMessageAt, + ConversationSessionState? State = null, + int NextOrdinal = 0); diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Conversation/ConversationSessionState.cs similarity index 70% rename from src/AgentCore.Application/Calls/CallSessionState.cs rename to src/AgentCore.Application/Conversation/ConversationSessionState.cs index 4bdb5368..31e683a9 100644 --- a/src/AgentCore.Application/Calls/CallSessionState.cs +++ b/src/AgentCore.Application/Conversation/ConversationSessionState.cs @@ -2,20 +2,20 @@ using System.Text.Json; using System.Text.Json.Nodes; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; -/// Everything one call's session holds that has no other durable home. -public sealed record CallSessionState +/// Everything one conversation's session holds that has no other durable home. +public sealed record ConversationSessionState { /// The slots of a state whose writers filled none. private static readonly IReadOnlyDictionary NoSlots = ReadOnlyDictionary.Empty; - /// The slots of a call whose knowledge probe asked about none. - private static readonly IReadOnlyDictionary NoClarifications = - ReadOnlyDictionary.Empty; + /// The slots of a conversation whose knowledge probe asked about none. + private static readonly IReadOnlyDictionary NoClarifications = + ReadOnlyDictionary.Empty; - /// The providers of a call whose document declares no harness switch. + /// The providers of a conversation whose document declares no harness switch. private static readonly IReadOnlyDictionary NoProviders = ReadOnlyDictionary.Empty; @@ -25,7 +25,7 @@ public sealed record CallSessionState /// Gets the shape this blob was written in. public int Version { get; init; } = CurrentVersion; - /// Gets the index the call's next turn takes. + /// Gets the index the conversation's next turn takes. public int NextTurnIndex { get; init; } /// Gets the stage the machine held. It is empty when the document declares no policy. @@ -41,7 +41,7 @@ public sealed record CallSessionState /// Gets what each slot's knowledge probe has spent of its ask budget, by slot name. A slot /// nothing has asked about is absent. /// - public IReadOnlyDictionary Clarifications { get; init; } = NoClarifications; + public IReadOnlyDictionary Clarifications { get; init; } = NoClarifications; /// /// Gets the MAF provider state a harness switch (todos:, mode:, memory:, @@ -51,9 +51,9 @@ public sealed record CallSessionState public IReadOnlyDictionary Providers { get; init; } = NoProviders; /// - /// Gets the opaque workflow session of a graph row's call, carrying the harness providers' + /// Gets the opaque workflow session of a graph row's conversation, carrying the harness providers' /// checkpointed state across turns. Only a graph row whose document declares a harness switch - /// writes one; rows 1 and 2 keep provider state in , and any other call + /// writes one; rows 1 and 2 keep provider state in , and any other conversation /// keeps neither. Absent in an old blob, which resumes with a fresh session. /// public JsonElement? WorkflowState { get; init; } diff --git a/src/AgentCore.Application/Calls/CallSpeechPairing.cs b/src/AgentCore.Application/Conversation/ConversationSpeechPairing.cs similarity index 66% rename from src/AgentCore.Application/Calls/CallSpeechPairing.cs rename to src/AgentCore.Application/Conversation/ConversationSpeechPairing.cs index 38a30b13..2437b9b5 100644 --- a/src/AgentCore.Application/Calls/CallSpeechPairing.cs +++ b/src/AgentCore.Application/Conversation/ConversationSpeechPairing.cs @@ -2,16 +2,16 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// -/// Refuses a document whose call transport and speech vendors cannot coexist. +/// Refuses a document whose conversation transport and speech vendors cannot coexist. /// /// /// /// A transport whose frames already carry text is the recognizer and the synthesizer. A /// document naming it for the pipe and something else for the ears or the mouth describes a -/// deployment that cannot exist, and the failure it would otherwise produce — a call that connects +/// deployment that cannot exist, and the failure it would otherwise produce — a conversation that connects /// and never transcribes — is among the most expensive kinds to diagnose. /// /// @@ -20,7 +20,7 @@ namespace AgentCore.Application.Calls; /// to learn that. /// /// -/// No vendor name appears here. is declared by the +/// No vendor name appears here. is declared by the /// adapter, so a second bundled vendor is one new adapter and no edit to this file. A guard that /// grew an || per vendor is the design this one exists to avoid. /// @@ -29,37 +29,37 @@ namespace AgentCore.Application.Calls; /// forgets to map a route still learns its document is self-contradictory. /// /// -public static class CallSpeechPairing +public static class ConversationSpeechPairing { - /// Checks that both speech roles are compatible with the selected call transport. - /// The providers.call block. + /// Checks that both speech roles are compatible with the selected conversation transport. + /// The providers.conversation block. /// The providers.speech block, with both of its roles. - /// The adapter providers.call.kind selected. + /// The adapter providers.conversation.kind selected. /// Any argument is . /// /// The transport carries text and at least one speech role names a different vendor. The /// exception carries one error per offending role, recognition first. /// public static void Validate( - CallProviderConfiguration call, + ConversationProviderConfiguration conversation, SpeechProviderConfiguration speech, - ICallAdapter selectedCall) + IConversationAdapter selectedConversation) { - ArgumentNullException.ThrowIfNull(call); + ArgumentNullException.ThrowIfNull(conversation); ArgumentNullException.ThrowIfNull(speech); - ArgumentNullException.ThrowIfNull(selectedCall); + ArgumentNullException.ThrowIfNull(selectedConversation); - if (!selectedCall.CarriesText) + if (!selectedConversation.CarriesText) { // The socket carries audio, so a separate speech vendor is exactly what is wanted and - // the kinds are expected to differ from the call's. + // the kinds are expected to differ from the conversation's. return; } List errors = []; - Check(errors, call.Kind, speech.Stt.Kind, "stt"); - Check(errors, call.Kind, speech.Tts.Kind, "tts"); + Check(errors, conversation.Kind, speech.Stt.Kind, "stt"); + Check(errors, conversation.Kind, speech.Tts.Kind, "tts"); if (errors.Count > 0) { @@ -69,12 +69,12 @@ public static void Validate( /// Adds one error when a role names a vendor the text-carrying transport is not. /// The errors collected so far. One start reports every offending role. - /// The vendor providers.call.kind names. + /// The vendor providers.conversation.kind names. /// The vendor this role names. /// The role's own name in the document, stt or tts. - private static void Check(List errors, string callKind, string roleKind, string role) + private static void Check(List errors, string conversationKind, string roleKind, string role) { - if (string.Equals(roleKind, callKind, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(roleKind, conversationKind, StringComparison.OrdinalIgnoreCase)) { return; } @@ -83,10 +83,10 @@ private static void Check(List errors, string callKind, stri { Pointer = $"/providers/speech/{role}/kind", Message = - $"providers.call is kind: {callKind}, and that transport carries text, so it " + $"providers.conversation is kind: {conversationKind}, and that transport carries text, so it " + $"performs recognition and synthesis itself. providers.speech.{role} is kind: " + $"{roleKind}, which would never be asked to do anything. Set " - + $"providers.speech.{role} to '{callKind}', or choose a call transport that " + + $"providers.speech.{role} to '{conversationKind}', or choose a conversation transport that " + $"carries audio.", Check = ConfigurationCheck.ReferenceResolution, }); diff --git a/src/AgentCore.Application/Calls/CallStateJson.cs b/src/AgentCore.Application/Conversation/ConversationStateJson.cs similarity index 66% rename from src/AgentCore.Application/Calls/CallStateJson.cs rename to src/AgentCore.Application/Conversation/ConversationStateJson.cs index 446b4e97..32404fd4 100644 --- a/src/AgentCore.Application/Calls/CallStateJson.cs +++ b/src/AgentCore.Application/Conversation/ConversationStateJson.cs @@ -1,9 +1,9 @@ using System.Text.Json; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; -/// How is encoded. Every store agrees on it. -public static class CallStateJson +/// How is encoded. Every store agrees on it. +public static class ConversationStateJson { /// The shared options. public static JsonSerializerOptions Options { get; } = Build(); diff --git a/src/AgentCore.Application/Conversation/ConversationStatus.cs b/src/AgentCore.Application/Conversation/ConversationStatus.cs new file mode 100644 index 00000000..6d281dbd --- /dev/null +++ b/src/AgentCore.Application/Conversation/ConversationStatus.cs @@ -0,0 +1,11 @@ +namespace AgentCore.Application.Conversation; + +/// Whether a conversation still belongs in a caller's list. +public enum ConversationStatus +{ + /// Listed as usual. + Regular, + + /// Kept, but out of the way. + Archived, +} diff --git a/src/AgentCore.Application/Calls/CallStoreFactory.cs b/src/AgentCore.Application/Conversation/ConversationStoreFactory.cs similarity index 69% rename from src/AgentCore.Application/Calls/CallStoreFactory.cs rename to src/AgentCore.Application/Conversation/ConversationStoreFactory.cs index 2bb0a10d..4285b104 100644 --- a/src/AgentCore.Application/Calls/CallStoreFactory.cs +++ b/src/AgentCore.Application/Conversation/ConversationStoreFactory.cs @@ -1,24 +1,24 @@ -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using AgentCore.Application.Providers; -namespace AgentCore.Application.Calls; +namespace AgentCore.Application.Conversation; /// /// Opens the store 0 backing the document names, from the adapters the host registered. /// -public static class CallStoreFactory +public static class ConversationStoreFactory { /// The built-in kind, and the one a document that names no provider gets. public const string MemoryKind = "memory"; - /// What this seam calls itself, so the shared selector writes its failures. + /// What this seam conversations itself, so the shared selector writes its failures. private static readonly VendorSeam Seam = - new("providers.calls", "/providers/calls/kind", "options.UseCallStores(...)", "stores"); + new("providers.conversations", "/providers/conversations/kind", "options.UseConversationStores(...)", "stores"); - /// Opens the store providers.calls names, or the built-in one. + /// Opens the store providers.conversations names, or the built-in one. /// The loaded document. /// The chain a credential resolves through, or . /// The vendors this host supports. @@ -28,19 +28,19 @@ public static class CallStoreFactory /// /// The document names a kind no adapter serves, or a kind two adapters answer to. /// - public static ValueTask OpenAsync( + public static ValueTask OpenAsync( AgentCoreConfiguration configuration, ISecretResolverPort? secrets, - IReadOnlyList adapters, + IReadOnlyList adapters, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(adapters); - if (configuration.Providers?.Calls is not { } entry + if (configuration.Providers?.Conversations is not { } entry || string.Equals(entry.Kind, MemoryKind, StringComparison.OrdinalIgnoreCase)) { - return ValueTask.FromResult(new InMemoryCallStore()); + return ValueTask.FromResult(new InMemoryConversationStore()); } var adapter = VendorAdapterSelector.Select(entry.Kind, adapters, Seam); diff --git a/src/AgentCore.Application/Conversation/Conversations.cs b/src/AgentCore.Application/Conversation/Conversations.cs new file mode 100644 index 00000000..21340dd2 --- /dev/null +++ b/src/AgentCore.Application/Conversation/Conversations.cs @@ -0,0 +1,199 @@ +using System.Text.Json; +using AgentCore.Application.Blobs; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Conversation; + +/// +/// Everything a host or a consumer does with a stored conversation: its row, its words, and the files it +/// published. The one door; the stores behind it are adapters nobody else needs to name. A consumer +/// takes it as ; the turn loop and the sweeper take it as +/// . +/// +public sealed class Conversations : IConversations, IConversationStore +{ + private readonly IConversationStore _conversations; + + private readonly IBlobStore? _blobs; + + /// Makes the door over the stores the document opened. + /// The store the rows and words live in. + /// The store the published files live in, or when the document names none. + public Conversations(IConversationStore conversations, IBlobStore? blobs) + { + ArgumentNullException.ThrowIfNull(conversations); + + _conversations = conversations; + _blobs = blobs; + } + + /// The adapter the rows live in. For a host checking which vendor it opened; go through the door for everything else. + public IConversationStore Store => _conversations; + + /// + public async ValueTask LoadAsync(string conversationId, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(conversationId); + + var record = await _conversations.GetAsync(conversationId, cancellationToken).ConfigureAwait(false); + + if (record is null) + { + return null; + } + + var messages = await _conversations.ReadAsync(conversationId, cancellationToken).ConfigureAwait(false); + var files = await LinkFilesAsync(conversationId, messages.Select(message => message.Content), cancellationToken).ConfigureAwait(false); + + return new StoredConversation(record, messages, files); + } + + /// Links every published file the messages carry and the store kept, each name once, in first-seen order. + /// The conversation that owns the files. + /// The messages to read the references off: the stored transcript, or one turn's updates. + /// Cancels the signing. + /// One link per kept file. + public async Task> LinkFilesAsync( + string conversationId, + IEnumerable messages, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(conversationId); + ArgumentNullException.ThrowIfNull(messages); + + if (_blobs is null) + { + return []; + } + + List kept = []; + + foreach (var file in messages.SelectMany(message => message.Contents).OfType()) + { + if (!file.Kept || !BlobName.IsSafe(file.Name)) + { + continue; + } + + BlobRef blob = new(conversationId, file.Name, file.MediaType, file.Length); + var at = kept.FindIndex(known => string.Equals(known.Name, blob.Name, StringComparison.Ordinal)); + + if (at >= 0) + { + kept[at] = blob; + } + else + { + kept.Add(blob); + } + } + + List links = []; + + foreach (var blob in kept) + { + var url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); + links.Add(new FileLink(blob, url)); + } + + return links; + } + + /// + public async ValueTask DeleteAsync(string conversationId, CancellationToken cancellationToken = default) + { + if (_blobs is not null) + { + await _blobs.DeleteByOwnerAsync(conversationId, cancellationToken).ConfigureAwait(false); + } + + await _conversations.DeleteAsync(conversationId, cancellationToken).ConfigureAwait(false); + } + + /// + public ValueTask CreateAsync(string conversationId, CancellationToken cancellationToken = default) + => _conversations.CreateAsync(conversationId, cancellationToken); + + /// + public ValueTask GetAsync(string conversationId, CancellationToken cancellationToken = default) + => _conversations.GetAsync(conversationId, cancellationToken); + + /// + public ValueTask ListAsync( + string principalKey, + string? after, + int limit, + ConversationStatus? status = null, + CancellationToken cancellationToken = default) + => _conversations.ListAsync(principalKey, after, limit, status, cancellationToken); + + /// + public ValueTask RenameAsync(string conversationId, string title, CancellationToken cancellationToken = default) + => _conversations.RenameAsync(conversationId, title, cancellationToken); + + /// + public ValueTask SetStatusAsync(string conversationId, ConversationStatus status, CancellationToken cancellationToken = default) + => _conversations.SetStatusAsync(conversationId, status, cancellationToken); + + /// + public ValueTask SetCustomAsync(string conversationId, JsonElement? custom, CancellationToken cancellationToken = default) + => _conversations.SetCustomAsync(conversationId, custom, cancellationToken); + + /// + public ValueTask SetExternalIdAsync(string conversationId, string? externalId, CancellationToken cancellationToken = default) + => _conversations.SetExternalIdAsync(conversationId, externalId, cancellationToken); + + /// + public ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, + CancellationToken cancellationToken = default) + => _conversations.AppendAsync(conversationId, messages, state, cancellationToken); + + /// + public ValueTask AppendMessageAsync(string conversationId, ChatMessage message, CancellationToken cancellationToken = default) + => _conversations.AppendMessageAsync(conversationId, message, cancellationToken); + + /// + public ValueTask RewriteAsync(string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => _conversations.RewriteAsync(conversationId, messageId, content, cancellationToken); + + /// + public ValueTask> ReadAsync(string conversationId, CancellationToken cancellationToken = default) + => _conversations.ReadAsync(conversationId, cancellationToken); + + /// + public ValueTask TruncateAsync(string conversationId, int fromOrdinal, CancellationToken cancellationToken = default) + => _conversations.TruncateAsync(conversationId, fromOrdinal, cancellationToken); + + /// + public ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default) + => _conversations.EraseAsync(conversationId, cancellationToken); + + /// + public ValueTask SweepAsync(TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) + => _conversations.SweepAsync(retention, batchSize, cancellationToken); + + /// + public ValueTask AttachPrincipalAsync(string conversationId, string principalKey, string role, CancellationToken cancellationToken = default) + => _conversations.AttachPrincipalAsync(conversationId, principalKey, role, cancellationToken); + + /// + public ValueTask DetachPrincipalAsync(string conversationId, string principalKey, CancellationToken cancellationToken = default) + => _conversations.DetachPrincipalAsync(conversationId, principalKey, cancellationToken); + + /// + public ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) + => _conversations.SaveContinuationAsync(continuationId, envelope, cancellationToken); + + /// + public ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + => _conversations.GetContinuationAsync(continuationId, cancellationToken); + + /// + public ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + => _conversations.DeleteContinuationAsync(continuationId, cancellationToken); +} diff --git a/src/AgentCore.Application/Conversation/Memory/InMemoryConversationStore.cs b/src/AgentCore.Application/Conversation/Memory/InMemoryConversationStore.cs new file mode 100644 index 00000000..d3563838 --- /dev/null +++ b/src/AgentCore.Application/Conversation/Memory/InMemoryConversationStore.cs @@ -0,0 +1,425 @@ +using System.Text.Json; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Conversation.Memory; + +/// The store backing that keeps every row in this process: a conversation, and its words. +public sealed class InMemoryConversationStore : IConversationStore +{ + private readonly Lock _lock = new(); + + private readonly Dictionary _conversations = []; + + private readonly Dictionary<(string ConversationId, int Ordinal), ConversationMessage> _rows = []; + + /// The resume blob of each conversation, beside the row rather than on it. + private readonly Dictionary _state = []; + + /// The next free ordinal of each conversation. Never rewound, even when its words are. + private readonly Dictionary _nextOrdinal = []; + + private readonly HashSet<(string ConversationId, string PrincipalKey)> _claims = []; + + /// One serialized agent session per continuation id, beside the conversations. + private readonly Dictionary _continuations = []; + + private readonly TimeProvider _time; + + /// Creates the store. + /// Where created_at comes from, or for the system clock. + public InMemoryConversationStore(TimeProvider? timeProvider = null) => _time = timeProvider ?? TimeProvider.System; + + /// + public ValueTask CreateAsync(string conversationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + lock (_lock) + { + if (!_conversations.TryGetValue(conversationId, out var existing)) + { + var now = _time.GetUtcNow(); + existing = new ConversationRecord(conversationId, null, ConversationStatus.Regular, null, null, now, null); + _conversations[conversationId] = existing; + } + + return ValueTask.FromResult(existing with + { + State = _state.GetValueOrDefault(conversationId), + NextOrdinal = _nextOrdinal.GetValueOrDefault(conversationId), + }); + } + } + + /// + public ValueTask GetAsync(string conversationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + lock (_lock) + { + var conversation = _conversations.GetValueOrDefault(conversationId); + + return ValueTask.FromResult(conversation is null + ? null + : conversation with + { + State = _state.GetValueOrDefault(conversationId), + NextOrdinal = _nextOrdinal.GetValueOrDefault(conversationId), + }); + } + } + + /// + public ValueTask ListAsync( + string principalKey, + string? after, + int limit, + ConversationStatus? status = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(principalKey); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limit); + + var hasCursor = ConversationCursor.TryDecode(after, out var sortAt, out var cursorId); + + lock (_lock) + { + var ordered = _claims + .Where(claim => claim.PrincipalKey == principalKey) + .Select(claim => _conversations.GetValueOrDefault(claim.ConversationId)) + .OfType() + .Where(conversation => status is null || conversation.Status == status) + .Where(conversation => !hasCursor + || SortValue(conversation) < sortAt + || (SortValue(conversation) == sortAt + && string.CompareOrdinal(conversation.ConversationId, cursorId) < 0)) + .OrderByDescending(SortValue) + .ThenByDescending(conversation => conversation.ConversationId, StringComparer.Ordinal) + .Take(limit) + .ToList(); + + var next = ordered.Count == limit + ? ConversationCursor.Encode(SortValue(ordered[^1]), ordered[^1].ConversationId) + : null; + + return ValueTask.FromResult(new ConversationPage(ordered, next)); + } + } + + /// + public ValueTask RenameAsync(string conversationId, string title, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + ArgumentNullException.ThrowIfNull(title); + + return Amend(conversationId, conversation => conversation with { Title = title }); + } + + /// + public ValueTask SetStatusAsync(string conversationId, ConversationStatus status, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + return Amend(conversationId, conversation => conversation with { Status = status }); + } + + /// + public ValueTask SetCustomAsync( + string conversationId, JsonElement? custom, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + return Amend(conversationId, conversation => conversation with { Custom = custom?.Clone() }); + } + + /// + public ValueTask SetExternalIdAsync( + string conversationId, string? externalId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + return Amend(conversationId, conversation => conversation with { ExternalId = externalId }); + } + + /// + public ValueTask DeleteAsync(string conversationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + _conversations.Remove(conversationId); + + _claims.RemoveWhere(claim => claim.ConversationId == conversationId); + + _state.Remove(conversationId); + + _nextOrdinal.Remove(conversationId); + + _continuations.Remove(conversationId); + + RemoveWords(conversationId); + + return default; + } + + /// + public ValueTask SweepAsync( + TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(retention, TimeSpan.Zero); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(batchSize); + + lock (_lock) + { + var cutoff = _time.GetUtcNow() - retention; + + // SortValue is the clock ListAsync ranks by, so a conversation is swept exactly when it has + // fallen off the end of the list. + // + // batchSize is read for its guard and then ignored. It exists to keep one transaction + // short in a durable backing, and this store has no transaction; honouring it here would + // only make the caller loop for the same answer. + var going = _conversations.Values + .Where(conversation => SortValue(conversation) < cutoff) + .Select(conversation => conversation.ConversationId) + .ToList(); + + foreach (var conversationId in going) + { + _conversations.Remove(conversationId); + + _claims.RemoveWhere(claim => claim.ConversationId == conversationId); + + _state.Remove(conversationId); + + _nextOrdinal.Remove(conversationId); + + _continuations.Remove(conversationId); + + RemoveWords(conversationId); + } + + return ValueTask.FromResult(going.Count); + } + } + + /// + public ValueTask AttachPrincipalAsync( + string conversationId, string principalKey, string role, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + ArgumentNullException.ThrowIfNull(principalKey); + ArgumentNullException.ThrowIfNull(role); + + lock (_lock) + { + _claims.Add((conversationId, principalKey)); + } + + return default; + } + + /// + public ValueTask DetachPrincipalAsync( + string conversationId, string principalKey, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + ArgumentNullException.ThrowIfNull(principalKey); + + lock (_lock) + { + _claims.Remove((conversationId, principalKey)); + } + + return default; + } + + /// + public ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + ArgumentNullException.ThrowIfNull(messages); + + if (messages.Count == 0) + { + return ValueTask.FromResult>([]); + } + + lock (_lock) + { + if (!_conversations.TryGetValue(conversationId, out var conversation)) + { + throw new InvalidOperationException($"Store 0 holds no conversation '{conversationId}' to append words to."); + } + + var fallbackTurnIndex = _state.GetValueOrDefault(conversationId)?.NextTurnIndex ?? 0; + var first = _nextOrdinal.GetValueOrDefault(conversationId); + + var rows = new List(messages.Count); + for (var index = 0; index < messages.Count; index++) + { + var draft = messages[index]; + ConversationMessage row = new( + conversationId, first + index, draft.TurnIndex ?? fallbackTurnIndex, draft.Content, draft.MessageId); + + rows.Add(row); + _rows.Add((row.ConversationId, row.Ordinal), row); + } + + _nextOrdinal[conversationId] = first + messages.Count; + + var now = _time.GetUtcNow(); + _conversations[conversationId] = conversation with { LastMessageAt = now }; + + if (state is not null) + { + _state[conversationId] = state; + } + + return ValueTask.FromResult>(rows); + } + } + + /// + public ValueTask RewriteAsync( + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + ArgumentException.ThrowIfNullOrEmpty(messageId); + ArgumentNullException.ThrowIfNull(content); + + lock (_lock) + { + foreach (var pair in _rows) + { + if (pair.Key.ConversationId != conversationId || pair.Value.MessageId != messageId) + { + continue; + } + + _rows[pair.Key] = pair.Value with { Content = content }; + break; + } + } + + return default; + } + + /// + public ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + lock (_lock) + { + IReadOnlyList rows = + [.. _rows.Values.Where(row => row.ConversationId == conversationId).OrderBy(row => row.Ordinal)]; + + return ValueTask.FromResult(rows); + } + } + + /// + public ValueTask TruncateAsync( + string conversationId, int fromOrdinal, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + lock (_lock) + { + var going = _rows.Keys + .Where(key => string.Equals(key.ConversationId, conversationId, StringComparison.Ordinal) + && key.Ordinal >= fromOrdinal) + .ToList(); + + foreach (var key in going) + { + _rows.Remove(key); + } + + return ValueTask.FromResult(going.Count); + } + } + + /// + public ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(conversationId); + + lock (_lock) + { + return ValueTask.FromResult(RemoveWords(conversationId)); + } + } + + /// + public ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(continuationId); + + lock (_lock) + { + _continuations[continuationId] = envelope.Clone(); + } + + return default; + } + + /// + public ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(continuationId); + + lock (_lock) + { + return ValueTask.FromResult( + _continuations.TryGetValue(continuationId, out var envelope) ? envelope : null); + } + } + + /// + public ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(continuationId); + + lock (_lock) + { + _continuations.Remove(continuationId); + } + + return default; + } + + private static DateTimeOffset SortValue(ConversationRecord conversation) => conversation.LastMessageAt ?? conversation.CreatedAt; + + private int RemoveWords(string conversationId) + { + var going = _rows.Keys.Where(key => key.ConversationId == conversationId).ToList(); + foreach (var key in going) + { + _rows.Remove(key); + } + + return going.Count; + } + + private ValueTask Amend(string conversationId, Func amend) + { + lock (_lock) + { + if (_conversations.TryGetValue(conversationId, out var conversation)) + { + _conversations[conversationId] = amend(conversation); + } + } + + return default; + } +} diff --git a/src/AgentCore.Application/Conversation/StoredConversation.cs b/src/AgentCore.Application/Conversation/StoredConversation.cs new file mode 100644 index 00000000..1f976d38 --- /dev/null +++ b/src/AgentCore.Application/Conversation/StoredConversation.cs @@ -0,0 +1,16 @@ +using AgentCore.Application.Blobs; +using AgentCore.Application.Transcript; + +namespace AgentCore.Application.Conversation; + +/// One conversation as the stores hold it: ready for a browser, nothing left to join. +/// The row. +/// Every stored message, oldest first. +/// +/// One link per file the messages name and the blob store kept, each name once, in first-seen order. +/// The links expire; read them out at once rather than keeping this record around. +/// +public sealed record StoredConversation( + ConversationRecord Conversation, + IReadOnlyList Messages, + IReadOnlyList Files); diff --git a/src/AgentCore.Application/Diagnostics/AgentCoreTelemetry.cs b/src/AgentCore.Application/Diagnostics/AgentCoreTelemetry.cs index 1edebca9..da3b2bf9 100644 --- a/src/AgentCore.Application/Diagnostics/AgentCoreTelemetry.cs +++ b/src/AgentCore.Application/Diagnostics/AgentCoreTelemetry.cs @@ -69,11 +69,11 @@ public static class AgentCoreTelemetry description: "Turns the moderation endpoint checked, by outcome."); /// Opens the span of one turn. - /// The id of the call. It goes on the span, and never on a metric. + /// The id of the conversation. It goes on the span, and never on a metric. /// The zero-based index of the turn. /// The stage the turn speaks in. /// The span, or when nothing listens. - internal static Activity? StartTurn(string callId, int turnIndex, string stageBefore) + internal static Activity? StartTurn(string conversationId, int turnIndex, string stageBefore) { Activity? activity = Source.StartActivity(TurnActivityName, ActivityKind.Internal); if (activity is null) @@ -81,7 +81,7 @@ public static class AgentCoreTelemetry return null; } - activity.SetTag("gen_ai.conversation.id", callId); + activity.SetTag("gen_ai.conversation.id", conversationId); activity.SetTag("agentcore.turn.index", turnIndex); if (stageBefore.Length > 0) @@ -121,7 +121,7 @@ internal static void EndTurn( if (failure is not null) { - // A failed turn still speaks a line, so the call is alive. The span says the turn failed + // A failed turn still speaks a line, so the conversation is alive. The span says the turn failed // and the reason names the row of section 8.7 it met. activity.SetStatus(ActivityStatusCode.Error, failure); } diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index b488445b..8ac1ab75 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -11,38 +11,38 @@ internal static partial class Log { /// Section 8.7, row two. The extractor returned an invalid object. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn that just ran. /// Why the extractor produced nothing. [LoggerMessage( EventId = 1, Level = LogLevel.Warning, - Message = "The extractor of call {CallId} produced nothing for turn {TurnIndex}: {Reason} " - + "The slots stay unchanged and the call continues.")] - public static partial void ExtractionFailed(ILogger logger, string callId, int turnIndex, string reason); + Message = "The extractor of conversation {ConversationId} produced nothing for turn {TurnIndex}: {Reason} " + + "The slots stay unchanged and the conversation continues.")] + public static partial void ExtractionFailed(ILogger logger, string conversationId, int turnIndex, string reason); /// Section 8.7, row six. A tool failed four times in a row and the run threw. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn that just ran. /// The message of the fault. [LoggerMessage( EventId = 2, Level = LogLevel.Error, - Message = "A tool of call {CallId} failed four times in turn {TurnIndex}: {Reason} " - + "The turn spoke the fallback and the call continues.")] - public static partial void ToolBudgetSpent(ILogger logger, string callId, int turnIndex, string reason); + Message = "A tool of conversation {ConversationId} failed four times in turn {TurnIndex}: {Reason} " + + "The turn spoke the fallback and the conversation continues.")] + public static partial void ToolBudgetSpent(ILogger logger, string conversationId, int turnIndex, string reason); /// Section 8.7, last row. The run returned quietly with no text. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn that just ran. [LoggerMessage( EventId = 3, Level = LogLevel.Warning, - Message = "Turn {TurnIndex} of call {CallId} returned an empty reply, so it spoke the fallback. " + Message = "Turn {TurnIndex} of conversation {ConversationId} returned an empty reply, so it spoke the fallback. " + "The run reached 40 tool rounds, or the model answered nothing.")] - public static partial void EmptyReply(ILogger logger, string callId, int turnIndex); + public static partial void EmptyReply(ILogger logger, string conversationId, int turnIndex); /// Section 8.7, row five. A guard threw at run time, or its rule did not parse. /// The logger of the composition root. @@ -51,79 +51,79 @@ internal static partial class Log [LoggerMessage( EventId = 4, Level = LogLevel.Warning, - Message = "The guard {Guard} failed. It is treated as false and the call continues.")] + Message = "The guard {Guard} failed. It is treated as false and the conversation continues.")] public static partial void GuardFailed(ILogger logger, string guard, Exception exception); - /// An observer of the call refused an event, or faulted behind its own enqueue. + /// An observer of the conversation refused an event, or faulted behind its own enqueue. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The wire token of the event kind. /// The cause. [LoggerMessage( EventId = 5, Level = LogLevel.Error, - Message = "The audit sink did not accept the {Kind} event of call {CallId}. " + Message = "The audit sink did not accept the {Kind} event of conversation {ConversationId}. " + "The turn continues and the chain has a gap.")] - public static partial void AuditAppendFailed(ILogger logger, string callId, string kind, Exception exception); + public static partial void AuditAppendFailed(ILogger logger, string conversationId, string kind, Exception exception); /// The moderation endpoint flagged what the caller said, so the agent refused the turn. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn. /// The categories the endpoint flagged, comma-separated, in its order. [LoggerMessage( EventId = 6, Level = LogLevel.Warning, - Message = "Moderation flagged turn {TurnIndex} of call {CallId} for {Categories}, " + Message = "Moderation flagged turn {TurnIndex} of conversation {ConversationId} for {Categories}, " + "so the agent refused it and spoke the refusal line.")] - public static partial void PromptRefused(ILogger logger, string callId, int turnIndex, string categories); + public static partial void PromptRefused(ILogger logger, string conversationId, int turnIndex, string categories); /// The moderation endpoint did not answer, so the turn ran unchecked. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn. /// What went wrong. [LoggerMessage( EventId = 7, Level = LogLevel.Warning, - Message = "Moderation did not answer for turn {TurnIndex} of call {CallId} ({Reason}). " + Message = "Moderation did not answer for turn {TurnIndex} of conversation {ConversationId} ({Reason}). " + "The turn ran unchecked, because moderation fails open.")] - public static partial void ModerationUnavailable(ILogger logger, string callId, int turnIndex, string reason); + public static partial void ModerationUnavailable(ILogger logger, string conversationId, int turnIndex, string reason); /// The audit queue had no room, so the event was dropped. /// The logger of the queue. - /// The id of the call the dropped event belongs to. + /// The id of the conversation the dropped event belongs to. /// The identity of the dropped event. [LoggerMessage( EventId = 8, Level = LogLevel.Error, - Message = "The audit queue was full, so event {EventId} of call {CallId} was dropped. " - + "The call continues and the chain has a gap.")] - public static partial void AuditQueueFull(ILogger logger, string callId, Guid eventId); + Message = "The audit queue was full, so event {EventId} of conversation {ConversationId} was dropped. " + + "The conversation continues and the chain has a gap.")] + public static partial void AuditQueueFull(ILogger logger, string conversationId, Guid eventId); /// A store 1 write was refused, so the turn has no durable record. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn that was being written. /// The cause. [LoggerMessage( EventId = 9, Level = LogLevel.Warning, - Message = "The transcript store did not accept turn {TurnIndex} of call {CallId}. " - + "The call continues and the turn has no durable record.")] - public static partial void TranscriptWriteFailed(ILogger logger, string callId, int turnIndex, Exception exception); + Message = "The transcript store did not accept turn {TurnIndex} of conversation {ConversationId}. " + + "The conversation continues and the turn has no durable record.")] + public static partial void TranscriptWriteFailed(ILogger logger, string conversationId, int turnIndex, Exception exception); /// A barge-in cut a reply, so the record now holds what the caller heard. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn whose reply was cut. /// How much of the reply was played, as the vendor reported it. [LoggerMessage( EventId = 10, Level = LogLevel.Debug, - Message = "A barge-in cut the reply of turn {TurnIndex} of call {CallId} " + Message = "A barge-in cut the reply of turn {TurnIndex} of conversation {ConversationId} " + "after {PlayedMilliseconds} ms, so the record holds what the caller heard.")] - public static partial void ReplyTruncated(ILogger logger, string callId, int turnIndex, double playedMilliseconds); + public static partial void ReplyTruncated(ILogger logger, string conversationId, int turnIndex, double playedMilliseconds); /// One knowledge retrieval answered, with what it cost and what it returned. /// The logger of the knowledge provider. @@ -146,32 +146,32 @@ public static partial void KnowledgeRetrieved( EventId = 12, Level = LogLevel.Error, Message = "The knowledge base did not answer agent {Agent}. The turn was told it is " - + "unreachable and the call continues. {Record}")] + + "unreachable and the conversation continues. {Record}")] public static partial void KnowledgeRetrievalFailed( ILogger logger, string agent, KnowledgeAuditRecord.LogView record, Exception exception); - /// A resumed call could not restore part of its stored state, so it went on without it. + /// A resumed conversation could not restore part of its stored state, so it went on without it. /// The logger of the session. - /// The id of the call being resumed. + /// The id of the conversation being resumed. /// Which part was dropped, and why it would not go back. [LoggerMessage( EventId = 13, Level = LogLevel.Warning, - Message = "Call {CallId} could not restore part of its stored state: {Reason} " - + "The call resumes without that part.")] - public static partial void StateRestorePartial(ILogger logger, string callId, string reason); + Message = "Conversation {ConversationId} could not restore part of its stored state: {Reason} " + + "The conversation resumes without that part.")] + public static partial void StateRestorePartial(ILogger logger, string conversationId, string reason); - /// One call had its tail withdrawn, because a caller sent an earlier message again. + /// One conversation had its tail withdrawn, because a caller sent an earlier message again. /// The logger of the history provider. - /// The call that was cut. + /// The conversation that was cut. /// The first ordinal withdrawn. It went too. - /// The turn the call had reached when the cut arrived. + /// The turn the conversation had reached when the cut arrived. [LoggerMessage( EventId = 14, Level = LogLevel.Debug, - Message = "An edit withdrew call {CallId} from ordinal {FromOrdinal} onward, " + Message = "An edit withdrew conversation {ConversationId} from ordinal {FromOrdinal} onward, " + "at turn {TurnIndex}.")] - public static partial void CallTruncated(ILogger logger, string callId, int fromOrdinal, int turnIndex); + public static partial void ConversationTruncated(ILogger logger, string conversationId, int fromOrdinal, int turnIndex); /// /// One turn composed its knowledge scope. Every facet logged @@ -179,16 +179,16 @@ public static partial void KnowledgeRetrievalFailed( /// names a key nothing ever sets. /// /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn. /// Where each facet's value came from. [LoggerMessage( EventId = 15, Level = LogLevel.Debug, - Message = "Call {CallId} turn {TurnIndex} composed the knowledge scope {Origins}.")] + Message = "Conversation {ConversationId} turn {TurnIndex} composed the knowledge scope {Origins}.")] public static partial void KnowledgeScopeComposed( ILogger logger, - string callId, + string conversationId, int turnIndex, IReadOnlyDictionary origins); @@ -216,7 +216,7 @@ public static partial void KnowledgeScopeComposed( EventId = 17, Level = LogLevel.Error, Message = "The probe of agent {Agent} did not answer for facet {Facet}. The turn was told the " - + "knowledge base holds nothing and the call continues.")] + + "knowledge base holds nothing and the conversation continues.")] public static partial void KnowledgeProbeFailed(ILogger logger, string agent, string facet, Exception exception); /// An agent declared a hosted tool, and its model reports it cannot run it. @@ -226,7 +226,7 @@ public static partial void KnowledgeScopeComposed( /// The marker type, such as HostedWebSearchTool, so the reader knows which hosted capability was missing. /// /// A phrase naming the model, such as "the model 'reply'" or "this agent's default - /// model" when the agent names none. Built at the call site so this message never renders an + /// model" when the agent names none. Built at the conversation site so this message never renders an /// empty pair of quotes. /// [LoggerMessage( @@ -240,46 +240,46 @@ public static partial void KnowledgeScopeComposed( /// Store 1 could not be read as a turn opened, so the turn ran on the words already held. /// The logger of the session. - /// The id of the call. + /// The id of the conversation. /// The zero-based index of the turn that was opening. /// The cause. [LoggerMessage( EventId = 19, Level = LogLevel.Warning, - Message = "The transcript store could not be read as turn {TurnIndex} of call {CallId} opened. " + Message = "The transcript store could not be read as turn {TurnIndex} of conversation {ConversationId} opened. " + "The turn runs on the words the session already holds; a message appended outside a " + "turn since the last read is not among them.")] - public static partial void TranscriptResyncFailed(ILogger logger, string callId, int turnIndex, Exception exception); + public static partial void TranscriptResyncFailed(ILogger logger, string conversationId, int turnIndex, Exception exception); - /// A call's workspace folder could not be deleted when the call ended. + /// A conversation's workspace folder could not be deleted when the conversation ended. /// The logger of the session. /// The folder that could not be deleted. /// The cause. [LoggerMessage( EventId = 20, Level = LogLevel.Warning, - Message = "Could not delete the call workspace at '{Path}'.")] + Message = "Could not delete the conversation workspace at '{Path}'.")] public static partial void WorkspaceDeleteFailed(ILogger logger, string path, Exception exception); - /// A call's shell executor could not be disposed when the call ended. + /// A conversation's shell executor could not be disposed when the conversation ended. /// The logger of the session. - /// The call's workspace folder, whose shell failed to dispose. + /// The conversation's workspace folder, whose shell failed to dispose. /// The cause. [LoggerMessage( EventId = 21, Level = LogLevel.Warning, - Message = "Could not dispose a shell: executor of the call at workspace '{Workspace}'.")] + Message = "Could not dispose a shell: executor of the conversation at workspace '{Workspace}'.")] public static partial void ShellDisposeFailed(ILogger logger, string workspace, Exception exception); - /// A call's background agent sessions could not be released when the call ended. + /// A conversation's background agent sessions could not be released when the conversation ended. /// The logger of the session. - /// The id of the call whose children were being released. + /// The id of the conversation whose children were being released. /// The cause. [LoggerMessage( EventId = 22, Level = LogLevel.Warning, - Message = "Could not release the background agent sessions of the call '{CallId}'.")] - public static partial void BackgroundReleaseFailed(ILogger logger, string callId, Exception exception); + Message = "Could not release the background agent sessions of the conversation '{ConversationId}'.")] + public static partial void BackgroundReleaseFailed(ILogger logger, string conversationId, Exception exception); /// A workspace file could not be published: the run had no call to own it. /// The logger of the tool. @@ -287,29 +287,29 @@ public static partial void KnowledgeScopeComposed( [LoggerMessage( EventId = 23, Level = LogLevel.Warning, - Message = "A file published through '{Tool}' was not kept: the run has no call id. " - + "Files are kept only for a run through a CallSession, or a background child of one.")] + Message = "A file published through '{Tool}' was not kept: the run has no conversation id. " + + "Files are kept only for a run through a ConversationSession, or a background child of one.")] public static partial void SandboxFileHasNoOwner(ILogger logger, string tool); /// A workspace file was refused by name or by policy, and the model was told why. /// The logger of the tool. - /// The call that would have owned the file. + /// The conversation that would have owned the file. /// The file's name. /// Why it was refused. [LoggerMessage( EventId = 24, Level = LogLevel.Warning, - Message = "The file '{Name}' of call {CallId} was not published: {Reason}.")] - public static partial void SandboxFileRefused(ILogger logger, string callId, string name, string reason); + Message = "The file '{Name}' of conversation {ConversationId} was not published: {Reason}.")] + public static partial void SandboxFileRefused(ILogger logger, string conversationId, string name, string reason); /// A workspace file could not be read or stored, and the model was told so. /// The logger of the tool. - /// The call that would have owned the file. + /// The conversation that would have owned the file. /// The file's name. /// The cause. [LoggerMessage( EventId = 25, Level = LogLevel.Warning, - Message = "The file '{Name}' of call {CallId} could not be published.")] - public static partial void SandboxFileCaptureFailed(ILogger logger, string callId, string name, Exception exception); + Message = "The file '{Name}' of conversation {ConversationId} could not be published.")] + public static partial void SandboxFileCaptureFailed(ILogger logger, string conversationId, string name, Exception exception); } diff --git a/src/AgentCore.Application/Diagnostics/LoggingCallObserver.cs b/src/AgentCore.Application/Diagnostics/LoggingConversationObserver.cs similarity index 55% rename from src/AgentCore.Application/Diagnostics/LoggingCallObserver.cs rename to src/AgentCore.Application/Diagnostics/LoggingConversationObserver.cs index 8e13b0a8..f55df47c 100644 --- a/src/AgentCore.Application/Diagnostics/LoggingCallObserver.cs +++ b/src/AgentCore.Application/Diagnostics/LoggingConversationObserver.cs @@ -9,7 +9,7 @@ namespace AgentCore.Application.Diagnostics; /// /// Writes the "log once" rows of section 8.7, one line for each fact that earns one. /// -internal sealed class LoggingCallObserver : ICallObserver +internal sealed class LoggingConversationObserver : IConversationObserver { /// The turn a line names when the fact carried no index. No turn has it. private const int NoTurn = -1; @@ -21,85 +21,85 @@ internal sealed class LoggingCallObserver : ICallObserver /// Where the lines go, or for . The /// library never throws for want of one. /// - public LoggingCallObserver(ILogger? logger = null) => _logger = logger ?? NullLogger.Instance; + public LoggingConversationObserver(ILogger? logger = null) => _logger = logger ?? NullLogger.Instance; /// - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { - ArgumentNullException.ThrowIfNull(callEvent); + ArgumentNullException.ThrowIfNull(conversationEvent); - switch (callEvent.Kind) + switch (conversationEvent.Kind) { - case CallEventKind.ToolFailed: - // Section 8.7, row six. The turn spoke the fallback and the call stays alive, so + case ConversationEventKind.ToolFailed: + // Section 8.7, row six. The turn spoke the fallback and the conversation stays alive, so // nothing here is fatal, and the level says Error because a spent retry budget is a // defect in the tool. // // This kind is now raised at two altitudes, and only the TURN one earns a line. A - // fact that carries a tool call id is one failing call, and a turn spends up to four - // of them; the chain of D23 keeps every one, which is where a record of a call + // fact that carries a tool call id is one failing conversation, and a turn spends up to four + // of them; the chain of D23 keeps every one, which is where a record of a conversation // belongs, and section 8.7 asks for one line and not four. The turn-level fact - // carries no call id, because the fault reaches the session with no function name on + // carries no conversation id, because the fault reaches the session with no function name on // it at all, so the absent key is exactly the test. - if (callEvent.Payload.ContainsKey(AuditPayloadKeys.ToolCallId)) + if (conversationEvent.Payload.ContainsKey(AuditPayloadKeys.ToolCallId)) { break; } Log.ToolBudgetSpent( _logger, - callEvent.CallId, - TurnOf(callEvent), - Detail(callEvent, AuditPayloadKeys.ToolError)); + conversationEvent.ConversationId, + TurnOf(conversationEvent), + Detail(conversationEvent, AuditPayloadKeys.ToolError)); break; - case CallEventKind.EmptyReply: + case ConversationEventKind.EmptyReply: // Section 8.7, last row. On a voice call the silence is the failure. - Log.EmptyReply(_logger, callEvent.CallId, TurnOf(callEvent)); + Log.EmptyReply(_logger, conversationEvent.ConversationId, TurnOf(conversationEvent)); break; - case CallEventKind.ExtractionFailed: - // Section 8.7, row two. The slots stay unchanged and the call continues, so this is a + case ConversationEventKind.ExtractionFailed: + // Section 8.7, row two. The slots stay unchanged and the conversation continues, so this is a // warning and never an error. Log.ExtractionFailed( _logger, - callEvent.CallId, - TurnOf(callEvent), - Detail(callEvent, CallEventPayloadKeys.Reason)); + conversationEvent.ConversationId, + TurnOf(conversationEvent), + Detail(conversationEvent, ConversationEventPayloadKeys.Reason)); break; - case CallEventKind.PromptFlagged: + case ConversationEventKind.PromptFlagged: Log.PromptRefused( _logger, - callEvent.CallId, - TurnOf(callEvent), - Detail(callEvent, AuditPayloadKeys.ModerationCategories)); + conversationEvent.ConversationId, + TurnOf(conversationEvent), + Detail(conversationEvent, AuditPayloadKeys.ModerationCategories)); break; - case CallEventKind.ModerationUnavailable: + case ConversationEventKind.ModerationUnavailable: // A vendor that did not answer is not a defect in this library, so it is a warning. Log.ModerationUnavailable( _logger, - callEvent.CallId, - TurnOf(callEvent), - Detail(callEvent, CallEventPayloadKeys.Reason)); + conversationEvent.ConversationId, + TurnOf(conversationEvent), + Detail(conversationEvent, ConversationEventPayloadKeys.Reason)); break; - case CallEventKind.StateRestorePartial: - // Not a turn's fact and not section 8.7's: it happens once, as the call opens, and it + case ConversationEventKind.StateRestorePartial: + // Not a turn's fact and not section 8.7's: it happens once, as the conversation opens, and it // carries no turn index. It earns a line all the same because it is the only signal - // there is. A document change costs a resumed call its stage or a slot, the chain + // there is. A document change costs a resumed conversation its stage or a slot, the chain // stores no diagnostic kind, and the caller notices only that the agent has forgotten // them — so without this line the fault is visible to nobody but a host that wrote an - // ICallObserver of its own. + // IConversationObserver of its own. Log.StateRestorePartial( _logger, - callEvent.CallId, - Detail(callEvent, CallEventPayloadKeys.Reason)); + conversationEvent.ConversationId, + Detail(conversationEvent, ConversationEventPayloadKeys.Reason)); break; default: - // The chain of D23 is the record of a normal call, and a log is not. + // The chain of D23 is the record of a normal conversation, and a log is not. break; } @@ -107,12 +107,12 @@ public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancell } /// Reads the turn a line names. - /// The fact being reported. + /// The fact being reported. /// Its turn index, or when it carried none. - private static int TurnOf(CallEvent callEvent) => callEvent.TurnIndex ?? NoTurn; + private static int TurnOf(ConversationEvent conversationEvent) => conversationEvent.TurnIndex ?? NoTurn; /// Reads one detail a line reports. - /// The fact being reported. + /// The fact being reported. /// The payload key the detail sits under. /// The detail, or an empty string when the fact carried none. /// @@ -120,6 +120,6 @@ public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancell /// for a payload. The line is still written: what happened is the point of it, and the detail is /// the part a reader may have to do without. /// - private static string Detail(CallEvent callEvent, string key) - => callEvent.Payload.TryGetValue(key, out string? detail) ? detail : string.Empty; + private static string Detail(ConversationEvent conversationEvent, string key) + => conversationEvent.Payload.TryGetValue(key, out string? detail) ? detail : string.Empty; } diff --git a/src/AgentCore.Application/Diagnostics/TelemetryCallObserver.cs b/src/AgentCore.Application/Diagnostics/TelemetryConversationObserver.cs similarity index 67% rename from src/AgentCore.Application/Diagnostics/TelemetryCallObserver.cs rename to src/AgentCore.Application/Diagnostics/TelemetryConversationObserver.cs index 8bd35957..76040910 100644 --- a/src/AgentCore.Application/Diagnostics/TelemetryCallObserver.cs +++ b/src/AgentCore.Application/Diagnostics/TelemetryConversationObserver.cs @@ -5,46 +5,46 @@ namespace AgentCore.Application.Diagnostics; /// -/// Counts the facts of a call on the three instruments of section 8.6. +/// Counts the facts of a conversation on the three instruments of section 8.6. /// -internal sealed class TelemetryCallObserver : ICallObserver +internal sealed class TelemetryConversationObserver : IConversationObserver { /// - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { - ArgumentNullException.ThrowIfNull(callEvent); + ArgumentNullException.ThrowIfNull(conversationEvent); - switch (callEvent.Kind) + switch (conversationEvent.Kind) { - case CallEventKind.PromptFlagged: + case ConversationEventKind.PromptFlagged: AgentCoreTelemetry.RecordModeration(AgentCoreTelemetry.ModerationFlagged); break; - case CallEventKind.ModerationUnavailable: + case ConversationEventKind.ModerationUnavailable: // The turn ran unchecked, because moderation fails open. This value is the only // record of that, so an operator alerts on it rather than on a log line. AgentCoreTelemetry.RecordModeration(AgentCoreTelemetry.ModerationUnavailable); break; - case CallEventKind.ModerationClean: + case ConversationEventKind.ModerationClean: AgentCoreTelemetry.RecordModeration(AgentCoreTelemetry.ModerationClean); break; - case CallEventKind.ToolFailed: + case ConversationEventKind.ToolFailed: AgentCoreTelemetry.RecordFailure(AgentCoreTelemetry.FailureTool); break; - case CallEventKind.EmptyReply: + case ConversationEventKind.EmptyReply: AgentCoreTelemetry.RecordFailure(AgentCoreTelemetry.FailureEmptyReply); break; - case CallEventKind.ExtractionFailed: + case ConversationEventKind.ExtractionFailed: AgentCoreTelemetry.RecordFailure(AgentCoreTelemetry.FailureExtraction); break; default: - // Six kinds reach here. Four of them — CallStarted, TurnCompleted, ReplyInterrupted - // and CallEnded — are counted below, as rows of the chain, and nowhere else. + // Six kinds reach here. Four of them — ConversationStarted, TurnCompleted, ReplyInterrupted + // and ConversationEnded — are counted below, as rows of the chain, and nowhere else. // // The other two, TranscriptWriteFailed and StateRestorePartial, are counted NOWHERE. // Neither has an instrument that would take it: agentcore.turn.failures counts what a @@ -58,11 +58,11 @@ public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancell } // Section 8.6 counts the events the turn loop handed to the sink, by kind, and it counted them - // whatever the sink then did with them: the old call sat at the top of CallSession.Append, + // whatever the sink then did with them: the old conversation sat at the top of ConversationSession.Append, // above the enqueue and above the try. A kind the chain does not store is not one of them, so // the six diagnostic kinds are counted by their failure or their verdict above, or not at all, // and never here. - if (CallEventKinds.TryGetAuditKind(callEvent.Kind, out AuditEventKind auditKind)) + if (ConversationEventKinds.TryGetAuditKind(conversationEvent.Kind, out AuditEventKind auditKind)) { AgentCoreTelemetry.RecordAuditEvent(AuditEventKinds.ToToken(auditKind)); } diff --git a/src/AgentCore.Application/Diagnostics/TelemetrySessionFactory.cs b/src/AgentCore.Application/Diagnostics/TelemetrySessionFactory.cs index 187cba33..2e19efc4 100644 --- a/src/AgentCore.Application/Diagnostics/TelemetrySessionFactory.cs +++ b/src/AgentCore.Application/Diagnostics/TelemetrySessionFactory.cs @@ -24,7 +24,7 @@ namespace AgentCore.Application.Diagnostics; /// public static class TelemetrySessionFactory { - /// What this seam calls itself, so the shared selector writes its failures. + /// What this seam conversations itself, so the shared selector writes its failures. private static readonly VendorSeam Seam = new("providers.telemetry", "/providers/telemetry/kind", "options.UseTelemetry(...)", "collectors"); diff --git a/src/AgentCore.Application/Embeddings/CompositeEmbeddingGeneratorFactory.cs b/src/AgentCore.Application/Embeddings/CompositeEmbeddingGeneratorFactory.cs index dc9704ba..0f272065 100644 --- a/src/AgentCore.Application/Embeddings/CompositeEmbeddingGeneratorFactory.cs +++ b/src/AgentCore.Application/Embeddings/CompositeEmbeddingGeneratorFactory.cs @@ -12,7 +12,7 @@ namespace AgentCore.Application.Embeddings; /// public static class CompositeEmbeddingGeneratorFactory { - /// What the embeddings field calls itself, so the shared selector writes its failures. + /// What the embeddings field conversations itself, so the shared selector writes its failures. private static readonly VendorSeam EmbeddingSeam = new("providers.embeddings.kind", "/providers/embeddings/kind", "options.UseEmbeddings(...)", "generators"); diff --git a/src/AgentCore.Application/Evaluation/ModerationEvaluatorFactory.cs b/src/AgentCore.Application/Evaluation/ModerationEvaluatorFactory.cs index 9f855517..1f0e19c1 100644 --- a/src/AgentCore.Application/Evaluation/ModerationEvaluatorFactory.cs +++ b/src/AgentCore.Application/Evaluation/ModerationEvaluatorFactory.cs @@ -24,7 +24,7 @@ namespace AgentCore.Application.Evaluation; /// public static class ModerationEvaluatorFactory { - /// What this seam calls itself, so the shared selector writes its failures. + /// What this seam conversations itself, so the shared selector writes its failures. private static readonly VendorSeam Seam = new("providers.moderation", "/providers/moderation/kind", "options.UseModeration(...)", "endpoints"); diff --git a/src/AgentCore.Application/Evaluation/ModerationVerdict.cs b/src/AgentCore.Application/Evaluation/ModerationVerdict.cs index 7a91f6f5..279921e3 100644 --- a/src/AgentCore.Application/Evaluation/ModerationVerdict.cs +++ b/src/AgentCore.Application/Evaluation/ModerationVerdict.cs @@ -16,7 +16,7 @@ namespace AgentCore.Application.Evaluation; /// /// It lives in Application/Evaluation/ and not beside the adapter, for two reasons. D3 forbids /// AgentCore.Application from referencing AgentCore.Infrastructure, and the code that -/// records a flagged turn sits in , which is in Application. And +/// records a flagged turn sits in , which is in Application. And /// D13 promises that replacing OpenAI with a self-hosted classifier behind the same /// is a one-file change, which holds only while this type names no vendor. /// diff --git a/src/AgentCore.Application/Evaluation/PromptModerator.cs b/src/AgentCore.Application/Evaluation/PromptModerator.cs index 07c598e8..37c0fdfd 100644 --- a/src/AgentCore.Application/Evaluation/PromptModerator.cs +++ b/src/AgentCore.Application/Evaluation/PromptModerator.cs @@ -18,17 +18,17 @@ namespace AgentCore.Application.Evaluation; /// /// D13 makes the moderation port and refuses a second one, so this type is /// not a port. It is the one place that turns an into the fact the -/// audit chain records, and it exists so that holds no registry +/// audit chain records, and it exists so that holds no registry /// key, no metric name, and no decode. /// /// /// D13 also says moderation checks EVERY turn, because the endpoint is free at any volume and counts -/// against no usage limit: "Sampling buys nothing when the call is free." Nothing here reads +/// against no usage limit: "Sampling buys nothing when the conversation is free." Nothing here reads /// , and nothing should. /// /// /// Nothing here catches. A timeout, a log line, and the decision to answer anyway all belong -/// to , which owns the turn and the clock. This type calls the +/// to , which owns the turn and the clock. This type calls the /// evaluator and reads the answer. /// /// @@ -59,7 +59,7 @@ public PromptModerator(IEvaluator evaluator) /// The registry is . /// /// A host that registers no moderation evaluator runs every turn and refuses none, exactly as a - /// host that binds no audit sink still answers a call. Moderation needs a vendor account, and a + /// host that binds no audit sink still answers a conversation. Moderation needs a vendor account, and a /// library that refused to run without one would be unusable in a test. /// public static PromptModerator? FromRegistry(EvaluatorRegistry registry) @@ -73,7 +73,7 @@ public PromptModerator(IEvaluator evaluator) /// Reads which categories flagged what the caller said. /// The words the caller spoke this turn. - /// Cancels the endpoint call. + /// Cancels the endpoint conversation. /// /// The categories, in the order the endpoint returned them, or an empty list when the endpoint /// flagged nothing. @@ -84,7 +84,7 @@ public PromptModerator(IEvaluator evaluator) /// is the fail-open rule, and it is deliberate: a vendor outage must not refuse every caller on /// a support line. answers for a /// failed evaluation, so the two cases meet here and the caller of this method cannot tell them - /// apart. counts them apart on a metric instead. + /// apart. counts them apart on a metric instead. /// public async ValueTask> FlaggedCategoriesAsync( string callerText, diff --git a/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs b/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs index cd91f0eb..ccf87e40 100644 --- a/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs +++ b/src/AgentCore.Application/Knowledge/CompositeKnowledgeStoreFactory.cs @@ -12,7 +12,7 @@ namespace AgentCore.Application.Knowledge; /// public static class CompositeKnowledgeStoreFactory { - /// What the knowledge field calls itself, so the shared selector writes its failures. + /// What the knowledge field conversations itself, so the shared selector writes its failures. private static readonly VendorSeam KnowledgeSeam = new("providers.knowledge.kind", "/providers/knowledge/kind", "options.UseKnowledgeStores(...)", "stores"); diff --git a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs index cb51e1aa..b727e429 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs @@ -4,7 +4,7 @@ namespace AgentCore.Application.Knowledge; /// -/// What one retrieval actually did — the reader is the on-call engineer, and the model never sees it. +/// What one retrieval actually did — the reader is the on-conversation engineer, and the model never sees it. /// internal sealed record KnowledgeAuditRecord { diff --git a/src/AgentCore.Application/Knowledge/KnowledgeCancellation.cs b/src/AgentCore.Application/Knowledge/KnowledgeCancellation.cs index 73c46fc3..23c056d5 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeCancellation.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeCancellation.cs @@ -5,7 +5,7 @@ namespace AgentCore.Application.Knowledge; /// /// /// The two are answered differently everywhere in this folder: a hang-up is rethrown and charges the -/// call nothing, while a failure is reported to the model and logged. +/// conversation nothing, while a failure is reported to the model and logged. /// internal static class KnowledgeCancellation { diff --git a/src/AgentCore.Application/Knowledge/KnowledgeNotices.cs b/src/AgentCore.Application/Knowledge/KnowledgeNotices.cs index d1516266..c5cd72a6 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeNotices.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeNotices.cs @@ -22,7 +22,7 @@ internal static class KnowledgeNotices /// What the model is told when the search ran and matched nothing. /// /// Tool mode only. Prefetch searches before every invocation on a query composed from recent - /// messages, so a greeting would otherwise open the call by announcing an empty knowledge base. + /// messages, so a greeting would otherwise open the conversation by announcing an empty knowledge base. /// internal const string Empty = "The knowledge base holds nothing for this question. Say so, and do not answer from memory."; diff --git a/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs index 072af390..8a8b48c7 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs @@ -7,9 +7,9 @@ namespace AgentCore.Application.Knowledge; // The prefetch half of one agent's knowledge block: runs the framework's own search provider // per invocation, bound to that invocation's turn. A shared provider cannot serve prefetch — // the framework invokes its search as (query, cancellation) with no turn — so this builds a -// provider per call around the same options, closing over the turn the session filed. State +// provider per conversation around the same options, closing over the turn the session filed. State // keys and post-invocation storage forward to the shared template: accumulation lives in -// the session store, not on any instance, so a fresh provider per call loses nothing. +// the session store, not on any instance, so a fresh provider per conversation loses nothing. internal sealed class KnowledgePrefetchProvider( AIContextProvider template, TextSearchProviderOptions options, diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs index 6a791d2f..41fd0ef6 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs @@ -23,7 +23,7 @@ internal static class KnowledgeProbe /// The live scope the main search just ran under. /// The id of the agent that asked, for the log line. /// The search text the framework composed. - /// The call's ambiguity holder, or inside a nested tool call. + /// The conversation's ambiguity holder, or inside a nested tool call. /// Whether this row's session carries the caller's own history. /// Where the probe's own log events go. /// The caller's own token — cancelling this is the caller hanging up, not a timeout. @@ -207,7 +207,7 @@ internal static class KnowledgeProbe // Whether the note repeats what was last named, and the record that follows from it, are one // transition under one lock acquisition. Deciding from an earlier Read() and writing after - // would let a concurrent participant on the same call slip between the two. + // would let a concurrent participant on the same conversation slip between the two. var repeats = false; clarifications.Update(facet, s => diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs index b479e81a..083b6727 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs @@ -21,7 +21,7 @@ internal static class KnowledgeProviderFactory /// /// Where the retrieval record and the framework's own provider log go, or /// when the host wired none. Ruling 21: this is the one reachable observability seam — the audit - /// sink is not, because AuditEvent requires a call id and a sequence number that this + /// sink is not, because AuditEvent requires a conversation id and a sequence number that this /// seam doesn't carry down here. /// /// The document's providers.knowledge.scope block, or . diff --git a/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs b/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs index 1d689d66..ab3fe317 100644 --- a/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs +++ b/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs @@ -10,10 +10,10 @@ namespace AgentCore.Application.Knowledge; /// internal static class StateKnowledgeScope { - /// Composes the turn's scope from the host's scope and the call's state. - /// The state of the call, as it stands at the start of this turn. + /// Composes the turn's scope from the host's scope and the conversation's state. + /// The state of the conversation, as it stands at the start of this turn. /// The document's providers.knowledge.scope block, or null. - /// What the host set for this call, or null when it set nothing. + /// What the host set for this conversation, or null when it set nothing. /// The scope, or unchanged when this document composes none. internal static KnowledgeScope? Compose( StateDocument state, KnowledgeScopeConfiguration? scope, KnowledgeScope? hostScope) diff --git a/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs b/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs index b7ef04f2..53f7f6fd 100644 --- a/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs +++ b/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs @@ -99,7 +99,7 @@ public IChatClient GetChatClient(ModelReference? model) return _vendor[entry.As]; } - // The vendor client stays one for each 'as' name. Only the call settings differ, so the + // The vendor client stays one for each 'as' name. Only the conversation settings differ, so the // wrapper sits above the shared client rather than beside it. ConfigureOptions clones the // caller's ChatOptions (or starts a new one) and never mutates them, which is the same // semantic a hand-rolled wrapper used to reimplement. diff --git a/src/AgentCore.Application/Policy/StagePolicy.cs b/src/AgentCore.Application/Policy/StagePolicy.cs index 1e625d31..994139cd 100644 --- a/src/AgentCore.Application/Policy/StagePolicy.cs +++ b/src/AgentCore.Application/Policy/StagePolicy.cs @@ -78,7 +78,7 @@ public StagePolicy(PolicyConfiguration policy, IGuardEvaluator guards) /// Gets the stage the machine holds. public StageConfiguration CurrentStage => _stages[_machine.State]; - /// Gets whether the stage the machine holds ends the call. + /// Gets whether the stage the machine holds ends the conversation. public bool IsTerminal => CurrentStage.Terminal; /// Gets the id of the agent that speaks in the stage the machine holds. @@ -91,7 +91,7 @@ public bool Declares(string stage) return _stages.ContainsKey(stage); } - /// Puts the machine back in the stage a previous session of this call left it in. + /// Puts the machine back in the stage a previous session of this conversation left it in. internal void RestoreStage(string stage) { ArgumentNullException.ThrowIfNull(stage); diff --git a/src/AgentCore.Application/Ports/ICallChannelFactory.cs b/src/AgentCore.Application/Ports/ICallChannelFactory.cs deleted file mode 100644 index 30e998c8..00000000 --- a/src/AgentCore.Application/Ports/ICallChannelFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -using AgentCore.Application.Calls; - -namespace AgentCore.Application.Ports; - -/// Opens the channel for one call. -public interface ICallChannelFactory -{ - /// Opens both halves of one call. - /// What the call is. - /// Abandons the attempt. - /// The pair. The caller disposes it when the call ends. - ValueTask OpenAsync(CallChannelContext context, CancellationToken cancellationToken = default); -} diff --git a/src/AgentCore.Application/Ports/ICallSessionFactory.cs b/src/AgentCore.Application/Ports/ICallSessionFactory.cs deleted file mode 100644 index 9a51bdab..00000000 --- a/src/AgentCore.Application/Ports/ICallSessionFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Runtime; - -namespace AgentCore.Application.Ports; - -/// -/// Creates one session for one call. -/// -public interface ICallSessionFactory -{ - /// Creates the session of one call. - CallSession Create(string? callId = null, CallSessionState? state = null); -} diff --git a/src/AgentCore.Application/Ports/ICallSessions.cs b/src/AgentCore.Application/Ports/ICallSessions.cs deleted file mode 100644 index c0ef9136..00000000 --- a/src/AgentCore.Application/Ports/ICallSessions.cs +++ /dev/null @@ -1,46 +0,0 @@ -using AgentCore.Application.Runtime; - -namespace AgentCore.Application.Ports; - -/// -/// Owns the session of a call for as long as the call needs it. -/// -/// -/// A call runs over many turns and one request carries one turn, so something has to hold the -/// session in between. This is that seam, and it owns the whole life of the session rather than -/// only the holding: a caller asks for the session of a call and never builds one itself. -/// -public interface ICallSessions -{ - /// Opens the session of one call. - /// The id the host gives the call, or to be given one. - /// Cancels the open. - /// The session, ready for its first turn. - ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default); - - /// Reads the session of one call, and marks the call as still live. - /// The id the request named. It is the . - /// Cancels the read. - /// The session, or when this holds no such call. - /// - /// A read is the only signal an implementation gets that a call is still being had, so an - /// implementation that expires an idle session must restart that session's clock here. A caller - /// that already holds the session for the whole call — the relay socket does — must therefore - /// still read it back on each turn, or its own call is the one that expires. - /// - ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default); - - /// Ends one call: waits for the words it still owes store 1, then drops it. - /// The id of the call that ended. - /// Cancels the close. - /// A task that completes once the session is gone and its writes are done. - /// - /// The order is the contract. A turn queues its rows and speaks, so a call can end with its last - /// turn still in flight, and the session is the only thing that can wait for those writes — once - /// it is dropped nothing can, and the durable record loses the turn the caller just had with no - /// error anywhere to say so. Every way a session ends comes through here, expiry included, so - /// no path can be written that skips the wait. An implementation must also dispose the session: - /// it owns processes (a call's shell: executors) that a dropped reference would leak. - /// - ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default); -} diff --git a/src/AgentCore.Application/Ports/ICallTitler.cs b/src/AgentCore.Application/Ports/ICallTitler.cs deleted file mode 100644 index a96fee72..00000000 --- a/src/AgentCore.Application/Ports/ICallTitler.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Ports; - -/// Makes a call's title from its words. -public interface ICallTitler -{ - /// Generates one call's title, streaming it as it arrives. - /// The call to title. - /// Stops the generation. - /// The title in pieces, in order. - IAsyncEnumerable GenerateAsync(string callId, CancellationToken cancellationToken = default); - - // A turn reaches store 1 only once it has finished, so a browser naming a conversation the - // moment it starts finds nothing there to read. It hands over what it is showing instead. - /// Generates one call's title from messages the caller holds, streaming it as it arrives. - /// The call to title. Its stored messages are not read. - /// The messages to name, with their roles. Empty leaves the call unnamed. - /// Stops the generation. - /// The title in pieces, in order. - IAsyncEnumerable GenerateFromAsync( - string callId, IReadOnlyList messages, CancellationToken cancellationToken = default); -} diff --git a/src/AgentCore.Application/Ports/ICallAdapter.cs b/src/AgentCore.Application/Ports/IConversationAdapter.cs similarity index 81% rename from src/AgentCore.Application/Ports/ICallAdapter.cs rename to src/AgentCore.Application/Ports/IConversationAdapter.cs index 9c364f8c..89cc6e18 100644 --- a/src/AgentCore.Application/Ports/ICallAdapter.cs +++ b/src/AgentCore.Application/Ports/IConversationAdapter.cs @@ -1,12 +1,12 @@ namespace AgentCore.Application.Ports; /// -/// Names the vendor behind one providers.call value: who carries the call. +/// Names the vendor behind one providers.conversation value: who carries the conversation. /// /// /// /// This is the selection face, and it is all the core can see. The routing face -/// lives in AgentCore.AspNetCore as ICallTransportAdapter, because it names +/// lives in AgentCore.AspNetCore as IConversationTransportAdapter, because it names /// IEndpointRouteBuilder and this assembly references no ASP.NET Core package. /// /// @@ -14,7 +14,7 @@ namespace AgentCore.Application.Ports; /// it is never forced to grow a routing member it would have to throw from. /// /// -public interface ICallAdapter : IVendorAdapter +public interface IConversationAdapter : IVendorAdapter { /// /// Gets whether this transport's frames already carry text. @@ -24,7 +24,7 @@ public interface ICallAdapter : IVendorAdapter /// means the vendor performs recognition and synthesis itself — the /// Telnyx Conversation Relay does — so both speech roles, /// providers.speech.stt.kind and providers.speech.tts.kind, must name that same - /// vendor, and enforces it. + /// vendor, and enforces it. /// /// /// means the frames carry audio and a separate speech vendor turns it diff --git a/src/AgentCore.Application/Ports/IConversationChannelFactory.cs b/src/AgentCore.Application/Ports/IConversationChannelFactory.cs new file mode 100644 index 00000000..5df60f74 --- /dev/null +++ b/src/AgentCore.Application/Ports/IConversationChannelFactory.cs @@ -0,0 +1,13 @@ +using AgentCore.Application.Conversation; + +namespace AgentCore.Application.Ports; + +/// Opens the channel for one conversation. +public interface IConversationChannelFactory +{ + /// Opens both halves of one conversation. + /// What the conversation is. + /// Abandons the attempt. + /// The pair. The caller disposes it when the conversation ends. + ValueTask OpenAsync(ConversationChannelContext context, CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/Ports/ICallInputPort.cs b/src/AgentCore.Application/Ports/IConversationInputPort.cs similarity index 73% rename from src/AgentCore.Application/Ports/ICallInputPort.cs rename to src/AgentCore.Application/Ports/IConversationInputPort.cs index 752e2c44..a68a8b8c 100644 --- a/src/AgentCore.Application/Ports/ICallInputPort.cs +++ b/src/AgentCore.Application/Ports/IConversationInputPort.cs @@ -1,19 +1,19 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; namespace AgentCore.Application.Ports; /// -/// What the caller did, for one call, as one ordered stream. +/// What the caller did, for one conversation, as one ordered stream. /// /// /// -/// One instance serves one call and is disposed with it. That is unlike every other port in this +/// One instance serves one conversation and is disposed with it. That is unlike every other port in this /// folder, which is bound once for the process, and it is why this one is /// . /// /// /// A barge-in arrives here, on the inbound stream, and not on -/// . It is an event the caller caused, and the order between "the +/// . It is an event the caller caused, and the order between "the /// caller cut in" and "the caller then said this" is what a turn loop must never get wrong. One /// ordered stream keeps that ordering inside the adapter, which is the only place that has the /// information to settle it. @@ -23,32 +23,32 @@ namespace AgentCore.Application.Ports; /// the Telnyx Conversation Relay receives text frames and passes them straight through. A /// transport whose socket carries audio runs recognition inside its own adapter and emits text /// here. Audio stops at the adapter's edge and never enters this assembly, which is D28 and -/// section 11 item 6c. That is also why this port is named for the call and not for speech: +/// section 11 item 6c. That is also why this port is named for the conversation and not for speech: /// names the vendor behind each speech role — one vendor, or two — /// and this does not. /// /// -public interface ICallInputPort : IAsyncDisposable +public interface IConversationInputPort : IAsyncDisposable { - /// Reads what the caller does, until the call ends. + /// Reads what the caller does, until the conversation ends. /// /// Abandons the read. Cancelling it throws, and never ends the stream quietly — see the remarks. /// - /// Every inbound event of the call, in order. + /// Every inbound event of the conversation, in order. /// /// /// One consumer only. This method may not be called a second time on one instance, and /// a second call throws. is a factory rather than a stream, /// so nothing in the type itself stops two enumerators from being taken over one socket, and - /// two consumers of one socket would each see half the call. + /// two consumers of one socket would each see half the conversation. /// /// - /// The call ending and the read being cancelled are two different endings, and every - /// implementation must tell them apart the same way. The call ending — the caller hung up, + /// The conversation ending and the read being cancelled are two different endings, and every + /// implementation must tell them apart the same way. The conversation ending — the caller hung up, /// the transport went away, the vendor closed the socket — completes the stream normally, and /// that is the ordinary end of an await foreach over it. Cancelling /// throws instead, - /// as any cancelled await does. A consumer therefore reads "the loop ended" as "the call is + /// as any cancelled await does. A consumer therefore reads "the loop ended" as "the conversation is /// over" and needs no flag to ask which happened, and an implementation may not swallow its /// consumer's own cancellation into a clean ending: a test double that throws where the real /// port completes, or the reverse, is a difference the whole point of this port is that nobody @@ -57,5 +57,5 @@ public interface ICallInputPort : IAsyncDisposable /// /// This port is already being read. /// was cancelled. - IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default); + IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default); } diff --git a/src/AgentCore.Application/Ports/ICallObserver.cs b/src/AgentCore.Application/Ports/IConversationObserver.cs similarity index 56% rename from src/AgentCore.Application/Ports/ICallObserver.cs rename to src/AgentCore.Application/Ports/IConversationObserver.cs index 122f0b33..059da490 100644 --- a/src/AgentCore.Application/Ports/ICallObserver.cs +++ b/src/AgentCore.Application/Ports/IConversationObserver.cs @@ -3,45 +3,45 @@ namespace AgentCore.Application.Ports; /// -/// Reads the facts of a call as the turn loop raises them. It never sits on the turn. +/// Reads the facts of a conversation as the turn loop raises them. It never sits on the turn. /// /// /// /// This is the one seam between the turn loop and everything that watches it. The audit chain of D23, /// the counters of section 8.6, and the "log once" rows of section 8.7 are three implementations of -/// this port, and knows none of them: it raises a -/// and moves on. +/// this port, and knows none of them: it raises a +/// and moves on. /// /// /// The contract of applies here in full, and for the same measurement. /// Section 7 puts a durable insert at 13 ms at p50 and 32 ms at p99, against 91 nanoseconds to /// enqueue, so an observer completes when it has ACCEPTED the fact and never when it has stored it. /// An implementation that awaits a database, an HTTP call, or a disk inside -/// has broken the contract, and the turn loop pays for it. +/// has broken the contract, and the turn loop pays for it. /// /// /// The dispatcher behind this port never lets an observer end a turn: a fault is logged once and /// swallowed, and an observer that does not complete at once is observed off-turn. An implementation -/// may therefore throw, and nothing that throws is retried. Observers of one call are also invoked in -/// the order the call raised the facts, so a late fact never overtakes an earlier one. +/// may therefore throw, and nothing that throws is retried. Observers of one conversation are also invoked in +/// the order the conversation raised the facts, so a late fact never overtakes an earlier one. /// /// -/// One instance serves every call, because a names its own call. Nothing here -/// is per call, and an implementation that holds per-call state must key it by -/// . +/// One instance serves every conversation, because a names its own conversation. Nothing here +/// is per conversation, and an implementation that holds per-call state must key it by +/// . /// /// -public interface ICallObserver +public interface IConversationObserver { - /// Takes one fact about a call. - /// What happened. Nothing edits it afterwards. + /// Takes one fact about a conversation. + /// What happened. Nothing edits it afterwards. /// /// Cancels the acceptance, and never the work behind it. The dispatcher passes - /// : the record belongs to the call, and not to a turn the + /// : the record belongs to the conversation, and not to a turn the /// caller may have cancelled. /// /// /// A task that completes when the observer has accepted the fact. It is not stored yet. /// - ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken); + ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken); } diff --git a/src/AgentCore.Application/Ports/ICallOutputPort.cs b/src/AgentCore.Application/Ports/IConversationOutputPort.cs similarity index 84% rename from src/AgentCore.Application/Ports/ICallOutputPort.cs rename to src/AgentCore.Application/Ports/IConversationOutputPort.cs index 27cb8027..5b6dbeb4 100644 --- a/src/AgentCore.Application/Ports/ICallOutputPort.cs +++ b/src/AgentCore.Application/Ports/IConversationOutputPort.cs @@ -1,13 +1,13 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; namespace AgentCore.Application.Ports; /// -/// What the agent says, for one call. +/// What the agent says, for one conversation. /// /// /// -/// One instance serves one call and is disposed with it, as is. +/// One instance serves one conversation and is disposed with it, as is. /// /// /// Three methods and no events. Every studied voice framework gives its speaking side a method @@ -15,7 +15,7 @@ namespace AgentCore.Application.Ports; /// languages they are written in: an event promises no ordering across threads. /// /// -public interface ICallOutputPort : IAsyncDisposable +public interface IConversationOutputPort : IAsyncDisposable { /// Speaks one fragment of the reply. /// The text to speak. Never empty. @@ -36,7 +36,7 @@ public interface ICallOutputPort : IAsyncDisposable /// /// This does not return the cut point, and the two are not simultaneous. The settled /// answer — what the caller heard, and for how long — arrives afterwards as a - /// on the input stream. A vendor that reports the cut itself + /// on the input stream. A vendor that reports the cut itself /// settles at once. One built from a separate synthesizer must wait for its own audio to /// finish draining first, and every implementation of that wait carries a deadline: two /// seconds is the budget, after which the reply counts as fully heard. diff --git a/src/AgentCore.Application/Ports/IConversationPort.cs b/src/AgentCore.Application/Ports/IConversationPort.cs index 8f6fbd09..b2b0b11c 100644 --- a/src/AgentCore.Application/Ports/IConversationPort.cs +++ b/src/AgentCore.Application/Ports/IConversationPort.cs @@ -5,21 +5,21 @@ namespace AgentCore.Application.Ports; /// -/// The inbound seam of one call: start or continue a turn, stream the reply, cancel it. +/// The inbound seam of one conversation: start or continue a turn, stream the reply, cancel it. /// public interface IConversationPort { - /// Gets the id of the call. - string CallId { get; } + /// Gets the id of the conversation. + string ConversationId { get; } /// Gets the stage the machine holds. It is empty when the document declares no policy. string Stage { get; } - /// Gets whether the call reached a terminal stage. A document with no policy never does. + /// Gets whether the conversation reached a terminal stage. A document with no policy never does. bool IsComplete { get; } - /// Gets or sets the knowledge scope the host opened for this call, or null for none. - /// Set it before the run: every turn composes its own scope from it. It outlives turns by construction — one call hears one customer. + /// Gets or sets the knowledge scope the host opened for this conversation, or null for none. + /// Set it before the run: every turn composes its own scope from it. It outlives turns by construction — one conversation hears one customer. KnowledgeScope? Scope { get; set; } /// Gets the turn that finished last, or before the first turn ends. @@ -30,7 +30,7 @@ public interface IConversationPort /// Cancels the model calls. /// The finished turn. It always carries a spoken line. /// - /// The call already ended, or another turn of this call is still running. + /// The conversation already ended, or another turn of this conversation is still running. /// Task RunTurnAsync(string userInput, CancellationToken cancellationToken = default); @@ -39,7 +39,7 @@ public interface IConversationPort /// Cancels the model calls. /// The finished turn. Its reply is empty while approval requests are pending. /// - /// The call already ended, or another turn of this call is still running. + /// The conversation already ended, or another turn of this conversation is still running. /// Task RunTurnMessageAsync(ChatMessage userInput, CancellationToken cancellationToken); @@ -53,7 +53,7 @@ public interface IConversationPort /// 40-fragment reply, and an adapter must not have to filter them again. /// /// - /// The call already ended, or another turn of this call is still running. + /// The conversation already ended, or another turn of this conversation is still running. /// IAsyncEnumerable RunTurnStreamingAsync( string userInput, @@ -64,7 +64,7 @@ IAsyncEnumerable RunTurnStreamingAsync( /// Cancels the model calls. /// The reply, one update at a time. Every update carries content. /// - /// The call already ended, or another turn of this call is still running. + /// The conversation already ended, or another turn of this conversation is still running. /// IAsyncEnumerable RunTurnMessageStreamingAsync( ChatMessage userInput, diff --git a/src/AgentCore.Application/Ports/IConversationSessionFactory.cs b/src/AgentCore.Application/Ports/IConversationSessionFactory.cs new file mode 100644 index 00000000..34b0dc46 --- /dev/null +++ b/src/AgentCore.Application/Ports/IConversationSessionFactory.cs @@ -0,0 +1,13 @@ +using AgentCore.Application.Conversation; +using AgentCore.Application.Runtime; + +namespace AgentCore.Application.Ports; + +/// +/// Creates one session for one conversation. +/// +public interface IConversationSessionFactory +{ + /// Creates the session of one conversation. + ConversationSession Create(string? conversationId = null, ConversationSessionState? state = null); +} diff --git a/src/AgentCore.Application/Ports/ICallSessionRegistry.cs b/src/AgentCore.Application/Ports/IConversationSessionRegistry.cs similarity index 84% rename from src/AgentCore.Application/Ports/ICallSessionRegistry.cs rename to src/AgentCore.Application/Ports/IConversationSessionRegistry.cs index 139fe4ea..993ba50c 100644 --- a/src/AgentCore.Application/Ports/ICallSessionRegistry.cs +++ b/src/AgentCore.Application/Ports/IConversationSessionRegistry.cs @@ -3,7 +3,7 @@ namespace AgentCore.Application.Ports; /// /// Finds the session store of one entry. /// -public interface ICallSessionRegistry +public interface IConversationSessionRegistry { /// Gets the names of the entries the document declares. IReadOnlyCollection Entries { get; } @@ -12,5 +12,5 @@ public interface ICallSessionRegistry /// The entry key, as the document declares it. /// The store for that entry. /// The entry is not declared. - ICallSessions ForSessions(string entry); + IConversationSessions ForSessions(string entry); } diff --git a/src/AgentCore.Application/Ports/IConversationSessions.cs b/src/AgentCore.Application/Ports/IConversationSessions.cs new file mode 100644 index 00000000..94e70343 --- /dev/null +++ b/src/AgentCore.Application/Ports/IConversationSessions.cs @@ -0,0 +1,46 @@ +using AgentCore.Application.Runtime; + +namespace AgentCore.Application.Ports; + +/// +/// Owns the session of a conversation for as long as the conversation needs it. +/// +/// +/// A conversation runs over many turns and one request carries one turn, so something has to hold the +/// session in between. This is that seam, and it owns the whole life of the session rather than +/// only the holding: a caller asks for the session of a conversation and never builds one itself. +/// +public interface IConversationSessions +{ + /// Opens the session of one conversation. + /// The id the host gives the conversation, or to be given one. + /// Cancels the open. + /// The session, ready for its first turn. + ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default); + + /// Reads the session of one conversation, and marks the conversation as still live. + /// The id the request named. It is the . + /// Cancels the read. + /// The session, or when this holds no such conversation. + /// + /// A read is the only signal an implementation gets that a conversation is still being had, so an + /// implementation that expires an idle session must restart that session's clock here. A caller + /// that already holds the session for the whole conversation — the relay socket does — must therefore + /// still read it back on each turn, or its own conversation is the one that expires. + /// + ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default); + + /// Ends one conversation: waits for the words it still owes store 1, then drops it. + /// The id of the conversation that ended. + /// Cancels the close. + /// A task that completes once the session is gone and its writes are done. + /// + /// The order is the contract. A turn queues its rows and speaks, so a conversation can end with its last + /// turn still in flight, and the session is the only thing that can wait for those writes — once + /// it is dropped nothing can, and the durable record loses the turn the caller just had with no + /// error anywhere to say so. Every way a session ends comes through here, expiry included, so + /// no path can be written that skips the wait. An implementation must also dispose the session: + /// it owns processes (a conversation's shell: executors) that a dropped reference would leak. + /// + ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/Ports/ICallStore.cs b/src/AgentCore.Application/Ports/IConversationStore.cs similarity index 56% rename from src/AgentCore.Application/Ports/ICallStore.cs rename to src/AgentCore.Application/Ports/IConversationStore.cs index f384ccdc..033c22ec 100644 --- a/src/AgentCore.Application/Ports/ICallStore.cs +++ b/src/AgentCore.Application/Ports/IConversationStore.cs @@ -1,70 +1,70 @@ using System.Text.Json; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; namespace AgentCore.Application.Ports; -/// Where store 0 keeps what a call is, apart from its words. -public interface ICallStore +/// Where store 0 keeps what a conversation is, apart from its words. +public interface IConversationStore { - /// Makes the call's row, or returns the one already there. - /// The call to record. + /// Makes the conversation's row, or returns the one already there. + /// The conversation to record. /// Cancels the write. - /// The row, whether this call made it or found it. - ValueTask CreateAsync(string callId, CancellationToken cancellationToken = default); + /// The row, whether this conversation made it or found it. + ValueTask CreateAsync(string conversationId, CancellationToken cancellationToken = default); - /// Reads one call's row. - /// The call to read. + /// Reads one conversation's row. + /// The conversation to read. /// Cancels the read. /// The row, or when store 0 holds none. - ValueTask GetAsync(string callId, CancellationToken cancellationToken = default); + ValueTask GetAsync(string conversationId, CancellationToken cancellationToken = default); - /// Lists one principal's calls, most recently active first. + /// Lists one principal's conversations, most recently active first. /// The opaque key to list by. /// A cursor from an earlier page, or for the first. /// How many rows this page may hold. /// The one status to return, or for every status. /// Cancels the read. /// The page, and a cursor when a following page exists. - ValueTask ListAsync( + ValueTask ListAsync( string principalKey, string? after, int limit, - CallStatus? status = null, + ConversationStatus? status = null, CancellationToken cancellationToken = default); - /// Sets a call's title. - /// The call to rename. + /// Sets a conversation's title. + /// The conversation to rename. /// What to show in a list. /// Cancels the write. - ValueTask RenameAsync(string callId, string title, CancellationToken cancellationToken = default); + ValueTask RenameAsync(string conversationId, string title, CancellationToken cancellationToken = default); - /// Archives a call, or brings it back. - /// The call to move. + /// Archives a conversation, or brings it back. + /// The conversation to move. /// Where to move it. /// Cancels the write. - ValueTask SetStatusAsync(string callId, CallStatus status, CancellationToken cancellationToken = default); + ValueTask SetStatusAsync(string conversationId, ConversationStatus status, CancellationToken cancellationToken = default); - /// Replaces a call's consumer-owned fields. - /// The call to write. + /// Replaces a conversation's consumer-owned fields. + /// The conversation to write. /// The fields, or to clear them. /// Cancels the write. - ValueTask SetCustomAsync(string callId, JsonElement? custom, CancellationToken cancellationToken = default); + ValueTask SetCustomAsync(string conversationId, JsonElement? custom, CancellationToken cancellationToken = default); - /// Replaces a call's consumer-owned id. - /// The call to write. - /// The consumer's own id for the call, or to clear it. + /// Replaces a conversation's consumer-owned id. + /// The conversation to write. + /// The consumer's own id for the conversation, or to clear it. /// Cancels the write. - ValueTask SetExternalIdAsync(string callId, string? externalId, CancellationToken cancellationToken = default); + ValueTask SetExternalIdAsync(string conversationId, string? externalId, CancellationToken cancellationToken = default); - /// Erases the call's row and every attachment to it. - /// The call to erase. + /// Erases the conversation's row and every attachment to it. + /// The conversation to erase. /// Cancels the delete. - ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default); + ValueTask DeleteAsync(string conversationId, CancellationToken cancellationToken = default); /// Writes a turn's new messages, and the state the session holds after them. - /// The call every message in belongs to. + /// The conversation every message in belongs to. /// The rows to write, oldest first. /// /// What the session holds after this turn, or to leave the stored state @@ -78,44 +78,44 @@ ValueTask ListAsync( /// The rows as written, in the order given, each with its ordinal and its turn index. /// /// - /// The store numbers every row from the call's own counter, in one atomic step, so two writers on - /// two machines never collide on an ordinal — one from the call's live session, the other from a + /// The store numbers every row from the conversation's own counter, in one atomic step, so two writers on + /// two machines never collide on an ordinal — one from the conversation's live session, the other from a /// host appending outside any turn. /// /// - /// The call named by does not exist. A row is never written against a - /// call that has no row of its own. + /// The conversation named by does not exist. A row is never written against a + /// conversation that has no row of its own. /// - ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, + ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, CancellationToken cancellationToken = default); /// - /// Appends one message to a call from outside any turn. The store numbers the row and stamps it - /// with the turn the call takes next. Works whether or not a session for the call is live. + /// Appends one message to a conversation from outside any turn. The store numbers the row and stamps it + /// with the turn the conversation takes next. Works whether or not a session for the conversation is live. /// - /// The call to append to. + /// The conversation to append to. /// The message to append. /// Cancels the write. /// The row as written: its ordinal, its turn index, and its id. - async ValueTask AppendMessageAsync( - string callId, + async ValueTask AppendMessageAsync( + string conversationId, ChatMessage message, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(message); - var messageId = string.IsNullOrEmpty(message.MessageId) ? CallMessageIds.New() : message.MessageId; - CallMessageDraft draft = new(TurnIndex: null, message, messageId); + var messageId = string.IsNullOrEmpty(message.MessageId) ? ConversationMessageIds.New() : message.MessageId; + ConversationMessageDraft draft = new(TurnIndex: null, message, messageId); - var rows = await AppendAsync(callId, [draft], state: null, cancellationToken).ConfigureAwait(false); + var rows = await AppendAsync(conversationId, [draft], state: null, cancellationToken).ConfigureAwait(false); return rows[0]; } /// Rewrites one already-written message in place, on a barge-in. - /// The call the message belongs to. + /// The conversation the message belongs to. /// /// The message to rewrite, by name rather than by ordinal: the session's in-memory ordinal is /// still provisional while a turn runs, but the message id is fixed the moment the row is cut. @@ -123,69 +123,69 @@ async ValueTask AppendMessageAsync( /// What the caller actually heard. /// Cancels the write. ValueTask RewriteAsync( - string callId, + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default); - /// Reads one whole call's words, oldest message first. - /// The call to read. + /// Reads one whole conversation's words, oldest message first. + /// The conversation to read. /// Cancels the read. - /// Every message of the call, or an empty list when it holds none. - ValueTask> ReadAsync( - string callId, + /// Every message of the conversation, or an empty list when it holds none. + ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default); - /// Withdraws the tail of a call's words, from one ordinal onward. - /// The call to cut. + /// Withdraws the tail of a conversation's words, from one ordinal onward. + /// The conversation to cut. /// The first ordinal to remove. It goes too. /// Cancels the delete. /// How many messages went. ValueTask TruncateAsync( - string callId, + string conversationId, int fromOrdinal, CancellationToken cancellationToken = default); - /// Erases one call's words, and leaves its row in the listing. - /// The call to quieten. + /// Erases one conversation's words, and leaves its row in the listing. + /// The conversation to quieten. /// Cancels the delete. /// How many messages went. - ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default); + ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default); - /// Deletes every call whose last activity is older than the retention window. + /// Deletes every conversation whose last activity is older than the retention window. /// - /// How long a call is kept, measured from its most recent message, or from when it was made when + /// How long a conversation is kept, measured from its most recent message, or from when it was made when /// it holds none. The window belongs to a deployment: it is not a schema key, and nothing here /// defaults it. /// /// - /// How many calls one transaction may delete. The sweep loops until a batch deletes nothing, so + /// How many conversations one transaction may delete. The sweep loops until a batch deletes nothing, so /// this bounds one transaction and never the work. /// /// Cancels the sweep between batches, and inside one. - /// How many calls went, over every batch. + /// How many conversations went, over every batch. ValueTask SweepAsync( TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default); - /// Gives a principal a claim on a call. - /// The call to claim. + /// Gives a principal a claim on a conversation. + /// The conversation to claim. /// The opaque key that claims it. - /// What the key is to this call. AgentCore assigns its values no meaning. + /// What the key is to this conversation. AgentCore assigns its values no meaning. /// Cancels the write. ValueTask AttachPrincipalAsync( - string callId, + string conversationId, string principalKey, string role, CancellationToken cancellationToken = default); - /// Takes a principal's claim off a call. - /// The call to unclaim. + /// Takes a principal's claim off a conversation. + /// The conversation to unclaim. /// The key to remove. /// Cancels the delete. ValueTask DetachPrincipalAsync( - string callId, + string conversationId, string principalKey, CancellationToken cancellationToken = default); @@ -194,7 +194,7 @@ ValueTask DetachPrincipalAsync( /// The serialized session, as the agent wrote it. /// Cancels the write. /// - /// The continuation names a call whose words live in store 1, so the map lives in this store: + /// The continuation names a conversation whose words live in store 1, so the map lives in this store: /// a resume must never find the key without the words. /// ValueTask SaveContinuationAsync( diff --git a/src/AgentCore.Application/Ports/ICallStoreAdapter.cs b/src/AgentCore.Application/Ports/IConversationStoreAdapter.cs similarity index 63% rename from src/AgentCore.Application/Ports/ICallStoreAdapter.cs rename to src/AgentCore.Application/Ports/IConversationStoreAdapter.cs index 84789839..4a25c965 100644 --- a/src/AgentCore.Application/Ports/ICallStoreAdapter.cs +++ b/src/AgentCore.Application/Ports/IConversationStoreAdapter.cs @@ -3,15 +3,15 @@ namespace AgentCore.Application.Ports; /// -/// Opens the store 0 backing behind one providers.calls value. +/// Opens the store 0 backing behind one providers.conversations value. /// -public interface ICallStoreAdapter : IVendorAdapter +public interface IConversationStoreAdapter : IVendorAdapter { /// Opens the store this vendor writes to, and hands it over. - /// The providers.calls block, whose kind named this adapter. + /// The providers.conversations block, whose kind named this adapter. /// The chain a credential resolves through, or . /// Cancels the open. - ValueTask OpenAsync( + ValueTask OpenAsync( VendorProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default); diff --git a/src/AgentCore.Application/Ports/IConversationTitler.cs b/src/AgentCore.Application/Ports/IConversationTitler.cs new file mode 100644 index 00000000..4ca049ff --- /dev/null +++ b/src/AgentCore.Application/Ports/IConversationTitler.cs @@ -0,0 +1,23 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Ports; + +/// Makes a conversation's title from its words. +public interface IConversationTitler +{ + /// Generates one conversation's title, streaming it as it arrives. + /// The conversation to title. + /// Stops the generation. + /// The title in pieces, in order. + IAsyncEnumerable GenerateAsync(string conversationId, CancellationToken cancellationToken = default); + + // A turn reaches store 1 only once it has finished, so a browser naming a conversation the + // moment it starts finds nothing there to read. It hands over what it is showing instead. + /// Generates one conversation's title from messages the caller holds, streaming it as it arrives. + /// The conversation to title. Its stored messages are not read. + /// The messages to name, with their roles. Empty leaves the conversation unnamed. + /// Stops the generation. + /// The title in pieces, in order. + IAsyncEnumerable GenerateFromAsync( + string conversationId, IReadOnlyList messages, CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/Ports/IConversations.cs b/src/AgentCore.Application/Ports/IConversations.cs new file mode 100644 index 00000000..288da45d --- /dev/null +++ b/src/AgentCore.Application/Ports/IConversations.cs @@ -0,0 +1,66 @@ +using System.Text.Json; +using AgentCore.Application.Conversation; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Ports; + +/// +/// The door a host or a consumer reads and writes stored conversations through: rows, words, and the +/// files a conversation published, together. What the turn loop and the sweeper need beyond this stays +/// on , which is the adapter seam and not a consumer surface. +/// +public interface IConversations +{ + /// + ValueTask CreateAsync(string conversationId, CancellationToken cancellationToken = default); + + /// + ValueTask GetAsync(string conversationId, CancellationToken cancellationToken = default); + + /// Reads one conversation whole: its row, its words, and a link to every file it kept. + /// The conversation to read. + /// Cancels the read. + /// The conversation, or when the store holds none under that id. + ValueTask LoadAsync(string conversationId, CancellationToken cancellationToken = default); + + /// + ValueTask ListAsync( + string principalKey, + string? after, + int limit, + ConversationStatus? status = null, + CancellationToken cancellationToken = default); + + /// + ValueTask RenameAsync(string conversationId, string title, CancellationToken cancellationToken = default); + + /// + ValueTask SetStatusAsync(string conversationId, ConversationStatus status, CancellationToken cancellationToken = default); + + /// + ValueTask SetCustomAsync(string conversationId, JsonElement? custom, CancellationToken cancellationToken = default); + + /// + ValueTask SetExternalIdAsync(string conversationId, string? externalId, CancellationToken cancellationToken = default); + + /// Deletes the conversation: its row, its words, its claims, and every file it kept. + /// The conversation to delete. + /// Cancels the delete. + ValueTask DeleteAsync(string conversationId, CancellationToken cancellationToken = default); + + /// + ValueTask AppendMessageAsync(string conversationId, ChatMessage message, CancellationToken cancellationToken = default); + + /// + ValueTask> ReadAsync(string conversationId, CancellationToken cancellationToken = default); + + /// + ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default); + + /// + ValueTask AttachPrincipalAsync(string conversationId, string principalKey, string role, CancellationToken cancellationToken = default); + + /// + ValueTask DetachPrincipalAsync(string conversationId, string principalKey, CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/Ports/IModerationAdapter.cs b/src/AgentCore.Application/Ports/IModerationAdapter.cs index 54a55b6a..6078bc9a 100644 --- a/src/AgentCore.Application/Ports/IModerationAdapter.cs +++ b/src/AgentCore.Application/Ports/IModerationAdapter.cs @@ -16,7 +16,7 @@ namespace AgentCore.Application.Ports; /// /// D13 makes the moderation port and refuses a second one, so this /// interface builds an rather than wrapping it. It is a factory, and never -/// a port that a turn calls. D13 also promises that replacing OpenAI with a self-hosted classifier +/// a port that a turn conversations. D13 also promises that replacing OpenAI with a self-hosted classifier /// is a one-file change: that file is the adapter, and this is the seam it plugs into. /// /// @@ -40,7 +40,7 @@ public interface IModerationAdapter : IVendorAdapter /// The evaluator. The host owns it for the life of the process. /// /// This runs once, while the host starts. A missing credential therefore stops the host and never - /// a call, which is what item 9 of section 11 asks for. It opens no socket, so a host with no + /// a conversation, which is what item 9 of section 11 asks for. It opens no socket, so a host with no /// route to the vendor still starts. /// ValueTask CreateAsync( diff --git a/src/AgentCore.Application/Ports/IRenderPort.cs b/src/AgentCore.Application/Ports/IRenderPort.cs index 71e1ac86..d281da32 100644 --- a/src/AgentCore.Application/Ports/IRenderPort.cs +++ b/src/AgentCore.Application/Ports/IRenderPort.cs @@ -5,6 +5,6 @@ namespace AgentCore.Application.Ports; /// public interface IRenderPort { - /// Sends one thing to be shown to the caller of the running call. + /// Sends one thing to be shown to the caller of the running conversation. void Publish(string name, string renderId, object data, bool transient = false); } diff --git a/src/AgentCore.Application/Ports/ISourcePort.cs b/src/AgentCore.Application/Ports/ISourcePort.cs index 2f68e5fa..b9c62c20 100644 --- a/src/AgentCore.Application/Ports/ISourcePort.cs +++ b/src/AgentCore.Application/Ports/ISourcePort.cs @@ -7,7 +7,7 @@ namespace AgentCore.Application.Ports; /// public interface ISourcePort { - /// Cites one source for the running call. + /// Cites one source for the running conversation. /// Where the answer came from. void Publish(SourceReference source); } diff --git a/src/AgentCore.Application/Ports/ISpeechAdapter.cs b/src/AgentCore.Application/Ports/ISpeechAdapter.cs index 4e89e045..116406c9 100644 --- a/src/AgentCore.Application/Ports/ISpeechAdapter.cs +++ b/src/AgentCore.Application/Ports/ISpeechAdapter.cs @@ -16,7 +16,7 @@ namespace AgentCore.Application.Ports; /// nothing else, on purpose. D15 makes every public member /// a permanent obligation, so a member is added when a caller exists for it and not before. The only /// vendor this solution ships is a bundled transport — the Telnyx Conversation Relay — and a relay -/// call is born from a socket the host already accepted: there is nothing for the adapter to create at +/// conversation is born from a socket the host already accepted: there is nothing for the adapter to create at /// selection time, because the frames arriving on that socket are the channel. A create method here /// today would be a signature no caller passes through and every future vendor must still honour. The /// first split vendor, whose speech is a separate service the process must dial, is the caller that @@ -25,22 +25,22 @@ namespace AgentCore.Application.Ports; /// /// So each role's kind is a naming field, not a selecting one: it answers "which /// vendor did the document mean", and nothing here turns that answer into a constructed adapter. -/// is what reads the names today, and only to check them -/// against providers.call.kind — because a transport whose frames already carry text, such as +/// is what reads the names today, and only to check them +/// against providers.conversation.kind — because a transport whose frames already carry text, such as /// the relay this solution ships, is itself the recognizer and the synthesizer, so once the names -/// agree there is nothing left to build. stays the seam's -/// per-call face: it answers "open both halves of this one call", opened once for every call +/// agree there is nothing left to build. stays the seam's +/// per-conversation face: it answers "open both halves of this one conversation", opened once for every conversation /// rather than once while the host starts. /// /// -/// providers.call and providers.speech are required of one another. The schema -/// writes required: ["call", "speech"] on the providers object, so a document that +/// providers.conversation and providers.speech are required of one another. The schema +/// writes required: ["conversation", "speech"] on the providers object, so a document that /// writes a providers section at all writes both, and AddAgentCoreAsync refuses a -/// configuration that registered a call transport and named no speech vendor. A transport whose +/// configuration that registered a conversation transport and named no speech vendor. A transport whose /// frames already carry text must further be named by both speech roles, because such a /// vendor performs recognition and synthesis itself and a document naming it for the pipe and /// something else for the ears or the mouth describes a deployment that cannot exist. -/// is what enforces that, while the host starts and before any +/// is what enforces that, while the host starts and before any /// route is mapped, because the agreement is a fact about the document rather than about a route. /// /// diff --git a/src/AgentCore.Application/Ports/ITelemetryAdapter.cs b/src/AgentCore.Application/Ports/ITelemetryAdapter.cs index 70d28e5d..299e1958 100644 --- a/src/AgentCore.Application/Ports/ITelemetryAdapter.cs +++ b/src/AgentCore.Application/Ports/ITelemetryAdapter.cs @@ -35,7 +35,7 @@ public interface ITelemetryAdapter : IVendorAdapter /// The running session. The host owns it for the life of the process. /// /// This runs once, while the host starts. A missing credential therefore stops the host and never - /// a call, which is what item 9 of section 11 asks for. It opens no socket: an exporter connects + /// a conversation, which is what item 9 of section 11 asks for. It opens no socket: an exporter connects /// when it first has something to send, so a host with no route to the collector still starts. /// ValueTask StartAsync( diff --git a/src/AgentCore.Application/Providers/VendorAdapterSelector.cs b/src/AgentCore.Application/Providers/VendorAdapterSelector.cs index 4c9b305c..467daef6 100644 --- a/src/AgentCore.Application/Providers/VendorAdapterSelector.cs +++ b/src/AgentCore.Application/Providers/VendorAdapterSelector.cs @@ -8,7 +8,7 @@ namespace AgentCore.Application.Providers; /// /// /// -/// Every seam — chat clients, knowledge, moderation, telemetry, speech, and the call transport — +/// Every seam — chat clients, knowledge, moderation, telemetry, speech, and the conversation transport — /// asked the same question and, before this type, each carried its own copy of the answer. The /// copies had drifted: four failed when two adapters answered to one kind, and the chat client one /// silently kept whichever the host listed last. @@ -26,7 +26,7 @@ public static class VendorAdapterSelector /// The adapter interface of one seam. /// The kind the document wrote. /// The vendors this host registered for that seam. - /// What this seam calls itself, for the failure messages. + /// What this seam conversations itself, for the failure messages. /// The one adapter serving . /// The adapters are . /// @@ -77,7 +77,7 @@ public static TAdapter Select( /// Writes what the host does register, and the move that would fix the document. /// /// A host that registered nothing has no kind to offer the reader instead, so that message names - /// the call itself — the shape AddAgentCoreAsync already uses when it names + /// the conversation itself — the shape AddAgentCoreAsync already uses when it names /// options.UseChatClients(...) to a host that bound no chat client adapter. A host that /// registered some other vendor is told to add one for this kind, because the list it just read /// is the rest of the answer. @@ -85,7 +85,7 @@ public static TAdapter Select( private static string Registered(Dictionary> byKind, VendorSeam seam) where TAdapter : IVendorAdapter => byKind.Count == 0 - ? $"no adapter. Call {seam.RegistrationHint}, or change the document." + ? $"no adapter. Conversation {seam.RegistrationHint}, or change the document." : string.Join(", ", byKind.Keys.Select(k => "'" + k + "'")) + ". Register an adapter for that kind, or change the document."; diff --git a/src/AgentCore.Application/Providers/VendorSeam.cs b/src/AgentCore.Application/Providers/VendorSeam.cs index 013e48b6..f86cd549 100644 --- a/src/AgentCore.Application/Providers/VendorSeam.cs +++ b/src/AgentCore.Application/Providers/VendorSeam.cs @@ -1,7 +1,7 @@ namespace AgentCore.Application.Providers; /// -/// What one vendor seam calls itself, so a shared selector can write its failures. +/// What one vendor seam conversations itself, so a shared selector can write its failures. /// /// /// The dotted path a reader would find in the document, such as providers.speech. @@ -12,11 +12,11 @@ namespace AgentCore.Application.Providers; /// /// /// The call a host makes to register a vendor for this seam, such as options.UseSpeech(...). -/// A host that registered nothing has no kind to be offered instead, so the failure names the call +/// A host that registered nothing has no kind to be offered instead, so the failure names the conversation /// to make rather than an empty list. /// /// -/// The plural noun this seam calls two of its vendors, such as stores. It exists so one +/// The plural noun this seam conversations two of its vendors, such as stores. It exists so one /// selector can preserve four seams' wording: knowledge writes stores, telemetry writes /// collectors, moderation writes endpoints, and speech writes vendors. A seam /// that names none through the three-argument constructor gets vendors. diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 932aead6..d2671d74 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -3,7 +3,7 @@ AgentCore.Application.Audit.AuditSinkFactory AgentCore.Application.Audit.Memory.InMemoryAuditSink AgentCore.Application.Audit.Memory.InMemoryAuditSink.AppendAsync(AgentCore.Domain.Audit.AuditEvent! auditEvent, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Audit.Memory.InMemoryAuditSink.Events.get -> System.Collections.Generic.IReadOnlyList! -AgentCore.Application.Audit.Memory.InMemoryAuditSink.EventsOf(string! callId) -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Audit.Memory.InMemoryAuditSink.EventsOf(string! conversationId) -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Audit.Memory.InMemoryAuditSink.InMemoryAuditSink() -> void AgentCore.Application.Audit.QueuedAuditSink AgentCore.Application.Audit.QueuedAuditSink.AppendAsync(AgentCore.Domain.Audit.AuditEvent! auditEvent, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask @@ -12,146 +12,146 @@ AgentCore.Application.Audit.QueuedAuditSink.DisposeAsync() -> System.Threading.T AgentCore.Application.Audit.QueuedAuditSink.FlushAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Audit.QueuedAuditSink.QueuedAuditSink(AgentCore.Application.Ports.IAuditSinkPort! inner, Microsoft.Extensions.Logging.ILogger? logger = null, int capacity = 10000, int batchSize = 100) -> void AgentCore.Application.Audit.QueuedAuditSink.Store.get -> AgentCore.Application.Ports.IAuditSinkPort! -AgentCore.Application.Calls.CallChannel -AgentCore.Application.Calls.CallChannel.$() -> AgentCore.Application.Calls.CallChannel! -AgentCore.Application.Calls.CallChannel.CallChannel(AgentCore.Application.Ports.ICallInputPort! Input, AgentCore.Application.Ports.ICallOutputPort! Output) -> void -AgentCore.Application.Calls.CallChannel.Deconstruct(out AgentCore.Application.Ports.ICallInputPort! Input, out AgentCore.Application.Ports.ICallOutputPort! Output) -> void -AgentCore.Application.Calls.CallChannel.DisposeAsync() -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallChannel.Equals(AgentCore.Application.Calls.CallChannel? other) -> bool -AgentCore.Application.Calls.CallChannel.Input.get -> AgentCore.Application.Ports.ICallInputPort! -AgentCore.Application.Calls.CallChannel.Input.init -> void -AgentCore.Application.Calls.CallChannel.Output.get -> AgentCore.Application.Ports.ICallOutputPort! -AgentCore.Application.Calls.CallChannel.Output.init -> void -AgentCore.Application.Calls.CallChannelContext -AgentCore.Application.Calls.CallChannelContext.$() -> AgentCore.Application.Calls.CallChannelContext! -AgentCore.Application.Calls.CallChannelContext.CallChannelContext(string! CallId, System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void -AgentCore.Application.Calls.CallChannelContext.CallId.get -> string! -AgentCore.Application.Calls.CallChannelContext.CallId.init -> void -AgentCore.Application.Calls.CallChannelContext.CustomParameters.get -> System.Collections.Generic.IReadOnlyDictionary? -AgentCore.Application.Calls.CallChannelContext.CustomParameters.init -> void -AgentCore.Application.Calls.CallChannelContext.Deconstruct(out string! CallId, out System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void -AgentCore.Application.Calls.CallChannelContext.Equals(AgentCore.Application.Calls.CallChannelContext? other) -> bool -AgentCore.Application.Calls.CallClarificationState -AgentCore.Application.Calls.CallClarificationState.$() -> AgentCore.Application.Calls.CallClarificationState! -AgentCore.Application.Calls.CallClarificationState.CallClarificationState() -> void -AgentCore.Application.Calls.CallClarificationState.Equals(AgentCore.Application.Calls.CallClarificationState? other) -> bool -AgentCore.Application.Calls.CallClarificationState.ProbeAsks.get -> int -AgentCore.Application.Calls.CallClarificationState.ProbeAsks.init -> void -AgentCore.Application.Calls.CallCursor -AgentCore.Application.Calls.CallInput -AgentCore.Application.Calls.CallInput.Barge -AgentCore.Application.Calls.CallInput.Barge.Barge(string! HeardText, System.TimeSpan PlayedDuration) -> void -AgentCore.Application.Calls.CallInput.Barge.Deconstruct(out string! HeardText, out System.TimeSpan PlayedDuration) -> void -AgentCore.Application.Calls.CallInput.Barge.Equals(AgentCore.Application.Calls.CallInput.Barge? other) -> bool -AgentCore.Application.Calls.CallInput.Barge.HeardText.get -> string! -AgentCore.Application.Calls.CallInput.Barge.HeardText.init -> void -AgentCore.Application.Calls.CallInput.Barge.PlayedDuration.get -> System.TimeSpan -AgentCore.Application.Calls.CallInput.Barge.PlayedDuration.init -> void -AgentCore.Application.Calls.CallInput.CallInput(AgentCore.Application.Calls.CallInput! original) -> void -AgentCore.Application.Calls.CallInput.Keypress -AgentCore.Application.Calls.CallInput.Keypress.Deconstruct(out string! Key) -> void -AgentCore.Application.Calls.CallInput.Keypress.Equals(AgentCore.Application.Calls.CallInput.Keypress? other) -> bool -AgentCore.Application.Calls.CallInput.Keypress.Key.get -> string! -AgentCore.Application.Calls.CallInput.Keypress.Key.init -> void -AgentCore.Application.Calls.CallInput.Keypress.Keypress(string! Key) -> void -AgentCore.Application.Calls.CallInput.Utterance -AgentCore.Application.Calls.CallInput.Utterance.Deconstruct(out string! Text, out string! Language, out bool IsFinal) -> void -AgentCore.Application.Calls.CallInput.Utterance.Equals(AgentCore.Application.Calls.CallInput.Utterance? other) -> bool -AgentCore.Application.Calls.CallInput.Utterance.IsFinal.get -> bool -AgentCore.Application.Calls.CallInput.Utterance.IsFinal.init -> void -AgentCore.Application.Calls.CallInput.Utterance.Language.get -> string! -AgentCore.Application.Calls.CallInput.Utterance.Language.init -> void -AgentCore.Application.Calls.CallInput.Utterance.Text.get -> string! -AgentCore.Application.Calls.CallInput.Utterance.Text.init -> void -AgentCore.Application.Calls.CallInput.Utterance.Utterance(string! Text, string! Language, bool IsFinal) -> void -AgentCore.Application.Calls.CallPage -AgentCore.Application.Calls.CallPage.$() -> AgentCore.Application.Calls.CallPage! -AgentCore.Application.Calls.CallPage.CallPage(System.Collections.Generic.IReadOnlyList! Calls, string? NextCursor) -> void -AgentCore.Application.Calls.CallPage.Calls.get -> System.Collections.Generic.IReadOnlyList! -AgentCore.Application.Calls.CallPage.Calls.init -> void -AgentCore.Application.Calls.CallPage.Deconstruct(out System.Collections.Generic.IReadOnlyList! Calls, out string? NextCursor) -> void -AgentCore.Application.Calls.CallPage.Equals(AgentCore.Application.Calls.CallPage? other) -> bool -AgentCore.Application.Calls.CallPage.NextCursor.get -> string? -AgentCore.Application.Calls.CallPage.NextCursor.init -> void -AgentCore.Application.Calls.CallRecord -AgentCore.Application.Calls.CallRecord.$() -> AgentCore.Application.Calls.CallRecord! -AgentCore.Application.Calls.CallRecord.CallId.get -> string! -AgentCore.Application.Calls.CallRecord.CallId.init -> void -AgentCore.Application.Calls.CallRecord.CallRecord(string! CallId, string? Title, AgentCore.Application.Calls.CallStatus Status, string? ExternalId, System.Text.Json.JsonElement? Custom, System.DateTimeOffset CreatedAt, System.DateTimeOffset? LastMessageAt, AgentCore.Application.Calls.CallSessionState? State = null, int NextOrdinal = 0) -> void -AgentCore.Application.Calls.CallRecord.CreatedAt.get -> System.DateTimeOffset -AgentCore.Application.Calls.CallRecord.CreatedAt.init -> void -AgentCore.Application.Calls.CallRecord.Custom.get -> System.Text.Json.JsonElement? -AgentCore.Application.Calls.CallRecord.Custom.init -> void -AgentCore.Application.Calls.CallRecord.Deconstruct(out string! CallId, out string? Title, out AgentCore.Application.Calls.CallStatus Status, out string? ExternalId, out System.Text.Json.JsonElement? Custom, out System.DateTimeOffset CreatedAt, out System.DateTimeOffset? LastMessageAt, out AgentCore.Application.Calls.CallSessionState? State, out int NextOrdinal) -> void -AgentCore.Application.Calls.CallRecord.Equals(AgentCore.Application.Calls.CallRecord? other) -> bool -AgentCore.Application.Calls.CallRecord.ExternalId.get -> string? -AgentCore.Application.Calls.CallRecord.ExternalId.init -> void -AgentCore.Application.Calls.CallRecord.LastMessageAt.get -> System.DateTimeOffset? -AgentCore.Application.Calls.CallRecord.LastMessageAt.init -> void -AgentCore.Application.Calls.CallRecord.NextOrdinal.get -> int -AgentCore.Application.Calls.CallRecord.NextOrdinal.init -> void -AgentCore.Application.Calls.CallRecord.State.get -> AgentCore.Application.Calls.CallSessionState? -AgentCore.Application.Calls.CallRecord.State.init -> void -AgentCore.Application.Calls.CallRecord.Status.get -> AgentCore.Application.Calls.CallStatus -AgentCore.Application.Calls.CallRecord.Status.init -> void -AgentCore.Application.Calls.CallRecord.Title.get -> string? -AgentCore.Application.Calls.CallRecord.Title.init -> void -AgentCore.Application.Calls.CallSessionState -AgentCore.Application.Calls.CallSessionState.$() -> AgentCore.Application.Calls.CallSessionState! -AgentCore.Application.Calls.CallSessionState.CallSessionState() -> void -AgentCore.Application.Calls.CallSessionState.Clarifications.get -> System.Collections.Generic.IReadOnlyDictionary! -AgentCore.Application.Calls.CallSessionState.Clarifications.init -> void -AgentCore.Application.Calls.CallSessionState.Equals(AgentCore.Application.Calls.CallSessionState? other) -> bool -AgentCore.Application.Calls.CallSessionState.IsComplete.get -> bool -AgentCore.Application.Calls.CallSessionState.IsComplete.init -> void -AgentCore.Application.Calls.CallSessionState.NextTurnIndex.get -> int -AgentCore.Application.Calls.CallSessionState.NextTurnIndex.init -> void -AgentCore.Application.Calls.CallSessionState.Providers.get -> System.Collections.Generic.IReadOnlyDictionary! -AgentCore.Application.Calls.CallSessionState.Providers.init -> void -AgentCore.Application.Calls.CallSessionState.Slots.get -> System.Collections.Generic.IReadOnlyDictionary! -AgentCore.Application.Calls.CallSessionState.Slots.init -> void -AgentCore.Application.Calls.CallSessionState.Stage.get -> string! -AgentCore.Application.Calls.CallSessionState.Stage.init -> void -AgentCore.Application.Calls.CallSessionState.Version.get -> int -AgentCore.Application.Calls.CallSessionState.Version.init -> void -AgentCore.Application.Calls.CallSessionState.WorkflowState.get -> System.Text.Json.JsonElement? -AgentCore.Application.Calls.CallSessionState.WorkflowState.init -> void -AgentCore.Application.Calls.CallSpeechPairing -AgentCore.Application.Calls.CallStateJson -AgentCore.Application.Calls.CallStatus -AgentCore.Application.Calls.CallStatus.Archived = 1 -> AgentCore.Application.Calls.CallStatus -AgentCore.Application.Calls.CallStatus.Regular = 0 -> AgentCore.Application.Calls.CallStatus -AgentCore.Application.Calls.CallStoreFactory -AgentCore.Application.Calls.ChatCallTitler -AgentCore.Application.Calls.ChatCallTitler.ChatCallTitler(AgentCore.Application.Ports.ICallStore! calls, Microsoft.Extensions.AI.IChatClient! client) -> void -AgentCore.Application.Calls.ChatCallTitler.GenerateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Calls.ChatCallTitler.GenerateFromAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Calls.Memory.InMemoryCallStore -AgentCore.Application.Calls.Memory.InMemoryCallStore.AppendAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Calls.CallSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> -AgentCore.Application.Calls.Memory.InMemoryCallStore.AttachPrincipalAsync(string! callId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.CreateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.DeleteAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.DetachPrincipalAsync(string! callId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.EraseAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.GetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.InMemoryCallStore(System.TimeProvider? timeProvider = null) -> void -AgentCore.Application.Calls.Memory.InMemoryCallStore.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Calls.CallStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.ReadAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> -AgentCore.Application.Calls.Memory.InMemoryCallStore.RenameAsync(string! callId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.RewriteAsync(string! callId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.SetCustomAsync(string! callId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.SetExternalIdAsync(string! callId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.SetStatusAsync(string! callId, AgentCore.Application.Calls.CallStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.Memory.InMemoryCallStore.TruncateAsync(string! callId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.ConversationChannel +AgentCore.Application.Conversation.ConversationChannel.$() -> AgentCore.Application.Conversation.ConversationChannel! +AgentCore.Application.Conversation.ConversationChannel.ConversationChannel(AgentCore.Application.Ports.IConversationInputPort! Input, AgentCore.Application.Ports.IConversationOutputPort! Output) -> void +AgentCore.Application.Conversation.ConversationChannel.Deconstruct(out AgentCore.Application.Ports.IConversationInputPort! Input, out AgentCore.Application.Ports.IConversationOutputPort! Output) -> void +AgentCore.Application.Conversation.ConversationChannel.DisposeAsync() -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.ConversationChannel.Equals(AgentCore.Application.Conversation.ConversationChannel? other) -> bool +AgentCore.Application.Conversation.ConversationChannel.Input.get -> AgentCore.Application.Ports.IConversationInputPort! +AgentCore.Application.Conversation.ConversationChannel.Input.init -> void +AgentCore.Application.Conversation.ConversationChannel.Output.get -> AgentCore.Application.Ports.IConversationOutputPort! +AgentCore.Application.Conversation.ConversationChannel.Output.init -> void +AgentCore.Application.Conversation.ConversationChannelContext +AgentCore.Application.Conversation.ConversationChannelContext.$() -> AgentCore.Application.Conversation.ConversationChannelContext! +AgentCore.Application.Conversation.ConversationChannelContext.ConversationChannelContext(string! ConversationId, System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void +AgentCore.Application.Conversation.ConversationChannelContext.ConversationId.get -> string! +AgentCore.Application.Conversation.ConversationChannelContext.ConversationId.init -> void +AgentCore.Application.Conversation.ConversationChannelContext.CustomParameters.get -> System.Collections.Generic.IReadOnlyDictionary? +AgentCore.Application.Conversation.ConversationChannelContext.CustomParameters.init -> void +AgentCore.Application.Conversation.ConversationChannelContext.Deconstruct(out string! ConversationId, out System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void +AgentCore.Application.Conversation.ConversationChannelContext.Equals(AgentCore.Application.Conversation.ConversationChannelContext? other) -> bool +AgentCore.Application.Conversation.ConversationClarificationState +AgentCore.Application.Conversation.ConversationClarificationState.$() -> AgentCore.Application.Conversation.ConversationClarificationState! +AgentCore.Application.Conversation.ConversationClarificationState.ConversationClarificationState() -> void +AgentCore.Application.Conversation.ConversationClarificationState.Equals(AgentCore.Application.Conversation.ConversationClarificationState? other) -> bool +AgentCore.Application.Conversation.ConversationClarificationState.ProbeAsks.get -> int +AgentCore.Application.Conversation.ConversationClarificationState.ProbeAsks.init -> void +AgentCore.Application.Conversation.ConversationCursor +AgentCore.Application.Conversation.ConversationInput +AgentCore.Application.Conversation.ConversationInput.Barge +AgentCore.Application.Conversation.ConversationInput.Barge.Barge(string! HeardText, System.TimeSpan PlayedDuration) -> void +AgentCore.Application.Conversation.ConversationInput.Barge.Deconstruct(out string! HeardText, out System.TimeSpan PlayedDuration) -> void +AgentCore.Application.Conversation.ConversationInput.Barge.Equals(AgentCore.Application.Conversation.ConversationInput.Barge? other) -> bool +AgentCore.Application.Conversation.ConversationInput.Barge.HeardText.get -> string! +AgentCore.Application.Conversation.ConversationInput.Barge.HeardText.init -> void +AgentCore.Application.Conversation.ConversationInput.Barge.PlayedDuration.get -> System.TimeSpan +AgentCore.Application.Conversation.ConversationInput.Barge.PlayedDuration.init -> void +AgentCore.Application.Conversation.ConversationInput.ConversationInput(AgentCore.Application.Conversation.ConversationInput! original) -> void +AgentCore.Application.Conversation.ConversationInput.Keypress +AgentCore.Application.Conversation.ConversationInput.Keypress.Deconstruct(out string! Key) -> void +AgentCore.Application.Conversation.ConversationInput.Keypress.Equals(AgentCore.Application.Conversation.ConversationInput.Keypress? other) -> bool +AgentCore.Application.Conversation.ConversationInput.Keypress.Key.get -> string! +AgentCore.Application.Conversation.ConversationInput.Keypress.Key.init -> void +AgentCore.Application.Conversation.ConversationInput.Keypress.Keypress(string! Key) -> void +AgentCore.Application.Conversation.ConversationInput.Utterance +AgentCore.Application.Conversation.ConversationInput.Utterance.Deconstruct(out string! Text, out string! Language, out bool IsFinal) -> void +AgentCore.Application.Conversation.ConversationInput.Utterance.Equals(AgentCore.Application.Conversation.ConversationInput.Utterance? other) -> bool +AgentCore.Application.Conversation.ConversationInput.Utterance.IsFinal.get -> bool +AgentCore.Application.Conversation.ConversationInput.Utterance.IsFinal.init -> void +AgentCore.Application.Conversation.ConversationInput.Utterance.Language.get -> string! +AgentCore.Application.Conversation.ConversationInput.Utterance.Language.init -> void +AgentCore.Application.Conversation.ConversationInput.Utterance.Text.get -> string! +AgentCore.Application.Conversation.ConversationInput.Utterance.Text.init -> void +AgentCore.Application.Conversation.ConversationInput.Utterance.Utterance(string! Text, string! Language, bool IsFinal) -> void +AgentCore.Application.Conversation.ConversationPage +AgentCore.Application.Conversation.ConversationPage.$() -> AgentCore.Application.Conversation.ConversationPage! +AgentCore.Application.Conversation.ConversationPage.ConversationPage(System.Collections.Generic.IReadOnlyList! Conversations, string? NextCursor) -> void +AgentCore.Application.Conversation.ConversationPage.Conversations.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Conversation.ConversationPage.Conversations.init -> void +AgentCore.Application.Conversation.ConversationPage.Deconstruct(out System.Collections.Generic.IReadOnlyList! Conversations, out string? NextCursor) -> void +AgentCore.Application.Conversation.ConversationPage.Equals(AgentCore.Application.Conversation.ConversationPage? other) -> bool +AgentCore.Application.Conversation.ConversationPage.NextCursor.get -> string? +AgentCore.Application.Conversation.ConversationPage.NextCursor.init -> void +AgentCore.Application.Conversation.ConversationRecord +AgentCore.Application.Conversation.ConversationRecord.$() -> AgentCore.Application.Conversation.ConversationRecord! +AgentCore.Application.Conversation.ConversationRecord.ConversationId.get -> string! +AgentCore.Application.Conversation.ConversationRecord.ConversationId.init -> void +AgentCore.Application.Conversation.ConversationRecord.ConversationRecord(string! ConversationId, string? Title, AgentCore.Application.Conversation.ConversationStatus Status, string? ExternalId, System.Text.Json.JsonElement? Custom, System.DateTimeOffset CreatedAt, System.DateTimeOffset? LastMessageAt, AgentCore.Application.Conversation.ConversationSessionState? State = null, int NextOrdinal = 0) -> void +AgentCore.Application.Conversation.ConversationRecord.CreatedAt.get -> System.DateTimeOffset +AgentCore.Application.Conversation.ConversationRecord.CreatedAt.init -> void +AgentCore.Application.Conversation.ConversationRecord.Custom.get -> System.Text.Json.JsonElement? +AgentCore.Application.Conversation.ConversationRecord.Custom.init -> void +AgentCore.Application.Conversation.ConversationRecord.Deconstruct(out string! ConversationId, out string? Title, out AgentCore.Application.Conversation.ConversationStatus Status, out string? ExternalId, out System.Text.Json.JsonElement? Custom, out System.DateTimeOffset CreatedAt, out System.DateTimeOffset? LastMessageAt, out AgentCore.Application.Conversation.ConversationSessionState? State, out int NextOrdinal) -> void +AgentCore.Application.Conversation.ConversationRecord.Equals(AgentCore.Application.Conversation.ConversationRecord? other) -> bool +AgentCore.Application.Conversation.ConversationRecord.ExternalId.get -> string? +AgentCore.Application.Conversation.ConversationRecord.ExternalId.init -> void +AgentCore.Application.Conversation.ConversationRecord.LastMessageAt.get -> System.DateTimeOffset? +AgentCore.Application.Conversation.ConversationRecord.LastMessageAt.init -> void +AgentCore.Application.Conversation.ConversationRecord.NextOrdinal.get -> int +AgentCore.Application.Conversation.ConversationRecord.NextOrdinal.init -> void +AgentCore.Application.Conversation.ConversationRecord.State.get -> AgentCore.Application.Conversation.ConversationSessionState? +AgentCore.Application.Conversation.ConversationRecord.State.init -> void +AgentCore.Application.Conversation.ConversationRecord.Status.get -> AgentCore.Application.Conversation.ConversationStatus +AgentCore.Application.Conversation.ConversationRecord.Status.init -> void +AgentCore.Application.Conversation.ConversationRecord.Title.get -> string? +AgentCore.Application.Conversation.ConversationRecord.Title.init -> void +AgentCore.Application.Conversation.ConversationSessionState +AgentCore.Application.Conversation.ConversationSessionState.$() -> AgentCore.Application.Conversation.ConversationSessionState! +AgentCore.Application.Conversation.ConversationSessionState.ConversationSessionState() -> void +AgentCore.Application.Conversation.ConversationSessionState.Clarifications.get -> System.Collections.Generic.IReadOnlyDictionary! +AgentCore.Application.Conversation.ConversationSessionState.Clarifications.init -> void +AgentCore.Application.Conversation.ConversationSessionState.Equals(AgentCore.Application.Conversation.ConversationSessionState? other) -> bool +AgentCore.Application.Conversation.ConversationSessionState.IsComplete.get -> bool +AgentCore.Application.Conversation.ConversationSessionState.IsComplete.init -> void +AgentCore.Application.Conversation.ConversationSessionState.NextTurnIndex.get -> int +AgentCore.Application.Conversation.ConversationSessionState.NextTurnIndex.init -> void +AgentCore.Application.Conversation.ConversationSessionState.Providers.get -> System.Collections.Generic.IReadOnlyDictionary! +AgentCore.Application.Conversation.ConversationSessionState.Providers.init -> void +AgentCore.Application.Conversation.ConversationSessionState.Slots.get -> System.Collections.Generic.IReadOnlyDictionary! +AgentCore.Application.Conversation.ConversationSessionState.Slots.init -> void +AgentCore.Application.Conversation.ConversationSessionState.Stage.get -> string! +AgentCore.Application.Conversation.ConversationSessionState.Stage.init -> void +AgentCore.Application.Conversation.ConversationSessionState.Version.get -> int +AgentCore.Application.Conversation.ConversationSessionState.Version.init -> void +AgentCore.Application.Conversation.ConversationSessionState.WorkflowState.get -> System.Text.Json.JsonElement? +AgentCore.Application.Conversation.ConversationSessionState.WorkflowState.init -> void +AgentCore.Application.Conversation.ConversationSpeechPairing +AgentCore.Application.Conversation.ConversationStateJson +AgentCore.Application.Conversation.ConversationStatus +AgentCore.Application.Conversation.ConversationStatus.Archived = 1 -> AgentCore.Application.Conversation.ConversationStatus +AgentCore.Application.Conversation.ConversationStatus.Regular = 0 -> AgentCore.Application.Conversation.ConversationStatus +AgentCore.Application.Conversation.ConversationStoreFactory +AgentCore.Application.Conversation.ChatConversationTitler +AgentCore.Application.Conversation.ChatConversationTitler.ChatConversationTitler(AgentCore.Application.Ports.IConversationStore! conversations, Microsoft.Extensions.AI.IChatClient! client) -> void +AgentCore.Application.Conversation.ChatConversationTitler.GenerateAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Conversation.ChatConversationTitler.GenerateFromAsync(string! conversationId, System.Collections.Generic.IReadOnlyList! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Conversation.Memory.InMemoryConversationStore +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.AppendAsync(string! conversationId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Conversation.ConversationSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.AttachPrincipalAsync(string! conversationId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.CreateAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.DeleteAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.DetachPrincipalAsync(string! conversationId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.EraseAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.GetAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.InMemoryConversationStore(System.TimeProvider? timeProvider = null) -> void +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Conversation.ConversationStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.ReadAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.RenameAsync(string! conversationId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.RewriteAsync(string! conversationId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.SetCustomAsync(string! conversationId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.SetExternalIdAsync(string! conversationId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.SetStatusAsync(string! conversationId, AgentCore.Application.Conversation.ConversationStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Memory.InMemoryConversationStore.TruncateAsync(string! conversationId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Configuration.Compilation.AgentCompaction AgentCore.Application.Configuration.Compilation.AgentCompilationContext AgentCore.Application.Configuration.Compilation.AgentCompilationContext.AgentCompilationContext(AgentCore.Application.Ports.IChatClientFactory! chatClients) -> void -AgentCore.Application.Configuration.Compilation.AgentCompilationContext.CallStore.get -> AgentCore.Application.Ports.ICallStore? -AgentCore.Application.Configuration.Compilation.AgentCompilationContext.CallStore.init -> void +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.ConversationStore.get -> AgentCore.Application.Ports.IConversationStore? +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.ConversationStore.init -> void AgentCore.Application.Configuration.Compilation.AgentCompilationContext.ChatClients.get -> AgentCore.Application.Ports.IChatClientFactory! AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Citations.get -> AgentCore.Application.Knowledge.IKnowledgeCitationFormatter? AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Citations.init -> void @@ -435,18 +435,18 @@ AgentCore.Application.Configuration.Schema.ApprovalConfiguration.ApprovalConfigu AgentCore.Application.Configuration.Schema.ApprovalConfiguration.Auto.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Configuration.Schema.ApprovalConfiguration.Auto.init -> void AgentCore.Application.Configuration.Schema.ApprovalConfiguration.Equals(AgentCore.Application.Configuration.Schema.ApprovalConfiguration? other) -> bool -AgentCore.Application.Configuration.Schema.CallProviderConfiguration -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.$() -> AgentCore.Application.Configuration.Schema.CallProviderConfiguration! -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.CallProviderConfiguration() -> void -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.CloseTimeoutSeconds.get -> int? -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.CloseTimeoutSeconds.init -> void -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.Equals(AgentCore.Application.Configuration.Schema.CallProviderConfiguration? other) -> bool -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.IdleTimeoutSeconds.get -> int? -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.IdleTimeoutSeconds.init -> void -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.Kind.get -> string! -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.Kind.init -> void -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.MaxFrameBytes.get -> int? -AgentCore.Application.Configuration.Schema.CallProviderConfiguration.MaxFrameBytes.init -> void +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.$() -> AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration! +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.ConversationProviderConfiguration() -> void +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.CloseTimeoutSeconds.get -> int? +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.CloseTimeoutSeconds.init -> void +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.Equals(AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.IdleTimeoutSeconds.get -> int? +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.IdleTimeoutSeconds.init -> void +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.Kind.get -> string! +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.Kind.init -> void +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.MaxFrameBytes.get -> int? +AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.MaxFrameBytes.init -> void AgentCore.Application.Configuration.Schema.CompactionConfiguration AgentCore.Application.Configuration.Schema.CompactionConfiguration.$() -> AgentCore.Application.Configuration.Schema.CompactionConfiguration! AgentCore.Application.Configuration.Schema.CompactionConfiguration.CompactionConfiguration() -> void @@ -795,10 +795,10 @@ AgentCore.Application.Configuration.Schema.ProvidersConfiguration AgentCore.Application.Configuration.Schema.ProvidersConfiguration.$() -> AgentCore.Application.Configuration.Schema.ProvidersConfiguration! AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Audit.get -> AgentCore.Application.Configuration.Schema.VendorProviderConfiguration? AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Audit.init -> void -AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Call.get -> AgentCore.Application.Configuration.Schema.CallProviderConfiguration? -AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Call.init -> void -AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Calls.get -> AgentCore.Application.Configuration.Schema.VendorProviderConfiguration? -AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Calls.init -> void +AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Conversation.get -> AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration? +AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Conversation.init -> void +AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Conversations.get -> AgentCore.Application.Configuration.Schema.VendorProviderConfiguration? +AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Conversations.init -> void AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Embeddings.get -> AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration? AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Embeddings.init -> void AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Equals(AgentCore.Application.Configuration.Schema.ProvidersConfiguration? other) -> bool @@ -1090,53 +1090,53 @@ AgentCore.Application.Ports.IAuditSinkAdapter.OpenAsync(AgentCore.Application.Co AgentCore.Application.Ports.IAuditSinkPort AgentCore.Application.Ports.IAuditSinkPort.AppendAsync(AgentCore.Domain.Audit.AuditEvent! auditEvent, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Ports.IAuditSinkPort.AppendManyAsync(System.Collections.Generic.IReadOnlyList! auditEvents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallAdapter -AgentCore.Application.Ports.ICallAdapter.CarriesText.get -> bool -AgentCore.Application.Ports.ICallChannelFactory -AgentCore.Application.Ports.ICallChannelFactory.OpenAsync(AgentCore.Application.Calls.CallChannelContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallInputPort -AgentCore.Application.Ports.ICallInputPort.ListenAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Ports.ICallObserver -AgentCore.Application.Ports.ICallObserver.OnCallEventAsync(AgentCore.Application.Runtime.CallEvent! callEvent, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallOutputPort -AgentCore.Application.Ports.ICallOutputPort.CompleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallOutputPort.SpeakAsync(string! fragment, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallOutputPort.StopAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallSessionFactory -AgentCore.Application.Ports.ICallSessionFactory.Create(string? callId = null, AgentCore.Application.Calls.CallSessionState? state = null) -> AgentCore.Application.Runtime.CallSession! -AgentCore.Application.Ports.ICallSessionRegistry -AgentCore.Application.Ports.ICallSessionRegistry.Entries.get -> System.Collections.Generic.IReadOnlyCollection! -AgentCore.Application.Ports.ICallSessionRegistry.ForSessions(string! entry) -> AgentCore.Application.Ports.ICallSessions! -AgentCore.Application.Ports.ICallSessions -AgentCore.Application.Ports.ICallSessions.CloseAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallSessions.OpenAsync(string? callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallSessions.TryGetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore -AgentCore.Application.Ports.ICallStore.AppendAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Calls.CallSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> -AgentCore.Application.Ports.ICallStore.AppendMessageAsync(string! callId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.AttachPrincipalAsync(string! callId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.CreateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.DeleteAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.DetachPrincipalAsync(string! callId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.EraseAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.GetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Calls.CallStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.ReadAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> -AgentCore.Application.Ports.ICallStore.RenameAsync(string! callId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.RewriteAsync(string! callId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.SetCustomAsync(string! callId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.SetExternalIdAsync(string! callId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.SetStatusAsync(string! callId, AgentCore.Application.Calls.CallStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStore.TruncateAsync(string! callId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallStoreAdapter -AgentCore.Application.Ports.ICallStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.ICallTitler -AgentCore.Application.Ports.ICallTitler.GenerateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Ports.ICallTitler.GenerateFromAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Ports.IConversationAdapter +AgentCore.Application.Ports.IConversationAdapter.CarriesText.get -> bool +AgentCore.Application.Ports.IConversationChannelFactory +AgentCore.Application.Ports.IConversationChannelFactory.OpenAsync(AgentCore.Application.Conversation.ConversationChannelContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationInputPort +AgentCore.Application.Ports.IConversationInputPort.ListenAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Ports.IConversationObserver +AgentCore.Application.Ports.IConversationObserver.OnConversationEventAsync(AgentCore.Application.Runtime.ConversationEvent! conversationEvent, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationOutputPort +AgentCore.Application.Ports.IConversationOutputPort.CompleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationOutputPort.SpeakAsync(string! fragment, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationOutputPort.StopAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationSessionFactory +AgentCore.Application.Ports.IConversationSessionFactory.Create(string? conversationId = null, AgentCore.Application.Conversation.ConversationSessionState? state = null) -> AgentCore.Application.Runtime.ConversationSession! +AgentCore.Application.Ports.IConversationSessionRegistry +AgentCore.Application.Ports.IConversationSessionRegistry.Entries.get -> System.Collections.Generic.IReadOnlyCollection! +AgentCore.Application.Ports.IConversationSessionRegistry.ForSessions(string! entry) -> AgentCore.Application.Ports.IConversationSessions! +AgentCore.Application.Ports.IConversationSessions +AgentCore.Application.Ports.IConversationSessions.CloseAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationSessions.OpenAsync(string? conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationSessions.TryGetAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore +AgentCore.Application.Ports.IConversationStore.AppendAsync(string! conversationId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Conversation.ConversationSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Ports.IConversationStore.AppendMessageAsync(string! conversationId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.AttachPrincipalAsync(string! conversationId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.CreateAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.DeleteAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.DetachPrincipalAsync(string! conversationId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.EraseAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.GetAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Conversation.ConversationStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.ReadAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Ports.IConversationStore.RenameAsync(string! conversationId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.RewriteAsync(string! conversationId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.SetCustomAsync(string! conversationId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.SetExternalIdAsync(string! conversationId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.SetStatusAsync(string! conversationId, AgentCore.Application.Conversation.ConversationStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStore.TruncateAsync(string! conversationId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationStoreAdapter +AgentCore.Application.Ports.IConversationStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversationTitler +AgentCore.Application.Ports.IConversationTitler.GenerateAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Ports.IConversationTitler.GenerateFromAsync(string! conversationId, System.Collections.Generic.IReadOnlyList! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! AgentCore.Application.Ports.IChatClientAdapter AgentCore.Application.Ports.IChatClientAdapter.CreateClientAsync(AgentCore.Application.Configuration.Schema.LlmProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Ports.IChatClientAdapter.ResolveHostedTool(Microsoft.Extensions.AI.AITool! marker, AgentCore.Application.Configuration.Schema.LlmProviderConfiguration! entry) -> Microsoft.Extensions.AI.AITool? @@ -1144,7 +1144,7 @@ AgentCore.Application.Ports.IChatClientFactory AgentCore.Application.Ports.IChatClientFactory.GetChatClient(AgentCore.Application.Configuration.Schema.ModelReference? model) -> Microsoft.Extensions.AI.IChatClient! AgentCore.Application.Ports.IChatClientFactory.ResolveHostedTool(Microsoft.Extensions.AI.AITool! marker, AgentCore.Application.Configuration.Schema.ModelReference? model) -> Microsoft.Extensions.AI.AITool? AgentCore.Application.Ports.IConversationPort -AgentCore.Application.Ports.IConversationPort.CallId.get -> string! +AgentCore.Application.Ports.IConversationPort.ConversationId.get -> string! AgentCore.Application.Ports.IConversationPort.Interrupt(string! utteranceUntilInterrupt, System.TimeSpan durationUntilInterrupt, bool cutsRunningTurn = true) -> bool AgentCore.Application.Ports.IConversationPort.IsComplete.get -> bool AgentCore.Application.Ports.IConversationPort.LastTurn.get -> AgentCore.Domain.TurnResult? @@ -1201,85 +1201,85 @@ AgentCore.Application.Providers.VendorSeam.VendorSeam() -> void AgentCore.Application.Providers.VendorSeam.VendorSeam(string! DocumentPath, string! Pointer, string! RegistrationHint, string! Plural) -> void AgentCore.Application.Providers.VendorSeam.VendorSeam(string! documentPath, string! pointer, string! registrationHint) -> void AgentCore.Application.Runtime.AgentCoreAgent -AgentCore.Application.Runtime.AgentCoreAgent.AgentCoreAgent(AgentCore.Application.Ports.ICallSessionFactory! sessions, string! entryName, string? description = null) -> void -AgentCore.Application.Runtime.AgentCoreAgent.CreateSessionAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Runtime.AgentCoreAgent.AgentCoreAgent(AgentCore.Application.Ports.IConversationSessionFactory! sessions, string! entryName, string? description = null) -> void +AgentCore.Application.Runtime.AgentCoreAgent.CreateSessionAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Runtime.AgentCoreAgent.EntryName.get -> string! -AgentCore.Application.Runtime.CallEvent -AgentCore.Application.Runtime.CallEvent.$() -> AgentCore.Application.Runtime.CallEvent! -AgentCore.Application.Runtime.CallEvent.AmendsEventId.get -> System.Guid? -AgentCore.Application.Runtime.CallEvent.AmendsEventId.init -> void -AgentCore.Application.Runtime.CallEvent.CallEvent() -> void -AgentCore.Application.Runtime.CallEvent.CallId.get -> string! -AgentCore.Application.Runtime.CallEvent.CallId.init -> void -AgentCore.Application.Runtime.CallEvent.Equals(AgentCore.Application.Runtime.CallEvent? other) -> bool -AgentCore.Application.Runtime.CallEvent.EventId.get -> System.Guid? -AgentCore.Application.Runtime.CallEvent.EventId.init -> void -AgentCore.Application.Runtime.CallEvent.Kind.get -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEvent.Kind.init -> void -AgentCore.Application.Runtime.CallEvent.OccurredAt.get -> System.DateTimeOffset -AgentCore.Application.Runtime.CallEvent.OccurredAt.init -> void -AgentCore.Application.Runtime.CallEvent.Payload.get -> System.Collections.Generic.IReadOnlyDictionary! -AgentCore.Application.Runtime.CallEvent.Payload.init -> void -AgentCore.Application.Runtime.CallEvent.TurnIndex.get -> int? -AgentCore.Application.Runtime.CallEvent.TurnIndex.init -> void -AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.CallEnded = 9 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.CallStarted = 0 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.EmptyReply = 5 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.ExtractionFailed = 6 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.ModerationClean = 3 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.ModerationUnavailable = 2 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.PromptFlagged = 1 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.ReplyInterrupted = 8 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.StateRestorePartial = 11 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.ToolFailed = 4 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.TranscriptResyncFailed = 13 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.TranscriptWriteFailed = 10 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.TurnCompleted = 7 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallEventKind.TurnSuperseded = 12 -> AgentCore.Application.Runtime.CallEventKind -AgentCore.Application.Runtime.CallObservers -AgentCore.Application.Runtime.CallSession -AgentCore.Application.Runtime.CallSession.CallId.get -> string! -AgentCore.Application.Runtime.CallSession.Compiled.get -> AgentCore.Application.Configuration.Compilation.CompiledAgent! -AgentCore.Application.Runtime.CallSession.DisposeAsync() -> System.Threading.Tasks.ValueTask -AgentCore.Application.Runtime.CallSession.EndCall(AgentCore.Domain.Audit.CallEndReason reason) -> bool -AgentCore.Application.Runtime.CallSession.FlushTranscriptAsync() -> System.Threading.Tasks.Task! -AgentCore.Application.Runtime.CallSession.Interrupt(string! utteranceUntilInterrupt, System.TimeSpan durationUntilInterrupt, bool cutsRunningTurn = true) -> bool -AgentCore.Application.Runtime.CallSession.IsComplete.get -> bool -AgentCore.Application.Runtime.CallSession.LastReplyMessageId.get -> string? -AgentCore.Application.Runtime.CallSession.LastTurn.get -> AgentCore.Domain.TurnResult? -AgentCore.Application.Runtime.CallSession.RunTurnAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -AgentCore.Application.Runtime.CallSession.RunTurnAtOriginAsync(string! userInput, AgentCore.Application.Runtime.CallTurnOrigin? origin, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -AgentCore.Application.Runtime.CallSession.RunTurnMessageAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! -AgentCore.Application.Runtime.CallSession.RunTurnMessageAtOriginAsync(Microsoft.Extensions.AI.ChatMessage! userInput, AgentCore.Application.Runtime.CallTurnOrigin? origin, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! -AgentCore.Application.Runtime.CallSession.RunTurnMessageStreamingAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Runtime.CallSession.RunTurnMessageStreamingAtOriginAsync(Microsoft.Extensions.AI.ChatMessage! userInput, AgentCore.Application.Runtime.CallTurnOrigin? origin, System.Threading.CancellationToken cancellationToken) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Runtime.CallSession.RunTurnStreamingAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Runtime.CallSession.RunTurnStreamingAtOriginAsync(string! userInput, AgentCore.Application.Runtime.CallTurnOrigin? origin, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! -AgentCore.Application.Runtime.CallSession.Scope.get -> AgentCore.Domain.Knowledge.KnowledgeScope? -AgentCore.Application.Runtime.CallSession.Scope.set -> void -AgentCore.Application.Runtime.CallSession.SetDelegatedTools(string! delegatingToolId, System.Collections.Generic.IReadOnlyList! tools) -> void -AgentCore.Application.Runtime.CallSession.SetHasScreen(bool hasScreen) -> void -AgentCore.Application.Runtime.CallSession.Stage.get -> string! -AgentCore.Application.Runtime.CallSession.State.get -> AgentCore.Application.State.StateDocument! -AgentCore.Application.Runtime.CallSession.Transcript.get -> System.Collections.Generic.IReadOnlyList! -AgentCore.Application.Runtime.CallSession.TryCreateApprovalAnswer(string! requestId, bool approved) -> Microsoft.Extensions.AI.ChatMessage? -AgentCore.Application.Runtime.CallSession.TryCreateApprovalAnswerAsync(string! requestId, bool approved, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Runtime.CallSession.Workspace.get -> string? -AgentCore.Application.Runtime.CallSessionFactory -AgentCore.Application.Runtime.CallSessionFactory.CallSessionFactory(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Configuration.Validation.IGuardEvaluator! guards, AgentCore.Application.State.StateExtractor? extractor = null, System.TimeProvider? timeProvider = null, Microsoft.Extensions.Logging.ILogger? logger = null, System.Collections.Generic.IEnumerable? observers = null, string? workspaceRoot = null) -> void -AgentCore.Application.Runtime.CallSessionFactory.Create(string? callId = null, AgentCore.Application.Calls.CallSessionState? state = null) -> AgentCore.Application.Runtime.CallSession! -AgentCore.Application.Runtime.CallTurnOrigin -AgentCore.Application.Runtime.CallTurnOrigin.$() -> AgentCore.Application.Runtime.CallTurnOrigin! -AgentCore.Application.Runtime.CallTurnOrigin.CallTurnOrigin(string? MessageId, string? ParentMessageId) -> void -AgentCore.Application.Runtime.CallTurnOrigin.Deconstruct(out string? MessageId, out string? ParentMessageId) -> void -AgentCore.Application.Runtime.CallTurnOrigin.Equals(AgentCore.Application.Runtime.CallTurnOrigin? other) -> bool -AgentCore.Application.Runtime.CallTurnOrigin.MessageId.get -> string? -AgentCore.Application.Runtime.CallTurnOrigin.MessageId.init -> void -AgentCore.Application.Runtime.CallTurnOrigin.NamesParent.get -> bool -AgentCore.Application.Runtime.CallTurnOrigin.NamesParent.init -> void -AgentCore.Application.Runtime.CallTurnOrigin.ParentMessageId.get -> string? -AgentCore.Application.Runtime.CallTurnOrigin.ParentMessageId.init -> void +AgentCore.Application.Runtime.ConversationEvent +AgentCore.Application.Runtime.ConversationEvent.$() -> AgentCore.Application.Runtime.ConversationEvent! +AgentCore.Application.Runtime.ConversationEvent.AmendsEventId.get -> System.Guid? +AgentCore.Application.Runtime.ConversationEvent.AmendsEventId.init -> void +AgentCore.Application.Runtime.ConversationEvent.ConversationEvent() -> void +AgentCore.Application.Runtime.ConversationEvent.ConversationId.get -> string! +AgentCore.Application.Runtime.ConversationEvent.ConversationId.init -> void +AgentCore.Application.Runtime.ConversationEvent.Equals(AgentCore.Application.Runtime.ConversationEvent? other) -> bool +AgentCore.Application.Runtime.ConversationEvent.EventId.get -> System.Guid? +AgentCore.Application.Runtime.ConversationEvent.EventId.init -> void +AgentCore.Application.Runtime.ConversationEvent.Kind.get -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEvent.Kind.init -> void +AgentCore.Application.Runtime.ConversationEvent.OccurredAt.get -> System.DateTimeOffset +AgentCore.Application.Runtime.ConversationEvent.OccurredAt.init -> void +AgentCore.Application.Runtime.ConversationEvent.Payload.get -> System.Collections.Generic.IReadOnlyDictionary! +AgentCore.Application.Runtime.ConversationEvent.Payload.init -> void +AgentCore.Application.Runtime.ConversationEvent.TurnIndex.get -> int? +AgentCore.Application.Runtime.ConversationEvent.TurnIndex.init -> void +AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ConversationEnded = 9 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ConversationStarted = 0 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.EmptyReply = 5 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ExtractionFailed = 6 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ModerationClean = 3 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ModerationUnavailable = 2 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.PromptFlagged = 1 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ReplyInterrupted = 8 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.StateRestorePartial = 11 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.ToolFailed = 4 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.TranscriptResyncFailed = 13 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.TranscriptWriteFailed = 10 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.TurnCompleted = 7 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationEventKind.TurnSuperseded = 12 -> AgentCore.Application.Runtime.ConversationEventKind +AgentCore.Application.Runtime.ConversationObservers +AgentCore.Application.Runtime.ConversationSession +AgentCore.Application.Runtime.ConversationSession.ConversationId.get -> string! +AgentCore.Application.Runtime.ConversationSession.Compiled.get -> AgentCore.Application.Configuration.Compilation.CompiledAgent! +AgentCore.Application.Runtime.ConversationSession.DisposeAsync() -> System.Threading.Tasks.ValueTask +AgentCore.Application.Runtime.ConversationSession.EndConversation(AgentCore.Domain.Audit.ConversationEndReason reason) -> bool +AgentCore.Application.Runtime.ConversationSession.FlushTranscriptAsync() -> System.Threading.Tasks.Task! +AgentCore.Application.Runtime.ConversationSession.Interrupt(string! utteranceUntilInterrupt, System.TimeSpan durationUntilInterrupt, bool cutsRunningTurn = true) -> bool +AgentCore.Application.Runtime.ConversationSession.IsComplete.get -> bool +AgentCore.Application.Runtime.ConversationSession.LastReplyMessageId.get -> string? +AgentCore.Application.Runtime.ConversationSession.LastTurn.get -> AgentCore.Domain.TurnResult? +AgentCore.Application.Runtime.ConversationSession.RunTurnAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +AgentCore.Application.Runtime.ConversationSession.RunTurnAtOriginAsync(string! userInput, AgentCore.Application.Runtime.ConversationTurnOrigin? origin, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +AgentCore.Application.Runtime.ConversationSession.RunTurnMessageAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +AgentCore.Application.Runtime.ConversationSession.RunTurnMessageAtOriginAsync(Microsoft.Extensions.AI.ChatMessage! userInput, AgentCore.Application.Runtime.ConversationTurnOrigin? origin, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +AgentCore.Application.Runtime.ConversationSession.RunTurnMessageStreamingAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Runtime.ConversationSession.RunTurnMessageStreamingAtOriginAsync(Microsoft.Extensions.AI.ChatMessage! userInput, AgentCore.Application.Runtime.ConversationTurnOrigin? origin, System.Threading.CancellationToken cancellationToken) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Runtime.ConversationSession.RunTurnStreamingAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Runtime.ConversationSession.RunTurnStreamingAtOriginAsync(string! userInput, AgentCore.Application.Runtime.ConversationTurnOrigin? origin, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Runtime.ConversationSession.Scope.get -> AgentCore.Domain.Knowledge.KnowledgeScope? +AgentCore.Application.Runtime.ConversationSession.Scope.set -> void +AgentCore.Application.Runtime.ConversationSession.SetDelegatedTools(string! delegatingToolId, System.Collections.Generic.IReadOnlyList! tools) -> void +AgentCore.Application.Runtime.ConversationSession.SetHasScreen(bool hasScreen) -> void +AgentCore.Application.Runtime.ConversationSession.Stage.get -> string! +AgentCore.Application.Runtime.ConversationSession.State.get -> AgentCore.Application.State.StateDocument! +AgentCore.Application.Runtime.ConversationSession.Transcript.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Runtime.ConversationSession.TryCreateApprovalAnswer(string! requestId, bool approved) -> Microsoft.Extensions.AI.ChatMessage? +AgentCore.Application.Runtime.ConversationSession.TryCreateApprovalAnswerAsync(string! requestId, bool approved, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Runtime.ConversationSession.Workspace.get -> string? +AgentCore.Application.Runtime.ConversationSessionFactory +AgentCore.Application.Runtime.ConversationSessionFactory.ConversationSessionFactory(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Configuration.Validation.IGuardEvaluator! guards, AgentCore.Application.State.StateExtractor? extractor = null, System.TimeProvider? timeProvider = null, Microsoft.Extensions.Logging.ILogger? logger = null, System.Collections.Generic.IEnumerable? observers = null, string? workspaceRoot = null) -> void +AgentCore.Application.Runtime.ConversationSessionFactory.Create(string? conversationId = null, AgentCore.Application.Conversation.ConversationSessionState? state = null) -> AgentCore.Application.Runtime.ConversationSession! +AgentCore.Application.Runtime.ConversationTurnOrigin +AgentCore.Application.Runtime.ConversationTurnOrigin.$() -> AgentCore.Application.Runtime.ConversationTurnOrigin! +AgentCore.Application.Runtime.ConversationTurnOrigin.ConversationTurnOrigin(string? MessageId, string? ParentMessageId) -> void +AgentCore.Application.Runtime.ConversationTurnOrigin.Deconstruct(out string? MessageId, out string? ParentMessageId) -> void +AgentCore.Application.Runtime.ConversationTurnOrigin.Equals(AgentCore.Application.Runtime.ConversationTurnOrigin? other) -> bool +AgentCore.Application.Runtime.ConversationTurnOrigin.MessageId.get -> string? +AgentCore.Application.Runtime.ConversationTurnOrigin.MessageId.init -> void +AgentCore.Application.Runtime.ConversationTurnOrigin.NamesParent.get -> bool +AgentCore.Application.Runtime.ConversationTurnOrigin.NamesParent.init -> void +AgentCore.Application.Runtime.ConversationTurnOrigin.ParentMessageId.get -> string? +AgentCore.Application.Runtime.ConversationTurnOrigin.ParentMessageId.init -> void AgentCore.Application.Scripting.ScriptRequest AgentCore.Application.Scripting.ScriptRequest.$() -> AgentCore.Application.Scripting.ScriptRequest! AgentCore.Application.Scripting.ScriptRequest.Code.get -> string! @@ -1318,13 +1318,13 @@ AgentCore.Application.Secrets.SecretResolutionException.SecretResolutionExceptio AgentCore.Application.Secrets.SecretResolutionException.SecretResolutionException(string! message) -> void AgentCore.Application.Secrets.SecretResolutionException.SecretResolutionException(string! message, System.Exception? innerException) -> void AgentCore.Application.Secrets.SecretResolverExtensions -AgentCore.Application.Sessions.Memory.InMemoryCallSessions -AgentCore.Application.Sessions.Memory.InMemoryCallSessions.CloseAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Sessions.Memory.InMemoryCallSessions.Count.get -> int -AgentCore.Application.Sessions.Memory.InMemoryCallSessions.InMemoryCallSessions(AgentCore.Application.Ports.ICallSessionFactory! factory, System.TimeSpan idleTimeout, System.TimeProvider! timeProvider) -> void -AgentCore.Application.Sessions.Memory.InMemoryCallSessions.OpenAsync(string? callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Sessions.Memory.InMemoryCallSessions.SweepAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Sessions.Memory.InMemoryCallSessions.TryGetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.CloseAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.Count.get -> int +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.InMemoryConversationSessions(AgentCore.Application.Ports.IConversationSessionFactory! factory, System.TimeSpan idleTimeout, System.TimeProvider! timeProvider) -> void +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.OpenAsync(string? conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.SweepAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.TryGetAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Application.Skills.SkillCatalog AgentCore.Application.Skills.SkillCatalog.Names.get -> System.Collections.Generic.IReadOnlySet! AgentCore.Application.Skills.SkillCatalog.SkillCatalog(Microsoft.Agents.AI.AgentSkillsSource! source, System.Collections.Generic.IReadOnlySet! names) -> void @@ -1334,8 +1334,8 @@ AgentCore.Application.State.CounterStateWriter AgentCore.Application.State.CounterStateWriter.Apply(AgentCore.Application.State.StateDocument! state) -> int AgentCore.Application.State.CounterStateWriter.CounterStateWriter(AgentCore.Application.Configuration.Validation.IGuardEvaluator! rules) -> void AgentCore.Application.State.StateDocument -AgentCore.Application.State.StateDocument.CallDurationSeconds.get -> double -AgentCore.Application.State.StateDocument.CallDurationSeconds.set -> void +AgentCore.Application.State.StateDocument.ConversationDurationSeconds.get -> double +AgentCore.Application.State.StateDocument.ConversationDurationSeconds.set -> void AgentCore.Application.State.StateDocument.Configuration.get -> AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! AgentCore.Application.State.StateDocument.IsUnfilled(string! slot) -> bool AgentCore.Application.State.StateDocument.Read(string! slot) -> System.Text.Json.Nodes.JsonNode? @@ -1445,46 +1445,46 @@ AgentCore.Application.Tools.ToolCallNames.Of(Microsoft.Extensions.AI.FunctionRes AgentCore.Application.Tools.ToolCallNames.ToolCallNames() -> void AgentCore.Application.Tools.ToolCallScope AgentCore.Application.Tools.ToolCallScope.$() -> AgentCore.Application.Tools.ToolCallScope! -AgentCore.Application.Tools.ToolCallScope.CallId.get -> string! -AgentCore.Application.Tools.ToolCallScope.CallId.init -> void -AgentCore.Application.Tools.ToolCallScope.Deconstruct(out string! CallId, out int TurnIndex, out string! Stage, out string? Workspace) -> void +AgentCore.Application.Tools.ToolCallScope.ConversationId.get -> string! +AgentCore.Application.Tools.ToolCallScope.ConversationId.init -> void +AgentCore.Application.Tools.ToolCallScope.Deconstruct(out string! ConversationId, out int TurnIndex, out string! Stage, out string? Workspace) -> void AgentCore.Application.Tools.ToolCallScope.Equals(AgentCore.Application.Tools.ToolCallScope? other) -> bool AgentCore.Application.Tools.ToolCallScope.Stage.get -> string! AgentCore.Application.Tools.ToolCallScope.Stage.init -> void -AgentCore.Application.Tools.ToolCallScope.ToolCallScope(string! CallId, int TurnIndex, string! Stage, string? Workspace = null) -> void +AgentCore.Application.Tools.ToolCallScope.ToolCallScope(string! ConversationId, int TurnIndex, string! Stage, string? Workspace = null) -> void AgentCore.Application.Tools.ToolCallScope.TurnIndex.get -> int AgentCore.Application.Tools.ToolCallScope.TurnIndex.init -> void AgentCore.Application.Tools.ToolCallScope.Workspace.get -> string? AgentCore.Application.Tools.ToolCallScope.Workspace.init -> void AgentCore.Application.Tools.ToolErrorResult AgentCore.Application.Tools.ToolResultJson -AgentCore.Application.Transcript.CallMessage -AgentCore.Application.Transcript.CallMessage.$() -> AgentCore.Application.Transcript.CallMessage! -AgentCore.Application.Transcript.CallMessage.CallId.get -> string! -AgentCore.Application.Transcript.CallMessage.CallId.init -> void -AgentCore.Application.Transcript.CallMessage.CallMessage(string! CallId, int Ordinal, int TurnIndex, Microsoft.Extensions.AI.ChatMessage! Content, string! MessageId) -> void -AgentCore.Application.Transcript.CallMessage.Content.get -> Microsoft.Extensions.AI.ChatMessage! -AgentCore.Application.Transcript.CallMessage.Content.init -> void -AgentCore.Application.Transcript.CallMessage.Deconstruct(out string! CallId, out int Ordinal, out int TurnIndex, out Microsoft.Extensions.AI.ChatMessage! Content, out string! MessageId) -> void -AgentCore.Application.Transcript.CallMessage.Equals(AgentCore.Application.Transcript.CallMessage? other) -> bool -AgentCore.Application.Transcript.CallMessage.MessageId.get -> string! -AgentCore.Application.Transcript.CallMessage.MessageId.init -> void -AgentCore.Application.Transcript.CallMessage.Ordinal.get -> int -AgentCore.Application.Transcript.CallMessage.Ordinal.init -> void -AgentCore.Application.Transcript.CallMessage.TurnIndex.get -> int -AgentCore.Application.Transcript.CallMessage.TurnIndex.init -> void -AgentCore.Application.Transcript.CallMessageDraft -AgentCore.Application.Transcript.CallMessageDraft.$() -> AgentCore.Application.Transcript.CallMessageDraft! -AgentCore.Application.Transcript.CallMessageDraft.CallMessageDraft(int? TurnIndex, Microsoft.Extensions.AI.ChatMessage! Content, string! MessageId) -> void -AgentCore.Application.Transcript.CallMessageDraft.Content.get -> Microsoft.Extensions.AI.ChatMessage! -AgentCore.Application.Transcript.CallMessageDraft.Content.init -> void -AgentCore.Application.Transcript.CallMessageDraft.Deconstruct(out int? TurnIndex, out Microsoft.Extensions.AI.ChatMessage! Content, out string! MessageId) -> void -AgentCore.Application.Transcript.CallMessageDraft.Equals(AgentCore.Application.Transcript.CallMessageDraft? other) -> bool -AgentCore.Application.Transcript.CallMessageDraft.MessageId.get -> string! -AgentCore.Application.Transcript.CallMessageDraft.MessageId.init -> void -AgentCore.Application.Transcript.CallMessageDraft.TurnIndex.get -> int? -AgentCore.Application.Transcript.CallMessageDraft.TurnIndex.init -> void -AgentCore.Application.Transcript.CallMessageIds +AgentCore.Application.Transcript.ConversationMessage +AgentCore.Application.Transcript.ConversationMessage.$() -> AgentCore.Application.Transcript.ConversationMessage! +AgentCore.Application.Transcript.ConversationMessage.ConversationId.get -> string! +AgentCore.Application.Transcript.ConversationMessage.ConversationId.init -> void +AgentCore.Application.Transcript.ConversationMessage.ConversationMessage(string! ConversationId, int Ordinal, int TurnIndex, Microsoft.Extensions.AI.ChatMessage! Content, string! MessageId) -> void +AgentCore.Application.Transcript.ConversationMessage.Content.get -> Microsoft.Extensions.AI.ChatMessage! +AgentCore.Application.Transcript.ConversationMessage.Content.init -> void +AgentCore.Application.Transcript.ConversationMessage.Deconstruct(out string! ConversationId, out int Ordinal, out int TurnIndex, out Microsoft.Extensions.AI.ChatMessage! Content, out string! MessageId) -> void +AgentCore.Application.Transcript.ConversationMessage.Equals(AgentCore.Application.Transcript.ConversationMessage? other) -> bool +AgentCore.Application.Transcript.ConversationMessage.MessageId.get -> string! +AgentCore.Application.Transcript.ConversationMessage.MessageId.init -> void +AgentCore.Application.Transcript.ConversationMessage.Ordinal.get -> int +AgentCore.Application.Transcript.ConversationMessage.Ordinal.init -> void +AgentCore.Application.Transcript.ConversationMessage.TurnIndex.get -> int +AgentCore.Application.Transcript.ConversationMessage.TurnIndex.init -> void +AgentCore.Application.Transcript.ConversationMessageDraft +AgentCore.Application.Transcript.ConversationMessageDraft.$() -> AgentCore.Application.Transcript.ConversationMessageDraft! +AgentCore.Application.Transcript.ConversationMessageDraft.ConversationMessageDraft(int? TurnIndex, Microsoft.Extensions.AI.ChatMessage! Content, string! MessageId) -> void +AgentCore.Application.Transcript.ConversationMessageDraft.Content.get -> Microsoft.Extensions.AI.ChatMessage! +AgentCore.Application.Transcript.ConversationMessageDraft.Content.init -> void +AgentCore.Application.Transcript.ConversationMessageDraft.Deconstruct(out int? TurnIndex, out Microsoft.Extensions.AI.ChatMessage! Content, out string! MessageId) -> void +AgentCore.Application.Transcript.ConversationMessageDraft.Equals(AgentCore.Application.Transcript.ConversationMessageDraft? other) -> bool +AgentCore.Application.Transcript.ConversationMessageDraft.MessageId.get -> string! +AgentCore.Application.Transcript.ConversationMessageDraft.MessageId.init -> void +AgentCore.Application.Transcript.ConversationMessageDraft.TurnIndex.get -> int? +AgentCore.Application.Transcript.ConversationMessageDraft.TurnIndex.init -> void +AgentCore.Application.Transcript.ConversationMessageIds AgentCore.Application.Transcript.RenderContent AgentCore.Application.Transcript.RenderContent.Data.get -> System.Text.Json.JsonElement AgentCore.Application.Transcript.RenderContent.Data.set -> void @@ -1500,13 +1500,13 @@ AgentCore.Application.Transcript.SourceContent.Source.get -> AgentCore.Domain.So AgentCore.Application.Transcript.SourceContent.Source.set -> void AgentCore.Application.Transcript.SourceContent.SourceContent() -> void AgentCore.Application.Transcript.TranscriptJson -abstract AgentCore.Application.Calls.CallInput.$() -> AgentCore.Application.Calls.CallInput! +abstract AgentCore.Application.Conversation.ConversationInput.$() -> AgentCore.Application.Conversation.ConversationInput! abstract AgentCore.Application.Tools.DeclaredTool.CallAsync(Microsoft.Extensions.AI.AIFunctionArguments! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask const AgentCore.Application.Audit.AuditSinkFactory.MemoryKind = "memory" -> string! const AgentCore.Application.Audit.QueuedAuditSink.DefaultBatchSize = 100 -> int const AgentCore.Application.Audit.QueuedAuditSink.DefaultCapacity = 10000 -> int -const AgentCore.Application.Calls.CallSessionState.CurrentVersion = 1 -> int -const AgentCore.Application.Calls.CallStoreFactory.MemoryKind = "memory" -> string! +const AgentCore.Application.Conversation.ConversationSessionState.CurrentVersion = 1 -> int +const AgentCore.Application.Conversation.ConversationStoreFactory.MemoryKind = "memory" -> string! const AgentCore.Application.Configuration.Compilation.AgentCompaction.DefaultFoldResultChars = 200 -> int const AgentCore.Application.Configuration.Compilation.AgentCompaction.DefaultKeep = 4 -> int const AgentCore.Application.Configuration.Compilation.AgentCompaction.DefaultStrategy = AgentCore.Application.Configuration.Schema.CompactionStrategyKind.ToolResult -> AgentCore.Application.Configuration.Schema.CompactionStrategyKind @@ -1532,7 +1532,7 @@ const AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.Def const AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.DefaultAnalyzer = "none" -> string! const AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.DefaultCitation = "source-locator" -> string! const AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.DefaultScoreFloor = 0.35 -> double -const AgentCore.Application.Configuration.Schema.ReservedStateSlots.CallDurationSeconds = "callDurationSeconds" -> string! +const AgentCore.Application.Configuration.Schema.ReservedStateSlots.ConversationDurationSeconds = "conversationDurationSeconds" -> string! const AgentCore.Application.Configuration.Schema.ReservedStateSlots.Stage = "stage" -> string! const AgentCore.Application.Configuration.Schema.ReservedStateSlots.TurnIndex = "turnIndex" -> string! const AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.DefaultExportIntervalMilliseconds = 60000 -> int @@ -1552,9 +1552,9 @@ const AgentCore.Application.Evaluation.RetrievedDocumentsContext.RetrievedDocume const AgentCore.Application.Knowledge.NoQueryAnalyzer.AnalyzerName = "none" -> string! const AgentCore.Application.Knowledge.SourceLocatorCitationFormatter.FormatterName = "source-locator" -> string! const AgentCore.Application.Policy.StagePolicy.TurnEndedTrigger = "TurnEnded" -> string! -const AgentCore.Application.Runtime.CallSession.EmptyReplyReason = "the run returned an empty reply, so the turn spoke the fallback." -> string! -const AgentCore.Application.Runtime.CallSession.FallbackReply = "I am sorry. I could not finish that. Please say it again." -> string! -const AgentCore.Application.Runtime.CallSession.ToolFailureReason = "a tool failed four times in a row, so the turn spoke the fallback." -> string! +const AgentCore.Application.Runtime.ConversationSession.EmptyReplyReason = "the run returned an empty reply, so the turn spoke the fallback." -> string! +const AgentCore.Application.Runtime.ConversationSession.FallbackReply = "I am sorry. I could not finish that. Please say it again." -> string! +const AgentCore.Application.Runtime.ConversationSession.ToolFailureReason = "a tool failed four times in a row, so the turn spoke the fallback." -> string! const AgentCore.Application.Secrets.KnownSecrets.GrafanaCloudApiTokenName = "grafana-cloud-api-token" -> string! const AgentCore.Application.Secrets.KnownSecrets.GrafanaCloudApiTokenVariable = "GRAFANA_CLOUD_API_TOKEN" -> string! const AgentCore.Application.Secrets.KnownSecrets.GrafanaCloudInstanceIdName = "grafana-cloud-instance-id" -> string! @@ -1573,39 +1573,39 @@ const AgentCore.Application.Tools.Builtin.BuiltinToolNames.FilePublish = "file.p const AgentCore.Application.Tools.ToolErrorResult.ErrorProperty = "error" -> string! const AgentCore.Application.Tools.ToolErrorResult.MessageProperty = "message" -> string! const AgentCore.Application.Tools.ToolErrorResult.ToolProperty = "tool" -> string! -override AgentCore.Application.Calls.CallChannel.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallChannel.GetHashCode() -> int -override AgentCore.Application.Calls.CallChannel.ToString() -> string! -override AgentCore.Application.Calls.CallChannelContext.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallChannelContext.GetHashCode() -> int -override AgentCore.Application.Calls.CallChannelContext.ToString() -> string! -override AgentCore.Application.Calls.CallClarificationState.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallClarificationState.GetHashCode() -> int -override AgentCore.Application.Calls.CallClarificationState.ToString() -> string! -override AgentCore.Application.Calls.CallInput.Barge.$() -> AgentCore.Application.Calls.CallInput.Barge! -override AgentCore.Application.Calls.CallInput.Barge.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallInput.Barge.GetHashCode() -> int -override AgentCore.Application.Calls.CallInput.Barge.ToString() -> string! -override AgentCore.Application.Calls.CallInput.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallInput.GetHashCode() -> int -override AgentCore.Application.Calls.CallInput.Keypress.$() -> AgentCore.Application.Calls.CallInput.Keypress! -override AgentCore.Application.Calls.CallInput.Keypress.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallInput.Keypress.GetHashCode() -> int -override AgentCore.Application.Calls.CallInput.Keypress.ToString() -> string! -override AgentCore.Application.Calls.CallInput.ToString() -> string! -override AgentCore.Application.Calls.CallInput.Utterance.$() -> AgentCore.Application.Calls.CallInput.Utterance! -override AgentCore.Application.Calls.CallInput.Utterance.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallInput.Utterance.GetHashCode() -> int -override AgentCore.Application.Calls.CallInput.Utterance.ToString() -> string! -override AgentCore.Application.Calls.CallPage.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallPage.GetHashCode() -> int -override AgentCore.Application.Calls.CallPage.ToString() -> string! -override AgentCore.Application.Calls.CallRecord.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallRecord.GetHashCode() -> int -override AgentCore.Application.Calls.CallRecord.ToString() -> string! -override AgentCore.Application.Calls.CallSessionState.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallSessionState.GetHashCode() -> int -override AgentCore.Application.Calls.CallSessionState.ToString() -> string! +override AgentCore.Application.Conversation.ConversationChannel.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationChannel.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationChannel.ToString() -> string! +override AgentCore.Application.Conversation.ConversationChannelContext.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationChannelContext.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationChannelContext.ToString() -> string! +override AgentCore.Application.Conversation.ConversationClarificationState.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationClarificationState.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationClarificationState.ToString() -> string! +override AgentCore.Application.Conversation.ConversationInput.Barge.$() -> AgentCore.Application.Conversation.ConversationInput.Barge! +override AgentCore.Application.Conversation.ConversationInput.Barge.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationInput.Barge.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationInput.Barge.ToString() -> string! +override AgentCore.Application.Conversation.ConversationInput.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationInput.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationInput.Keypress.$() -> AgentCore.Application.Conversation.ConversationInput.Keypress! +override AgentCore.Application.Conversation.ConversationInput.Keypress.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationInput.Keypress.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationInput.Keypress.ToString() -> string! +override AgentCore.Application.Conversation.ConversationInput.ToString() -> string! +override AgentCore.Application.Conversation.ConversationInput.Utterance.$() -> AgentCore.Application.Conversation.ConversationInput.Utterance! +override AgentCore.Application.Conversation.ConversationInput.Utterance.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationInput.Utterance.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationInput.Utterance.ToString() -> string! +override AgentCore.Application.Conversation.ConversationPage.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationPage.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationPage.ToString() -> string! +override AgentCore.Application.Conversation.ConversationRecord.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationRecord.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationRecord.ToString() -> string! +override AgentCore.Application.Conversation.ConversationSessionState.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.ConversationSessionState.GetHashCode() -> int +override AgentCore.Application.Conversation.ConversationSessionState.ToString() -> string! override AgentCore.Application.Configuration.Compilation.ResolvedClarification.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Compilation.ResolvedClarification.GetHashCode() -> int override AgentCore.Application.Configuration.Compilation.ResolvedClarification.ToString() -> string! @@ -1654,9 +1654,9 @@ override AgentCore.Application.Configuration.Schema.AgentsConfiguration.ToString override AgentCore.Application.Configuration.Schema.ApprovalConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.ApprovalConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.ApprovalConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.ToString() -> string! override AgentCore.Application.Configuration.Schema.CompactionConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.CompactionConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.CompactionConfiguration.ToString() -> string! @@ -1792,12 +1792,12 @@ override AgentCore.Application.Knowledge.KnowledgePoint.ToString() -> string! override AgentCore.Application.Providers.VendorSeam.GetHashCode() -> int override AgentCore.Application.Runtime.AgentCoreAgent.Description.get -> string? override AgentCore.Application.Runtime.AgentCoreAgent.Name.get -> string? -override AgentCore.Application.Runtime.CallEvent.Equals(object? obj) -> bool -override AgentCore.Application.Runtime.CallEvent.GetHashCode() -> int -override AgentCore.Application.Runtime.CallEvent.ToString() -> string! -override AgentCore.Application.Runtime.CallTurnOrigin.Equals(object? obj) -> bool -override AgentCore.Application.Runtime.CallTurnOrigin.GetHashCode() -> int -override AgentCore.Application.Runtime.CallTurnOrigin.ToString() -> string! +override AgentCore.Application.Runtime.ConversationEvent.Equals(object? obj) -> bool +override AgentCore.Application.Runtime.ConversationEvent.GetHashCode() -> int +override AgentCore.Application.Runtime.ConversationEvent.ToString() -> string! +override AgentCore.Application.Runtime.ConversationTurnOrigin.Equals(object? obj) -> bool +override AgentCore.Application.Runtime.ConversationTurnOrigin.GetHashCode() -> int +override AgentCore.Application.Runtime.ConversationTurnOrigin.ToString() -> string! override AgentCore.Application.Scripting.ScriptRequest.Equals(object? obj) -> bool override AgentCore.Application.Scripting.ScriptRequest.GetHashCode() -> int override AgentCore.Application.Scripting.ScriptRequest.ToString() -> string! @@ -1826,42 +1826,42 @@ override AgentCore.Application.Tools.Registry.ToolSourceContext.ToString() -> st override AgentCore.Application.Tools.ToolCallScope.Equals(object? obj) -> bool override AgentCore.Application.Tools.ToolCallScope.GetHashCode() -> int override AgentCore.Application.Tools.ToolCallScope.ToString() -> string! -override AgentCore.Application.Transcript.CallMessage.Equals(object? obj) -> bool -override AgentCore.Application.Transcript.CallMessage.GetHashCode() -> int -override AgentCore.Application.Transcript.CallMessage.ToString() -> string! -override AgentCore.Application.Transcript.CallMessageDraft.Equals(object? obj) -> bool -override AgentCore.Application.Transcript.CallMessageDraft.GetHashCode() -> int -override AgentCore.Application.Transcript.CallMessageDraft.ToString() -> string! -override sealed AgentCore.Application.Calls.CallInput.Barge.Equals(AgentCore.Application.Calls.CallInput? other) -> bool -override sealed AgentCore.Application.Calls.CallInput.Keypress.Equals(AgentCore.Application.Calls.CallInput? other) -> bool -override sealed AgentCore.Application.Calls.CallInput.Utterance.Equals(AgentCore.Application.Calls.CallInput? other) -> bool +override AgentCore.Application.Transcript.ConversationMessage.Equals(object? obj) -> bool +override AgentCore.Application.Transcript.ConversationMessage.GetHashCode() -> int +override AgentCore.Application.Transcript.ConversationMessage.ToString() -> string! +override AgentCore.Application.Transcript.ConversationMessageDraft.Equals(object? obj) -> bool +override AgentCore.Application.Transcript.ConversationMessageDraft.GetHashCode() -> int +override AgentCore.Application.Transcript.ConversationMessageDraft.ToString() -> string! +override sealed AgentCore.Application.Conversation.ConversationInput.Barge.Equals(AgentCore.Application.Conversation.ConversationInput? other) -> bool +override sealed AgentCore.Application.Conversation.ConversationInput.Keypress.Equals(AgentCore.Application.Conversation.ConversationInput? other) -> bool +override sealed AgentCore.Application.Conversation.ConversationInput.Utterance.Equals(AgentCore.Application.Conversation.ConversationInput? other) -> bool override sealed AgentCore.Application.Tools.DeclaredTool.InvokeCoreAsync(Microsoft.Extensions.AI.AIFunctionArguments! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask static AgentCore.Application.Audit.AuditSinkFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -static AgentCore.Application.Calls.CallChannel.operator !=(AgentCore.Application.Calls.CallChannel? left, AgentCore.Application.Calls.CallChannel? right) -> bool -static AgentCore.Application.Calls.CallChannel.operator ==(AgentCore.Application.Calls.CallChannel? left, AgentCore.Application.Calls.CallChannel? right) -> bool -static AgentCore.Application.Calls.CallChannelContext.operator !=(AgentCore.Application.Calls.CallChannelContext? left, AgentCore.Application.Calls.CallChannelContext? right) -> bool -static AgentCore.Application.Calls.CallChannelContext.operator ==(AgentCore.Application.Calls.CallChannelContext? left, AgentCore.Application.Calls.CallChannelContext? right) -> bool -static AgentCore.Application.Calls.CallClarificationState.operator !=(AgentCore.Application.Calls.CallClarificationState? left, AgentCore.Application.Calls.CallClarificationState? right) -> bool -static AgentCore.Application.Calls.CallClarificationState.operator ==(AgentCore.Application.Calls.CallClarificationState? left, AgentCore.Application.Calls.CallClarificationState? right) -> bool -static AgentCore.Application.Calls.CallCursor.Encode(System.DateTimeOffset sortAt, string! callId) -> string! -static AgentCore.Application.Calls.CallCursor.TryDecode(string? cursor, out System.DateTimeOffset sortAt, out string! callId) -> bool -static AgentCore.Application.Calls.CallInput.Barge.operator !=(AgentCore.Application.Calls.CallInput.Barge? left, AgentCore.Application.Calls.CallInput.Barge? right) -> bool -static AgentCore.Application.Calls.CallInput.Barge.operator ==(AgentCore.Application.Calls.CallInput.Barge? left, AgentCore.Application.Calls.CallInput.Barge? right) -> bool -static AgentCore.Application.Calls.CallInput.Keypress.operator !=(AgentCore.Application.Calls.CallInput.Keypress? left, AgentCore.Application.Calls.CallInput.Keypress? right) -> bool -static AgentCore.Application.Calls.CallInput.Keypress.operator ==(AgentCore.Application.Calls.CallInput.Keypress? left, AgentCore.Application.Calls.CallInput.Keypress? right) -> bool -static AgentCore.Application.Calls.CallInput.Utterance.operator !=(AgentCore.Application.Calls.CallInput.Utterance? left, AgentCore.Application.Calls.CallInput.Utterance? right) -> bool -static AgentCore.Application.Calls.CallInput.Utterance.operator ==(AgentCore.Application.Calls.CallInput.Utterance? left, AgentCore.Application.Calls.CallInput.Utterance? right) -> bool -static AgentCore.Application.Calls.CallInput.operator !=(AgentCore.Application.Calls.CallInput? left, AgentCore.Application.Calls.CallInput? right) -> bool -static AgentCore.Application.Calls.CallInput.operator ==(AgentCore.Application.Calls.CallInput? left, AgentCore.Application.Calls.CallInput? right) -> bool -static AgentCore.Application.Calls.CallPage.operator !=(AgentCore.Application.Calls.CallPage? left, AgentCore.Application.Calls.CallPage? right) -> bool -static AgentCore.Application.Calls.CallPage.operator ==(AgentCore.Application.Calls.CallPage? left, AgentCore.Application.Calls.CallPage? right) -> bool -static AgentCore.Application.Calls.CallRecord.operator !=(AgentCore.Application.Calls.CallRecord? left, AgentCore.Application.Calls.CallRecord? right) -> bool -static AgentCore.Application.Calls.CallRecord.operator ==(AgentCore.Application.Calls.CallRecord? left, AgentCore.Application.Calls.CallRecord? right) -> bool -static AgentCore.Application.Calls.CallSessionState.operator !=(AgentCore.Application.Calls.CallSessionState? left, AgentCore.Application.Calls.CallSessionState? right) -> bool -static AgentCore.Application.Calls.CallSessionState.operator ==(AgentCore.Application.Calls.CallSessionState? left, AgentCore.Application.Calls.CallSessionState? right) -> bool -static AgentCore.Application.Calls.CallSpeechPairing.Validate(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! call, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! speech, AgentCore.Application.Ports.ICallAdapter! selectedCall) -> void -static AgentCore.Application.Calls.CallStateJson.Options.get -> System.Text.Json.JsonSerializerOptions! -static AgentCore.Application.Calls.CallStoreFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static AgentCore.Application.Conversation.ConversationChannel.operator !=(AgentCore.Application.Conversation.ConversationChannel? left, AgentCore.Application.Conversation.ConversationChannel? right) -> bool +static AgentCore.Application.Conversation.ConversationChannel.operator ==(AgentCore.Application.Conversation.ConversationChannel? left, AgentCore.Application.Conversation.ConversationChannel? right) -> bool +static AgentCore.Application.Conversation.ConversationChannelContext.operator !=(AgentCore.Application.Conversation.ConversationChannelContext? left, AgentCore.Application.Conversation.ConversationChannelContext? right) -> bool +static AgentCore.Application.Conversation.ConversationChannelContext.operator ==(AgentCore.Application.Conversation.ConversationChannelContext? left, AgentCore.Application.Conversation.ConversationChannelContext? right) -> bool +static AgentCore.Application.Conversation.ConversationClarificationState.operator !=(AgentCore.Application.Conversation.ConversationClarificationState? left, AgentCore.Application.Conversation.ConversationClarificationState? right) -> bool +static AgentCore.Application.Conversation.ConversationClarificationState.operator ==(AgentCore.Application.Conversation.ConversationClarificationState? left, AgentCore.Application.Conversation.ConversationClarificationState? right) -> bool +static AgentCore.Application.Conversation.ConversationCursor.Encode(System.DateTimeOffset sortAt, string! conversationId) -> string! +static AgentCore.Application.Conversation.ConversationCursor.TryDecode(string? cursor, out System.DateTimeOffset sortAt, out string! conversationId) -> bool +static AgentCore.Application.Conversation.ConversationInput.Barge.operator !=(AgentCore.Application.Conversation.ConversationInput.Barge? left, AgentCore.Application.Conversation.ConversationInput.Barge? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.Barge.operator ==(AgentCore.Application.Conversation.ConversationInput.Barge? left, AgentCore.Application.Conversation.ConversationInput.Barge? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.Keypress.operator !=(AgentCore.Application.Conversation.ConversationInput.Keypress? left, AgentCore.Application.Conversation.ConversationInput.Keypress? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.Keypress.operator ==(AgentCore.Application.Conversation.ConversationInput.Keypress? left, AgentCore.Application.Conversation.ConversationInput.Keypress? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.Utterance.operator !=(AgentCore.Application.Conversation.ConversationInput.Utterance? left, AgentCore.Application.Conversation.ConversationInput.Utterance? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.Utterance.operator ==(AgentCore.Application.Conversation.ConversationInput.Utterance? left, AgentCore.Application.Conversation.ConversationInput.Utterance? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.operator !=(AgentCore.Application.Conversation.ConversationInput? left, AgentCore.Application.Conversation.ConversationInput? right) -> bool +static AgentCore.Application.Conversation.ConversationInput.operator ==(AgentCore.Application.Conversation.ConversationInput? left, AgentCore.Application.Conversation.ConversationInput? right) -> bool +static AgentCore.Application.Conversation.ConversationPage.operator !=(AgentCore.Application.Conversation.ConversationPage? left, AgentCore.Application.Conversation.ConversationPage? right) -> bool +static AgentCore.Application.Conversation.ConversationPage.operator ==(AgentCore.Application.Conversation.ConversationPage? left, AgentCore.Application.Conversation.ConversationPage? right) -> bool +static AgentCore.Application.Conversation.ConversationRecord.operator !=(AgentCore.Application.Conversation.ConversationRecord? left, AgentCore.Application.Conversation.ConversationRecord? right) -> bool +static AgentCore.Application.Conversation.ConversationRecord.operator ==(AgentCore.Application.Conversation.ConversationRecord? left, AgentCore.Application.Conversation.ConversationRecord? right) -> bool +static AgentCore.Application.Conversation.ConversationSessionState.operator !=(AgentCore.Application.Conversation.ConversationSessionState? left, AgentCore.Application.Conversation.ConversationSessionState? right) -> bool +static AgentCore.Application.Conversation.ConversationSessionState.operator ==(AgentCore.Application.Conversation.ConversationSessionState? left, AgentCore.Application.Conversation.ConversationSessionState? right) -> bool +static AgentCore.Application.Conversation.ConversationSpeechPairing.Validate(AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration! conversation, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! speech, AgentCore.Application.Ports.IConversationAdapter! selectedConversation) -> void +static AgentCore.Application.Conversation.ConversationStateJson.Options.get -> System.Text.Json.JsonSerializerOptions! +static AgentCore.Application.Conversation.ConversationStoreFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static AgentCore.Application.Configuration.Compilation.AgentCompaction.Compose(AgentCore.Application.Configuration.Schema.AgentDefaults? defaults, AgentCore.Application.Configuration.Schema.AgentConfiguration! agent) -> AgentCore.Application.Configuration.Compilation.ResolvedCompaction? static AgentCore.Application.Configuration.Compilation.AgentHarness.Compose(AgentCore.Application.Configuration.Schema.AgentDefaults? defaults, AgentCore.Application.Configuration.Schema.AgentConfiguration! agent) -> AgentCore.Application.Configuration.Compilation.ResolvedHarness! static AgentCore.Application.Configuration.Compilation.AgentInstructions.Compose(AgentCore.Application.Configuration.Schema.AgentDefaults? defaults, AgentCore.Application.Configuration.Schema.AgentConfiguration! agent) -> string? @@ -1917,8 +1917,8 @@ static AgentCore.Application.Configuration.Schema.AgentsConfiguration.operator ! static AgentCore.Application.Configuration.Schema.AgentsConfiguration.operator ==(AgentCore.Application.Configuration.Schema.AgentsConfiguration? left, AgentCore.Application.Configuration.Schema.AgentsConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.ApprovalConfiguration.operator !=(AgentCore.Application.Configuration.Schema.ApprovalConfiguration? left, AgentCore.Application.Configuration.Schema.ApprovalConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.ApprovalConfiguration.operator ==(AgentCore.Application.Configuration.Schema.ApprovalConfiguration? left, AgentCore.Application.Configuration.Schema.ApprovalConfiguration? right) -> bool -static AgentCore.Application.Configuration.Schema.CallProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.CallProviderConfiguration? left, AgentCore.Application.Configuration.Schema.CallProviderConfiguration? right) -> bool -static AgentCore.Application.Configuration.Schema.CallProviderConfiguration.operator ==(AgentCore.Application.Configuration.Schema.CallProviderConfiguration? left, AgentCore.Application.Configuration.Schema.CallProviderConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration? left, AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration.operator ==(AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration? left, AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.CompactionConfiguration.operator !=(AgentCore.Application.Configuration.Schema.CompactionConfiguration? left, AgentCore.Application.Configuration.Schema.CompactionConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.CompactionConfiguration.operator ==(AgentCore.Application.Configuration.Schema.CompactionConfiguration? left, AgentCore.Application.Configuration.Schema.CompactionConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.operator !=(AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration? left, AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration? right) -> bool @@ -2041,12 +2041,12 @@ static AgentCore.Application.Llm.CompositeChatClientFactory.CreateAsync(AgentCor static AgentCore.Application.Providers.VendorAdapterSelector.Select(string! kind, System.Collections.Generic.IReadOnlyList! adapters, AgentCore.Application.Providers.VendorSeam seam) -> TAdapter static AgentCore.Application.Providers.VendorSeam.operator !=(AgentCore.Application.Providers.VendorSeam left, AgentCore.Application.Providers.VendorSeam right) -> bool static AgentCore.Application.Providers.VendorSeam.operator ==(AgentCore.Application.Providers.VendorSeam left, AgentCore.Application.Providers.VendorSeam right) -> bool -static AgentCore.Application.Runtime.CallEvent.operator !=(AgentCore.Application.Runtime.CallEvent? left, AgentCore.Application.Runtime.CallEvent? right) -> bool -static AgentCore.Application.Runtime.CallEvent.operator ==(AgentCore.Application.Runtime.CallEvent? left, AgentCore.Application.Runtime.CallEvent? right) -> bool -static AgentCore.Application.Runtime.CallObservers.Standard(AgentCore.Application.Ports.IAuditSinkPort! auditSink, Microsoft.Extensions.Logging.ILogger? logger, System.Collections.Generic.IEnumerable? hostObservers = null) -> System.Collections.Generic.IReadOnlyList! -static AgentCore.Application.Runtime.CallSessionFactory.CreateExtractor(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Ports.IChatClientFactory! chatClients) -> AgentCore.Application.State.StateExtractor? -static AgentCore.Application.Runtime.CallTurnOrigin.operator !=(AgentCore.Application.Runtime.CallTurnOrigin? left, AgentCore.Application.Runtime.CallTurnOrigin? right) -> bool -static AgentCore.Application.Runtime.CallTurnOrigin.operator ==(AgentCore.Application.Runtime.CallTurnOrigin? left, AgentCore.Application.Runtime.CallTurnOrigin? right) -> bool +static AgentCore.Application.Runtime.ConversationEvent.operator !=(AgentCore.Application.Runtime.ConversationEvent? left, AgentCore.Application.Runtime.ConversationEvent? right) -> bool +static AgentCore.Application.Runtime.ConversationEvent.operator ==(AgentCore.Application.Runtime.ConversationEvent? left, AgentCore.Application.Runtime.ConversationEvent? right) -> bool +static AgentCore.Application.Runtime.ConversationObservers.Standard(AgentCore.Application.Ports.IAuditSinkPort! auditSink, Microsoft.Extensions.Logging.ILogger? logger, System.Collections.Generic.IEnumerable? hostObservers = null) -> System.Collections.Generic.IReadOnlyList! +static AgentCore.Application.Runtime.ConversationSessionFactory.CreateExtractor(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Ports.IChatClientFactory! chatClients) -> AgentCore.Application.State.StateExtractor? +static AgentCore.Application.Runtime.ConversationTurnOrigin.operator !=(AgentCore.Application.Runtime.ConversationTurnOrigin? left, AgentCore.Application.Runtime.ConversationTurnOrigin? right) -> bool +static AgentCore.Application.Runtime.ConversationTurnOrigin.operator ==(AgentCore.Application.Runtime.ConversationTurnOrigin? left, AgentCore.Application.Runtime.ConversationTurnOrigin? right) -> bool static AgentCore.Application.Scripting.ScriptRequest.operator !=(AgentCore.Application.Scripting.ScriptRequest? left, AgentCore.Application.Scripting.ScriptRequest? right) -> bool static AgentCore.Application.Scripting.ScriptRequest.operator ==(AgentCore.Application.Scripting.ScriptRequest? left, AgentCore.Application.Scripting.ScriptRequest? right) -> bool static AgentCore.Application.Scripting.ScriptResult.Failed(string! error) -> AgentCore.Application.Scripting.ScriptResult! @@ -2087,11 +2087,11 @@ static AgentCore.Application.Tools.ToolCallScope.operator ==(AgentCore.Applicati static AgentCore.Application.Tools.ToolErrorResult.Create(string! tool, string! message) -> System.Text.Json.Nodes.JsonObject! static AgentCore.Application.Tools.ToolErrorResult.IsError(System.Text.Json.Nodes.JsonNode? result) -> bool static AgentCore.Application.Tools.ToolResultJson.ToNode(object? value) -> System.Text.Json.Nodes.JsonNode? -static AgentCore.Application.Transcript.CallMessage.operator !=(AgentCore.Application.Transcript.CallMessage? left, AgentCore.Application.Transcript.CallMessage? right) -> bool -static AgentCore.Application.Transcript.CallMessage.operator ==(AgentCore.Application.Transcript.CallMessage? left, AgentCore.Application.Transcript.CallMessage? right) -> bool -static AgentCore.Application.Transcript.CallMessageDraft.operator !=(AgentCore.Application.Transcript.CallMessageDraft? left, AgentCore.Application.Transcript.CallMessageDraft? right) -> bool -static AgentCore.Application.Transcript.CallMessageDraft.operator ==(AgentCore.Application.Transcript.CallMessageDraft? left, AgentCore.Application.Transcript.CallMessageDraft? right) -> bool -static AgentCore.Application.Transcript.CallMessageIds.New() -> string! +static AgentCore.Application.Transcript.ConversationMessage.operator !=(AgentCore.Application.Transcript.ConversationMessage? left, AgentCore.Application.Transcript.ConversationMessage? right) -> bool +static AgentCore.Application.Transcript.ConversationMessage.operator ==(AgentCore.Application.Transcript.ConversationMessage? left, AgentCore.Application.Transcript.ConversationMessage? right) -> bool +static AgentCore.Application.Transcript.ConversationMessageDraft.operator !=(AgentCore.Application.Transcript.ConversationMessageDraft? left, AgentCore.Application.Transcript.ConversationMessageDraft? right) -> bool +static AgentCore.Application.Transcript.ConversationMessageDraft.operator ==(AgentCore.Application.Transcript.ConversationMessageDraft? left, AgentCore.Application.Transcript.ConversationMessageDraft? right) -> bool +static AgentCore.Application.Transcript.ConversationMessageIds.New() -> string! static AgentCore.Application.Transcript.TranscriptJson.Options.get -> System.Text.Json.JsonSerializerOptions! static readonly AgentCore.Application.Configuration.Compilation.ResolvedClarification.None -> AgentCore.Application.Configuration.Compilation.ResolvedClarification! static readonly AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.DefaultMeters -> System.Collections.Generic.IReadOnlyList! @@ -2101,10 +2101,10 @@ static readonly AgentCore.Application.Secrets.KnownSecrets.GrafanaCloudInstanceI static readonly AgentCore.Application.Secrets.KnownSecrets.OpenAi -> AgentCore.Application.Secrets.SecretName! static readonly AgentCore.Application.Secrets.KnownSecrets.PostgresConnectionString -> AgentCore.Application.Secrets.SecretName! static readonly AgentCore.Application.Secrets.KnownSecrets.Qdrant -> AgentCore.Application.Secrets.SecretName! -static readonly AgentCore.Application.Sessions.Memory.InMemoryCallSessions.DefaultIdleTimeout -> System.TimeSpan -virtual AgentCore.Application.Calls.CallInput.EqualityContract.get -> System.Type! -virtual AgentCore.Application.Calls.CallInput.Equals(AgentCore.Application.Calls.CallInput? other) -> bool -virtual AgentCore.Application.Calls.CallInput.PrintMembers(System.Text.StringBuilder! builder) -> bool +static readonly AgentCore.Application.Sessions.Memory.InMemoryConversationSessions.DefaultIdleTimeout -> System.TimeSpan +virtual AgentCore.Application.Conversation.ConversationInput.EqualityContract.get -> System.Type! +virtual AgentCore.Application.Conversation.ConversationInput.Equals(AgentCore.Application.Conversation.ConversationInput? other) -> bool +virtual AgentCore.Application.Conversation.ConversationInput.PrintMembers(System.Text.StringBuilder! builder) -> bool virtual AgentCore.Application.Tools.Binding.ToolBinding.Invoke(System.Text.Json.Nodes.JsonObject! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask ~override AgentCore.Application.Providers.VendorSeam.Equals(object obj) -> bool ~override AgentCore.Application.Providers.VendorSeam.ToString() -> string @@ -2221,36 +2221,35 @@ AgentCore.Application.Blobs.FileLink.Equals(AgentCore.Application.Blobs.FileLink AgentCore.Application.Blobs.FileLink.FileLink(AgentCore.Application.Blobs.BlobRef! Blob, System.Uri? Url) -> void AgentCore.Application.Blobs.FileLink.Url.get -> System.Uri? AgentCore.Application.Blobs.FileLink.Url.init -> void -AgentCore.Application.Calls.CallRepository -AgentCore.Application.Calls.CallRepository.AppendAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Calls.CallSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> -AgentCore.Application.Calls.CallRepository.AppendMessageAsync(string! callId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.AttachPrincipalAsync(string! callId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.CallRepository(AgentCore.Application.Ports.ICallStore! calls, AgentCore.Application.Ports.IBlobStore? blobs) -> void -AgentCore.Application.Calls.CallRepository.CreateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.DeleteAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.DetachPrincipalAsync(string! callId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.EraseAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.GetAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.KeepsFiles.get -> bool -AgentCore.Application.Calls.CallRepository.LinkFilesAsync(string! callId, System.Collections.Generic.IEnumerable! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! -AgentCore.Application.Calls.CallRepository.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Calls.CallStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.ReadAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> -AgentCore.Application.Calls.CallRepository.RenameAsync(string! callId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.RewriteAsync(string! callId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.SetCustomAsync(string! callId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.SetExternalIdAsync(string! callId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.SetStatusAsync(string! callId, AgentCore.Application.Calls.CallStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Calls.CallRepository.TruncateAsync(string! callId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations +AgentCore.Application.Conversation.Conversations.AppendAsync(string! conversationId, System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Conversation.ConversationSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Conversation.Conversations.AppendMessageAsync(string! conversationId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.AttachPrincipalAsync(string! conversationId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.Conversations(AgentCore.Application.Ports.IConversationStore! conversations, AgentCore.Application.Ports.IBlobStore? blobs) -> void +AgentCore.Application.Conversation.Conversations.CreateAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.DeleteAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.DeleteContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.DetachPrincipalAsync(string! conversationId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.EraseAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.GetAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.GetContinuationAsync(string! continuationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.LinkFilesAsync(string! conversationId, System.Collections.Generic.IEnumerable! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +AgentCore.Application.Conversation.Conversations.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Conversation.ConversationStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.ReadAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Conversation.Conversations.RenameAsync(string! conversationId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.RewriteAsync(string! conversationId, string! messageId, Microsoft.Extensions.AI.ChatMessage! content, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.SaveContinuationAsync(string! continuationId, System.Text.Json.JsonElement envelope, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.SetCustomAsync(string! conversationId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.SetExternalIdAsync(string! conversationId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.SetStatusAsync(string! conversationId, AgentCore.Application.Conversation.ConversationStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.SweepAsync(System.TimeSpan retention, int batchSize = 500, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.Conversations.TruncateAsync(string! conversationId, int fromOrdinal, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask override AgentCore.Application.Blobs.FileLink.Equals(object? obj) -> bool override AgentCore.Application.Blobs.FileLink.GetHashCode() -> int override AgentCore.Application.Blobs.FileLink.ToString() -> string! static AgentCore.Application.Blobs.FileLink.operator ==(AgentCore.Application.Blobs.FileLink? left, AgentCore.Application.Blobs.FileLink? right) -> bool static AgentCore.Application.Blobs.FileLink.operator !=(AgentCore.Application.Blobs.FileLink? left, AgentCore.Application.Blobs.FileLink? right) -> bool -AgentCore.Application.Calls.CallRepository.Store.get -> AgentCore.Application.Ports.ICallStore! +AgentCore.Application.Conversation.Conversations.Store.get -> AgentCore.Application.Ports.IConversationStore! AgentCore.Application.Transcript.FileContent AgentCore.Application.Transcript.FileContent.FileId.get -> string! AgentCore.Application.Transcript.FileContent.FileId.set -> void @@ -2295,3 +2294,35 @@ AgentCore.Application.Configuration.Schema.ShellConfiguration.MemoryMb.get -> in AgentCore.Application.Configuration.Schema.ShellConfiguration.MemoryMb.init -> void AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Secrets.get -> AgentCore.Application.Secrets.ResolvedSecrets? AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Secrets.init -> void +AgentCore.Application.Conversation.Conversations.LoadAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.StoredConversation +AgentCore.Application.Conversation.StoredConversation.Conversation.get -> AgentCore.Application.Conversation.ConversationRecord! +AgentCore.Application.Conversation.StoredConversation.Conversation.init -> void +AgentCore.Application.Conversation.StoredConversation.Files.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Conversation.StoredConversation.Files.init -> void +AgentCore.Application.Conversation.StoredConversation.Messages.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Conversation.StoredConversation.Messages.init -> void +AgentCore.Application.Conversation.StoredConversation.StoredConversation(AgentCore.Application.Conversation.ConversationRecord! Conversation, System.Collections.Generic.IReadOnlyList! Messages, System.Collections.Generic.IReadOnlyList! Files) -> void +AgentCore.Application.Ports.IConversations +AgentCore.Application.Ports.IConversations.AppendMessageAsync(string! conversationId, Microsoft.Extensions.AI.ChatMessage! message, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.AttachPrincipalAsync(string! conversationId, string! principalKey, string! role, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.CreateAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.DeleteAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.DetachPrincipalAsync(string! conversationId, string! principalKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.EraseAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.GetAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.ListAsync(string! principalKey, string? after, int limit, AgentCore.Application.Conversation.ConversationStatus? status = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.LoadAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.ReadAsync(string! conversationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Ports.IConversations.RenameAsync(string! conversationId, string! title, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.SetCustomAsync(string! conversationId, System.Text.Json.JsonElement? custom, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.SetExternalIdAsync(string! conversationId, string? externalId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Ports.IConversations.SetStatusAsync(string! conversationId, AgentCore.Application.Conversation.ConversationStatus status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Conversation.StoredConversation.$() -> AgentCore.Application.Conversation.StoredConversation! +AgentCore.Application.Conversation.StoredConversation.Deconstruct(out AgentCore.Application.Conversation.ConversationRecord! Conversation, out System.Collections.Generic.IReadOnlyList! Messages, out System.Collections.Generic.IReadOnlyList! Files) -> void +AgentCore.Application.Conversation.StoredConversation.Equals(AgentCore.Application.Conversation.StoredConversation? other) -> bool +override AgentCore.Application.Conversation.StoredConversation.Equals(object? obj) -> bool +override AgentCore.Application.Conversation.StoredConversation.GetHashCode() -> int +override AgentCore.Application.Conversation.StoredConversation.ToString() -> string! +static AgentCore.Application.Conversation.StoredConversation.operator ==(AgentCore.Application.Conversation.StoredConversation? left, AgentCore.Application.Conversation.StoredConversation? right) -> bool +static AgentCore.Application.Conversation.StoredConversation.operator !=(AgentCore.Application.Conversation.StoredConversation? left, AgentCore.Application.Conversation.StoredConversation? right) -> bool diff --git a/src/AgentCore.Application/Runtime/AgentCoreAgent.cs b/src/AgentCore.Application/Runtime/AgentCoreAgent.cs index d7919f63..7a7e5ba9 100644 --- a/src/AgentCore.Application/Runtime/AgentCoreAgent.cs +++ b/src/AgentCore.Application/Runtime/AgentCoreAgent.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Ports; using System.Runtime.CompilerServices; using System.Text.Json; @@ -12,27 +12,27 @@ namespace AgentCore.Application.Runtime; /// /// /// -/// is the turn loop — moderation, the stage machine, the writers, the audit +/// is the turn loop — moderation, the stage machine, the writers, the audit /// chain, barge-in — and its seam is , which only this library's /// own adapters read. This shim puts the same loop behind , the seam the wider /// ecosystem reads: anything that drives an AIAgent — the framework's protocol hosts (A2A, /// AG-UI, the OpenAI-compatible endpoints, all prerelease as of Microsoft.Agents.AI 1.17.0), -/// AsAIFunction(), an evaluation harness — can drive a call without learning one AgentCore +/// AsAIFunction(), an evaluation harness — can drive a conversation without learning one AgentCore /// type beyond this one. /// /// -/// One is one call. -/// starts the call, and every run with that session is one turn of it. The session wraps the -/// , and a host that needs the parts of the loop the AIAgent surface -/// does not carry — , -/// , the stage, -/// the transcript — asks the session for it: session.GetService<CallSession>(). +/// One is one conversation. +/// starts the conversation, and every run with that session is one turn of it. The session wraps the +/// , and a host that needs the parts of the loop the AIAgent surface +/// does not carry — , +/// , the stage, +/// the transcript — asks the session for it: session.GetService<ConversationSession>(). /// /// /// The session owns the transcript, so a run takes one user message and not a history. The /// run reads the text of the LAST user message and ignores everything in front of it, which is the /// same rule the /v1/responses endpoint applies to its input: an earlier message -/// of the call is already in the session. A host must not replay history here — replaying it would +/// of the conversation is already in the session. A host must not replay history here — replaying it would /// put every turn in the transcript twice. /// /// @@ -41,24 +41,24 @@ namespace AgentCore.Application.Runtime; /// it cannot honor. /// /// -/// This agent is a process singleton, like the compiled agent it runs: everything per call lives in -/// the session. It holds no lock and no state of its own, so 26 concurrent calls are 26 sessions +/// This agent is a process singleton, like the compiled agent it runs: everything per conversation lives in +/// the session. It holds no lock and no state of its own, so 26 concurrent conversations are 26 sessions /// over one instance. /// /// public sealed class AgentCoreAgent : AIAgent { - private readonly ICallSessionFactory _sessions; + private readonly IConversationSessionFactory _sessions; private readonly string? _description; /// Creates the shim over one compiled entry's turn loop. - /// The factory that starts one for each call. + /// The factory that starts one for each conversation. /// The entry this agent serves. Reported as . /// The description the agent reports, or . /// is . /// is null or empty. - public AgentCoreAgent(ICallSessionFactory sessions, string entryName, string? description = null) + public AgentCoreAgent(IConversationSessionFactory sessions, string entryName, string? description = null) { ArgumentNullException.ThrowIfNull(sessions); ArgumentException.ThrowIfNullOrEmpty(entryName); @@ -77,22 +77,22 @@ public AgentCoreAgent(ICallSessionFactory sessions, string entryName, string? de /// public override string? Description => _description; - /// Starts one call under the id the host names. - /// The id the host gives the call. The vendor's call id belongs here. + /// Starts one conversation under the id the host names. + /// The id the host gives the conversation. The vendor's conversation id belongs here. /// Unused. The signature mirrors the framework's. - /// The session of the new call, with no turn run yet. + /// The session of the new conversation, with no turn run yet. /// /// makes an id up, exactly as - /// does when it is handed none. A voice host has the - /// vendor's call id before the first turn, and the audit chain of the call should carry it, so + /// does when it is handed none. A voice host has the + /// vendor's conversation id before the first turn, and the audit chain of the conversation should carry it, so /// this overload exists for the same reason ChatClientAgent.CreateSessionAsync(string) /// does. /// - /// is null or empty. - public ValueTask CreateSessionAsync(string callId, CancellationToken cancellationToken = default) + /// is null or empty. + public ValueTask CreateSessionAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentException.ThrowIfNullOrEmpty(callId); - return new(new AgentCoreAgentSession(_sessions.Create(callId))); + ArgumentException.ThrowIfNullOrEmpty(conversationId); + return new(new AgentCoreAgentSession(_sessions.Create(conversationId))); } /// @@ -102,22 +102,22 @@ protected override ValueTask CreateSessionCoreAsync(CancellationTo /// /// /// - /// What travels is the call's id and what its session alone holds: the stage, whether the - /// machine finished, and the slots the writers filled. That is a + /// What travels is the conversation's id and what its session alone holds: the stage, whether the + /// machine finished, and the slots the writers filled. That is a /// under the id it belongs to — the same pairing ChatClientAgentSession writes as /// { conversationId, stateBag }, and for the same reason. State that travelled without - /// its id would come back on a call that has none of its words behind it. + /// its id would come back on a conversation that has none of its words behind it. /// /// /// The words are not here. They are store 1, which is durable already, so a checkpoint /// that carried them would give one conversation two records and one chance to disagree. The /// price is that this is a key and not a copy: a host moving a session between processes still - /// needs the shared store behind it, or the revived call answers with an empty transcript. + /// needs the shared store behind it, or the revived conversation answers with an empty transcript. /// /// /// This blob is not store 0's. A host's reach /// the nested state member too, not the envelope alone, so that member is encoded to the - /// host's rules and not to , which every store agrees on. It + /// host's rules and not to , which every store agrees on. It /// is harmless while the member stays inside the envelope, because this seam and its reader are /// symmetric. Lifting it out and writing it to store 0 is what would not be. /// @@ -127,18 +127,18 @@ protected override ValueTask SerializeSessionCoreAsync( JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) { - // Refused, where a run answers a null session by making one. The fabricated call is the - // framework's one-shot shape for a RUN — one turn of a call nothing continues — and there is + // Refused, where a run answers a null session by making one. The fabricated conversation is the + // framework's one-shot shape for a RUN — one turn of a conversation nothing continues — and there is // no such thing as a one-shot serialize: what it would write is an envelope naming a fresh // random id beside an empty state, and a host would keep that as its checkpoint and never // learn it points at nothing. The parameter is not nullable, so this only catches a caller // that went around the type. ArgumentNullException.ThrowIfNull(session); - var call = Resolve(session); + var conversation = Resolve(session); return new(JsonSerializer.SerializeToElement( - new SerializedSession(call.CallId, call.Snapshot(), EntryName), - jsonSerializerOptions ?? CallStateJson.Options)); + new SerializedSession(conversation.ConversationId, conversation.Snapshot(), EntryName), + jsonSerializerOptions ?? ConversationStateJson.Options)); } /// @@ -146,32 +146,32 @@ protected override ValueTask SerializeSessionCoreAsync( /// /// Reads back what wrote — see its remarks for what the /// blob does and does not carry. It is host-facing, so what arrives is not necessarily anything - /// this library wrote, and it stays lenient about that: a blob that names no call gets a new id, + /// this library wrote, and it stays lenient about that: a blob that names no conversation gets a new id, /// exactly as does, and state the /// document no longer allows is dropped slot by slot with a diagnostic rather than refusing the - /// call. That second contract is 's and this method does not + /// conversation. That second contract is 's and this method does not /// double it. /// /// /// The one blob it refuses carries neither member. That is not a validation layer over - /// but a guard against one specific confusion this library - /// creates itself: a bare is the literal value in store 0's - /// call.state column, so a host reaching for "the state of this call" reaches for the - /// wrong one of two shapes. Read as an envelope it names no call and holds no state, and the + /// but a guard against one specific confusion this library + /// creates itself: a bare is the literal value in store 0's + /// conversation.state column, so a host reaching for "the state of this conversation" reaches for the + /// wrong one of two shapes. Read as an envelope it names no conversation and holds no state, and the /// failure is silent and total — a new random id, and the transcript orphaned behind it. /// can never write that blob, so refusing it costs the /// lenient path nothing. /// /// - /// Store 0 outranks what arrives here. The state travels with the call's id, and the - /// first turn of the revived call reads store 0 under that id; where store 0 holds state of its + /// Store 0 outranks what arrives here. The state travels with the conversation's id, and the + /// first turn of the revived conversation reads store 0 under that id; where store 0 holds state of its /// own it wins outright, because its blob rides the same batch as the words. So this decides - /// only a call store 0 does not know, or knows without state. See - /// . + /// only a conversation store 0 does not know, or knows without state. See + /// . /// /// /// - /// names no call and holds no state. + /// names no conversation and holds no state. /// protected override ValueTask DeserializeSessionCoreAsync( JsonElement serializedState, @@ -179,15 +179,15 @@ protected override ValueTask DeserializeSessionCoreAsync( CancellationToken cancellationToken = default) { var stored = serializedState.Deserialize( - jsonSerializerOptions ?? CallStateJson.Options); + jsonSerializerOptions ?? ConversationStateJson.Options); - if (stored is null or { CallId: null, State: null }) + if (stored is null or { ConversationId: null, State: null }) { throw new ArgumentException( - "The serialized session names no call and holds no state, so it is not one this " - + "agent wrote. It expects { callId, state } — the call's id beside its state. A " - + "bare CallSessionState, the value store 0 keeps in call.state, is the other shape " - + "and reading it as this one would lose the call's transcript.", + "The serialized session names no conversation and holds no state, so it is not one this " + + "agent wrote. It expects { conversationId, state } — the conversation's id beside its state. A " + + "bare ConversationSessionState, the value store 0 keeps in conversation.state, is the other shape " + + "and reading it as this one would lose the conversation's transcript.", nameof(serializedState)); } @@ -197,7 +197,7 @@ protected override ValueTask DeserializeSessionCoreAsync( $"The session names entry '{stored.Entry}' and this agent serves entry '{EntryName}'."); } - return new(new AgentCoreAgentSession(_sessions.Create(stored.CallId, stored.State))); + return new(new AgentCoreAgentSession(_sessions.Create(stored.ConversationId, stored.State))); } /// @@ -209,8 +209,8 @@ protected override async Task RunCoreAsync( { ArgumentNullException.ThrowIfNull(messages); - var call = Resolve(session); - var turn = await call.RunTurnMessageAsync(UserMessage(messages), cancellationToken).ConfigureAwait(false); + var conversation = Resolve(session); + var turn = await conversation.RunTurnMessageAsync(UserMessage(messages), cancellationToken).ConfigureAwait(false); return new AgentResponse(new ChatMessage(ChatRole.Assistant, turn.ReplyText)) { @@ -232,41 +232,41 @@ protected override IAsyncEnumerable RunCoreStreamingAsync( return RunCoreStreamingCoreAsync(messages, session, cancellationToken); } - /// Streams one turn of the resolved call, wrapping each update with this agent's id. + /// Streams one turn of the resolved conversation, wrapping each update with this agent's id. private async IAsyncEnumerable RunCoreStreamingCoreAsync( IEnumerable messages, AgentSession? session, [EnumeratorCancellation] CancellationToken cancellationToken) { - var call = Resolve(session); + var conversation = Resolve(session); - // The stream is already filtered: CallSession drops the lifecycle updates, so every update + // The stream is already filtered: ConversationSession drops the lifecycle updates, so every update // here carries content. The wrap changes the type and nothing else. - await foreach (var update in call.RunTurnMessageStreamingAsync(UserMessage(messages), cancellationToken) + await foreach (var update in conversation.RunTurnMessageStreamingAsync(UserMessage(messages), cancellationToken) .ConfigureAwait(false)) { yield return new AgentResponseUpdate(update) { AgentId = Id }; } } - /// Finds the call a run belongs to. + /// Finds the conversation a run belongs to. /// The session the caller passed, or . - /// The call to run the turn on. + /// The conversation to run the turn on. /// /// A session is the framework's one-shot shape — ChatClientAgent - /// answers it with a session it throws away — so it runs one turn of a call nothing can continue. + /// answers it with a session it throws away — so it runs one turn of a conversation nothing can continue. /// A session another agent created is refused, in the framework's own words: every /// AIAgent implementation measured (ChatClientAgent, the workflow host) refuses a foreign /// session rather than guessing at its state. /// /// belongs to another agent type. - private CallSession Resolve(AgentSession? session) => session switch + private ConversationSession Resolve(AgentSession? session) => session switch { null => _sessions.Create(), - AgentCoreAgentSession own => own.Call, + AgentCoreAgentSession own => own.Conversation, _ => throw new ArgumentException( $"Incompatible session type: {session.GetType()} (expecting {typeof(AgentCoreAgentSession)}). " - + "Only a session this agent created can carry one of its calls.", + + "Only a session this agent created can carry one of its conversations.", nameof(session)), }; @@ -275,7 +275,7 @@ private async IAsyncEnumerable RunCoreStreamingCoreAsync( /// The last user message that carries words or an approval answer. /// /// The same rule the /v1/responses endpoint applies: the session owns the - /// transcript, so an earlier message of the call is already in the session, and only the last + /// transcript, so an earlier message of the conversation is already in the session, and only the last /// user message is new. See the remarks on . /// /// No user message carries words or an answer, so there is no turn to run. @@ -298,34 +298,34 @@ private static ChatMessage UserMessage(IEnumerable messages) nameof(messages)); } - /// One serialized session: the call it is, the entry it belongs to, and the state it held. - /// The id of the call. Store 1 is keyed by it, so it is the half that finds the words. + /// One serialized session: the conversation it is, the entry it belongs to, and the state it held. + /// The id of the conversation. Store 1 is keyed by it, so it is the half that finds the words. /// What the session alone held, or when the blob named none. /// The entry that wrote the blob. A key minted by one entry never reads on another. /// - /// A separate shape from on purpose. That one is the value store 0 - /// writes under a call_id column, so putting the id inside it would give one fact two + /// A separate shape from on purpose. That one is the value store 0 + /// writes under a conversation_id column, so putting the id inside it would give one fact two /// homes; here there is no column, so the envelope carries the key beside the value instead. /// Internal because it is a wire shape and not a promise: D15 makes every public type permanent. /// - internal sealed record SerializedSession(string? CallId, CallSessionState? State, string? Entry); + internal sealed record SerializedSession(string? ConversationId, ConversationSessionState? State, string? Entry); - /// One call, as the framework sees it. + /// One conversation, as the framework sees it. /// - /// It stays internal: a host reaches the call through GetService<CallSession>() on + /// It stays internal: a host reaches the call through GetService<ConversationSession>() on /// the base, and D15 makes every public type a permanent promise this /// wrapper does not need to be. /// internal sealed class AgentCoreAgentSession : AgentSession { - internal AgentCoreAgentSession(CallSession call) => Call = call; + internal AgentCoreAgentSession(ConversationSession conversation) => Conversation = conversation; - /// Gets the call this session carries. - internal CallSession Call { get; } + /// Gets the conversation this session carries. + internal ConversationSession Conversation { get; } /// /// - /// Answers the (and its + /// Answers the (and its /// seam), so a host holding only the framework types reaches barge-in, the stage, and the /// transcript without a cast. /// @@ -333,8 +333,8 @@ internal sealed class AgentCoreAgentSession : AgentSession { ArgumentNullException.ThrowIfNull(serviceType); - return serviceKey is null && serviceType.IsInstanceOfType(Call) - ? Call + return serviceKey is null && serviceType.IsInstanceOfType(Conversation) + ? Conversation : base.GetService(serviceType, serviceKey); } } diff --git a/src/AgentCore.Application/Runtime/CallEventKinds.cs b/src/AgentCore.Application/Runtime/CallEventKinds.cs deleted file mode 100644 index e2d49a12..00000000 --- a/src/AgentCore.Application/Runtime/CallEventKinds.cs +++ /dev/null @@ -1,53 +0,0 @@ -using AgentCore.Domain.Audit; - -namespace AgentCore.Application.Runtime; - -/// -/// What one is to the audit vocabulary, in one place. -/// -internal static class CallEventKinds -{ - /// - /// Reads the audit kind one call event maps to, when the chain stores it at all. - /// - public static bool TryGetAuditKind(CallEventKind kind, out AuditEventKind auditKind) - { - switch (kind) - { - case CallEventKind.CallStarted: auditKind = AuditEventKind.CallStarted; return true; - case CallEventKind.PromptFlagged: auditKind = AuditEventKind.PromptFlagged; return true; - case CallEventKind.ToolFailed: auditKind = AuditEventKind.ToolFailed; return true; - case CallEventKind.TurnCompleted: auditKind = AuditEventKind.TurnCompleted; return true; - case CallEventKind.ReplyInterrupted: auditKind = AuditEventKind.ReplyInterrupted; return true; - case CallEventKind.CallEnded: auditKind = AuditEventKind.CallEnded; return true; - case CallEventKind.TurnSuperseded: auditKind = AuditEventKind.TurnSuperseded; return true; - default: auditKind = default; return false; - } - } - - /// - /// Names one kind for a log line. - /// - public static string ToToken(CallEventKind kind) - { - if (TryGetAuditKind(kind, out AuditEventKind auditKind)) - { - return AuditEventKinds.ToToken(auditKind); - } - - return kind switch - { - CallEventKind.ModerationUnavailable => "moderation.unavailable", - CallEventKind.ModerationClean => "moderation.clean", - CallEventKind.EmptyReply => "reply.empty", - CallEventKind.ExtractionFailed => "extraction.failed", - CallEventKind.TranscriptWriteFailed => "transcript.write.failed", - CallEventKind.StateRestorePartial => "state.restore.partial", - CallEventKind.TranscriptResyncFailed => "transcript.resync.failed", - - // A kind outside the closed set must not cost the report the fault it is carrying, so this - // names the value instead of throwing over it. - _ => kind.ToString(), - }; - } -} diff --git a/src/AgentCore.Application/Runtime/Clarifications.cs b/src/AgentCore.Application/Runtime/Clarifications.cs index a5ef1e06..4c7a630e 100644 --- a/src/AgentCore.Application/Runtime/Clarifications.cs +++ b/src/AgentCore.Application/Runtime/Clarifications.cs @@ -1,10 +1,10 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using Microsoft.Agents.AI; namespace AgentCore.Application.Runtime; /// -/// One call's memory of what the knowledge probe has asked and named, and the per-turn latch that +/// One conversation's memory of what the knowledge probe has asked and named, and the per-turn latch that /// lets several search-tool calls in one turn share a single probe (K36, K43). /// internal sealed class Clarifications @@ -57,13 +57,13 @@ internal void Update(string name, Action mutate) /// /// Claims this turn's one probe search. Several search-tool calls in one turn, or several graph - /// participants sharing this call, race here, and exactly one wins. + /// participants sharing this conversation, race here, and exactly one wins. /// /// /// The turn's probe. is true for the one caller that must run the search /// and then report through or , and false for /// every other caller this turn, which replays the winner's outcome through - /// instead. The handle names the turn's own payload, so a call + /// instead. The handle names the turn's own payload, so a conversation /// that outlives its turn publishes to a latch nothing is waiting on rather than to the next /// turn's. A winner must resolve the latch on every path out, including a throw, or the turn's /// other callers wait out their full margin for an outcome that is never coming. @@ -91,7 +91,7 @@ internal Probe ClaimProbe() /// probe rather than the turn before it. /// /// - /// Must run exactly once per turn, from CallTurnRunner.BeginTurn and nowhere else. + /// Must run exactly once per turn, from ConversationTurnRunner.BeginTurn and nowhere else. /// internal void BeginTurn() { @@ -117,16 +117,16 @@ internal void Withdraw() } } - /// Reads what every slot has spent of its ask budget, for the call's stored state. + /// Reads what every slot has spent of its ask budget, for the conversation's stored state. /// /// One entry per slot that has spent anything. A slot that has never been asked about is left - /// out, so a call that reached no ambiguity stores nothing. + /// out, so a conversation that reached no ambiguity stores nothing. /// - internal IReadOnlyDictionary Spent() + internal IReadOnlyDictionary Spent() { lock (_gate) { - Dictionary spent = new(StringComparer.Ordinal); + Dictionary spent = new(StringComparer.Ordinal); foreach (var (name, state) in _slots) { @@ -135,14 +135,14 @@ internal IReadOnlyDictionary Spent() continue; } - spent[name] = new CallClarificationState { ProbeAsks = state.ProbeAsks }; + spent[name] = new ConversationClarificationState { ProbeAsks = state.ProbeAsks }; } return spent; } } - /// Puts back what an earlier session of this call spent of its ask budget. + /// Puts back what an earlier session of this conversation spent of its ask budget. /// What read from that session. /// /// The record of what was last named is deliberately not restored: it belongs to a turn the @@ -150,7 +150,7 @@ internal IReadOnlyDictionary Spent() /// gives — a caller who drops and comes back must not buy a fresh /// maxAsks and hear the same question all over again. /// - internal void RestoreSpent(IReadOnlyDictionary spent) + internal void RestoreSpent(IReadOnlyDictionary spent) { ArgumentNullException.ThrowIfNull(spent); diff --git a/src/AgentCore.Application/Runtime/CallEvent.cs b/src/AgentCore.Application/Runtime/ConversationEvent.cs similarity index 75% rename from src/AgentCore.Application/Runtime/CallEvent.cs rename to src/AgentCore.Application/Runtime/ConversationEvent.cs index b2dc510e..f98f79a4 100644 --- a/src/AgentCore.Application/Runtime/CallEvent.cs +++ b/src/AgentCore.Application/Runtime/ConversationEvent.cs @@ -3,15 +3,15 @@ namespace AgentCore.Application.Runtime; /// -/// One fact about a call, as the turn loop saw it. Nothing edits it afterwards. +/// One fact about a conversation, as the turn loop saw it. Nothing edits it afterwards. /// -public sealed record CallEvent +public sealed record ConversationEvent { - /// Gets the id of the call the fact belongs to. - public required string CallId { get; init; } + /// Gets the id of the conversation the fact belongs to. + public required string ConversationId { get; init; } /// Gets what happened. - public required CallEventKind Kind { get; init; } + public required ConversationEventKind Kind { get; init; } /// Gets the moment it happened, read from the clock of the session. public required DateTimeOffset OccurredAt { get; init; } @@ -24,7 +24,7 @@ public sealed record CallEvent /// /// Gets the zero-based index of the turn the fact belongs to, or for a - /// fact about the call itself. + /// fact about the conversation itself. /// public int? TurnIndex { get; init; } diff --git a/src/AgentCore.Application/Runtime/CallEventChain.cs b/src/AgentCore.Application/Runtime/ConversationEventChain.cs similarity index 77% rename from src/AgentCore.Application/Runtime/CallEventChain.cs rename to src/AgentCore.Application/Runtime/ConversationEventChain.cs index d09c5a36..7edcded2 100644 --- a/src/AgentCore.Application/Runtime/CallEventChain.cs +++ b/src/AgentCore.Application/Runtime/ConversationEventChain.cs @@ -4,32 +4,32 @@ namespace AgentCore.Application.Runtime; /// -/// The event chain of one call. It gives every fact its identity, hands it to the observers, and +/// The event chain of one conversation. It gives every fact its identity, hands it to the observers, and /// closes the chain once. /// -internal sealed class CallEventChain +internal sealed class ConversationEventChain { - private readonly string _callId; + private readonly string _conversationId; - private readonly CallObserverDispatcher _observers; + private readonly ConversationObserverDispatcher _observers; private readonly TimeProvider _time; private int _ended; - internal CallEventChain(string callId, CallObserverDispatcher observers, TimeProvider time) + internal ConversationEventChain(string conversationId, ConversationObserverDispatcher observers, TimeProvider time) { - _callId = callId; + _conversationId = conversationId; _observers = observers; _time = time; } - /// Gets whether the chain already closed. Nothing may be appended behind call.ended. + /// Gets whether the chain already closed. Nothing may be appended behind conversation.ended. internal bool HasEnded => Volatile.Read(ref _ended) == 1; - /// Raises one durable fact of this call, and gives it its identity. + /// Raises one durable fact of this conversation, and gives it its identity. internal Guid Raise( - CallEventKind kind, + ConversationEventKind kind, DateTimeOffset occurredAt, int? turnIndex, Guid? amends = null, @@ -48,21 +48,21 @@ internal Guid Raise( /// The turn it belongs to. /// The detail the fact carries. internal void RaiseDiagnostic( - CallEventKind kind, + ConversationEventKind kind, DateTimeOffset occurredAt, int? turnIndex, IReadOnlyDictionary? payload = null) => Dispatch(kind, occurredAt, turnIndex, eventId: null, amends: null, payload); - /// Closes the chain of this call, once. - /// Why the call ended. + /// Closes the chain of this conversation, once. + /// Why the conversation ended. /// The moment it ended. /// The stage the machine stopped in, or . - /// when this call wrote the event, and when it already had. - internal bool EndCall(CallEndReason reason, DateTimeOffset endedAt, string? terminalStage = null) + /// when this conversation wrote the event, and when it already had. + internal bool EndConversation(ConversationEndReason reason, DateTimeOffset endedAt, string? terminalStage = null) { // The token is read first, so a value outside the closed set writes no event at all. - var token = CallEndReasons.ToToken(reason); + var token = ConversationEndReasons.ToToken(reason); if (Interlocked.Exchange(ref _ended, 1) == 1) { @@ -79,7 +79,7 @@ internal bool EndCall(CallEndReason reason, DateTimeOffset endedAt, string? term payload[AuditPayloadKeys.StageAfter] = terminalStage; } - _ = Raise(CallEventKind.CallEnded, endedAt, turnIndex: null, payload: payload); + _ = Raise(ConversationEventKind.ConversationEnded, endedAt, turnIndex: null, payload: payload); return true; } @@ -95,7 +95,7 @@ internal bool EndCall(CallEndReason reason, DateTimeOffset endedAt, string? term /// The played duration, or . /// /// The identity of the turn.completed fact, so a barge-in that arrives after this turn - /// already ended can name it through . + /// already ended can name it through . /// internal Guid WriteTurnEvents( int turnIndex, @@ -110,7 +110,7 @@ internal Guid WriteTurnEvents( if (toolFault is not null) { _ = Raise( - CallEventKind.ToolFailed, + ConversationEventKind.ToolFailed, endedAt, turnIndex, payload: new Dictionary(StringComparer.Ordinal) @@ -120,7 +120,7 @@ internal Guid WriteTurnEvents( } var completed = Raise( - CallEventKind.TurnCompleted, + ConversationEventKind.TurnCompleted, endedAt, turnIndex, payload: new Dictionary(StringComparer.Ordinal) @@ -151,7 +151,7 @@ internal void RaiseReplyInterrupted( string heard, TimeSpan played) => _ = Raise( - CallEventKind.ReplyInterrupted, + ConversationEventKind.ReplyInterrupted, occurredAt, turnIndex, amends: amendsEventId, @@ -171,7 +171,7 @@ internal void RaiseModeration(int turnIndex, TurnDisposition? disposition) { case ModerationOutcome.Flagged: _ = Raise( - CallEventKind.PromptFlagged, + ConversationEventKind.PromptFlagged, _time.GetUtcNow(), turnIndex, payload: new Dictionary(StringComparer.Ordinal) @@ -182,18 +182,18 @@ internal void RaiseModeration(int turnIndex, TurnDisposition? disposition) case ModerationOutcome.Unavailable: RaiseDiagnostic( - CallEventKind.ModerationUnavailable, + ConversationEventKind.ModerationUnavailable, _time.GetUtcNow(), turnIndex, payload: new Dictionary(StringComparer.Ordinal) { - [CallEventPayloadKeys.Reason] = - disposition.ModerationReason ?? CallSession.ModerationFaultedReason, + [ConversationEventPayloadKeys.Reason] = + disposition.ModerationReason ?? ConversationSession.ModerationFaultedReason, }); break; case ModerationOutcome.Clean: - RaiseDiagnostic(CallEventKind.ModerationClean, _time.GetUtcNow(), turnIndex); + RaiseDiagnostic(ConversationEventKind.ModerationClean, _time.GetUtcNow(), turnIndex); break; default: @@ -202,11 +202,11 @@ internal void RaiseModeration(int turnIndex, TurnDisposition? disposition) } /// Raises the fact of one tool call that did not run to completion. - /// The turn the call belongs to. + /// The turn the conversation belongs to. /// What the function-invocation loop saw. internal void RaiseToolFailure(int turnIndex, ToolFailure failure) => _ = Raise( - CallEventKind.ToolFailed, + ConversationEventKind.ToolFailed, _time.GetUtcNow(), turnIndex, payload: new Dictionary(StringComparer.Ordinal) @@ -220,26 +220,26 @@ internal void RaiseToolFailure(int turnIndex, ToolFailure failure) /// Raises the fact of one store 1 write the backing store refused. internal void RaiseDroppedTranscriptWrite(int turnIndex, Exception exception) => RaiseDiagnostic( - CallEventKind.TranscriptWriteFailed, + ConversationEventKind.TranscriptWriteFailed, _time.GetUtcNow(), turnIndex, payload: new Dictionary(StringComparer.Ordinal) { - [CallEventPayloadKeys.Reason] = $"{exception.GetType().Name}: {exception.Message}", + [ConversationEventPayloadKeys.Reason] = $"{exception.GetType().Name}: {exception.Message}", }); /// Raises the fact of one store 1 read that failed as a turn opened. internal void RaiseFailedTranscriptResync(int turnIndex, Exception exception) => RaiseDiagnostic( - CallEventKind.TranscriptResyncFailed, + ConversationEventKind.TranscriptResyncFailed, _time.GetUtcNow(), turnIndex, payload: new Dictionary(StringComparer.Ordinal) { - [CallEventPayloadKeys.Reason] = $"{exception.GetType().Name}: {exception.Message}", + [ConversationEventPayloadKeys.Reason] = $"{exception.GetType().Name}: {exception.Message}", }); - /// Hands one fact to everything watching the call, and never waits for it. + /// Hands one fact to everything watching the conversation, and never waits for it. /// What happened. /// When it happened. /// The turn it belongs to, or . @@ -247,15 +247,15 @@ internal void RaiseFailedTranscriptResync(int turnIndex, Exception exception) /// The identity it corrects, or . /// The detail it carries. private void Dispatch( - CallEventKind kind, + ConversationEventKind kind, DateTimeOffset occurredAt, int? turnIndex, Guid? eventId, Guid? amends, IReadOnlyDictionary? payload) - => _observers.Dispatch(new CallEvent + => _observers.Dispatch(new ConversationEvent { - CallId = _callId, + ConversationId = _conversationId, Kind = kind, OccurredAt = occurredAt, EventId = eventId, diff --git a/src/AgentCore.Application/Runtime/CallEventKind.cs b/src/AgentCore.Application/Runtime/ConversationEventKind.cs similarity index 76% rename from src/AgentCore.Application/Runtime/CallEventKind.cs rename to src/AgentCore.Application/Runtime/ConversationEventKind.cs index a654d307..c4cbc87d 100644 --- a/src/AgentCore.Application/Runtime/CallEventKind.cs +++ b/src/AgentCore.Application/Runtime/ConversationEventKind.cs @@ -1,12 +1,12 @@ namespace AgentCore.Application.Runtime; /// -/// The closed set of facts one call raises to its observers. +/// The closed set of facts one conversation raises to its observers. /// -public enum CallEventKind +public enum ConversationEventKind { - /// A session of the call started. It is the first fact of every session. - CallStarted = 0, + /// A session of the conversation started. It is the first fact of every session. + ConversationStarted = 0, /// Moderation flagged what the CALLER said, so the agent refused to answer that turn. PromptFlagged = 1, @@ -38,10 +38,10 @@ public enum CallEventKind /// A store 1 write was refused, so the durable copy of some words was lost. TranscriptWriteFailed = 10, - /// The host ended the call. It is the last fact of the session that ended it. - CallEnded = 9, + /// The host ended the conversation. It is the last fact of the session that ended it. + ConversationEnded = 9, - /// A resumed call could not restore part of its stored state: the document changed under it. + /// A resumed conversation could not restore part of its stored state: the document changed under it. StateRestorePartial = 11, /// diff --git a/src/AgentCore.Application/Runtime/ConversationEventKinds.cs b/src/AgentCore.Application/Runtime/ConversationEventKinds.cs new file mode 100644 index 00000000..bed7adb6 --- /dev/null +++ b/src/AgentCore.Application/Runtime/ConversationEventKinds.cs @@ -0,0 +1,53 @@ +using AgentCore.Domain.Audit; + +namespace AgentCore.Application.Runtime; + +/// +/// What one is to the audit vocabulary, in one place. +/// +internal static class ConversationEventKinds +{ + /// + /// Reads the audit kind one conversation event maps to, when the chain stores it at all. + /// + public static bool TryGetAuditKind(ConversationEventKind kind, out AuditEventKind auditKind) + { + switch (kind) + { + case ConversationEventKind.ConversationStarted: auditKind = AuditEventKind.ConversationStarted; return true; + case ConversationEventKind.PromptFlagged: auditKind = AuditEventKind.PromptFlagged; return true; + case ConversationEventKind.ToolFailed: auditKind = AuditEventKind.ToolFailed; return true; + case ConversationEventKind.TurnCompleted: auditKind = AuditEventKind.TurnCompleted; return true; + case ConversationEventKind.ReplyInterrupted: auditKind = AuditEventKind.ReplyInterrupted; return true; + case ConversationEventKind.ConversationEnded: auditKind = AuditEventKind.ConversationEnded; return true; + case ConversationEventKind.TurnSuperseded: auditKind = AuditEventKind.TurnSuperseded; return true; + default: auditKind = default; return false; + } + } + + /// + /// Names one kind for a log line. + /// + public static string ToToken(ConversationEventKind kind) + { + if (TryGetAuditKind(kind, out AuditEventKind auditKind)) + { + return AuditEventKinds.ToToken(auditKind); + } + + return kind switch + { + ConversationEventKind.ModerationUnavailable => "moderation.unavailable", + ConversationEventKind.ModerationClean => "moderation.clean", + ConversationEventKind.EmptyReply => "reply.empty", + ConversationEventKind.ExtractionFailed => "extraction.failed", + ConversationEventKind.TranscriptWriteFailed => "transcript.write.failed", + ConversationEventKind.StateRestorePartial => "state.restore.partial", + ConversationEventKind.TranscriptResyncFailed => "transcript.resync.failed", + + // A kind outside the closed set must not cost the report the fault it is carrying, so this + // names the value instead of throwing over it. + _ => kind.ToString(), + }; + } +} diff --git a/src/AgentCore.Application/Runtime/CallEventPayloadKeys.cs b/src/AgentCore.Application/Runtime/ConversationEventPayloadKeys.cs similarity index 66% rename from src/AgentCore.Application/Runtime/CallEventPayloadKeys.cs rename to src/AgentCore.Application/Runtime/ConversationEventPayloadKeys.cs index d1cb9245..6544c451 100644 --- a/src/AgentCore.Application/Runtime/CallEventPayloadKeys.cs +++ b/src/AgentCore.Application/Runtime/ConversationEventPayloadKeys.cs @@ -3,9 +3,9 @@ namespace AgentCore.Application.Runtime; /// -/// The payload keys a diagnostic-only carries. +/// The payload keys a diagnostic-only carries. /// -internal static class CallEventPayloadKeys +internal static class ConversationEventPayloadKeys { /// /// Why a diagnostic-only event happened, in the words the turn loop used. diff --git a/src/AgentCore.Application/Runtime/CallObserverDispatcher.cs b/src/AgentCore.Application/Runtime/ConversationObserverDispatcher.cs similarity index 73% rename from src/AgentCore.Application/Runtime/CallObserverDispatcher.cs rename to src/AgentCore.Application/Runtime/ConversationObserverDispatcher.cs index 2c22a059..83dd188a 100644 --- a/src/AgentCore.Application/Runtime/CallObserverDispatcher.cs +++ b/src/AgentCore.Application/Runtime/ConversationObserverDispatcher.cs @@ -6,7 +6,7 @@ namespace AgentCore.Application.Runtime; /// -/// Hands each fact of a call to every observer, in order, and never waits for one. +/// Hands each fact of a conversation to every observer, in order, and never waits for one. /// /// /// @@ -17,7 +17,7 @@ namespace AgentCore.Application.Runtime; /// while the row is still being written. /// /// -/// Nothing here propagates. An observer records the call and is never a part of it, so one that +/// Nothing here propagates. An observer records the conversation and is never a part of it, so one that /// throws is logged once and the turn goes on. That holds for a fault raised before the first await /// and for a fault raised long after the turn ended, and it holds for each observer separately: a /// refusing sink does not cost the counters or the log their reading of the same fact. @@ -25,15 +25,15 @@ namespace AgentCore.Application.Runtime; /// /// Order is a guarantee, and it is a guarantee per observer. A bare fire-and-forget task per /// event lets two slow deliveries land out of order, and an audit chain whose events arrive shuffled -/// is not a record of the call. Every observer therefore has a tail of its own in +/// is not a record of the conversation. Every observer therefore has a tail of its own in /// , and a dispatch chains onto that observer's tail under : -/// the facts of one dispatcher reach ONE observer in the order the call produced them, however long +/// the facts of one dispatcher reach ONE observer in the order the conversation produced them, however long /// any one of them takes. That is the whole of what the chain of D23 asks for. /// /// /// It is deliberately not one guarantee across observers. A single shared tail would queue every /// later counter and every later log line behind a sink still writing an earlier row, so the two -/// fast readings would pay the slow one's price on every event after it, for the rest of the call. +/// fast readings would pay the slow one's price on every event after it, for the rest of the conversation. /// With a tail each, a slow observer delays only itself, and telemetry and logging keep their old /// synchronous cost whatever the sink is doing. /// @@ -51,14 +51,14 @@ namespace AgentCore.Application.Runtime; /// turn loop does when the sink is a queue, which is the shape D23 asks for. /// /// -/// One dispatcher belongs to one call, because the ordering guarantee is per dispatcher and a shared -/// instance would make every call queue behind every other. The observers behind it are shared, and +/// One dispatcher belongs to one conversation, because the ordering guarantee is per dispatcher and a shared +/// instance would make every conversation queue behind every other. The observers behind it are shared, and /// they hold no per-call state. /// /// -internal sealed class CallObserverDispatcher +internal sealed class ConversationObserverDispatcher { - private readonly ICallObserver[] _observers; + private readonly IConversationObserver[] _observers; private readonly ILogger _logger; private readonly Lock _gate = new(); @@ -69,16 +69,16 @@ internal sealed class CallObserverDispatcher /// private readonly Task?[] _tails; - /// Creates the dispatcher of one call. + /// Creates the dispatcher of one conversation. /// - /// Everything that watches the call. Each one takes every fact, in the order they are given here. + /// Everything that watches the conversation. Each one takes every fact, in the order they are given here. /// An empty set is legal, and it makes every dispatch a no-op. /// /// /// The logger an observer's fault is reported to, or for /// . The library never throws for want of one. /// - public CallObserverDispatcher(IEnumerable observers, ILogger? logger = null) + public ConversationObserverDispatcher(IEnumerable observers, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(observers); @@ -87,19 +87,19 @@ public CallObserverDispatcher(IEnumerable observers, ILogger? log _logger = logger ?? NullLogger.Instance; } - /// Gets the number of observers watching the call. + /// Gets the number of observers watching the conversation. public int Count => _observers.Length; /// Hands one fact to every observer, and never waits for them. - /// What happened. - /// is . + /// What happened. + /// is . /// /// It returns as soon as the observers have accepted the fact, which for a well-behaved observer /// is before it returns at all. Nothing an observer does can make this method throw or block. /// - public void Dispatch(CallEvent callEvent) + public void Dispatch(ConversationEvent conversationEvent) { - ArgumentNullException.ThrowIfNull(callEvent); + ArgumentNullException.ThrowIfNull(conversationEvent); if (_observers.Length == 0) { @@ -109,7 +109,7 @@ public void Dispatch(CallEvent callEvent) lock (_gate) { // The observers are offered the fact one after another rather than all at once, so the - // order they were registered in is the order they read the call in. + // order they were registered in is the order they read the conversation in. for (int index = 0; index < _observers.Length; index++) { Task? tail = _tails[index]; @@ -119,15 +119,15 @@ public void Dispatch(CallEvent callEvent) // for it to follow. if (tail is null || tail.IsCompleted) { - Task delivery = DeliverAsync(_observers[index], callEvent); + Task delivery = DeliverAsync(_observers[index], conversationEvent); _tails[index] = delivery.IsCompleted ? null : delivery; continue; } // An earlier fact is still open at THIS observer. This one waits behind it, so that - // observer never sees the turns of a call out of the order the call ran them — and + // observer never sees the turns of a conversation out of the order the conversation ran them — and // every other observer still reads this fact now, whatever the slow one is doing. - _tails[index] = ContinueAsync(tail, _observers[index], callEvent); + _tails[index] = ContinueAsync(tail, _observers[index], conversationEvent); } } } @@ -135,9 +135,9 @@ public void Dispatch(CallEvent callEvent) /// Waits for the earlier fact of one observer, then delivers this one to it. /// The delivery of that observer already outstanding. /// The observer both facts belong to. - /// The fact queued behind the earlier one. + /// The fact queued behind the earlier one. /// A task that always completes, and never faults. - private async Task ContinueAsync(Task previous, ICallObserver observer, CallEvent callEvent) + private async Task ContinueAsync(Task previous, IConversationObserver observer, ConversationEvent conversationEvent) { try { @@ -152,24 +152,24 @@ private async Task ContinueAsync(Task previous, ICallObserver observer, CallEven // this one is owed to the observer whatever happened to the fact before it. } - await DeliverAsync(observer, callEvent).ConfigureAwait(false); + await DeliverAsync(observer, conversationEvent).ConfigureAwait(false); } /// Offers one fact to one observer. /// The observer the fact is owed to. - /// What happened. + /// What happened. /// A task that always completes, and never faults. /// /// A slow observer delays only the later facts of its own tail, off the turn, where the cost is /// nobody's. /// - private async Task DeliverAsync(ICallObserver observer, CallEvent callEvent) + private async Task DeliverAsync(IConversationObserver observer, ConversationEvent conversationEvent) { try { - // CancellationToken.None: the record belongs to the call, not to the turn the caller may + // CancellationToken.None: the record belongs to the conversation, not to the turn the caller may // have cancelled. - ValueTask pending = observer.OnCallEventAsync(callEvent, CancellationToken.None); + ValueTask pending = observer.OnConversationEventAsync(conversationEvent, CancellationToken.None); if (pending.IsCompletedSuccessfully) { return; @@ -177,27 +177,27 @@ private async Task DeliverAsync(ICallObserver observer, CallEvent callEvent) await pending.ConfigureAwait(false); } -#pragma warning disable CA1031 // An observer records the call and is never a part of it. +#pragma warning disable CA1031 // An observer records the conversation and is never a part of it. catch (Exception exception) #pragma warning restore CA1031 { - Report(callEvent, exception); + Report(conversationEvent, exception); } } /// Writes the one line an observer's fault is worth, and never throws. - /// The fact the observer refused. + /// The fact the observer refused. /// The cause. - private void Report(CallEvent callEvent, Exception exception) + private void Report(ConversationEvent conversationEvent, Exception exception) { try { - // The token is read from CallEventKinds, which is also what AuditCallObserver and - // TelemetryCallObserver ask about a kind. One mapping, so a line and a row never + // The token is read from ConversationEventKinds, which is also what AuditConversationObserver and + // TelemetryConversationObserver ask about a kind. One mapping, so a line and a row never // disagree about what the observer refused. - Log.AuditAppendFailed(_logger, callEvent.CallId, CallEventKinds.ToToken(callEvent.Kind), exception); + Log.AuditAppendFailed(_logger, conversationEvent.ConversationId, ConversationEventKinds.ToToken(conversationEvent.Kind), exception); } -#pragma warning disable CA1031 // A logger that refuses the report is still not a part of the call. +#pragma warning disable CA1031 // A logger that refuses the report is still not a part of the conversation. catch (Exception) #pragma warning restore CA1031 { diff --git a/src/AgentCore.Application/Runtime/CallObservers.cs b/src/AgentCore.Application/Runtime/ConversationObservers.cs similarity index 76% rename from src/AgentCore.Application/Runtime/CallObservers.cs rename to src/AgentCore.Application/Runtime/ConversationObservers.cs index a4c2a06a..3aa205dc 100644 --- a/src/AgentCore.Application/Runtime/CallObservers.cs +++ b/src/AgentCore.Application/Runtime/ConversationObservers.cs @@ -6,46 +6,46 @@ namespace AgentCore.Application.Runtime; /// -/// Assembles the readings of one call, in the order every call then pays for. +/// Assembles the readings of one conversation, in the order every conversation then pays for. /// /// /// /// The composition root resolves an — always one, since /// providers.audit falls back to the in-process memory kind — and an -/// , and knows nothing of . This is what turns them +/// , and knows nothing of . This is what turns them /// into the telemetry, logging, and audit readings of one fact. It is composition, so it belongs to -/// the composition root and not to : the factory is handed the +/// the composition root and not to : the factory is handed the /// finished list and holds no opinion about what is in it. /// /// -/// The observers it builds are shared and hold no per-call state, so one list serves every call. +/// The observers it builds are shared and hold no per-call state, so one list serves every conversation. /// The ordering guarantee is not here either — each session gets a -/// of its own, because that guarantee is per instance and a -/// shared one would make every call queue behind every other. +/// of its own, because that guarantee is per instance and a +/// shared one would make every conversation queue behind every other. /// /// -public static class CallObservers +public static class ConversationObservers { /// Builds the list one host's bindings ask for. /// /// The sink the chain of D23 is appended to. There is always one: the composition root reads /// providers.audit, which names the in-process memory kind when the document names /// no vendor, so a host that configures nothing still hands a real sink down rather than a hole. - /// One sink serves every call, because a session names itself on every event. + /// One sink serves every conversation, because a session names itself on every event. /// /// /// The logger the three "log once" rows of section 8.7 write to, or for a /// logger that writes nowhere. The library never throws for want of one. /// /// - /// The host's own readings of a call, or for a host that adds none. + /// The host's own readings of a conversation, or for a host that adds none. /// /// The readings, in the order the dispatcher offers each fact to them. /// is . - public static IReadOnlyList Standard( + public static IReadOnlyList Standard( IAuditSinkPort auditSink, ILogger? logger, - IEnumerable? hostObservers = null) + IEnumerable? hostObservers = null) { ArgumentNullException.ThrowIfNull(auditSink); @@ -58,7 +58,7 @@ public static IReadOnlyList Standard( // What the order no longer decides is what a LATER fact costs. Each observer has a tail of // its own inside the dispatcher, so a sink still writing an earlier row holds up nothing but // its own next row: telemetry and logging keep their old synchronous cost on every event - // whatever the sink is doing, and the remarks on TelemetryCallObserver still hold that a kind + // whatever the sink is doing, and the remarks on TelemetryConversationObserver still hold that a kind // is counted whatever the sink then does with it. Order is guaranteed per observer, which is // all the chain of D23 needs, and the slow one pays for itself alone, off the turn. // @@ -67,10 +67,10 @@ public static IReadOnlyList Standard( // the same position: the composition root resolves providers.audit into a sink for every // host, falling back to the in-process memory kind when the document names no vendor, so // there is no longer a "bound nothing" shape for this list to have. The chain of D23 is - // therefore written on every call, and a host that wants it durable changes where it goes, + // therefore written on every conversation, and a host that wants it durable changes where it goes, // not whether it is taken. - ICallObserver[] library = - [new TelemetryCallObserver(), new LoggingCallObserver(logger), new AuditCallObserver(auditSink)]; + IConversationObserver[] library = + [new TelemetryConversationObserver(), new LoggingConversationObserver(logger), new AuditConversationObserver(auditSink)]; // The host's own observers go after all three. An observer bound through // AgentCoreOptions.UseObservers is code this library did not write and cannot measure, and diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/ConversationSession.cs similarity index 72% rename from src/AgentCore.Application/Runtime/CallSession.cs rename to src/AgentCore.Application/Runtime/ConversationSession.cs index ea0819c7..1b4da065 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession.cs @@ -1,5 +1,5 @@ using System.Text.Json; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Configuration.Validation; @@ -19,9 +19,9 @@ namespace AgentCore.Application.Runtime; /// -/// The turn loop of one call. It owns the state, the stage machine, and the transcript. +/// The turn loop of one conversation. It owns the state, the stage machine, and the transcript. /// -public sealed class CallSession : IConversationPort, IAsyncDisposable +public sealed class ConversationSession : IConversationPort, IAsyncDisposable { /// /// The line the caller hears when a turn fails and the document names none. @@ -68,7 +68,7 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private readonly TimeProvider _time; - private readonly CallEventChain _events; + private readonly ConversationEventChain _events; private readonly DateTimeOffset _startedAt; @@ -82,9 +82,9 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private readonly Clarifications _clarifications = new(); - private readonly CallWorkspace? _workspace; + private readonly ConversationWorkspace? _workspace; - private readonly CallShells? _shells; + private readonly ConversationShells? _shells; // Phase 1 seam: one live-state owner, verb-split operators. The helpers below hold this // session and operate on the same fields under the same lock; only ownership of the verbs @@ -97,7 +97,7 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable internal TimeProvider Time => _time; - internal CallEventChain Events => _events; + internal ConversationEventChain Events => _events; internal DateTimeOffset StartedAt => _startedAt; @@ -109,16 +109,16 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable internal Lock InterruptLock => _interruptLock; - internal CallShells? Shells => _shells; + internal ConversationShells? Shells => _shells; - internal CallWorkspace? WorkspaceRoot => _workspace; + internal ConversationWorkspace? WorkspaceRoot => _workspace; internal AgentSession? AgentSession { get; set; } /// - /// The call's shared workflow session on a graph row whose document declares a harness + /// The conversation's shared workflow session on a graph row whose document declares a harness /// switch. MAF restores the participants' provider state from its checkpoints on every - /// turn; any other call runs every turn fresh and leaves this . + /// turn; any other conversation runs every turn fresh and leaves this . /// internal AgentSession? GraphSession { get; set; } @@ -130,55 +130,55 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable internal CancellationTokenSource? RunCancellation { get; set; } - internal CallInterruptionTracker.Interruption? Interruption { get; set; } + internal ConversationInterruptionTracker.Interruption? Interruption { get; set; } internal Guid? AmendableEventId { get; set; } - internal CallSessionState? Checkpoint { get; set; } + internal ConversationSessionState? Checkpoint { get; set; } internal Clarifications Clarifications => _clarifications; - internal CallTurnRunner Runner { get; } + internal ConversationTurnRunner Runner { get; } - internal CallTurnStream Stream { get; } + internal ConversationTurnStream Stream { get; } - internal CallTurnCompletion Completion { get; } + internal ConversationTurnCompletion Completion { get; } - internal CallTurnWriters Writers { get; } + internal ConversationTurnWriters Writers { get; } - internal CallInterruptionTracker Interruptions { get; } + internal ConversationInterruptionTracker Interruptions { get; } - internal CallTranscriptLedger Ledger { get; } + internal ConversationTranscriptLedger Ledger { get; } - internal CallSessionStateStore States { get; } + internal ConversationSessionStateStore States { get; } - internal CallSessionLifetime Lifetime { get; } + internal ConversationSessionLifetime Lifetime { get; } /// - /// Creates the session of one call. + /// Creates the session of one conversation. /// - internal CallSession( - string callId, + internal ConversationSession( + string conversationId, CompiledAgent compiled, IGuardEvaluator guards, StateExtractor? extractor, TimeProvider timeProvider, - CallObserverDispatcher? observers = null, + ConversationObserverDispatcher? observers = null, ILogger? logger = null, - CallWorkspace? workspace = null) + ConversationWorkspace? workspace = null) { - ArgumentException.ThrowIfNullOrEmpty(callId); + ArgumentException.ThrowIfNullOrEmpty(conversationId); ArgumentNullException.ThrowIfNull(compiled); ArgumentNullException.ThrowIfNull(guards); ArgumentNullException.ThrowIfNull(timeProvider); - CallId = callId; + ConversationId = conversationId; _logger = logger ?? NullLogger.Instance; _workspace = workspace; - _shells = workspace is null ? null : new CallShells(workspace.Path, _logger); + _shells = workspace is null ? null : new ConversationShells(workspace.Path, _logger); _compiled = compiled; @@ -193,13 +193,13 @@ internal CallSession( _time = timeProvider; // The seam is optional and it has a working default. A host that binds nothing to watch the - // call still answers it, and the library never throws for want of an observer. - _events = new CallEventChain(callId, observers ?? new CallObserverDispatcher([]), timeProvider); + // conversation still answers it, and the library never throws for want of an observer. + _events = new ConversationEventChain(conversationId, observers ?? new ConversationObserverDispatcher([]), timeProvider); _startedAt = timeProvider.GetUtcNow(); // An entry with no policy: has no stage machine. The single-agent row and both graph rows - // read that way, and neither of them ever ends a call by itself. + // read that way, and neither of them ever ends a conversation by itself. _policy = compiled.Policy is null ? null : compiled.CreatePolicy(guards); State = new StateDocument(compiled.Configuration, _policy?.Stage); @@ -210,35 +210,35 @@ internal CallSession( // load-bearing. ConstStateWriter.Apply(State); - // The first fact of this SESSION, and not necessarily of the call: a resumed call raises a + // The first fact of this SESSION, and not necessarily of the conversation: a resumed conversation raises a // second one, behind the turns of the session before it. Nothing allocates a position here // any more — store 3 assigns the sequence — so a second one collides with nothing, and it is - // raised rather than suppressed because a session picking the call up is a fact that + // raised rather than suppressed because a session picking the conversation up is a fact that // happened and the chain is where facts that happened go. Suppressing it is also not - // available from here: knowing whether the call already has words needs the store read that - // only OpenSessionAsync can do, and moving the raise there would let a call opened, never - // spoken to, and then ended through EndCall write a call.ended with no call.started in front + // available from here: knowing whether the conversation already has words needs the store read that + // only OpenSessionAsync can do, and moving the raise there would let a conversation opened, never + // spoken to, and then ended through EndConversation write a conversation.ended with no conversation.started in front // of it. - _ = _events.Raise(CallEventKind.CallStarted, _startedAt, turnIndex: null); - - Runner = new CallTurnRunner(this); - Stream = new CallTurnStream(this); - Completion = new CallTurnCompletion(this); - Writers = new CallTurnWriters(this); - Interruptions = new CallInterruptionTracker(this); - Ledger = new CallTranscriptLedger(this); - States = new CallSessionStateStore(this); - Lifetime = new CallSessionLifetime(this); + _ = _events.Raise(ConversationEventKind.ConversationStarted, _startedAt, turnIndex: null); + + Runner = new ConversationTurnRunner(this); + Stream = new ConversationTurnStream(this); + Completion = new ConversationTurnCompletion(this); + Writers = new ConversationTurnWriters(this); + Interruptions = new ConversationInterruptionTracker(this); + Ledger = new ConversationTranscriptLedger(this); + States = new ConversationSessionStateStore(this); + Lifetime = new ConversationSessionLifetime(this); } /// - /// Gets the id of the call. + /// Gets the id of the conversation. /// - public string CallId { get; } + public string ConversationId { get; } /// - /// Gets the folder this call owns on disk, or when the host bound no - /// workspace root. The folder is deleted when the call ends. + /// Gets the folder this conversation owns on disk, or when the host bound no + /// workspace root. The folder is deleted when the conversation ends. /// public string? Workspace => _workspace?.Path; @@ -248,23 +248,23 @@ internal CallSession( public string Stage => State.Stage; /// - /// Gets whether the call reached a terminal stage. An entry with no policy never does. + /// Gets whether the conversation reached a terminal stage. An entry with no policy never does. /// public bool IsComplete { get; internal set; } /// - /// Gets the state of this call. Every guard and every increment rule reads it. + /// Gets the state of this conversation. Every guard and every increment rule reads it. /// public StateDocument State { get; } /// - /// Gets or sets the knowledge scope the host opened for this call, or null for none. Set it + /// Gets or sets the knowledge scope the host opened for this conversation, or null for none. Set it /// before the run; every turn composes its own scope from it. /// public KnowledgeScope? Scope { get; set; } /// - /// Gets the conversation, oldest first. Every stage of the call reads it. + /// Gets the conversation, oldest first. Every stage of the conversation reads it. /// public IReadOnlyList Transcript => Ledger.Session() is { } session ? _history.Read(session) : []; @@ -280,25 +280,25 @@ public IReadOnlyList Transcript public string? LastReplyMessageId { get; internal set; } /// - /// Gets the compiled agent this session runs. Every call shares it. + /// Gets the compiled agent this session runs. Every conversation shares it. /// public CompiledAgent Compiled => _compiled; /// - /// Whether this call keeps one workflow session across turns: a graph row whose document + /// Whether this conversation keeps one workflow session across turns: a graph row whose document /// declares a harness switch. Everything else either carries history on a long-lived /// session already (rows 1 and 2) or keeps no provider state at all. /// internal bool ReusesGraphSession => !_sessionCarriesHistory && _compiled.HarnessStateKeys.Count > 0; /// - /// Gives the runs this call delegates through one tool a set of tools of their own. + /// Gives the runs this conversation delegates through one tool a set of tools of their own. /// public void SetDelegatedTools(string delegatingToolId, IReadOnlyList tools) => Runner.SetDelegatedTools(delegatingToolId, tools); /// - /// Gives this call the screen its tools draw on, or takes it away. + /// Gives this conversation the screen its tools draw on, or takes it away. /// public void SetHasScreen(bool hasScreen) => Runner.SetHasScreen(hasScreen); @@ -318,7 +318,7 @@ public Task RunTurnMessageAsync(ChatMessage userInput, CancellationT /// Runs one turn that knows where it sits in the conversation the caller can see. /// public Task RunTurnAtOriginAsync( - string userInput, CallTurnOrigin? origin, CancellationToken cancellationToken = default) + string userInput, ConversationTurnOrigin? origin, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(userInput); @@ -330,7 +330,7 @@ public Task RunTurnAtOriginAsync( /// the caller can see. /// public Task RunTurnMessageAtOriginAsync( - ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) + ChatMessage userInput, ConversationTurnOrigin? origin, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userInput); @@ -340,7 +340,7 @@ public Task RunTurnMessageAtOriginAsync( /// Runs one turn and streams the reply as it arrives. /// The reply, one update at a time. Every update carries content. /// - /// The call already reached a terminal stage, another turn of this call is still running, or the + /// The conversation already reached a terminal stage, another turn of this conversation is still running, or the /// stage the machine holds names no agent. /// public IAsyncEnumerable RunTurnStreamingAsync( @@ -350,18 +350,18 @@ public IAsyncEnumerable RunTurnStreamingAsync( /// Runs one turn from a message the caller built and streams the reply as it arrives. /// The reply, one update at a time. Every update carries content. /// - /// The call already reached a terminal stage, another turn of this call is still running, or the + /// The conversation already reached a terminal stage, another turn of this conversation is still running, or the /// stage the machine holds names no agent. /// public IAsyncEnumerable RunTurnMessageStreamingAsync( ChatMessage userInput, CancellationToken cancellationToken) => RunTurnMessageStreamingAtOriginAsync(userInput, origin: null, cancellationToken); - /// Builds the answer message for one queued approval request of this call. + /// Builds the answer message for one queued approval request of this conversation. public ChatMessage? TryCreateApprovalAnswer(string requestId, bool approved) => Ledger.TryCreateApprovalAnswer(requestId, approved); - /// Builds the answer message for one queued approval request of a resumed call. + /// Builds the answer message for one queued approval request of a resumed conversation. /// The id of the pending request this answers. /// Whether the tool may run. /// Cancels the resume. @@ -378,7 +378,7 @@ public IAsyncEnumerable RunTurnMessageStreamingAsync( /// public IAsyncEnumerable RunTurnStreamingAtOriginAsync( string userInput, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(userInput); @@ -393,7 +393,7 @@ public IAsyncEnumerable RunTurnStreamingAtOriginAsync( /// public IAsyncEnumerable RunTurnMessageStreamingAtOriginAsync( ChatMessage userInput, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userInput); @@ -410,28 +410,28 @@ public bool Interrupt( bool cutsRunningTurn = true) => Interruptions.Interrupt(utteranceUntilInterrupt, durationUntilInterrupt, cutsRunningTurn); - /// Closes the call, and writes the last event of its chain. - public bool EndCall(CallEndReason reason) => Lifetime.EndCall(reason); + /// Closes the conversation, and writes the last event of its chain. + public bool EndConversation(ConversationEndReason reason) => Lifetime.EndConversation(reason); /// - /// Disposes this call's background sessions and shell executors. Idempotent: a session already + /// Disposes this conversation's background sessions and shell executors. Idempotent: a session already /// disposed, or one that never had either, disposes nothing. /// public ValueTask DisposeAsync() => Lifetime.DisposeAsync(); /// - /// Waits for every store 1 write this call has queued. + /// Waits for every store 1 write this conversation has queued. /// public Task FlushTranscriptAsync() => Ledger.FlushTranscriptAsync(); /// - /// Reads the state this call would resume from, as it stands right now. The provider state is + /// Reads the state this conversation would resume from, as it stands right now. The provider state is /// read off the live bag with no turn lock around it, so a host serializing mid-turn gets the /// bag as it stands at that instant, not a turn-boundary snapshot. A graph row that reuses /// its session instead attaches that session's last turn-end serialization. /// - internal CallSessionState Snapshot() => States.Snapshot(); + internal ConversationSessionState Snapshot() => States.Snapshot(); - /// Names the state this call resumes from when store 0 holds none of its own. - internal void Resume(CallSessionState stored) => States.Resume(stored); + /// Names the state this conversation resumes from when store 0 holds none of its own. + internal void Resume(ConversationSessionState stored) => States.Resume(stored); } diff --git a/src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationInterruptionTracker.cs similarity index 94% rename from src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationInterruptionTracker.cs index 3e68a71a..72992843 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationInterruptionTracker.cs @@ -1,8 +1,8 @@ namespace AgentCore.Application.Runtime; -internal sealed class CallInterruptionTracker +internal sealed class ConversationInterruptionTracker { - private readonly CallSession _session; + private readonly ConversationSession _session; // One session runs one turn at a time. Lives here, with the rest of the live run, so the // guard and the release travel together; BeginTurn enters through TryEnterTurn. @@ -17,7 +17,7 @@ internal sealed class CallInterruptionTracker /// internal bool RunIsAudible { get => _runIsAudible; set => _runIsAudible = value; } - internal CallInterruptionTracker(CallSession session) + internal ConversationInterruptionTracker(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; @@ -37,7 +37,7 @@ internal CallInterruptionTracker(CallSession session) /// itself streaming. /// /// - /// when this call recorded the barge-in, either by ending the running + /// when this conversation recorded the barge-in, either by ending the running /// turn or by amending the turn that finished last, and when there was /// nothing to record it against. /// @@ -88,7 +88,7 @@ internal CancellationTokenSource StartRun(CancellationToken cancellationToken) return cancellation; } - /// Takes the turn slot, unless a turn of this call is still running. + /// Takes the turn slot, unless a turn of this conversation is still running. /// when another turn holds the slot. internal bool TryEnterTurn() => Interlocked.Exchange(ref _running, 1) == 0; @@ -123,7 +123,7 @@ internal void EndRun(CancellationTokenSource cancellation) /// internal bool AmendLastTurn(Interruption cut) { - // The chain has already closed, so nothing may be appended behind call.ended. + // The chain has already closed, so nothing may be appended behind conversation.ended. if (_session.Events.HasEnded || _session.AmendableEventId is not { } completedEventId || _session.LastTurn is not { InterruptedAfter: null } finished diff --git a/src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationSessionLifetime.cs similarity index 54% rename from src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationSessionLifetime.cs index 14c06e03..270b6280 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationSessionLifetime.cs @@ -3,47 +3,47 @@ namespace AgentCore.Application.Runtime; -internal sealed class CallSessionLifetime +internal sealed class ConversationSessionLifetime { - private readonly CallSession _session; + private readonly ConversationSession _session; - // The background release runs once per call: both DisposeAsync and the turn-end path reach + // The background release runs once per conversation: both DisposeAsync and the turn-end path reach // it, and a second release would re-cancel children that already went away. private int _backgroundReleased; - internal CallSessionLifetime(CallSession session) + internal ConversationSessionLifetime(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; } - /// Closes the call, and writes the last event of its chain. - /// Why the call ended, as one member of the closed set. + /// Closes the conversation, and writes the last event of its chain. + /// Why the conversation ended, as one member of the closed set. /// - /// when this call wrote the event, and when the - /// call had already ended. + /// when this conversation wrote the event, and when the + /// conversation had already ended. /// /// /// is not a member of the closed set. /// - internal bool EndCall(CallEndReason reason) + internal bool EndConversation(ConversationEndReason reason) { // The event is written before the flag moves. A value outside the closed set therefore ends - // no call and writes nothing. - var wrote = _session.Events.EndCall(reason, _session.Time.GetUtcNow()); + // no conversation and writes nothing. + var wrote = _session.Events.EndConversation(reason, _session.Time.GetUtcNow()); _session.IsComplete = true; DeleteWorkspace(); return wrote; } /// - /// Deletes this call's workspace, if it has one. Called once the chain has recorded why the - /// call ended, from every path that can end it. + /// Deletes this conversation's workspace, if it has one. Called once the chain has recorded why the + /// conversation ended, from every path that can end it. /// internal void DeleteWorkspace() => _session.WorkspaceRoot?.Delete(_session.Logger); /// - /// Disposes this call's background sessions and shell executors. Idempotent: a session already + /// Disposes this conversation's background sessions and shell executors. Idempotent: a session already /// disposed, or one that never had either, disposes nothing. /// internal async ValueTask DisposeAsync() @@ -53,8 +53,8 @@ internal async ValueTask DisposeAsync() } /// - /// Cancels the background children still running on this call's session and releases it, once - /// per call. Skipped when the call never opened a session or the document names no background + /// Cancels the background children still running on this conversation's session and releases it, once + /// per conversation. Skipped when the conversation never opened a session or the document names no background /// children. Release precedes the shells: a child cancelled here may be inside a shell tool. /// internal async ValueTask ReleaseBackgroundSessionsAsync() @@ -67,12 +67,12 @@ internal async ValueTask ReleaseBackgroundSessionsAsync() } await BackgroundSessionRelease.ReleaseAsync( - _session.Compiled.BackgroundProviders, session, _session.CallId, _session.Logger, CancellationToken.None).ConfigureAwait(false); + _session.Compiled.BackgroundProviders, session, _session.ConversationId, _session.Logger, CancellationToken.None).ConfigureAwait(false); } /// - /// Disposes this call's shell executors, if it has any. does not call - /// this: a tool that ends the call mid-turn still needs the shell for the rest of that turn, so + /// Disposes this conversation's shell executors, if it has any. does not conversation + /// this: a tool that ends the conversation mid-turn still needs the shell for the rest of that turn, so /// only the turn-end path and tear it down. /// internal ValueTask DisposeShellsAsync() => _session.Shells?.DisposeAsync() ?? ValueTask.CompletedTask; diff --git a/src/AgentCore.Application/Runtime/CallSession/CallSessionStateStore.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationSessionStateStore.cs similarity index 80% rename from src/AgentCore.Application/Runtime/CallSession/CallSessionStateStore.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationSessionStateStore.cs index b2ae1506..1f7e60cb 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallSessionStateStore.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationSessionStateStore.cs @@ -1,25 +1,25 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime.Harness; namespace AgentCore.Application.Runtime; -internal sealed class CallSessionStateStore +internal sealed class ConversationSessionStateStore { - private readonly CallSession _session; + private readonly ConversationSession _session; - internal CallSessionStateStore(CallSession session) + internal ConversationSessionStateStore(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; } - /// Puts back what a previous session of this call had, as far as the document still allows. - internal void Restore(CallSessionState stored) + /// Puts back what a previous session of this conversation had, as far as the document still allows. + internal void Restore(ConversationSessionState stored) { - if (stored.Version != CallSessionState.CurrentVersion) + if (stored.Version != ConversationSessionState.CurrentVersion) { - Dropped($"the stored state is version {stored.Version} and this build writes {CallSessionState.CurrentVersion}."); + Dropped($"the stored state is version {stored.Version} and this build writes {ConversationSessionState.CurrentVersion}."); return; } @@ -45,13 +45,13 @@ internal void Restore(CallSessionState stored) { // Both, and in this order. The machine is what picks the agent and what the next // transition fires from; the reserved slot is what the guards and the audit chain read. - // Moving one without the other is worse than moving neither, because the call would + // Moving one without the other is worse than moving neither, because the conversation would // then report a stage it was not actually running in. _session.Policy?.RestoreStage(stored.Stage); _session.State.Stage = stored.Stage; // Only on this branch. A stored 'true' was read off a terminal stage, so restoring it - // beside a stage that was refused would bring the call back only to have it turn every + // beside a stage that was refused would bring the conversation back only to have it turn every // turn away — the one outcome this whole method exists to avoid. _session.IsComplete = stored.IsComplete; } @@ -60,7 +60,7 @@ internal void Restore(CallSessionState stored) Dropped(refusedStage); } - // Before the slots, and unconditionally: the ask budget is per call, not per session, so a + // Before the slots, and unconditionally: the ask budget is per conversation, not per session, so a // caller who dropped and reconnected must not buy a fresh maxAsks and hear every clarification // over again. A refused stage does not refuse this — the questions were still asked. _session.Clarifications.RestoreSpent(stored.Clarifications); @@ -70,7 +70,7 @@ internal void Restore(CallSessionState stored) if (ReservedStateSlots.Contains(slot.Key)) { // TryWrite throws on a reserved slot rather than answering false, and an exception - // here would escape OpenSessionAsync and refuse the call outright. Snapshot never + // here would escape OpenSessionAsync and refuse the conversation outright. Snapshot never // writes one, but this blob is arbitrary JSON out of store 0 and a host hands one // straight in through DeserializeSessionAsync, so the guard is the caller's and not // the blob's. @@ -93,22 +93,22 @@ internal void Restore(CallSessionState stored) } void Dropped(string reason) => _session.Events.RaiseDiagnostic( - CallEventKind.StateRestorePartial, + ConversationEventKind.StateRestorePartial, _session.Time.GetUtcNow(), turnIndex: null, payload: new Dictionary(StringComparer.Ordinal) { - [CallEventPayloadKeys.Reason] = reason, + [ConversationEventPayloadKeys.Reason] = reason, }); } /// - /// Reads the state this call would resume from, as it stands right now. The provider state is + /// Reads the state this conversation would resume from, as it stands right now. The provider state is /// read off the live bag with no turn lock around it, so a host serializing mid-turn gets the /// bag as it stands at that instant, not a turn-boundary snapshot. A graph row that reuses /// its session instead attaches that session's last turn-end serialization. /// - internal CallSessionState Snapshot() + internal ConversationSessionState Snapshot() { lock (_session.InterruptLock) { @@ -129,7 +129,7 @@ internal CallSessionState Snapshot() IsComplete = _session.IsComplete, Slots = _session.State.WrittenSlots(), - // The turn index this call has reached, which is already the NEXT one by the time the + // The turn index this conversation has reached, which is already the NEXT one by the time the // commit reads it. NextTurnIndex = _session.State.TurnIndex, @@ -138,13 +138,13 @@ internal CallSessionState Snapshot() Providers = HarnessSessionState.Capture(_session.AgentSession, _session.Compiled.HarnessStateKeys), // Turn-boundary workflow checkpoints on a graph row that reuses its session; every - // other call leaves this empty and keeps provider state in Providers above. + // other conversation leaves this empty and keeps provider state in Providers above. WorkflowState = _session.GraphBlob, }; } - /// Names the state this call resumes from when store 0 holds none of its own. - internal void Resume(CallSessionState stored) + /// Names the state this conversation resumes from when store 0 holds none of its own. + internal void Resume(ConversationSessionState stored) { ArgumentNullException.ThrowIfNull(stored); @@ -156,7 +156,7 @@ internal void Resume(CallSessionState stored) if (_session.AgentSession is not null) { throw new InvalidOperationException( - $"The call '{_session.CallId}' has already run a turn, and a call resumes only as its " + $"The conversation '{_session.ConversationId}' has already run a turn, and a conversation resumes only as its " + "first turn opens it. Hand the state to the factory that builds the session " + "instead."); } diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTranscriptLedger.cs similarity index 70% rename from src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTranscriptLedger.cs index b9ff8009..29b77a92 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTranscriptLedger.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Diagnostics; using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Transcript; @@ -9,19 +9,19 @@ namespace AgentCore.Application.Runtime; // The transcript half of the session (MAF history-provider seam): opening the session once, // re-syncing it with store 0 before every later turn, draining writes, and naming approval -// answers. Reads and publishes the live session through the owning CallSession. -internal sealed class CallTranscriptLedger +// answers. Reads and publishes the live session through the owning ConversationSession. +internal sealed class ConversationTranscriptLedger { - private readonly CallSession _session; + private readonly ConversationSession _session; - internal CallTranscriptLedger(CallSession session) + internal ConversationTranscriptLedger(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; } /// - /// Opens the session of this call, once, and re-syncs it with store 0 before handing it to every + /// Opens the session of this conversation, once, and re-syncs it with store 0 before handing it to every /// later turn. /// /// Cancels the open. @@ -34,9 +34,9 @@ internal async ValueTask OpenSessionAsync(CancellationToken cancel return opened; } - var record = await _session.Compiled.CallStore.CreateAsync(_session.CallId, cancellationToken).ConfigureAwait(false); + var record = await _session.Compiled.ConversationStore.CreateAsync(_session.ConversationId, cancellationToken).ConfigureAwait(false); - CallSessionState? checkpoint; + ConversationSessionState? checkpoint; lock (_session.InterruptLock) { checkpoint = _session.Checkpoint; @@ -46,35 +46,35 @@ internal async ValueTask OpenSessionAsync(CancellationToken cancel // rather than merging with it. Store 0's blob is written in the same batch as the turn's // words, so its state and store 1's words are of one moment and cannot disagree; a // checkpoint's state beside store 1's words can be of two. So the checkpoint decides only a - // call store 0 does not know, or knows without state. + // conversation store 0 does not know, or knows without state. var stored = record.State ?? checkpoint; AgentSession session; if (_session.SessionCarriesHistory) { - session = stored is { Version: CallSessionState.CurrentVersion, Providers.Count: > 0 } + session = stored is { Version: ConversationSessionState.CurrentVersion, Providers.Count: > 0 } ? await _session.Compiled.TurnAgent.DeserializeSessionAsync( HarnessSessionState.Wrap(stored.Providers), cancellationToken: cancellationToken).ConfigureAwait(false) : await _session.Compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); } else { - session = new CallHistorySession(); + session = new ConversationHistorySession(); // Rows 1 and 2 restore provider state onto their long-lived session above. A graph - // row instead keeps one workflow session for the whole call: MAF restores each + // row instead keeps one workflow session for the whole conversation: MAF restores each // participant's provider state from its checkpoints whenever a turn runs on it. if (_session.ReusesGraphSession) { - _session.GraphSession = stored is { Version: CallSessionState.CurrentVersion, WorkflowState: { } blob } + _session.GraphSession = stored is { Version: ConversationSessionState.CurrentVersion, WorkflowState: { } blob } ? await _session.Compiled.TurnAgent.DeserializeSessionAsync(blob, cancellationToken: cancellationToken).ConfigureAwait(false) : await _session.Compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); } } - IReadOnlyList spoken = record.LastMessageAt is null + IReadOnlyList spoken = record.LastMessageAt is null ? [] - : await _session.Compiled.CallStore.ReadAsync(_session.CallId, cancellationToken).ConfigureAwait(false); + : await _session.Compiled.ConversationStore.ReadAsync(_session.ConversationId, cancellationToken).ConfigureAwait(false); lock (_session.InterruptLock) { @@ -82,9 +82,9 @@ internal async ValueTask OpenSessionAsync(CancellationToken cancel { _session.AgentSession = session; - _session.State.TurnIndex = _session.History.BeginCall( + _session.State.TurnIndex = _session.History.BeginConversation( session, - _session.CallId, + _session.ConversationId, spoken, _session.Events.RaiseDroppedTranscriptWrite, new TranscriptMarks(record.NextOrdinal, stored?.NextTurnIndex ?? 0)); @@ -104,9 +104,9 @@ internal async ValueTask OpenSessionAsync(CancellationToken cancel /// /// Brings the session's words back in line with store 1 before a turn after the first, when and - /// only when someone else wrote to the call in between. + /// only when someone else wrote to the conversation in between. /// - /// The session of this call. + /// The session of this conversation. /// Cancels the reads. private async ValueTask ResyncTranscriptAsync(AgentSession opened, CancellationToken cancellationToken) { @@ -114,30 +114,30 @@ private async ValueTask ResyncTranscriptAsync(AgentSession opened, CancellationT try { - var refreshed = await _session.Compiled.CallStore.GetAsync(_session.CallId, cancellationToken).ConfigureAwait(false) + var refreshed = await _session.Compiled.ConversationStore.GetAsync(_session.ConversationId, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException( - $"Store 0 holds no call '{_session.CallId}' for its own session to resync against."); + $"Store 0 holds no conversation '{_session.ConversationId}' for its own session to resync against."); if (refreshed.NextOrdinal == _session.History.NextOrdinal(opened)) { return; } - var rows = await _session.Compiled.CallStore.ReadAsync(_session.CallId, cancellationToken).ConfigureAwait(false); + var rows = await _session.Compiled.ConversationStore.ReadAsync(_session.ConversationId, cancellationToken).ConfigureAwait(false); _session.History.Resync(opened, rows, refreshed.NextOrdinal); } -#pragma warning disable CA1031 // A store that cannot be read never ends a call: the turn runs on the words the session holds. +#pragma warning disable CA1031 // A store that cannot be read never ends a conversation: the turn runs on the words the session holds. catch (Exception exception) when (exception is not OperationCanceledException) #pragma warning restore CA1031 { - Log.TranscriptResyncFailed(_session.Logger, _session.CallId, _session.State.TurnIndex, exception); + Log.TranscriptResyncFailed(_session.Logger, _session.ConversationId, _session.State.TurnIndex, exception); _session.Events.RaiseFailedTranscriptResync(_session.State.TurnIndex, exception); } } /// - /// Reads the session of this call, or null before its first turn opened one. + /// Reads the session of this conversation, or null before its first turn opened one. /// /// The session. internal AgentSession? Session() @@ -149,9 +149,9 @@ private async ValueTask ResyncTranscriptAsync(AgentSession opened, CancellationT } /// - /// Waits for every store 1 write this call has queued. + /// Waits for every store 1 write this conversation has queued. /// - /// A task that completes when the words of the call are durable. + /// A task that completes when the words of the conversation are durable. internal async Task FlushTranscriptAsync() { if (Session() is { } session) @@ -160,12 +160,12 @@ internal async Task FlushTranscriptAsync() } } - /// Builds the answer message for one queued approval request of this call. + /// Builds the answer message for one queued approval request of this conversation. /// The id the caller answers. /// Whether the tool may run. /// - /// The user message carrying the approval response, or when this call - /// queues no request under that id: answered already, another call's, or never asked. + /// The user message carrying the approval response, or when this conversation + /// queues no request under that id: answered already, another conversation's, or never asked. /// internal ChatMessage? TryCreateApprovalAnswer(string requestId, bool approved) { @@ -176,6 +176,6 @@ internal async Task FlushTranscriptAsync() : null; } - /// The session a graph row's call holds, so store 1 has somewhere to live. - private sealed class CallHistorySession : AgentSession; + /// The session a graph row's conversation holds, so store 1 has somewhere to live. + private sealed class ConversationHistorySession : AgentSession; } diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurn.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurn.cs similarity index 84% rename from src/AgentCore.Application/Runtime/CallSession/CallTurn.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTurn.cs index 388f19cb..42a922aa 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurn.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurn.cs @@ -7,10 +7,10 @@ namespace AgentCore.Application.Runtime; // The turn's working set, carried from preparation through commit. Built once per turn in -// CallTurnRunner.BeginTurn for the same reason Activity is: CallTurnStream reopens the state +// ConversationTurnRunner.BeginTurn for the same reason Activity is: ConversationTurnStream reopens the state // scope on every step of a streaming turn, and collectors built per step would lose whatever an // earlier step drew before a later step could attach it to a message. -internal sealed record CallTurn( +internal sealed record ConversationTurn( AIAgent Agent, AgentSession Session, List Request, diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs similarity index 88% rename from src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs index 796dbf0b..d10a0be7 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnCommit.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs @@ -5,13 +5,13 @@ namespace AgentCore.Application.Runtime; /// /// The publish half of a turn: appends the transcript, writes the turn's events, and tears the -/// call down when it is over. decides the turn; this commits it. +/// conversation down when it is over. decides the turn; this commits it. /// -internal sealed class CallTurnCommit +internal sealed class ConversationTurnCommit { - private readonly CallSession _session; + private readonly ConversationSession _session; - internal CallTurnCommit(CallSession session) + internal ConversationTurnCommit(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; @@ -20,7 +20,7 @@ internal CallTurnCommit(CallSession session) // One lock, one moment. A late barge-in reads all four of these together, so a window in // which LastTurn already names this turn while the span or the ordinal still names the one // before it would let an amendment rewrite the wrong part of the transcript. - internal TurnResult Publish(CallTurn turn, ReplyOutcome outcome, TranscriptEntry addition, TurnResult result, CallInterruptionTracker.Interruption? interruption) + internal TurnResult Publish(ConversationTurn turn, ReplyOutcome outcome, TranscriptEntry addition, TurnResult result, ConversationInterruptionTracker.Interruption? interruption) { lock (_session.InterruptLock) { @@ -98,14 +98,14 @@ internal TurnResult Publish(CallTurn turn, ReplyOutcome outcome, TranscriptEntry return result; } - internal async Task EndCallIfOverAsync(DateTimeOffset endedAt, string stageAfter) + internal async Task EndConversationIfOverAsync(DateTimeOffset endedAt, string stageAfter) { if (_session.IsComplete) { - // The machine reached a terminal stage, so the call is over and the chain closes here. + // The machine reached a terminal stage, so the conversation is over and the chain closes here. // The stage rides as detail, because the reason a report counts is the same one for // every terminal stage the document declares. - _session.Events.EndCall(CallEndReason.AgentCompleted, endedAt, stageAfter); + _session.Events.EndConversation(ConversationEndReason.AgentCompleted, endedAt, stageAfter); } if (!_session.IsComplete && !_session.Events.HasEnded) @@ -121,7 +121,7 @@ internal async Task EndCallIfOverAsync(DateTimeOffset endedAt, string stageAfter // deleted out from under a still-live container. await _session.Lifetime.DisposeShellsAsync().ConfigureAwait(false); - // A tool running mid-turn (a file_memory_write, say) can call EndCall itself, which + // A tool running mid-turn (a file_memory_write, say) can call EndConversation itself, which // deletes the workspace and then IsComplete overwrites the flag when the policy also // reaches a terminal stage. _events.HasEnded survives that overwrite, so the folder a // tool recreated after the mid-turn delete is still cleaned up here. diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCompletion.cs similarity index 89% rename from src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCompletion.cs index c1cbf492..73dde7da 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCompletion.cs @@ -8,17 +8,17 @@ namespace AgentCore.Application.Runtime; -internal sealed class CallTurnCompletion +internal sealed class ConversationTurnCompletion { - private readonly CallSession _session; + private readonly ConversationSession _session; - private readonly CallTurnCommit _commit; + private readonly ConversationTurnCommit _commit; - internal CallTurnCompletion(CallSession session) + internal ConversationTurnCompletion(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; - _commit = new CallTurnCommit(session); + _commit = new ConversationTurnCommit(session); } /// Runs every writer, then lets the machine pick the stage of the next turn. @@ -40,7 +40,7 @@ internal CallTurnCompletion(CallSession session) /// . /// internal async Task CompleteTurnAsync( - CallTurn turn, + ConversationTurn turn, AgentResponse response, string? toolFault, TurnDisposition? disposition, @@ -85,7 +85,7 @@ internal async Task CompleteTurnAsync( // it. The same read stamps every audit event of this turn. var endedAt = _session.Time.GetUtcNow(); _session.State.TurnIndex++; - _session.State.CallDurationSeconds = (endedAt - _session.StartedAt).TotalSeconds; + _session.State.ConversationDurationSeconds = (endedAt - _session.StartedAt).TotalSeconds; // The counters write last. _session.Counters.Apply(_session.State); @@ -93,7 +93,7 @@ internal async Task CompleteTurnAsync( var stageAfter = AdvanceStage(turn); TurnResult result = new( - _session.CallId, + _session.ConversationId, turn.Index, turn.StageBefore, stageAfter, @@ -108,8 +108,8 @@ internal async Task CompleteTurnAsync( }; // A graph row that reuses its session persists it here, before the commit below reads - // it into store 0: the next turn resumes from these checkpoints, and a resumed call - // rebuilds them. Rows 1 and 2 need nothing — their session outlives the call. + // it into store 0: the next turn resumes from these checkpoints, and a resumed conversation + // rebuilds them. Rows 1 and 2 need nothing — their session outlives the conversation. if (_session.ReusesGraphSession && _session.GraphSession is { } shared) { _session.GraphBlob = await turn.Agent.SerializeSessionAsync(shared, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -124,15 +124,15 @@ internal async Task CompleteTurnAsync( stageAfter, result.Failure); - await _commit.EndCallIfOverAsync(endedAt, stageAfter).ConfigureAwait(false); + await _commit.EndConversationIfOverAsync(endedAt, stageAfter).ConfigureAwait(false); return result; } private ReplyOutcome ResolveReply( - CallTurn turn, + ConversationTurn turn, AgentResponse response, - CallInterruptionTracker.Interruption? interruption, + ConversationInterruptionTracker.Interruption? interruption, TurnDisposition? disposition, string? toolFault) { @@ -146,7 +146,7 @@ private ReplyOutcome ResolveReply( var reply = SpokenReply.From(response.Messages); var spokenReply = reply; TimeSpan? interruptedAfter = null; - string? failure = toolFault is null ? null : CallSession.ToolFailureReason + " " + toolFault; + string? failure = toolFault is null ? null : ConversationSession.ToolFailureReason + " " + toolFault; // The tool calls still waiting on a human answer. A pending turn is not a failure: the // run suspended instead of answering, so the empty-reply substitution below is skipped, @@ -165,9 +165,9 @@ private ReplyOutcome ResolveReply( || string.IsNullOrWhiteSpace(reply) || disposition?.Fallback is FallbackCause.EmptyReply)) { - // Section 8.7, last row. A quiet run is silence on a voice call, so an empty reply is a + // Section 8.7, last row. A quiet run is silence on a voice conversation, so an empty reply is a // failure even though nothing threw. - failure ??= CallSession.EmptyReplyReason; + failure ??= ConversationSession.EmptyReplyReason; reply = _session.Compiled.FallbackReply; spokenReply = reply; } @@ -179,7 +179,7 @@ private ReplyOutcome ResolveReply( // the same endedAt every other event of the turn carries. if (toolFault is null && failure is not null) { - _session.Events.RaiseDiagnostic(CallEventKind.EmptyReply, _session.Time.GetUtcNow(), turn.Index); + _session.Events.RaiseDiagnostic(ConversationEventKind.EmptyReply, _session.Time.GetUtcNow(), turn.Index); } return new ReplyOutcome(reply, spokenReply, failure, toolFault, interruptedAfter, approvals); @@ -226,40 +226,40 @@ private TranscriptEntry TranscriptAddition(AgentResponse response, ReplyOutcome // The extractor's deadline is here and not on the whole turn, because the raise of the turn's // events and the stage advance must always run. - private async Task ExtractAsync(CallTurn turn, AgentResponse response, CancellationToken cancellationToken) + private async Task ExtractAsync(ConversationTurn turn, AgentResponse response, CancellationToken cancellationToken) { string? extractionFailure; using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - deadline.CancelAfter(CallSession.TurnCompletionTimeout); + deadline.CancelAfter(ConversationSession.TurnCompletionTimeout); try { extractionFailure = await _session.Writers.ExtractAsync(turn, response, deadline.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { - extractionFailure = CallSession.ExtractionTimedOutReason; + extractionFailure = ConversationSession.ExtractionTimedOutReason; } if (extractionFailure is not null) { // Section 8.7, row two: leave the slots unchanged, report once for the turn, and continue - // the call. State extraction must never drop a call. The reason rides on the event + // the conversation. State extraction must never drop a conversation. The reason rides on the event // because the line an operator reads is the same one the turn loop used to write itself. _session.Events.RaiseDiagnostic( - CallEventKind.ExtractionFailed, + ConversationEventKind.ExtractionFailed, _session.Time.GetUtcNow(), turn.Index, payload: new Dictionary(StringComparer.Ordinal) { - [CallEventPayloadKeys.Reason] = extractionFailure, + [ConversationEventPayloadKeys.Reason] = extractionFailure, }); } return extractionFailure; } - private string AdvanceStage(CallTurn turn) + private string AdvanceStage(ConversationTurn turn) { if (_session.Policy is null) { @@ -311,7 +311,7 @@ private static List ApprovalRequestsOf(AgentResponse response) /// Reports calls the model named that no tool answered. /// The turn that just ran. /// What the agent answered. - private void ReportUndeclaredToolCalls(CallTurn turn, AgentResponse response) + private void ReportUndeclaredToolCalls(ConversationTurn turn, AgentResponse response) { var invoked = new HashSet(turn.Results.CallIds, StringComparer.Ordinal); diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnRunner.cs similarity index 81% rename from src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnRunner.cs index 13598c8b..4c90e2bc 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnRunner.cs @@ -13,10 +13,10 @@ namespace AgentCore.Application.Runtime; // The prepare half of the turn loop (OpenAI turn_preparation seam): guards, withdrawal, // request building, and the non-streaming run core. Owns no committed state; everything it -// reads lives on the owning CallSession, which keeps the single live-state owner of Phase 1. -internal sealed class CallTurnRunner +// reads lives on the owning ConversationSession, which keeps the single live-state owner of Phase 1. +internal sealed class ConversationTurnRunner { - private readonly CallSession _session; + private readonly ConversationSession _session; private (string ToolId, IReadOnlyList Tools)? _delegatedTools; @@ -24,14 +24,14 @@ internal sealed class CallTurnRunner private TimeZoneInfo? _timeZone; - internal CallTurnRunner(CallSession session) + internal ConversationTurnRunner(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; } /// - /// Gives the runs this call delegates through one tool a set of tools of their own. + /// Gives the runs this conversation delegates through one tool a set of tools of their own. /// /// The kind: agent tool whose delegated runs are offered these. /// The tools. An empty list offers nothing, exactly as never calling this does. @@ -45,22 +45,22 @@ internal void SetDelegatedTools(string delegatingToolId, IReadOnlyList t } /// - /// Gives this call the screen its tools draw on, or takes it away. + /// Gives this conversation the screen its tools draw on, or takes it away. /// internal void SetHasScreen(bool hasScreen) => _hasScreen = hasScreen; /// - /// Tells this call which zone the person is in, so the clock line reads their date. + /// Tells this conversation which zone the person is in, so the clock line reads their date. /// internal void SetTimeZone(TimeZoneInfo zone) => _timeZone = zone; - /// Runs one turn of the call against the session the call holds. + /// Runs one turn of the conversation against the session the conversation holds. /// What the caller said or answered. /// Where the turn hangs, or null for a caller that does not say. /// Cancels the turn. /// What the turn did. internal async Task RunTurnCoreAsync( - ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) + ChatMessage userInput, ConversationTurnOrigin? origin, CancellationToken cancellationToken) { var session = await _session.Ledger.OpenSessionAsync(cancellationToken).ConfigureAwait(false); @@ -94,7 +94,7 @@ internal async Task RunTurnCoreAsync( } catch (Exception exception) when (exception is not OperationCanceledException) { - // Section 8.7, sixth row. The run throws, the turn ends, and the call lives. + // Section 8.7, sixth row. The run throws, the turn ends, and the conversation lives. toolFault = exception.Message; response = new AgentResponse(); } @@ -102,7 +102,7 @@ internal async Task RunTurnCoreAsync( // CompleteTurnAsync publishes LastTurn itself, under the same lock that records what a // late barge-in may still amend. Assigning it a second time here could overwrite an // amendment that landed in between. - return await _session.Completion.CompleteTurnAsync(turn, response, toolFault, CallTurnStream.ReadDisposition(response), cancellationToken) + return await _session.Completion.CompleteTurnAsync(turn, response, toolFault, ConversationTurnStream.ReadDisposition(response), cancellationToken) .ConfigureAwait(false); } finally @@ -117,15 +117,15 @@ internal async Task RunTurnCoreAsync( /// turn. /// /// What the caller said or answered: words, an approval answer, or both. - /// The session of this call. + /// The session of this conversation. /// Where the turn hangs, or null for a caller that does not say. /// Everything the rest of the turn needs. - internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTurnOrigin? origin = null) + internal ConversationTurn BeginTurn(ChatMessage userInput, AgentSession session, ConversationTurnOrigin? origin = null) { if (_session.IsComplete) { throw new InvalidOperationException( - $"The call '{_session.CallId}' reached the terminal stage '{_session.Stage}', so it runs no further turn."); + $"The conversation '{_session.ConversationId}' reached the terminal stage '{_session.Stage}', so it runs no further turn."); } var agent = ResolveAgent(); @@ -135,7 +135,7 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur if (!_session.Interruptions.TryEnterTurn()) { throw new InvalidOperationException( - $"A turn of the call '{_session.CallId}' is still running. One call runs one turn at a time."); + $"A turn of the conversation '{_session.ConversationId}' is still running. One conversation runs one turn at a time."); } Activity? activity = null; @@ -147,8 +147,8 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur // inside one streaming turn. _session.Clarifications.BeginTurn(); - // Behind both guards, because the withdrawal deletes: a turn refused for a terminal call or - // for one already running must not have taken the tail of the call with it on the way out. + // Behind both guards, because the withdrawal deletes: a turn refused for a terminal conversation or + // for one already running must not have taken the tail of the conversation with it on the way out. // Ahead of the request below, because the words it withdraws have to be gone from the live // history this run reads and not only from the store. The turn index is deliberately not // wound back with them: store 3 keeps its rows for the withdrawn turns, and two turns at one @@ -164,7 +164,7 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur // The framework has never heard of a turn, so the turn loop names this one before the run. _session.History.BeginTurn(session, _session.State.TurnIndex); - // Rows 1 and 2 read the call out of the session, so the run carries the new message alone + // Rows 1 and 2 read the conversation out of the session, so the run carries the new message alone // and the provider prepends the rest. A graph row that reuses its session reads the same // way: the resumed conversation already carries what came before. Any other graph row // takes no provider, so its history rides the request, rendered into the one role a node @@ -185,18 +185,18 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur request = [spoken]; } - // One turn is one span. The call id rides here, on a span attribute, because T61 refuses it + // One turn is one span. The conversation id rides here, on a span attribute, because T61 refuses it // on a metric. The span is disposed in the finally of whichever run method opened the turn. - activity = AgentCoreTelemetry.StartTurn(_session.CallId, _session.State.TurnIndex, _session.State.Stage); + activity = AgentCoreTelemetry.StartTurn(_session.ConversationId, _session.State.TurnIndex, _session.State.Stage); var knowledge = StateKnowledgeScope.Compose( _session.State, _session.Compiled.Configuration.Providers?.Knowledge?.Scope, _session.Scope); if (knowledge is { Origins.Count: > 0 }) { - Log.KnowledgeScopeComposed(_session.Logger, _session.CallId, _session.State.TurnIndex, knowledge.Origins); + Log.KnowledgeScopeComposed(_session.Logger, _session.ConversationId, _session.State.TurnIndex, knowledge.Origins); } - return new CallTurn( + return new ConversationTurn( agent, session, request, @@ -217,15 +217,15 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur { // Only the run methods' own finally frees the session and closes the span, and it starts // after this method returns. A throw while the turn is still being built would otherwise - // leave _running set, so every later turn of the call is refused as one already running. + // leave _running set, so every later turn of the conversation is refused as one already running. activity?.Dispose(); _session.Interruptions.ReleaseTurn(); throw; } } - /// Takes back everything the call said after the message this turn hangs off. - internal void WithdrawSuperseded(AgentSession session, CallTurnOrigin? origin) + /// Takes back everything the conversation said after the message this turn hangs off. + internal void WithdrawSuperseded(AgentSession session, ConversationTurnOrigin? origin) { if (origin is not { NamesParent: true } || _session.History.TruncateFrom(session, origin.ParentMessageId) is not { } withdrawn) @@ -243,7 +243,7 @@ internal void WithdrawSuperseded(AgentSession session, CallTurnOrigin? origin) // which turns it replaced. The rows of those turns are already deleted, so nothing else in // any store can answer that afterwards. _ = _session.Events.Raise( - CallEventKind.TurnSuperseded, + ConversationEventKind.TurnSuperseded, _session.Time.GetUtcNow(), _session.State.TurnIndex, payload: new Dictionary(StringComparer.Ordinal) @@ -269,7 +269,7 @@ internal AIAgent ResolveAgent() || _session.Compiled.TurnAgentForStage(_session.Policy.Stage) is not { } agent) { throw new InvalidOperationException( - $"The stage '{_session.Policy.Stage}' of the call '{_session.CallId}' names no agent, so no turn can run."); + $"The stage '{_session.Policy.Stage}' of the conversation '{_session.ConversationId}' names no agent, so no turn can run."); } return agent; @@ -280,8 +280,8 @@ internal AIAgent ResolveAgent() /// /// The turn about to run. /// Cancels the open. - /// The call's session on rows 1 and 2, the call's shared workflow session on a graph row that reuses one, and a fresh workflow session on any other graph row. - internal async ValueTask RunSessionAsync(CallTurn turn, CancellationToken cancellationToken) + /// The conversation's session on rows 1 and 2, the conversation's shared workflow session on a graph row that reuses one, and a fresh workflow session on any other graph row. + internal async ValueTask RunSessionAsync(ConversationTurn turn, CancellationToken cancellationToken) { if (_session.SessionCarriesHistory) { @@ -299,10 +299,10 @@ internal async ValueTask RunSessionAsync(CallTurn turn, Cancellati /// Builds the invocation one turn hands its tools. /// The turn about to run. /// Everything a tool of this turn may need, as one explicit value. - internal TurnInvocation TurnInvocationOf(CallTurn turn) + internal TurnInvocation TurnInvocationOf(ConversationTurn turn) => new() { - CallId = _session.CallId, + ConversationId = _session.ConversationId, TurnIndex = turn.Index, Stage = turn.StageBefore, Instructions = turn.Reminder, diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnStream.cs similarity index 95% rename from src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnStream.cs index 5e798600..aee3e3ca 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnStream.cs @@ -5,24 +5,24 @@ namespace AgentCore.Application.Runtime; -internal sealed class CallTurnStream +internal sealed class ConversationTurnStream { - private readonly CallSession _session; + private readonly ConversationSession _session; - internal CallTurnStream(CallSession session) + internal ConversationTurnStream(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; } - /// Streams one turn of the call against the session the call holds. + /// Streams one turn of the conversation against the session the conversation holds. /// What the caller said or answered. /// Where the turn hangs, or null for a caller that does not say. /// Cancels the model calls. /// The reply, one update at a time. internal IAsyncEnumerable RunTurnStreamingCoreAsync( ChatMessage userInput, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userInput); @@ -33,7 +33,7 @@ internal IAsyncEnumerable RunTurnStreamingCoreAsync( /// Streams one turn. The caller checks the arguments. private async IAsyncEnumerable RunTurnStreamingIteratorAsync( ChatMessage userInput, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, [EnumeratorCancellation] CancellationToken cancellationToken) { var session = await _session.Ledger.OpenSessionAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnWriters.cs similarity index 85% rename from src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnWriters.cs index a94948c2..c4292ca0 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnWriters.cs @@ -6,11 +6,11 @@ namespace AgentCore.Application.Runtime; -internal sealed class CallTurnWriters +internal sealed class ConversationTurnWriters { - private readonly CallSession _session; + private readonly ConversationSession _session; - internal CallTurnWriters(CallSession session) + internal ConversationTurnWriters(ConversationSession session) { ArgumentNullException.ThrowIfNull(session); _session = session; @@ -21,7 +21,7 @@ internal CallTurnWriters(CallSession session) /// What the agent answered. /// Cancels the model call. /// The reason the extractor produced nothing, or . - internal async Task ExtractAsync(CallTurn turn, AgentResponse response, CancellationToken cancellationToken) + internal async Task ExtractAsync(ConversationTurn turn, AgentResponse response, CancellationToken cancellationToken) { if (_session.Extractor is null || _session.Compiled.Configuration.Extractor is not { When: ExtractorTrigger.AfterReply }) { @@ -31,7 +31,7 @@ internal CallTurnWriters(CallSession session) // The extractor reads the finished turn and, in front of it, the last thing the agent said // before the caller spoke. A caller answering a question — "the ENT one", "yes", "the second // one" — cannot be read without the question, and the state document cannot carry it because - // nothing was written yet. The rest of the call stays out: the document already carries every + // nothing was written yet. The rest of the conversation stays out: the document already carries every // earlier answer. Measured 2026-09-02: with the question in view every such answer resolved, // and a turn where only the agent had named a machine still filled nothing. List finished = [turn.Spoken, .. response.Messages]; @@ -61,8 +61,8 @@ internal void ApplyToolResults(IEnumerable messages) { switch (content) { - case FunctionCallContent call: - names.Called(call); + case FunctionCallContent conversation: + names.Called(conversation); break; case FunctionResultContent result when names.Of(result) is { } toolId: diff --git a/src/AgentCore.Application/Runtime/CallSession/ReplyOutcome.cs b/src/AgentCore.Application/Runtime/ConversationSession/ReplyOutcome.cs similarity index 100% rename from src/AgentCore.Application/Runtime/CallSession/ReplyOutcome.cs rename to src/AgentCore.Application/Runtime/ConversationSession/ReplyOutcome.cs diff --git a/src/AgentCore.Application/Runtime/CallSession/TranscriptEntry.cs b/src/AgentCore.Application/Runtime/ConversationSession/TranscriptEntry.cs similarity index 100% rename from src/AgentCore.Application/Runtime/CallSession/TranscriptEntry.cs rename to src/AgentCore.Application/Runtime/ConversationSession/TranscriptEntry.cs diff --git a/src/AgentCore.Application/Runtime/CallSessionFactory.cs b/src/AgentCore.Application/Runtime/ConversationSessionFactory.cs similarity index 73% rename from src/AgentCore.Application/Runtime/CallSessionFactory.cs rename to src/AgentCore.Application/Runtime/ConversationSessionFactory.cs index 1c14cc92..ed41786f 100644 --- a/src/AgentCore.Application/Runtime/CallSessionFactory.cs +++ b/src/AgentCore.Application/Runtime/ConversationSessionFactory.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; @@ -9,9 +9,9 @@ namespace AgentCore.Application.Runtime; /// -/// Builds one for each call, over one compiled agent. +/// Builds one for each conversation, over one compiled agent. /// -public sealed class CallSessionFactory : ICallSessionFactory +public sealed class ConversationSessionFactory : IConversationSessionFactory { private readonly CompiledAgent _compiled; @@ -21,23 +21,23 @@ public sealed class CallSessionFactory : ICallSessionFactory private readonly TimeProvider _time; - private readonly ICallObserver[] _observers; + private readonly IConversationObserver[] _observers; private readonly ILogger? _logger; private readonly string? _workspaceRoot; /// - /// Creates the factory. When is bound, every call this factory + /// Creates the factory. When is bound, every conversation this factory /// builds gets its own folder under it; unbound, a session it builds has no workspace. /// - public CallSessionFactory( + public ConversationSessionFactory( CompiledAgent compiled, IGuardEvaluator guards, StateExtractor? extractor = null, TimeProvider? timeProvider = null, ILogger? logger = null, - IEnumerable? observers = null, + IEnumerable? observers = null, string? workspaceRoot = null) { ArgumentNullException.ThrowIfNull(compiled); @@ -52,7 +52,7 @@ public CallSessionFactory( // Copied, not held: the list is the caller's, and a caller that keeps adding to it after this // must not change what a session already built. The order is the caller's too — see - // CallObservers.Standard, which is where the cost of that order is argued. + // ConversationObservers.Standard, which is where the cost of that order is argued. _observers = observers is null ? [] : [.. observers]; } @@ -77,24 +77,24 @@ public CallSessionFactory( } /// - public CallSession Create(string? callId = null, CallSessionState? state = null) + public ConversationSession Create(string? conversationId = null, ConversationSessionState? state = null) { - var resolvedCallId = string.IsNullOrWhiteSpace(callId) ? Guid.NewGuid().ToString("N") : callId; + var resolvedConversationId = string.IsNullOrWhiteSpace(conversationId) ? Guid.NewGuid().ToString("N") : conversationId; - var workspace = _workspaceRoot is null ? null : CallWorkspace.Create(_workspaceRoot, resolvedCallId); + var workspace = _workspaceRoot is null ? null : ConversationWorkspace.Create(_workspaceRoot, resolvedConversationId); - CallSession session = new( - resolvedCallId, + ConversationSession session = new( + resolvedConversationId, _compiled, _guards, _extractor, _time, - new CallObserverDispatcher(_observers, _logger), + new ConversationObserverDispatcher(_observers, _logger), _logger, workspace); // Named, not applied. The session resumes on its first turn, where store 0's own copy - // outranks this one — see the remarks on CallSession.Resume. + // outranks this one — see the remarks on ConversationSession.Resume. if (state is not null) { session.Resume(state); diff --git a/src/AgentCore.Application/Runtime/CallTurnOrigin.cs b/src/AgentCore.Application/Runtime/ConversationTurnOrigin.cs similarity index 78% rename from src/AgentCore.Application/Runtime/CallTurnOrigin.cs rename to src/AgentCore.Application/Runtime/ConversationTurnOrigin.cs index 3c2139cf..0b058921 100644 --- a/src/AgentCore.Application/Runtime/CallTurnOrigin.cs +++ b/src/AgentCore.Application/Runtime/ConversationTurnOrigin.cs @@ -2,14 +2,14 @@ namespace AgentCore.Application.Runtime; /// Where a turn's words sit in the conversation the caller can see. /// -/// What the caller calls the message it is sending, or to let the call name +/// What the caller calls the message it is sending, or to let the conversation name /// it. The name is the caller's, and AgentCore reads it only as the handle a later edit anchors on. /// /// -/// The message these words hang off, or when they start the call afresh. +/// The message these words hang off, or when they start the conversation afresh. /// Read only when is set. /// -public sealed record CallTurnOrigin(string? MessageId, string? ParentMessageId) +public sealed record ConversationTurnOrigin(string? MessageId, string? ParentMessageId) { /// Gets whether the caller answered for where this turn hangs. public required bool NamesParent { get; init; } diff --git a/src/AgentCore.Application/Runtime/CallWorkspace.cs b/src/AgentCore.Application/Runtime/ConversationWorkspace.cs similarity index 60% rename from src/AgentCore.Application/Runtime/CallWorkspace.cs rename to src/AgentCore.Application/Runtime/ConversationWorkspace.cs index 975e4573..7ac8247f 100644 --- a/src/AgentCore.Application/Runtime/CallWorkspace.cs +++ b/src/AgentCore.Application/Runtime/ConversationWorkspace.cs @@ -4,65 +4,65 @@ namespace AgentCore.Application.Runtime; /// -/// The folder one call owns on disk: created with the call, and deleted when it ends. +/// The folder one conversation owns on disk: created with the conversation, and deleted when it ends. /// -internal sealed class CallWorkspace +internal sealed class ConversationWorkspace { - private CallWorkspace(string path) => Path = path; + private ConversationWorkspace(string path) => Path = path; /// Gets the folder's path. public string Path { get; } /// - /// Creates (or, for a resumed call, reuses) the folder root/callId. + /// Creates (or, for a resumed conversation, reuses) the folder root/conversationId. /// /// The root a host bound. - /// - /// The call's id. A host-given id must not escape : the combined path is - /// checked, not the text of the id, so this also refuses a callId of ".", which + /// + /// The conversation's id. A host-given id must not escape : the combined path is + /// checked, not the text of the id, so this also refuses a conversationId of ".", which /// would otherwise resolve straight back to the root. /// /// - /// is empty or white space, or resolves to a path that is not a strict + /// is empty or white space, or resolves to a path that is not a strict /// child of . /// - public static CallWorkspace Create(string root, string callId) + public static ConversationWorkspace Create(string root, string conversationId) { ArgumentException.ThrowIfNullOrEmpty(root); - ArgumentException.ThrowIfNullOrWhiteSpace(callId); + ArgumentException.ThrowIfNullOrWhiteSpace(conversationId); - if (callId.Contains('/', StringComparison.Ordinal) || callId.Contains('\\', StringComparison.Ordinal)) + if (conversationId.Contains('/', StringComparison.Ordinal) || conversationId.Contains('\\', StringComparison.Ordinal)) { throw new ArgumentException( - $"The call id '{callId}' must not contain a directory separator.", nameof(callId)); + $"The conversation id '{conversationId}' must not contain a directory separator.", nameof(conversationId)); } var fullRoot = System.IO.Path.GetFullPath(root); - var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(fullRoot, callId)); + var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(fullRoot, conversationId)); var rootWithSeparator = fullRoot.EndsWith(System.IO.Path.DirectorySeparatorChar) ? fullRoot : fullRoot + System.IO.Path.DirectorySeparatorChar; // GetFullPath can normalise the last segment away from what the caller wrote — on Windows it - // strips trailing spaces and periods, so " ." or "call-1." would otherwise alias the root or - // an unrelated sibling. Requiring the resolved folder name to still equal callId catches that, + // strips trailing spaces and periods, so " ." or "conversation-1." would otherwise alias the root or + // an unrelated sibling. Requiring the resolved folder name to still equal conversationId catches that, // on top of the plain containment check. if (!path.StartsWith(rootWithSeparator, StringComparison.Ordinal) || path.Length <= rootWithSeparator.Length - || !string.Equals(System.IO.Path.GetFileName(path), callId, StringComparison.Ordinal)) + || !string.Equals(System.IO.Path.GetFileName(path), conversationId, StringComparison.Ordinal)) { throw new ArgumentException( - $"The call id '{callId}' must resolve to a folder under the workspace root.", nameof(callId)); + $"The conversation id '{conversationId}' must resolve to a folder under the workspace root.", nameof(conversationId)); } Directory.CreateDirectory(path); - return new CallWorkspace(path); + return new ConversationWorkspace(path); } /// /// Deletes the folder recursively. Safe to call twice: the second call finds nothing and does - /// not log. Never throws out of a caller ending a call. + /// not log. Never throws out of a caller ending a conversation. /// /// Where a failed delete is logged, at Warning. May be . public void Delete(ILogger? logger) @@ -77,7 +77,7 @@ public void Delete(ILogger? logger) } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { - // A concurrent delete from outside this call may have removed the folder in the window + // A concurrent delete from outside this conversation may have removed the folder in the window // between the failing operation and this check; that is not a failure worth logging. if (logger is not null && Directory.Exists(Path)) { diff --git a/src/AgentCore.Application/Runtime/FallbackAgent.cs b/src/AgentCore.Application/Runtime/FallbackAgent.cs index 163dc187..58c491d5 100644 --- a/src/AgentCore.Application/Runtime/FallbackAgent.cs +++ b/src/AgentCore.Application/Runtime/FallbackAgent.cs @@ -10,8 +10,8 @@ namespace AgentCore.Application.Runtime; /// /// /// R1: a tool that fails four times in a row throws out of the run, and section 8.7 says that must -/// never kill the call. R2: at 40 tool rounds the framework sends request 41 with no tools and -/// returns quietly, with no exception — on a voice call that silence is the failure, so an empty +/// never kill the conversation. R2: at 40 tool rounds the framework sends request 41 with no tools and +/// returns quietly, with no exception — on a voice conversation that silence is the failure, so an empty /// reply is read rather than trusting the absence of an error. Both end here, and both leave the /// turn an ordinary successful run. /// @@ -37,7 +37,7 @@ namespace AgentCore.Application.Runtime; /// reply the caller hears, so a quiet output node reads as the silence it is. /// /// -/// It holds no per-call state: one instance is compiled once and shared by every call under T44 and +/// It holds no per-call state: one instance is compiled once and shared by every conversation under T44 and /// R7. /// /// @@ -75,7 +75,7 @@ protected override async Task RunCoreAsync( response = await base.RunCoreAsync(messages, session, options, cancellationToken) .ConfigureAwait(false); } -#pragma warning disable CA1031 // Section 8.7, row six: the run throws, the turn ends, and the call lives. +#pragma warning disable CA1031 // Section 8.7, row six: the run throws, the turn ends, and the conversation lives. catch (Exception exception) when (exception is not OperationCanceledException) #pragma warning restore CA1031 { diff --git a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs index a253135d..31205fbe 100644 --- a/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs +++ b/src/AgentCore.Application/Runtime/Harness/BackgroundChildAgent.cs @@ -4,13 +4,13 @@ namespace AgentCore.Application.Runtime.Harness; /// -/// Wraps one background: child so every session it gets knows which call started it, +/// Wraps one background: child so every session it gets knows which conversation started it, /// which zone the person on that call is in, and which workspace and shells that call owns. /// /// /// BackgroundAgentsProvider creates the child session inside the parent's tool call, before /// it hands the run to a task. At that moment is still the -/// parent's run, and its options carry the parent's turn. That is the only place the call id can +/// parent's run, and its options carry the parent's turn. That is the only place the conversation id can /// cross from parent to child: the provider passes the child null run options and a fresh session, /// and its task-to-session map is private. Proven by probe P2 against Microsoft.Agents.AI 1.21.0. /// @@ -25,9 +25,9 @@ protected override async ValueTask CreateSessionCoreAsync(Cancella var turn = TurnInvocation.From(parent?.RunOptions); - if (turn?.CallId is { } callId) + if (turn?.ConversationId is { } conversationId) { - session.StateBag.SetValue(BlobOwnerKey.Value, callId); + session.StateBag.SetValue(BlobOwnerKey.Value, conversationId); } if (turn?.TimeZone is { } zone) @@ -44,7 +44,7 @@ protected override async ValueTask CreateSessionCoreAsync(Cancella } /// - /// The part of the parent's turn a child may share: the call, its workspace folder, and its + /// The part of the parent's turn a child may share: the conversation, its workspace folder, and its /// shells, so files: and shell: on the child work on the same disk. Every drain, /// screen, tool list, and clarification stays with the parent; a child's publish reports a /// link in its result instead. @@ -52,7 +52,7 @@ protected override async ValueTask CreateSessionCoreAsync(Cancella private static TurnInvocation Shared(TurnInvocation parent) => new() { - CallId = parent.CallId, + ConversationId = parent.ConversationId, TurnIndex = parent.TurnIndex, Stage = parent.Stage, Workspace = parent.Workspace, diff --git a/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs b/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs index 312d4771..932e0cd1 100644 --- a/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs +++ b/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs @@ -5,14 +5,14 @@ namespace AgentCore.Application.Runtime.Harness; /// -/// Releases the harness background providers' sessions when a call ends, so children still +/// Releases the harness background providers' sessions when a conversation ends, so children still /// running cannot outlive it. A task that spans turns is untouched until the end. /// internal static class BackgroundSessionRelease { /// /// How long the release waits for running children to acknowledge the cancel before the - /// call's own teardown continues. Bounded like the extractor deadline: teardown never hangs + /// conversation's own teardown continues. Bounded like the extractor deadline: teardown never hangs /// on a child. /// private static readonly TimeSpan ReleaseTimeout = TimeSpan.FromSeconds(5); @@ -22,21 +22,21 @@ internal static class BackgroundSessionRelease /// session. Best effort: one provider's fault is logged and the rest still release. /// /// Every background provider the document compiled. - /// The session of the call that ended. - /// The id of the call, for the log. + /// The session of the conversation that ended. + /// The id of the conversation, for the log. /// The logger of the session. /// Cancels the release. #pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. public static async ValueTask ReleaseAsync( IReadOnlyList providers, AgentSession session, - string callId, + string conversationId, ILogger logger, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(providers); ArgumentNullException.ThrowIfNull(session); - ArgumentException.ThrowIfNullOrEmpty(callId); + ArgumentException.ThrowIfNullOrEmpty(conversationId); ArgumentNullException.ThrowIfNull(logger); foreach (var provider in providers) @@ -48,7 +48,7 @@ await provider.ReleaseSessionAsync(session, cancelRunning: true, ReleaseTimeout, } catch (Exception exception) when (exception is not OperationCanceledException) { - Log.BackgroundReleaseFailed(logger, callId, exception); + Log.BackgroundReleaseFailed(logger, conversationId, exception); } } } diff --git a/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs b/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs index ba1fc48b..978b78c7 100644 --- a/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs +++ b/src/AgentCore.Application/Runtime/Harness/BlobOwnerKey.cs @@ -2,17 +2,17 @@ namespace AgentCore.Application.Runtime.Harness; /// /// The key under which a background child's -/// session carries the id of the call that started it. +/// session carries the id of the conversation that started it. /// /// -/// A parent run has a turn filed in TurnRegistry, so its providers read the call id there. +/// A parent run has a turn filed in TurnRegistry, so its providers read the conversation id there. /// A child session has no turn: the framework starts it with fresh, empty state and null run /// options. stamps this key when the session is created, so the -/// file.publish tool a background child calls can still find the call that owns the file +/// file.publish tool a background child calls can still find the conversation that owns the file /// when the turn lookup finds nothing. /// internal static class BlobOwnerKey { - /// The key. The value is the call id, a string. + /// The key. The value is the conversation id, a string. public const string Value = "urn:agentcore:blob-owner"; } diff --git a/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs b/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs index 43febd1d..8a7111a7 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallerTimeZone.cs @@ -3,7 +3,7 @@ namespace AgentCore.Application.Runtime.Harness; /// -/// The time zone the person on a call is in, as the host learned it — from the browser, on the +/// The time zone the person on a conversation is in, as the host learned it — from the browser, on the /// request. The clock line reads the date in it instead of the server's zone. It is set per /// request, not once: a person who travels moves the clock with them, and a request that names /// no zone leaves the last one in place. @@ -26,22 +26,22 @@ public static class CallerTimeZone return TimeZoneInfo.TryFindSystemTimeZoneById(id.Trim(), out var zone) ? zone : null; } - /// Puts the caller's zone on the call a session carries, replacing what was there. - /// A session this framework created: it names the call. + /// Puts the caller's zone on the conversation a session carries, replacing what was there. + /// A session this framework created: it names the conversation. /// The zone the caller is in. - /// The session names no call. + /// The session names no conversation. public static void Set(AgentSession session, TimeZoneInfo zone) { ArgumentNullException.ThrowIfNull(session); ArgumentNullException.ThrowIfNull(zone); - if (session.GetService() is not { } call) + if (session.GetService() is not { } conversation) { throw new InvalidOperationException( "The session is not one this agent created, so it names no call to put the zone on."); } - call.Runner.SetTimeZone(zone); + conversation.Runner.SetTimeZone(zone); } /// Stamps the zone onto a child session, so a run on it reads the caller's date. diff --git a/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs b/src/AgentCore.Application/Runtime/Harness/ConversationFilesProvider.cs similarity index 80% rename from src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs rename to src/AgentCore.Application/Runtime/Harness/ConversationFilesProvider.cs index 0cc99fcd..673f2ef7 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/ConversationFilesProvider.cs @@ -4,24 +4,24 @@ namespace AgentCore.Application.Runtime.Harness; // The store behind an agent's files: block, bound per invocation: the framework's -// own file-access tools do the work, rooted at the running call's workspace folder. A -// shared store cannot serve every call — the overrides take no session — so this builds -// the framework provider per call around the same options, exactly like the prefetch +// own file-access tools do the work, rooted at the running conversation's workspace folder. A +// shared store cannot serve every conversation — the overrides take no session — so this builds +// the framework provider per conversation around the same options, exactly like the prefetch // search provider. State keys and post-invocation storage forward to the shared template: // accumulation lives in the session store, not on any instance. #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. -internal sealed class CallFilesProvider : AIContextProvider, IDisposable +internal sealed class ConversationFilesProvider : AIContextProvider, IDisposable { private const string NoTurnMessage = - "A files: tool runs only while a turn runs through a CallSession with a workspace root bound."; + "A files: tool runs only while a turn runs through a ConversationSession with a workspace root bound."; private readonly FileAccessProvider _template; private readonly FileAccessProviderOptions _options; - public CallFilesProvider(string root, FileAccessProviderOptions options) + public ConversationFilesProvider(string root, FileAccessProviderOptions options) { ArgumentNullException.ThrowIfNull(root); ArgumentNullException.ThrowIfNull(options); diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs b/src/AgentCore.Application/Runtime/Harness/ConversationShellEnvironmentProvider.cs similarity index 69% rename from src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs rename to src/AgentCore.Application/Runtime/Harness/ConversationShellEnvironmentProvider.cs index 9c7f017c..86bebaa5 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/ConversationShellEnvironmentProvider.cs @@ -6,18 +6,18 @@ namespace AgentCore.Application.Runtime.Harness; /// /// The instructions behind an agent's shell: block: the shell family, version, working -/// directory and CLI versions, probed once per call through that call's executor and rendered -/// with MAF's own formatter. No StateKeys — the snapshot lives on -/// and dies with the call, so resume re-probes a fresh environment. +/// directory and CLI versions, probed once per call through that conversation's executor and rendered +/// with MAF's own formatter. No StateKeys — the snapshot lives on +/// and dies with the conversation, so resume re-probes a fresh environment. /// -internal sealed class CallShellEnvironmentProvider : AIContextProvider +internal sealed class ConversationShellEnvironmentProvider : AIContextProvider { private const string NoTurnMessage = - "A shell: tool runs only while a turn runs through a CallSession with a workspace root bound."; + "A shell: tool runs only while a turn runs through a ConversationSession with a workspace root bound."; - private readonly CallShellOptions _options; + private readonly ConversationShellOptions _options; - public CallShellEnvironmentProvider(CallShellOptions options) + public ConversationShellEnvironmentProvider(ConversationShellOptions options) { ArgumentNullException.ThrowIfNull(options); _options = options; diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs b/src/AgentCore.Application/Runtime/Harness/ConversationShellOptions.cs similarity index 90% rename from src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs rename to src/AgentCore.Application/Runtime/Harness/ConversationShellOptions.cs index 2d8e4397..e33d780e 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs +++ b/src/AgentCore.Application/Runtime/Harness/ConversationShellOptions.cs @@ -5,7 +5,7 @@ namespace AgentCore.Application.Runtime.Harness; /// /// What one agent's shell: block resolved to. Built once at compile time and shared by every -/// call of that agent; keys one executor per instance of this record. +/// conversation of that agent; keys one executor per instance of this record. /// /// Where the shell runs. /// The command filter, or for none. @@ -18,7 +18,7 @@ namespace AgentCore.Application.Runtime.Harness; /// The container image. only. /// The Docker network mode. only. /// The container memory limit. only. -internal sealed record CallShellOptions( +internal sealed record ConversationShellOptions( ShellKind Kind, ShellPolicy? Policy, TimeSpan? Timeout, diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs b/src/AgentCore.Application/Runtime/Harness/ConversationShellProvider.cs similarity index 69% rename from src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs rename to src/AgentCore.Application/Runtime/Harness/ConversationShellProvider.cs index b062ad4e..15ecbc9c 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/ConversationShellProvider.cs @@ -5,18 +5,18 @@ namespace AgentCore.Application.Runtime.Harness; /// /// The context provider behind an agent's shell: block: on every invocation it hands the -/// model this call's shell executor as MAF's own tool. No instructions of our own — MAF's tool +/// model this conversation's shell executor as MAF's own tool. No instructions of our own — MAF's tool /// description is what the model reads — and no StateKeys, because the shell keeps no /// session state. /// -internal sealed class CallShellProvider : AIContextProvider +internal sealed class ConversationShellProvider : AIContextProvider { private const string NoTurnMessage = - "A shell: tool runs only while a turn runs through a CallSession with a workspace root bound."; + "A shell: tool runs only while a turn runs through a ConversationSession with a workspace root bound."; - private readonly CallShellOptions _options; + private readonly ConversationShellOptions _options; - public CallShellProvider(CallShellOptions options) + public ConversationShellProvider(ConversationShellOptions options) { ArgumentNullException.ThrowIfNull(options); _options = options; diff --git a/src/AgentCore.Application/Runtime/Harness/CallShells.cs b/src/AgentCore.Application/Runtime/Harness/ConversationShells.cs similarity index 81% rename from src/AgentCore.Application/Runtime/Harness/CallShells.cs rename to src/AgentCore.Application/Runtime/Harness/ConversationShells.cs index 9f7bee8a..fa4d5886 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShells.cs +++ b/src/AgentCore.Application/Runtime/Harness/ConversationShells.cs @@ -7,11 +7,11 @@ namespace AgentCore.Application.Runtime.Harness; /// -/// The shell executors one call has started. One per -/// instance the agent declares, created on first ask, plus one +/// The shell executors one conversation has started. One per +/// instance the agent declares, created on first ask, plus one /// probed environment snapshot per options for the model to read before its first command. /// -internal sealed class CallShells : IAsyncDisposable +internal sealed class ConversationShells : IAsyncDisposable { private readonly string _workspace; @@ -19,16 +19,16 @@ internal sealed class CallShells : IAsyncDisposable private readonly Lock _lock = new(); - private readonly Dictionary _executors = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary _executors = new(ReferenceEqualityComparer.Instance); - private readonly Dictionary> _environments = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary> _environments = new(ReferenceEqualityComparer.Instance); private bool _disposed; - /// Creates the holder for one call. - /// The call's workspace folder, the executor's working directory. + /// Creates the holder for one conversation. + /// The conversation's workspace folder, the executor's working directory. /// Where a failed dispose is logged, at Warning. May be . - public CallShells(string workspace, ILogger? logger) + public ConversationShells(string workspace, ILogger? logger) { ArgumentException.ThrowIfNullOrEmpty(workspace); _workspace = workspace; @@ -36,10 +36,10 @@ public CallShells(string workspace, ILogger? logger) } /// - /// Gets this call's executor for , creating it on first ask. + /// Gets this conversation's executor for , creating it on first ask. /// - /// This call's shells have already been torn down. - public ShellExecutor Get(CallShellOptions options) + /// This conversation's shells have already been torn down. + public ShellExecutor Get(ConversationShellOptions options) { ArgumentNullException.ThrowIfNull(options); @@ -50,7 +50,7 @@ public ShellExecutor Get(CallShellOptions options) } } - private ShellExecutor GetLocked(CallShellOptions options) + private ShellExecutor GetLocked(ConversationShellOptions options) { if (_executors.TryGetValue(options, out var existing)) { @@ -63,13 +63,13 @@ private ShellExecutor GetLocked(CallShellOptions options) } /// - /// Probes this call's executor for once and caches the snapshot - /// for the rest of the call. A faulted or cancelled probe is dropped so the next turn + /// Probes this conversation's executor for once and caches the snapshot + /// for the rest of the conversation. A faulted or cancelled probe is dropped so the next turn /// retries; resume re-probes a fresh environment. /// - /// This call's shells have already been torn down. + /// This conversation's shells have already been torn down. public Task GetEnvironmentAsync( - CallShellOptions options, CancellationToken cancellationToken = default) + ConversationShellOptions options, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(options); @@ -87,7 +87,7 @@ public Task GetEnvironmentAsync( _ = probe.ContinueWith( static (task, state) => { - if ((task.IsFaulted || task.IsCanceled) && state is (CallShells shells, CallShellOptions key)) + if ((task.IsFaulted || task.IsCanceled) && state is (ConversationShells shells, ConversationShellOptions key)) { lock (shells._lock) { @@ -110,7 +110,7 @@ public Task GetEnvironmentAsync( private static async Task ProbeAsync( ShellExecutor executor, CancellationToken cancellationToken) { - // A throwaway MAF prober per call: its single-executor pin is harmless because the + // A throwaway MAF prober per conversation: its single-executor pin is harmless because the // instance never leaves this probe. Probing runs commands, so for kind: docker the // container starts on the first turn even when the model never runs a command. That // is the price of the block: shell: declares intent, and the hints matter most @@ -128,7 +128,7 @@ private static async Task ProbeAsync( /// private static readonly string[] CleanEnvironmentAllowlist = ["PATH", "HOME", "LANG", "TMPDIR"]; - private ShellExecutor Create(CallShellOptions options) + private ShellExecutor Create(ConversationShellOptions options) { switch (options.Kind) { @@ -156,7 +156,7 @@ private ShellExecutor Create(CallShellOptions options) return new LocalShellExecutor(localOptions); case ShellKind.Docker: - // MountReadonly is false because the workspace is this call's own scratch folder, + // MountReadonly is false because the workspace is this conversation's own scratch folder, // and files: already writes to it. Every other Docker default (network none, // read-only root, nobody user, pids limit) stays unless the shell: block overrides it. DockerShellExecutorOptions dockerOptions = new() @@ -227,7 +227,7 @@ private ShellExecutor Create(CallShellOptions options) } /// - /// Disposes every executor this call started. Idempotent, and never throws out: a failed + /// Disposes every executor this conversation started. Idempotent, and never throws out: a failed /// dispose is logged at Warning through instead. A second /// concurrent caller returns immediately rather than wait for the first dispose to finish — the /// executors are only ever taken out and disposed once. diff --git a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs index 60fa5ae6..5929aa9a 100644 --- a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs +++ b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs @@ -8,7 +8,7 @@ namespace AgentCore.Application.Runtime.Harness; /// /// Moves the harness providers' MAF state — todos:, mode:, memory:, /// files:, background: — and the approval queue and standing rules between a live -/// 's state bag and . +/// 's state bag and . /// internal static class HarnessSessionState { diff --git a/src/AgentCore.Application/Runtime/Harness/PendingApprovalQueue.cs b/src/AgentCore.Application/Runtime/Harness/PendingApprovalQueue.cs index 924a8e31..830404ec 100644 --- a/src/AgentCore.Application/Runtime/Harness/PendingApprovalQueue.cs +++ b/src/AgentCore.Application/Runtime/Harness/PendingApprovalQueue.cs @@ -6,7 +6,7 @@ namespace AgentCore.Application.Runtime.Harness; /// /// The framework's pending approval queue, read off a session's state bag. The queue is a JSON -/// array of {toolCall: {name, arguments, callId}, requiresConfirmation, requestId} under +/// array of {toolCall: {name, arguments, conversationId}, requiresConfirmation, requestId} under /// — a MAF-internal shape pinned by probe /// docs/probes/harness-agentic/approval-roundtrip/, not a contract. Every read here is /// lenient: an entry that lost its shape is skipped, never thrown, because the turn must end @@ -37,16 +37,16 @@ internal static IReadOnlyList Read(JsonElement bag) if (entry.ValueKind != JsonValueKind.Object || !entry.TryGetProperty("requestId", out var id) || id.ValueKind != JsonValueKind.String - || !entry.TryGetProperty("toolCall", out var call) - || call.ValueKind != JsonValueKind.Object - || !call.TryGetProperty("name", out var name) + || !entry.TryGetProperty("toolCall", out var conversation) + || conversation.ValueKind != JsonValueKind.Object + || !conversation.TryGetProperty("name", out var name) || name.ValueKind != JsonValueKind.String) { continue; } using var empty = JsonDocument.Parse("{}"); - var arguments = call.TryGetProperty("arguments", out var args) && args.ValueKind == JsonValueKind.Object + var arguments = conversation.TryGetProperty("arguments", out var args) && args.ValueKind == JsonValueKind.Object ? args.Clone() : empty.RootElement.Clone(); @@ -77,18 +77,18 @@ internal static IReadOnlyList Read(JsonElement bag) if (entry.ValueKind != JsonValueKind.Object || !entry.TryGetProperty("requestId", out var id) || id.GetString() != requestId - || !entry.TryGetProperty("toolCall", out var call) - || call.ValueKind != JsonValueKind.Object - || !call.TryGetProperty("name", out var name) + || !entry.TryGetProperty("toolCall", out var conversation) + || conversation.ValueKind != JsonValueKind.Object + || !conversation.TryGetProperty("name", out var name) || name.ValueKind != JsonValueKind.String - || !call.TryGetProperty("callId", out var callId) - || callId.ValueKind != JsonValueKind.String) + || !conversation.TryGetProperty("callId", out var conversationId) + || conversationId.ValueKind != JsonValueKind.String) { continue; } Dictionary arguments = new(StringComparer.Ordinal); - if (call.TryGetProperty("arguments", out var args) && args.ValueKind == JsonValueKind.Object) + if (conversation.TryGetProperty("arguments", out var args) && args.ValueKind == JsonValueKind.Object) { foreach (var argument in args.EnumerateObject()) { @@ -96,7 +96,7 @@ internal static IReadOnlyList Read(JsonElement bag) } } - var toolCall = new FunctionCallContent(callId.GetString()!, name.GetString()!, arguments); + var toolCall = new FunctionCallContent(conversationId.GetString()!, name.GetString()!, arguments); return new ChatMessage(ChatRole.User, [new ToolApprovalResponseContent(requestId, approved, toolCall)]); } diff --git a/src/AgentCore.Application/Runtime/ModerationAgent.cs b/src/AgentCore.Application/Runtime/ModerationAgent.cs index 6484465a..b73d97bd 100644 --- a/src/AgentCore.Application/Runtime/ModerationAgent.cs +++ b/src/AgentCore.Application/Runtime/ModerationAgent.cs @@ -123,13 +123,13 @@ private async ValueTask JudgeAsync( { // The deadline passed, and not the caller's own token. A cancel the host asked for // still propagates, because that is the host ending the turn and not a slow vendor. - return Unavailable(CallSession.ModerationTimedOutReason); + return Unavailable(ConversationSession.ModerationTimedOutReason); } #pragma warning disable CA1031 // Moderation guards the turn. It must never be the thing that drops it. catch (Exception exception) when (exception is not OperationCanceledException) #pragma warning restore CA1031 { - return Unavailable(CallSession.ModerationFaultedReason); + return Unavailable(ConversationSession.ModerationFaultedReason); } } diff --git a/src/AgentCore.Application/Runtime/ToolCallScopes.cs b/src/AgentCore.Application/Runtime/ToolCallScopes.cs index 2e593e62..1c3e74d9 100644 --- a/src/AgentCore.Application/Runtime/ToolCallScopes.cs +++ b/src/AgentCore.Application/Runtime/ToolCallScopes.cs @@ -2,16 +2,16 @@ namespace AgentCore.Application.Runtime; -// The of one turn, built from the invocation the call runs under. +// The of one turn, built from the invocation the conversation runs under. internal static class ToolCallScopes { /// The message the binder throws with when no turn reached the tool. internal const string NoTurnMessage = "A binding declared a ToolCallScope parameter, and no turn is open on this flow of execution. " - + "A bound tool receives a ToolCallScope only while a turn runs through a CallSession. Run the " - + "tool through a CallSession, or take the ToolCallScope parameter off the binding."; + + "A bound tool receives a ToolCallScope only while a turn runs through a ConversationSession. Run the " + + "tool through a ConversationSession, or take the ToolCallScope parameter off the binding."; - /// Builds the scope of the call and turn one invocation belongs to. + /// Builds the scope of the conversation and turn one invocation belongs to. /// The turn the tool call runs under. /// The scope. /// is . @@ -19,6 +19,6 @@ internal static ToolCallScope From(TurnInvocation invocation) { ArgumentNullException.ThrowIfNull(invocation); - return new ToolCallScope(invocation.CallId, invocation.TurnIndex, invocation.Stage, invocation.Workspace); + return new ToolCallScope(invocation.ConversationId, invocation.TurnIndex, invocation.Stage, invocation.Workspace); } } diff --git a/src/AgentCore.Application/Runtime/Turn/TurnMessages.cs b/src/AgentCore.Application/Runtime/Turn/TurnMessages.cs index f61180f1..588ace5c 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnMessages.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnMessages.cs @@ -24,10 +24,10 @@ internal static class TurnMessages internal const string AgentLinePrefix = "You: "; /// - /// Renders the call so far into the one role a workflow node still recognises. + /// Renders the conversation so far into the one role a workflow node still recognises. /// - /// The caller-facing history of this call, oldest first. - /// One system message, or on the first turn of a call. + /// The caller-facing history of this conversation, oldest first. + /// One system message, or on the first turn of a conversation. internal static ChatMessage? GraphHistory(IReadOnlyList history) { StringBuilder rendered = new(); diff --git a/src/AgentCore.Application/Runtime/TurnDisposition.cs b/src/AgentCore.Application/Runtime/TurnDisposition.cs index 6a5ed920..7c0e595f 100644 --- a/src/AgentCore.Application/Runtime/TurnDisposition.cs +++ b/src/AgentCore.Application/Runtime/TurnDisposition.cs @@ -28,7 +28,7 @@ internal enum FallbackCause EmptyReply, } -/// What the pipeline layers report back to about a turn. +/// What the pipeline layers report back to about a turn. /// /// What the endpoint decided, or that it could not, or when the pipeline /// carries no at all because the host moderates nothing. diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs index a7901438..8dd675e7 100644 --- a/src/AgentCore.Application/Runtime/TurnInvocation.cs +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -18,8 +18,8 @@ internal sealed record TurnInvocation /// argument will never be called this, and the binder intercepts the type before JSON binding. internal const string ArgumentsKey = "urn:agentcore:turn"; - /// Gets the id of the call the turn belongs to. - public required string CallId { get; init; } + /// Gets the id of the conversation the turn belongs to. + public required string ConversationId { get; init; } /// Gets the zero-based index of the turn now running. public required int TurnIndex { get; init; } @@ -27,28 +27,28 @@ internal sealed record TurnInvocation /// Gets the stage the machine holds. Empty when the entry declares no policy. public required string Stage { get; init; } - /// Gets the folder this call owns on disk, or . + /// Gets the folder this conversation owns on disk, or . public string? Workspace { get; init; } - /// Gets this call's shell executors, or . - public CallShells? Shells { get; init; } + /// Gets this conversation's shell executors, or . + public ConversationShells? Shells { get; init; } /// Gets what the turn may see of the knowledge base, or . public KnowledgeScope? Knowledge { get; init; } - /// Gets the call's ambiguity holder, or inside a nested tool call. + /// Gets the conversation's ambiguity holder, or inside a nested tool call. public Clarifications? Clarifications { get; init; } /// Gets the instructions for this one invocation, or for none. public string? Instructions { get; init; } - /// Gets the zone the person on the call is in, or when the host named none. + /// Gets the zone the person on the conversation is in, or when the host named none. public TimeZoneInfo? TimeZone { get; init; } /// Gets whether this row's session carries the caller's own history. public bool CarriesHistory { get; init; } - /// Gets the screen this call draws on, or when it has none. + /// Gets the screen this conversation draws on, or when it has none. public IRenderPort? Screen { get; init; } /// Gets what the turn cites into. Never on a loop-built turn. @@ -63,7 +63,7 @@ internal sealed record TurnInvocation /// Gets what the turn publishes files into. Never on a loop-built turn. public TurnFiles? Files { get; init; } - /// Gets the tools a delegated run of this call is offered, or for none. + /// Gets the tools a delegated run of this conversation is offered, or for none. public IReadOnlyList? Tools { get; init; } /// Gets the id of the delegating tool are meant for. @@ -80,7 +80,7 @@ internal sealed record TurnInvocation public bool Nested { get; init; } /// - /// Gets the live state document of the call running this turn, or + /// Gets the live state document of the conversation running this turn, or /// outside a turn. The graph-state wrapper snapshots it into the run just before the run starts; /// nothing writes the document mid-run (writers and the extractor commit after), so the snapshot /// reads what the old ambient read at edge time. diff --git a/src/AgentCore.Application/Scripting/ScriptRequest.cs b/src/AgentCore.Application/Scripting/ScriptRequest.cs index 57cb803f..5d8117c5 100644 --- a/src/AgentCore.Application/Scripting/ScriptRequest.cs +++ b/src/AgentCore.Application/Scripting/ScriptRequest.cs @@ -12,7 +12,7 @@ namespace AgentCore.Application.Scripting; public sealed record ScriptRequest(string Code, JsonNode Data) { /// - /// The name of a function the script may call with its result instead of returning it, or + /// The name of a function the script may conversation with its result instead of returning it, or /// when only return counts. A model that was told to call a tool /// named present will call present(tree) from inside its code about as often as it /// returns the tree. diff --git a/src/AgentCore.Application/Secrets/KnownSecrets.cs b/src/AgentCore.Application/Secrets/KnownSecrets.cs index e3dcba63..ee838ce5 100644 --- a/src/AgentCore.Application/Secrets/KnownSecrets.cs +++ b/src/AgentCore.Application/Secrets/KnownSecrets.cs @@ -50,7 +50,7 @@ public static class KnownSecrets /// The one OpenAI credential, which chat, embedding, and moderation all read. public static readonly SecretName OpenAi = new(OpenAiApiKeyName, OpenAiApiKeyVariable); - /// The Qdrant API key the vector store sends on every call. + /// The Qdrant API key the vector store sends on every conversation. public static readonly SecretName Qdrant = new(QdrantApiKeyName, QdrantApiKeyVariable); /// The PostgreSQL connection string the audit chain and the transcript are written through. diff --git a/src/AgentCore.Application/Secrets/SecretResolutionException.cs b/src/AgentCore.Application/Secrets/SecretResolutionException.cs index ce77c316..686d4831 100644 --- a/src/AgentCore.Application/Secrets/SecretResolutionException.cs +++ b/src/AgentCore.Application/Secrets/SecretResolutionException.cs @@ -4,7 +4,7 @@ namespace AgentCore.Application.Secrets; /// The one exception a secret reference raises when nothing resolves it. /// /// -/// It fails at startup, like every other configuration failure, so a call never discovers a missing +/// It fails at startup, like every other configuration failure, so a conversation never discovers a missing /// credential in the middle of a turn. The message names the secret and the place the document /// wrote it. It never holds the value of any secret, resolved or not. /// @@ -50,7 +50,7 @@ public static SecretResolutionException Unresolved( secretName, $"the secret '{secretName}' did not resolve.{where} No resolver in the chain holds that name. " + "AgentCore resolves every ${secret:name} reference at startup, so this fails before the " - + "first call rather than during one.", + + "first conversation rather than during one.", innerException); } } diff --git a/src/AgentCore.Application/Secrets/SecretResolverExtensions.cs b/src/AgentCore.Application/Secrets/SecretResolverExtensions.cs index 3a21d11f..887a4ce2 100644 --- a/src/AgentCore.Application/Secrets/SecretResolverExtensions.cs +++ b/src/AgentCore.Application/Secrets/SecretResolverExtensions.cs @@ -27,7 +27,7 @@ namespace AgentCore.Application.Secrets; /// /// /// The failure is , so a missing credential is a startup -/// failure like every other configuration failure and a call never discovers one mid-turn. The +/// failure like every other configuration failure and a conversation never discovers one mid-turn. The /// message names both halves, because the reader has two places to put a key and needs to be told /// both. It never holds the value of anything, resolved or not. /// diff --git a/src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs b/src/AgentCore.Application/Sessions/Memory/InMemoryConversationSessions.cs similarity index 65% rename from src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs rename to src/AgentCore.Application/Sessions/Memory/InMemoryConversationSessions.cs index 90a2a197..b4e39937 100644 --- a/src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs +++ b/src/AgentCore.Application/Sessions/Memory/InMemoryConversationSessions.cs @@ -6,38 +6,38 @@ namespace AgentCore.Application.Sessions.Memory; /// -/// The default . It holds every session in this process. +/// The default . It holds every session in this process. /// /// /// /// This does not survive a restart and does not span instances. A process that stops loses every /// call it was holding, and a second instance behind a load balancer never sees the sessions of the -/// first. A deployment that needs either registers another before +/// first. A deployment that needs either registers another before /// AddAgentCore, and this steps aside. /// /// /// A session is dropped when it has been untouched for the idle timeout. The voice path does not -/// wait for that — the socket closing is a real end, and it closes the call itself. The timeout is +/// wait for that — the socket closing is a real end, and it closes the conversation itself. The timeout is /// for the text path, where a caller who simply stops replying never reaches a terminal stage and /// would otherwise be held for the life of the process. /// /// -public sealed class InMemoryCallSessions : ICallSessions +public sealed class InMemoryConversationSessions : IConversationSessions { /// The idle timeout a host gets when it names none. public static readonly TimeSpan DefaultIdleTimeout = TimeSpan.FromMinutes(30); private readonly ConcurrentDictionary _sessions = new(StringComparer.Ordinal); - private readonly ICallSessionFactory _factory; + private readonly IConversationSessionFactory _factory; private readonly TimeSpan _idleTimeout; private readonly TimeProvider _time; /// Creates the store. - /// Builds the session of a call that is not held yet. + /// Builds the session of a conversation that is not held yet. /// How long an untouched session is kept. It slides on every read. /// The clock the idle timeout is measured on. - public InMemoryCallSessions( - ICallSessionFactory factory, TimeSpan idleTimeout, TimeProvider timeProvider) + public InMemoryConversationSessions( + IConversationSessionFactory factory, TimeSpan idleTimeout, TimeProvider timeProvider) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(timeProvider); @@ -52,38 +52,38 @@ public InMemoryCallSessions( public int Count => _sessions.Count; /// - public ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default) + public ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var session = _factory.Create(callId); - _sessions[session.CallId] = new Entry(session, _time.GetUtcNow()); + var session = _factory.Create(conversationId); + _sessions[session.ConversationId] = new Entry(session, _time.GetUtcNow()); return ValueTask.FromResult(session); } /// - public ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default) + public ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); cancellationToken.ThrowIfCancellationRequested(); - if (!_sessions.TryGetValue(callId, out var entry)) + if (!_sessions.TryGetValue(conversationId, out var entry)) { - return ValueTask.FromResult(null); + return ValueTask.FromResult(null); } - _sessions.TryUpdate(callId, entry with { Touched = _time.GetUtcNow() }, entry); - return ValueTask.FromResult(entry.Session); + _sessions.TryUpdate(conversationId, entry with { Touched = _time.GetUtcNow() }, entry); + return ValueTask.FromResult(entry.Session); } /// - public async ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); // Taken out first so a second caller cannot be handed a session that is already draining, // then flushed while this method still holds the only reference to it. - if (_sessions.TryRemove(callId, out var entry)) + if (_sessions.TryRemove(conversationId, out var entry)) { // A store that throws on flush must not leave the session's shells running with // nothing left to hold a reference to them. @@ -113,7 +113,7 @@ public async ValueTask SweepAsync(CancellationToken cancellationToken = default) var cutoff = _time.GetUtcNow() - _idleTimeout; List? faults = null; - foreach (var (callId, entry) in _sessions.ToArray()) + foreach (var (conversationId, entry) in _sessions.ToArray()) { cancellationToken.ThrowIfCancellationRequested(); @@ -126,7 +126,7 @@ public async ValueTask SweepAsync(CancellationToken cancellationToken = default) // dictionary for the life of the process, which is the leak this sweep exists to stop. try { - await ExpireAsync(callId, entry.Session, cancellationToken).ConfigureAwait(false); + await ExpireAsync(conversationId, entry.Session, cancellationToken).ConfigureAwait(false); } catch (Exception fault) when (fault is not OperationCanceledException) { @@ -140,22 +140,22 @@ public async ValueTask SweepAsync(CancellationToken cancellationToken = default) } } - /// Ends one expired call, chain first and session second. + /// Ends one expired conversation, chain first and session second. /// - /// §11 item 6 makes call.ended the last event of every call, and expiry is a way a call + /// §11 item 6 makes conversation.ended the last event of every conversation, and expiry is a way a conversation /// ends. Nothing else writes it here: the relay closes its own chain from the socket and the /// turn loop closes its own from a terminal stage, so a caller who simply stops replying is the - /// one ending that would otherwise leave a chain with no end. + /// one ending that would otherwise leave a chain with no end. /// is idempotent, so a session that already closed its chain keeps the reason it wrote. - /// The reason is because the closed set of §6 holds no - /// reason for an abandoned call; see the amendment owed on that enum. + /// The reason is because the closed set of §6 holds no + /// reason for an abandoned conversation; see the amendment owed on that enum. /// private async ValueTask ExpireAsync( - string callId, CallSession session, CancellationToken cancellationToken) + string conversationId, ConversationSession session, CancellationToken cancellationToken) { - _ = session.EndCall(CallEndReason.Faulted); - await CloseAsync(callId, cancellationToken).ConfigureAwait(false); + _ = session.EndConversation(ConversationEndReason.Faulted); + await CloseAsync(conversationId, cancellationToken).ConfigureAwait(false); } - private sealed record Entry(CallSession Session, DateTimeOffset Touched); + private sealed record Entry(ConversationSession Session, DateTimeOffset Touched); } diff --git a/src/AgentCore.Application/Skills/SkillsProviderFactory.cs b/src/AgentCore.Application/Skills/SkillsProviderFactory.cs index 1eb54d7d..1343fa62 100644 --- a/src/AgentCore.Application/Skills/SkillsProviderFactory.cs +++ b/src/AgentCore.Application/Skills/SkillsProviderFactory.cs @@ -47,7 +47,7 @@ internal static AIContextProvider Create( AgentSkillsProviderOptions options = new() { - // Nothing answers an approval request mid-call, so an approval-gated tool would stall + // Nothing answers an approval request mid-conversation, so an approval-gated tool would stall // the turn. The script tool keeps its approval, and the wrapper removes it entirely. DisableLoadSkillApproval = true, DisableReadSkillResourceApproval = true, diff --git a/src/AgentCore.Application/State/ConstStateWriter.cs b/src/AgentCore.Application/State/ConstStateWriter.cs index 3bb0fc70..f081619d 100644 --- a/src/AgentCore.Application/State/ConstStateWriter.cs +++ b/src/AgentCore.Application/State/ConstStateWriter.cs @@ -6,12 +6,12 @@ namespace AgentCore.Application.State; /// Writer 4 of section 8.3. It fills a slot from a fixed value. /// /// -/// A constant never changes, so this writer runs once, when the call starts. +/// A constant never changes, so this writer runs once, when the conversation starts. /// public static class ConstStateWriter { /// Fills every writer: const slot from its value:. - /// The state of one call. + /// The state of one conversation. /// The number of slots this writer filled. public static int Apply(StateDocument state) { diff --git a/src/AgentCore.Application/State/CounterStateWriter.cs b/src/AgentCore.Application/State/CounterStateWriter.cs index 6f1ecde5..ea2f5152 100644 --- a/src/AgentCore.Application/State/CounterStateWriter.cs +++ b/src/AgentCore.Application/State/CounterStateWriter.cs @@ -25,7 +25,7 @@ public CounterStateWriter(IGuardEvaluator rules) } /// Increments every writer: counter slot whose rule is true. - /// The state of one call. + /// The state of one conversation. /// The number of slots this writer incremented. public int Apply(StateDocument state) { diff --git a/src/AgentCore.Application/State/StateDocument.cs b/src/AgentCore.Application/State/StateDocument.cs index cbaa094f..28d25b93 100644 --- a/src/AgentCore.Application/State/StateDocument.cs +++ b/src/AgentCore.Application/State/StateDocument.cs @@ -5,15 +5,15 @@ namespace AgentCore.Application.State; /// -/// The declared state of one call, plus the three reserved slots. +/// The declared state of one conversation, plus the three reserved slots. /// public sealed class StateDocument { private readonly ConcurrentDictionary _written = new(StringComparer.Ordinal); - /// Creates the state of one call from the declared slots. + /// Creates the state of one conversation from the declared slots. /// The loaded document. - /// The stage the call starts in, or when there is no policy. + /// The stage the conversation starts in, or when there is no policy. public StateDocument(AgentCoreConfiguration configuration, string? stage = null) { ArgumentNullException.ThrowIfNull(configuration); @@ -31,8 +31,8 @@ public StateDocument(AgentCoreConfiguration configuration, string? stage = null) /// Gets or sets the reserved turnIndex slot. The turn loop owns it. public int TurnIndex { get; set; } - /// Gets or sets the reserved callDurationSeconds slot. The turn loop owns it. - public double CallDurationSeconds { get; set; } + /// Gets or sets the reserved conversationDurationSeconds slot. The turn loop owns it. + public double ConversationDurationSeconds { get; set; } /// Gets the names of the declared slots. The reserved slots are not declared. public IEnumerable SlotNames => Configuration.State.Keys; @@ -130,7 +130,7 @@ private static bool IsMember(IReadOnlyList members, JsonNode? value) snapshot[ReservedStateSlots.Stage] = JsonValue.Create(Stage); snapshot[ReservedStateSlots.TurnIndex] = JsonValue.Create(TurnIndex); - snapshot[ReservedStateSlots.CallDurationSeconds] = JsonValue.Create(CallDurationSeconds); + snapshot[ReservedStateSlots.ConversationDurationSeconds] = JsonValue.Create(ConversationDurationSeconds); return snapshot; } @@ -163,6 +163,6 @@ private static bool IsMember(IReadOnlyList members, JsonNode? value) return string.Equals(slot, ReservedStateSlots.TurnIndex, StringComparison.Ordinal) ? JsonValue.Create(TurnIndex) - : JsonValue.Create(CallDurationSeconds); + : JsonValue.Create(ConversationDurationSeconds); } } diff --git a/src/AgentCore.Application/State/StateExtractionResult.cs b/src/AgentCore.Application/State/StateExtractionResult.cs index b73d1102..25db8c0c 100644 --- a/src/AgentCore.Application/State/StateExtractionResult.cs +++ b/src/AgentCore.Application/State/StateExtractionResult.cs @@ -4,7 +4,7 @@ namespace AgentCore.Application.State; /// What one extractor call did to the state. /// /// -/// Section 8.7: the extractor never drops a call. A reply that does not deserialize leaves every +/// Section 8.7: the extractor never drops a conversation. A reply that does not deserialize leaves every /// slot unchanged, and the turn loop logs it once and continues. /// /// Whether the reply parsed into the object the schema describes. @@ -19,7 +19,7 @@ public sealed record StateExtractionResult( int Rejected, string? Failure) { - /// Gets the result of a call that produced nothing usable. + /// Gets the result of a conversation that produced nothing usable. /// The reason. /// A result that changed no slot. public static StateExtractionResult Failed(string failure) => new(false, 0, 0, 0, failure); diff --git a/src/AgentCore.Application/State/StateExtractor.cs b/src/AgentCore.Application/State/StateExtractor.cs index a5b22848..81530a66 100644 --- a/src/AgentCore.Application/State/StateExtractor.cs +++ b/src/AgentCore.Application/State/StateExtractor.cs @@ -21,7 +21,7 @@ namespace AgentCore.Application.State; /// null answer means the model did not answer, and it leaves the slot at its previous value. /// /// -/// The extractor has no retry. One call runs, and a reply that does not deserialize leaves the slots +/// The extractor has no retry. One conversation runs, and a reply that does not deserialize leaves the slots /// unchanged. The stage machine stays where it is and the agent tries again next turn. /// /// @@ -31,7 +31,7 @@ public sealed class StateExtractor public const string SchemaName = "agentcore_state"; private const string SystemPrompt = - "You read one finished turn of a phone call and report typed state. " + "You read one finished turn of a phone conversation and report typed state. " + "Answer with one JSON object that matches the schema. " + "Set a field only when this turn shows the answer. " + "Leave every other field null. Null means you did not answer, and it keeps the earlier value. " @@ -144,10 +144,10 @@ public static JsonElement BuildSchema(AgentCoreConfiguration configuration) /// /// Runs one extractor call against the finished turn, then writes what it answered. /// - /// The state of one call. + /// The state of one conversation. /// The finished turn, newest last. /// Cancels the model call. - /// What the call did to the state. + /// What the conversation did to the state. public Task ExtractAsync( StateDocument state, IEnumerable transcript, @@ -160,11 +160,11 @@ public Task ExtractAsync( } /// Runs one extractor call against the finished turn, then writes what it answered. - /// The state of one call. + /// The state of one conversation. /// The finished turn, newest last. - /// The call's ambiguity holder. reads and writes it. + /// The conversation's ambiguity holder. reads and writes it. /// Cancels the model call. - /// What the call did to the state. + /// What the conversation did to the state. internal async Task ExtractAsync( StateDocument state, IEnumerable transcript, @@ -189,7 +189,7 @@ internal async Task ExtractAsync( } catch (Exception exception) when (exception is not OperationCanceledException) { - // State extraction must never drop a call. Section 8.7. + // State extraction must never drop a conversation. Section 8.7. return StateExtractionResult.Failed($"the extractor call failed: {exception.Message}"); } @@ -197,7 +197,7 @@ internal async Task ExtractAsync( } /// Writes one extractor reply into the state. - /// The state of one call. + /// The state of one conversation. /// The raw JSON the model returned. /// What the reply did to the state. public StateExtractionResult Write(StateDocument state, string? replyText) @@ -208,10 +208,10 @@ public StateExtractionResult Write(StateDocument state, string? replyText) } /// Writes one extractor reply into the state. - /// The state of one call. + /// The state of one conversation. /// The raw JSON the model returned. /// - /// The call's ambiguity holder (K36). A write that lands clears the slot's lastNamed + /// The conversation's ambiguity holder (K36). A write that lands clears the slot's lastNamed /// record (K30); a refused write leaves it alone. /// /// What the reply did to the state. diff --git a/src/AgentCore.Application/State/ToolStateWriter.cs b/src/AgentCore.Application/State/ToolStateWriter.cs index 1a7ad576..4f11c86b 100644 --- a/src/AgentCore.Application/State/ToolStateWriter.cs +++ b/src/AgentCore.Application/State/ToolStateWriter.cs @@ -14,7 +14,7 @@ namespace AgentCore.Application.State; public static class ToolStateWriter { /// Fills every slot that reads the result of one tool. - /// The state of one call. + /// The state of one conversation. /// The id of the tool that just returned. /// The tool result, as a node tree. /// The number of slots this writer filled. diff --git a/src/AgentCore.Application/State/UnfilledSlotReminder.cs b/src/AgentCore.Application/State/UnfilledSlotReminder.cs index 3e84694e..094421ba 100644 --- a/src/AgentCore.Application/State/UnfilledSlotReminder.cs +++ b/src/AgentCore.Application/State/UnfilledSlotReminder.cs @@ -22,7 +22,7 @@ public static class UnfilledSlotReminder /// /// Lists the slots the current stage waits on and that still read as null. /// - /// The state of one call. + /// The state of one conversation. /// The stage the machine holds. /// The unfilled slot names, in document order. public static IReadOnlyList UnfilledSlots(StateDocument state, StageConfiguration stage) @@ -77,7 +77,7 @@ public static IReadOnlyList UnfilledSlots(StateDocument state, StageConf } /// Builds the reminder for the stage the machine holds. - /// The state of one call. + /// The state of one conversation. /// The stage the machine holds. /// The reminder text, or when no slot is unfilled. public static string? Build(StateDocument state, StageConfiguration stage) diff --git a/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs b/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs index 7c673e1e..c0ff9199 100644 --- a/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs +++ b/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs @@ -6,7 +6,7 @@ namespace AgentCore.Application.Tools.Binding; /// One host delegate a kind: binding tool calls. /// /// The arguments the model filled, as one JSON object. -/// Cancels the call. +/// Cancels the conversation. /// /// The result the model reads. A reaches the model exactly as it is written. /// @@ -42,7 +42,7 @@ public ToolBindingRegistry Register(string name, ToolBinding binding) /// The method the tool calls. Its parameters are the arguments the model fills, and their JSON /// Schema, so the declaration this name serves must write no parameters:. A /// on a parameter reaches the model. A - /// parameter of type is filled by the runtime with the call the turn + /// parameter of type is filled by the runtime with the conversation the turn /// belongs to, and is not exposed to the model. /// /// This registry, so a host chains its registrations. diff --git a/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs b/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs index c92d1aab..9241a91e 100644 --- a/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs +++ b/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs @@ -5,7 +5,7 @@ namespace AgentCore.Application.Tools.Binding; // The runtime-filled parameters a bound tool declares. The model never sees them: they bind -// from the turn the invoking client filed in the call's arguments. +// from the turn the invoking client filed in the conversation's arguments. internal static class ToolParameterBindings { /// Binds one runtime-filled parameter, or answers for the model's own. diff --git a/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs b/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs index 1616ed4b..4cdb310b 100644 --- a/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs +++ b/src/AgentCore.Application/Tools/Builtin/BuiltinToolNames.cs @@ -6,6 +6,6 @@ public static class BuiltinToolNames /// Lets the model provider run a web search of its own. public const string WebSearch = "web.search"; - /// Hands one file from the call's workspace to the person, through the blob store. + /// Hands one file from the conversation's workspace to the person, through the blob store. public const string FilePublish = "file.publish"; } diff --git a/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs b/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs index 3c7b3f91..a3fdaf93 100644 --- a/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs +++ b/src/AgentCore.Application/Tools/Builtin/BuiltinToolOptions.cs @@ -12,7 +12,7 @@ internal static class BuiltinToolOptions /// Builds the options every built-in is created with. /// The declaration the document holds. /// The options: the declared id as the name, the resolved description, no result schema, - /// and the turn bound from the call rather than filled by the model. + /// and the turn bound from the conversation rather than filled by the model. internal static AIFunctionFactoryOptions Options(ToolConfiguration tool) => new() { Name = tool.Id, diff --git a/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs b/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs index ed1c7d89..c8e59498 100644 --- a/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs +++ b/src/AgentCore.Application/Tools/Builtin/FilePublishTool.cs @@ -14,12 +14,12 @@ namespace AgentCore.Application.Tools.Builtin; /// -/// Copies one file out of the running call's workspace into the blob store, owned by the call, and +/// Copies one file out of the running conversation's workspace into the blob store, owned by the conversation, and /// files a on the turn so the card reaches the person. /// /// /// A background child runs with no turn, so it has no drain to file the card on: its blob is still -/// stored under the parent call, and the link goes back to the child in the result alone. +/// stored under the parent conversation, and the link goes back to the child in the result alone. /// internal sealed class FilePublishTool { @@ -37,7 +37,7 @@ internal sealed class FilePublishTool /// The declaration the document holds. Its id is the name the model calls. /// The store providers.blobs opened. /// The cap and the allowlist. - /// The root every call's folder sits under. + /// The root every conversation's folder sits under. /// Where a refused file is reported. public FilePublishTool(ToolConfiguration tool, IBlobStore blobs, BlobPolicy policy, string workspaceRoot, ILogger logger) { @@ -72,10 +72,10 @@ private async ValueTask PublishAsync( if (OwnerOf(turn) is not { } owner) { Log.SandboxFileHasNoOwner(_logger, _tool.Id); - return Failed("no call is running, so there is nobody to hand the file to."); + return Failed("no conversation is running, so there is nobody to hand the file to."); } - var (callId, workspace) = owner; + var (conversationId, workspace) = owner; if (ResolveInside(workspace, path) is not { } full) { @@ -92,13 +92,13 @@ private async ValueTask PublishAsync( if (!BlobName.IsSafe(name)) { - Log.SandboxFileRefused(_logger, callId, name, "the name is not a plain file name"); + Log.SandboxFileRefused(_logger, conversationId, name, "the name is not a plain file name"); return Failed($"'{name}' is not a plain file name. Rename the file and publish it again."); } if (_policy.WhyRefused(name, length) is { } reason) { - Log.SandboxFileRefused(_logger, callId, name, reason); + Log.SandboxFileRefused(_logger, conversationId, name, reason); return Failed($"'{name}' was refused: {reason}. Allowed extensions: {string.Join(", ", _policy.AllowedExtensions)}; " + $"largest file: {_policy.MaxBytes} bytes."); } @@ -111,14 +111,14 @@ private async ValueTask PublishAsync( await using var content = File.OpenRead(full); blob = await _blobs - .PutAsync(new BlobWrite(callId, name, BlobMediaTypes.Of(name), content, length), cancellationToken) + .PutAsync(new BlobWrite(conversationId, name, BlobMediaTypes.Of(name), content, length), cancellationToken) .ConfigureAwait(false); url = await _blobs.LinkAsync(blob, BlobLink.Lifetime, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (exception is not OperationCanceledException) { - Log.SandboxFileCaptureFailed(_logger, callId, name, exception); + Log.SandboxFileCaptureFailed(_logger, conversationId, name, exception); return Failed($"'{name}' could not be stored: {exception.Message}"); } @@ -142,12 +142,12 @@ private async ValueTask PublishAsync( } /// - /// The call that owns the file and its folder: the filed turn, or for a background child the + /// The conversation that owns the file and its folder: the filed turn, or for a background child the /// stamp its session carries and the folder that call id names under the root. /// - private (string CallId, string Workspace)? OwnerOf(TurnInvocation? turn) + private (string ConversationId, string Workspace)? OwnerOf(TurnInvocation? turn) { - if (turn is { CallId: { } fromTurn }) + if (turn is { ConversationId: { } fromTurn }) { return turn.Workspace is { } workspace ? (fromTurn, workspace) : null; } diff --git a/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs b/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs index 47aa499a..9bedb4c3 100644 --- a/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs +++ b/src/AgentCore.Application/Tools/Builtin/FilePublishToolDefinition.cs @@ -17,7 +17,7 @@ internal sealed class FilePublishToolDefinition : IBuiltinToolDefinition /// public string DefaultDescription => "Hands one file from the workspace to the person and returns a link to it. " - + "A file that is not published is lost when the call ends."; + + "A file that is not published is lost when the conversation ends."; /// public AITool Build(ToolConfiguration tool, BuiltinToolPorts ports) diff --git a/src/AgentCore.Application/Tools/DeclaredTool.cs b/src/AgentCore.Application/Tools/DeclaredTool.cs index 368ab089..10c58ccd 100644 --- a/src/AgentCore.Application/Tools/DeclaredTool.cs +++ b/src/AgentCore.Application/Tools/DeclaredTool.cs @@ -40,7 +40,7 @@ protected DeclaredTool(ToolConfiguration tool) /// The entry point. Delegates straight to . /// The arguments the model filled. - /// Cancels the call. + /// Cancels the conversation. /// Exactly what returned. protected sealed override async ValueTask InvokeCoreAsync( AIFunctionArguments arguments, @@ -53,7 +53,7 @@ protected DeclaredTool(ToolConfiguration tool) /// Runs the tool. /// The arguments the model filled. - /// Cancels the call. + /// Cancels the conversation. /// The result the model reads. protected abstract ValueTask CallAsync(AIFunctionArguments arguments, CancellationToken cancellationToken); diff --git a/src/AgentCore.Application/Tools/Registry/ToolRegistration.cs b/src/AgentCore.Application/Tools/Registry/ToolRegistration.cs index 086f0840..908ada1b 100644 --- a/src/AgentCore.Application/Tools/Registry/ToolRegistration.cs +++ b/src/AgentCore.Application/Tools/Registry/ToolRegistration.cs @@ -8,7 +8,7 @@ namespace AgentCore.Application.Tools.Registry; /// The name the model calls. It is unique across every source. /// The sentence the model reads to decide when to call it. /// -/// Builds the tool. It runs at most once, on the first resolve, and never during a call. +/// Builds the tool. It runs at most once, on the first resolve, and never during a conversation. /// /// /// How long one call may take, or for no deadline of its own. A source sets diff --git a/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs b/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs index b758e47b..12d0264c 100644 --- a/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs +++ b/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs @@ -81,9 +81,9 @@ private static AITool Limit(ToolRegistration registration) } // A source that asked for a deadline and quietly did not get one is the worst of both: the - // document says the call is bounded and nothing bounds it. Only an AIFunction has a call to + // document says the conversation is bounded and nothing bounds it. Only an AIFunction has a conversation to // put a deadline around, so a source that names one for anything else is wrong about its own - // tool, and says so at boot rather than on a live call. + // tool, and says so at boot rather than on a live conversation. return tool is AIFunction function ? new TimeLimitedTool(function, limit) : throw ToolSourceError.Fail( diff --git a/src/AgentCore.Application/Tools/ToolCallScope.cs b/src/AgentCore.Application/Tools/ToolCallScope.cs index 4112c642..5e8b1b49 100644 --- a/src/AgentCore.Application/Tools/ToolCallScope.cs +++ b/src/AgentCore.Application/Tools/ToolCallScope.cs @@ -1,8 +1,8 @@ namespace AgentCore.Application.Tools; -/// The call a bound tool runs in. A binding declares a parameter of this type to receive it; the model never sees that parameter. -/// The call the turn belongs to. +/// The conversation a bound tool runs in. A binding declares a parameter of this type to receive it; the model never sees that parameter. +/// The conversation the turn belongs to. /// The zero-based index of the turn now running. -/// The stage the call's state machine holds. Empty when the document declares no policy. -/// The call's folder on disk, or when the host bound no workspace root. -public sealed record ToolCallScope(string CallId, int TurnIndex, string Stage, string? Workspace = null); +/// The stage the conversation's state machine holds. Empty when the document declares no policy. +/// The conversation's folder on disk, or when the host bound no workspace root. +public sealed record ToolCallScope(string ConversationId, int TurnIndex, string Stage, string? Workspace = null); diff --git a/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs b/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs index 0c95a6f5..77ff9ce0 100644 --- a/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs +++ b/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs @@ -1,6 +1,6 @@ using System.Runtime.CompilerServices; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Diagnostics; using AgentCore.Application.Ports; using Microsoft.Agents.AI; @@ -11,70 +11,70 @@ namespace AgentCore.Application.Transcript; /// -/// Reports one store 1 write that was dropped, so the call can raise a diagnostic for it. +/// Reports one store 1 write that was dropped, so the conversation can raise a diagnostic for it. /// internal delegate void TranscriptWriteDropped(int turnIndex, Exception exception); /// -/// Store 1: the words of a call, held for the session by the provider and written through to a backing store. +/// Store 1: the words of a conversation, held for the session by the provider and written through to a backing store. /// internal sealed class AgentCoreChatHistoryProvider : ChatHistoryProvider { - private readonly ConditionalWeakTable _gates = []; + private readonly ConditionalWeakTable _gates = []; - private readonly ICallStore _store; + private readonly IConversationStore _store; private readonly ILogger _logger; /// Creates the provider over a backing store. - public AgentCoreChatHistoryProvider(ICallStore? store = null, ILogger? logger = null) + public AgentCoreChatHistoryProvider(IConversationStore? store = null, ILogger? logger = null) { - _store = store ?? new InMemoryCallStore(); + _store = store ?? new InMemoryConversationStore(); _logger = logger ?? NullLogger.Instance; } /// - /// Opens a call on one session: names it, reads back what it already said, and says where a + /// Opens a conversation on one session: names it, reads back what it already said, and says where a /// dropped write is reported. /// - /// The session this call runs on. - /// The call being opened. + /// The session this conversation runs on. + /// The conversation being opened. /// - /// What store 1 already holds for this call, which is empty for a call that is new. A second - /// session of one call is handed the first session's words here, and nowhere else. + /// What store 1 already holds for this conversation, which is empty for a conversation that is new. A second + /// session of one conversation is handed the first session's words here, and nowhere else. /// /// Where a dropped store 1 write is reported, if anywhere. /// - /// How far the call had got, from store 0's own counters — or the zero marks of a call that has + /// How far the conversation had got, from store 0's own counters — or the zero marks of a conversation that has /// never spoken. The words cannot say this on their own, because an edit deletes the rows that /// would otherwise answer for it. /// - /// The index the next turn of this call takes. - public int BeginCall( + /// The index the next turn of this conversation takes. + public int BeginConversation( AgentSession session, - string callId, - IReadOnlyList spoken, + string conversationId, + IReadOnlyList spoken, TranscriptWriteDropped? report = null, TranscriptMarks marks = default) { ArgumentNullException.ThrowIfNull(session); - ArgumentException.ThrowIfNullOrEmpty(callId); + ArgumentException.ThrowIfNullOrEmpty(conversationId); ArgumentNullException.ThrowIfNull(spoken); return UnderLock( session, (transcript, gate) => { - transcript.CallId = callId; + transcript.ConversationId = conversationId; gate.Dropped = report; return transcript.Resume(spoken, marks); }); } - /// Reads the ordinal the session expects the call's next row to take. - /// The session this call runs on. + /// Reads the ordinal the session expects the conversation's next row to take. + /// The session this conversation runs on. /// /// The next free ordinal as the session counts it. Equal to store 0's own counter unless a row was /// written by someone else, or one of this session's own writes was dropped. @@ -87,13 +87,13 @@ public int NextOrdinal(AgentSession session) } /// - /// Replaces the call's live history with what store 1 now holds, so a later turn sees a row a + /// Replaces the conversation's live history with what store 1 now holds, so a later turn sees a row a /// host appended from outside any turn. /// - /// The session this call runs on. - /// Every stored message of the call, as store 1 now holds it. - /// The next free ordinal of the call, from store 0's own counter. - public void Resync(AgentSession session, IReadOnlyList rows, int nextOrdinal) + /// The session this conversation runs on. + /// Every stored message of the conversation, as store 1 now holds it. + /// The next free ordinal of the conversation, from store 0's own counter. + public void Resync(AgentSession session, IReadOnlyList rows, int nextOrdinal) { ArgumentNullException.ThrowIfNull(session); ArgumentNullException.ThrowIfNull(rows); @@ -124,7 +124,7 @@ public void BeginTurn(AgentSession session, int turnIndex) } /// - /// Reads the whole call, oldest message first. + /// Reads the whole conversation, oldest message first. /// public IReadOnlyList Read(AgentSession session) { @@ -133,19 +133,19 @@ public IReadOnlyList Read(AgentSession session) return UnderLock(session, static transcript => transcript.Read()); } - /// Adds one finished turn's messages to the call, and the state that follows them. - /// The session this call runs on. + /// Adds one finished turn's messages to the conversation, and the state that follows them. + /// The session this conversation runs on. /// The messages the turn produced. /// /// The state to store beside the words, or to store none. A value, read - /// by the caller before it calls: everything the turn writes to the state document — the clock + /// by the caller before it conversations: everything the turn writes to the state document — the clock /// fields, the counters, the stage and whether the machine finished — is already final when the - /// caller enters its commit lock, and the late barge-in path that runs after this call amends + /// caller enters its commit lock, and the late barge-in path that runs after this conversation amends /// the record of the turn without touching any of it. So there is nothing later to wait for. /// /// /// What the caller calls the first of these messages, or to name it in the - /// append. Only the first: the rest are this call's own words, which no caller had a name for. + /// append. Only the first: the rest are this conversation's own words, which no caller had a name for. /// /// /// The name the last of these messages was written under, so the caller can be told what to hang @@ -154,7 +154,7 @@ public IReadOnlyList Read(AgentSession session) public string? AppendTurn( AgentSession session, IReadOnlyList messages, - CallSessionState? state = null, + ConversationSessionState? state = null, string? firstMessageId = null) { ArgumentNullException.ThrowIfNull(session); @@ -172,28 +172,28 @@ public IReadOnlyList Read(AgentSession session) var rows = transcript.Append(messages, firstMessageId); var drafts = rows - .Select(row => new CallMessageDraft(row.TurnIndex, row.Content, row.MessageId)) + .Select(row => new ConversationMessageDraft(row.TurnIndex, row.Content, row.MessageId)) .ToArray(); Enqueue( gate, () => new ValueTask(_store.AppendAsync( - transcript.CallId, drafts, state, CancellationToken.None).AsTask()), + transcript.ConversationId, drafts, state, CancellationToken.None).AsTask()), transcript); return rows[^1].MessageId; }); } - /// Withdraws everything the call said after one message, because a caller replaced it. - /// The session this call runs on. + /// Withdraws everything the conversation said after one message, because a caller replaced it. + /// The session this conversation runs on. /// /// The message the caller's new words hang off. Everything after it goes. Pass - /// to withdraw the whole call, which is what an edit of its first message + /// to withdraw the whole conversation, which is what an edit of its first message /// asks for. /// /// /// The turns the withdrawal took, or when nothing went. Nothing goes when - /// the call holds no message of that name — a caller naming a message this host never stored — + /// the conversation holds no message of that name — a caller naming a message this host never stored — /// and the turn then runs as a plain new turn. /// public WithdrawnTurns? TruncateFrom(AgentSession session, string? parentMessageId) @@ -223,12 +223,12 @@ public IReadOnlyList Read(AgentSession session) return null; } - Log.CallTruncated(_logger, transcript.CallId, from, transcript.TurnIndex); + Log.ConversationTruncated(_logger, transcript.ConversationId, from, transcript.TurnIndex); Enqueue( gate, () => new ValueTask( - _store.TruncateAsync(transcript.CallId, from, CancellationToken.None).AsTask()), + _store.TruncateAsync(transcript.ConversationId, from, CancellationToken.None).AsTask()), transcript); return withdrawn; @@ -236,20 +236,20 @@ public IReadOnlyList Read(AgentSession session) } /// Adds the caller-facing turn of a graph row: what the caller said, and what it heard. - /// The session this call runs on. + /// The session this conversation runs on. /// What the caller said. /// What the caller heard, or when it heard nothing. /// /// The state to store beside the words, on the same terms as - /// . + /// . /// /// What the caller calls the message it sent, if it named one. - /// + /// public string? AppendCallerFacingTurn( AgentSession session, ChatMessage spoken, ChatMessage? heard, - CallSessionState? state = null, + ConversationSessionState? state = null, string? firstMessageId = null) { ArgumentNullException.ThrowIfNull(spoken); @@ -275,13 +275,13 @@ public bool TruncateLastReply(AgentSession session, string heard, TimeSpan playe return false; } - Log.ReplyTruncated(_logger, rows[0].CallId, rows[0].TurnIndex, played.TotalMilliseconds); + Log.ReplyTruncated(_logger, rows[0].ConversationId, rows[0].TurnIndex, played.TotalMilliseconds); foreach (var row in rows) { Enqueue( gate, - () => _store.RewriteAsync(row.CallId, row.MessageId, row.Content, CancellationToken.None), + () => _store.RewriteAsync(row.ConversationId, row.MessageId, row.Content, CancellationToken.None), transcript); } @@ -290,7 +290,7 @@ public bool TruncateLastReply(AgentSession session, string heard, TimeSpan playe } /// - /// Waits for every write this call has queued to reach the store. + /// Waits for every write this conversation has queued to reach the store. /// public Task DrainAsync(AgentSession session) { @@ -316,13 +316,13 @@ protected override ValueTask> ProvideChatHistoryAsync( protected override ValueTask StoreChatHistoryAsync( InvokedContext context, CancellationToken cancellationToken = default) => default; - /// Queues one store write behind everything this call has already queued. - private void Enqueue(CallGate gate, Func write, CallTranscript transcript) - => gate.Writes = WriteAfterAsync(gate.Writes, gate, write, transcript.CallId, transcript.TurnIndex); + /// Queues one store write behind everything this conversation has already queued. + private void Enqueue(ConversationGate gate, Func write, ConversationTranscript transcript) + => gate.Writes = WriteAfterAsync(gate.Writes, gate, write, transcript.ConversationId, transcript.TurnIndex); - /// Writes to the store, and lets the call outlive a store that refuses. + /// Writes to the store, and lets the conversation outlive a store that refuses. private async Task WriteAfterAsync( - Task previous, CallGate gate, Func write, string callId, int turnIndex) + Task previous, ConversationGate gate, Func write, string conversationId, int turnIndex) { await previous.ConfigureAwait(false); @@ -330,21 +330,21 @@ private async Task WriteAfterAsync( { await write().ConfigureAwait(false); } -#pragma warning disable CA1031 // A store 1 write failure never ends a call, and never breaks the chain behind it. +#pragma warning disable CA1031 // A store 1 write failure never ends a conversation, and never breaks the chain behind it. catch (Exception exception) #pragma warning restore CA1031 { - Log.TranscriptWriteFailed(_logger, callId, turnIndex, exception); + Log.TranscriptWriteFailed(_logger, conversationId, turnIndex, exception); - // The words are lost and the call is not. The report is what turns that into a fact the + // The words are lost and the conversation is not. The report is what turns that into a fact the // host can count; the contract of TranscriptWriteDropped is that it cannot throw, which // is what keeps this chain from ever faulting. gate.Dropped?.Invoke(turnIndex, exception); } } - /// Runs one piece of work against the call's transcript, alone. - private TResult UnderLock(AgentSession session, Func work) + /// Runs one piece of work against the conversation's transcript, alone. + private TResult UnderLock(AgentSession session, Func work) { var gate = GateFor(session); @@ -354,24 +354,24 @@ private TResult UnderLock(AgentSession session, Func(AgentSession session, Func work) + private TResult UnderLock(AgentSession session, Func work) => UnderLock(session, (transcript, _) => work(transcript)); - private CallGate GateFor(AgentSession session) => _gates.GetValue(session, static _ => new CallGate()); + private ConversationGate GateFor(AgentSession session) => _gates.GetValue(session, static _ => new ConversationGate()); - /// What one call holds outside its state bag: its lock, its transcript, and its queue of store writes. - private sealed class CallGate + /// What one conversation holds outside its state bag: its lock, its transcript, and its queue of store writes. + private sealed class ConversationGate { - /// Gets the lock every read and every change of this call's transcript takes. + /// Gets the lock every read and every change of this conversation's transcript takes. public Lock Sync { get; } = new(); - /// Gets the call's live transcript. It never enters the state bag, so serializing the bag stays small. - public CallTranscript Transcript { get; } = new(); + /// Gets the conversation's live transcript. It never enters the state bag, so serializing the bag stays small. + public ConversationTranscript Transcript { get; } = new(); - /// Gets or sets the tail of this call's store writes. It never faults. + /// Gets or sets the tail of this conversation's store writes. It never faults. public Task Writes { get; set; } = Task.CompletedTask; - /// Gets or sets where a dropped write of this call is reported, if anywhere. + /// Gets or sets where a dropped write of this conversation is reported, if anywhere. public TranscriptWriteDropped? Dropped { get; set; } } } diff --git a/src/AgentCore.Application/Transcript/CallMessage.cs b/src/AgentCore.Application/Transcript/ConversationMessage.cs similarity index 66% rename from src/AgentCore.Application/Transcript/CallMessage.cs rename to src/AgentCore.Application/Transcript/ConversationMessage.cs index c880850f..93734a8f 100644 --- a/src/AgentCore.Application/Transcript/CallMessage.cs +++ b/src/AgentCore.Application/Transcript/ConversationMessage.cs @@ -2,16 +2,16 @@ namespace AgentCore.Application.Transcript; -/// One stored message of one call. It is one row of store 1. -/// The call the message belongs to. +/// One stored message of one conversation. It is one row of store 1. +/// The conversation the message belongs to. /// -/// The message's position within the call. It is monotonic and never reused. It is not dense: an +/// The message's position within the conversation. It is monotonic and never reused. It is not dense: an /// edit deletes the rows it replaces and the ordinals they held are not issued again, because /// store 3 still holds audit rows against the turns those ordinals belonged to. /// /// The turn the message belongs to. It is the join to the audit chain. /// The message itself. -/// What this message is called. Unique within the call. +/// What this message is called. Unique within the conversation. /// /// It is the handle an edit names its parent by, and nothing else — AgentCore reads it for that and /// gives it no other meaning. A caller's own id is kept when one arrives, and one is minted when @@ -19,5 +19,5 @@ namespace AgentCore.Application.Transcript; /// host gives it one. /// /// -public sealed record CallMessage( - string CallId, int Ordinal, int TurnIndex, ChatMessage Content, string MessageId); +public sealed record ConversationMessage( + string ConversationId, int Ordinal, int TurnIndex, ChatMessage Content, string MessageId); diff --git a/src/AgentCore.Application/Transcript/CallMessageDraft.cs b/src/AgentCore.Application/Transcript/ConversationMessageDraft.cs similarity index 50% rename from src/AgentCore.Application/Transcript/CallMessageDraft.cs rename to src/AgentCore.Application/Transcript/ConversationMessageDraft.cs index c89e2375..9f6acdee 100644 --- a/src/AgentCore.Application/Transcript/CallMessageDraft.cs +++ b/src/AgentCore.Application/Transcript/ConversationMessageDraft.cs @@ -2,11 +2,11 @@ namespace AgentCore.Application.Transcript; -/// One message to write to a call. The store gives it its ordinal. +/// One message to write to a conversation. The store gives it its ordinal. /// /// The turn the message belongs to, or for a message written outside any -/// turn, which the store stamps with the turn the call's session takes next. +/// turn, which the store stamps with the turn the conversation's session takes next. /// /// The message itself. -/// What the message is called. Unique within the call. Never empty. -public sealed record CallMessageDraft(int? TurnIndex, ChatMessage Content, string MessageId); +/// What the message is called. Unique within the conversation. Never empty. +public sealed record ConversationMessageDraft(int? TurnIndex, ChatMessage Content, string MessageId); diff --git a/src/AgentCore.Application/Transcript/CallMessageIds.cs b/src/AgentCore.Application/Transcript/ConversationMessageIds.cs similarity index 85% rename from src/AgentCore.Application/Transcript/CallMessageIds.cs rename to src/AgentCore.Application/Transcript/ConversationMessageIds.cs index 18a63f4d..5d4504e0 100644 --- a/src/AgentCore.Application/Transcript/CallMessageIds.cs +++ b/src/AgentCore.Application/Transcript/ConversationMessageIds.cs @@ -1,7 +1,7 @@ namespace AgentCore.Application.Transcript; /// Mints the name a message takes when nobody names it. -public static class CallMessageIds +public static class ConversationMessageIds { /// Mints a new message id. public static string New() => Guid.CreateVersion7().ToString("n"); diff --git a/src/AgentCore.Application/Transcript/CallTranscript.cs b/src/AgentCore.Application/Transcript/ConversationTranscript.cs similarity index 76% rename from src/AgentCore.Application/Transcript/CallTranscript.cs rename to src/AgentCore.Application/Transcript/ConversationTranscript.cs index 5b5ea2f3..52891fe5 100644 --- a/src/AgentCore.Application/Transcript/CallTranscript.cs +++ b/src/AgentCore.Application/Transcript/ConversationTranscript.cs @@ -2,32 +2,32 @@ namespace AgentCore.Application.Transcript; -/// The words of one call, and the ordinals that address them. -internal sealed class CallTranscript +/// The words of one conversation, and the ordinals that address them. +internal sealed class ConversationTranscript { - /// Gets or sets the id of the call. The turn loop stamps it. - public string CallId { get; set; } = string.Empty; + /// Gets or sets the id of the conversation. The turn loop stamps it. + public string ConversationId { get; set; } = string.Empty; /// Gets or sets the zero-based index of the turn now running. The turn loop stamps it. public int TurnIndex { get; set; } - /// Gets or sets the next free ordinal of the call. + /// Gets or sets the next free ordinal of the conversation. public int NextOrdinal { get; set; } - /// Gets or sets the reply a barge-in would cut, or null when the call has spoken none. + /// Gets or sets the reply a barge-in would cut, or null when the conversation has spoken none. public int? LastAssistantOrdinal { get; set; } /// - /// Gets or sets the live history of the call, oldest first. It needs a setter, not just a getter: + /// Gets or sets the live history of the conversation, oldest first. It needs a setter, not just a getter: /// with no setter, System.Text.Json silently skips it on deserialize instead of populating it. /// public List Messages { get; set; } = []; - /// Reads a call that already has words back into a transcript that has none. - /// Every stored message of the call. Order does not matter. - /// How far the call had got, from the state stored beside these words. - /// The index the next turn of this call takes. - public int Resume(IReadOnlyList rows, TranscriptMarks marks) + /// Reads a conversation that already has words back into a transcript that has none. + /// Every stored message of the conversation. Order does not matter. + /// How far the conversation had got, from the state stored beside these words. + /// The index the next turn of this conversation takes. + public int Resume(IReadOnlyList rows, TranscriptMarks marks) { Resync(rows, marks.NextOrdinal); @@ -36,11 +36,11 @@ public int Resume(IReadOnlyList rows, TranscriptMarks marks) /// /// Replaces the live history with what store 1 now holds, without disturbing - /// or . + /// or . /// - /// Every stored message of the call, as store 1 now holds it. Order does not matter. - /// The next free ordinal of the call, from store 0's own counter. - public void Resync(IReadOnlyList rows, int nextOrdinal) + /// Every stored message of the conversation, as store 1 now holds it. Order does not matter. + /// The next free ordinal of the conversation, from store 0's own counter. + public void Resync(IReadOnlyList rows, int nextOrdinal) { ArgumentNullException.ThrowIfNull(rows); @@ -66,7 +66,7 @@ public void Resync(IReadOnlyList rows, int nextOrdinal) /// Finds the ordinal a message sits at, by the name a caller knows it under. /// What the caller calls the message. - /// The ordinal, or when the call holds no message of that name. + /// The ordinal, or when the conversation holds no message of that name. public int? OrdinalOf(string messageId) { ArgumentException.ThrowIfNullOrEmpty(messageId); @@ -75,7 +75,7 @@ public void Resync(IReadOnlyList rows, int nextOrdinal) ?.Ordinal; } - /// Withdraws the tail of the call, from one ordinal onward. + /// Withdraws the tail of the conversation, from one ordinal onward. /// The first ordinal to drop. It goes too. /// The turns the withdrawal took, or when nothing went. public WithdrawnTurns? TruncateFrom(int fromOrdinal) @@ -113,21 +113,21 @@ private void RestoreLastAssistantOrdinal() /// Opens a turn, so the rows it appends carry its index. public void BeginTurn(int turnIndex) => TurnIndex = turnIndex; - /// Reads the whole call, oldest message first. + /// Reads the whole conversation, oldest message first. public IReadOnlyList Read() => [.. Messages.Select(stored => stored.Message)]; - /// Adds new messages to the call, and returns the rows they became. + /// Adds new messages to the conversation, and returns the rows they became. /// The messages the turn produced, oldest first. /// /// What the caller calls the first of them, or to name it here. Only the /// first: it is the one the caller sent and so the only one the caller had a name for. /// - public IReadOnlyList Append( + public IReadOnlyList Append( IReadOnlyList messages, string? firstMessageId = null) { ArgumentNullException.ThrowIfNull(messages); - var rows = new List(messages.Count); + var rows = new List(messages.Count); for (var index = 0; index < messages.Count; index++) { var message = messages[index]; @@ -141,7 +141,7 @@ public IReadOnlyList Append( // included. Messages is the live history, serialised into the session state bag every // turn, so it never sees either: a multi-kilobyte RenderContent, or a SourceContent citing // a document, has no business growing that bag. - rows.Add(new CallMessage(CallId, ordinal, TurnIndex, message, messageId)); + rows.Add(new ConversationMessage(ConversationId, ordinal, TurnIndex, message, messageId)); Messages.Add(new StoredMessage { @@ -163,7 +163,7 @@ public IReadOnlyList Append( } /// Cuts the turn the caller was hearing down to the words the caller actually heard. - public IReadOnlyList TruncateLastReply(string heard) + public IReadOnlyList TruncateLastReply(string heard) { ArgumentNullException.ThrowIfNull(heard); @@ -173,7 +173,7 @@ public IReadOnlyList TruncateLastReply(string heard) return []; } - List rows = []; + List rows = []; foreach (var stored in Messages) { if (stored.TurnIndex != spoken.TurnIndex || stored.Message.Role != ChatRole.Assistant) @@ -193,26 +193,26 @@ public IReadOnlyList TruncateLastReply(string heard) corrected.Contents = isReply && heard.Length > 0 ? [new TextContent(heard), .. kept] : kept; stored.Message = corrected; - rows.Add(new CallMessage( - CallId, stored.Ordinal, stored.TurnIndex, corrected, stored.MessageId)); + rows.Add(new ConversationMessage( + ConversationId, stored.Ordinal, stored.TurnIndex, corrected, stored.MessageId)); } return rows; } /// Mints a name for a row the caller had no name for. - private static string NewMessageId() => CallMessageIds.New(); + private static string NewMessageId() => ConversationMessageIds.New(); /// One message of the live history, with the ordinal its stored row carries. internal sealed class StoredMessage { - /// Gets or sets the message's position within the call. + /// Gets or sets the message's position within the conversation. public int Ordinal { get; set; } /// Gets or sets the turn the message belongs to. It is the join to the audit chain. public int TurnIndex { get; set; } - /// Gets or sets the name this message is known by, inside the call and outside it. + /// Gets or sets the name this message is known by, inside the conversation and outside it. public string MessageId { get; set; } = string.Empty; /// Gets or sets the message. A barge-in replaces it with what the caller heard. diff --git a/src/AgentCore.Application/Transcript/TranscriptMarks.cs b/src/AgentCore.Application/Transcript/TranscriptMarks.cs index b89ca71b..a39b53ba 100644 --- a/src/AgentCore.Application/Transcript/TranscriptMarks.cs +++ b/src/AgentCore.Application/Transcript/TranscriptMarks.cs @@ -1,6 +1,6 @@ namespace AgentCore.Application.Transcript; -/// How far a call has got, in places rather than in counts. -/// The next ordinal the call issues. -/// The index the call's next turn takes. +/// How far a conversation has got, in places rather than in counts. +/// The next ordinal the conversation issues. +/// The index the conversation's next turn takes. internal readonly record struct TranscriptMarks(int NextOrdinal, int NextTurnIndex); diff --git a/src/AgentCore.AspNetCore/Call/.editorconfig b/src/AgentCore.AspNetCore/Call/.editorconfig deleted file mode 100644 index 326992e9..00000000 --- a/src/AgentCore.AspNetCore/Call/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -[*.cs] - -# CA1716: "Rename namespace AgentCore.AspNetCore.Call so that it no longer conflicts with the -# reserved language keyword 'Call'." This assembly does not target VB.NET or other languages that -# reserve the word, and the namespace name is deliberate: task 0 of the call-transport-seam plan -# renamed the call's text pipe out of Speech and into Call, matching the folder, and every later -# task in that plan depends on this name. -dotnet_diagnostic.CA1716.severity = none diff --git a/src/AgentCore.AspNetCore/Call/CallSeams.cs b/src/AgentCore.AspNetCore/Call/CallSeams.cs deleted file mode 100644 index 5ed11643..00000000 --- a/src/AgentCore.AspNetCore/Call/CallSeams.cs +++ /dev/null @@ -1,11 +0,0 @@ -using AgentCore.Application.Providers; - -namespace AgentCore.AspNetCore.Call; - -/// The names the call seam uses in every failure it raises. -internal static class CallSeams -{ - /// The providers.call seam. - public static readonly VendorSeam Call = - new("providers.call", "/providers/call/kind", "options.UseCall(...)"); -} diff --git a/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs b/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs deleted file mode 100644 index a1624595..00000000 --- a/src/AgentCore.AspNetCore/Call/ICallTransportAdapter.cs +++ /dev/null @@ -1,20 +0,0 @@ -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Ports; -using Microsoft.AspNetCore.Http; - -namespace AgentCore.AspNetCore.Call; - -/// -/// A call vendor this process is dialled in to, which therefore owns an inbound route. -/// -public interface ICallTransportAdapter : ICallAdapter -{ - /// Builds the handler the call route answers every entry with. - /// The providers.call block, including its limits. - /// - /// The delegate the call route runs. The URL names the entry, and the route has already - /// refused one the document does not declare; the handler reads it with - /// . - /// - RequestDelegate CreateHandler(CallProviderConfiguration configuration); -} diff --git a/src/AgentCore.AspNetCore/Call/ConnectionTaskObserver.cs b/src/AgentCore.AspNetCore/Conversation/ConnectionTaskObserver.cs similarity index 90% rename from src/AgentCore.AspNetCore/Call/ConnectionTaskObserver.cs rename to src/AgentCore.AspNetCore/Conversation/ConnectionTaskObserver.cs index 050df1ba..c64f62e2 100644 --- a/src/AgentCore.AspNetCore/Call/ConnectionTaskObserver.cs +++ b/src/AgentCore.AspNetCore/Conversation/ConnectionTaskObserver.cs @@ -1,4 +1,4 @@ -namespace AgentCore.AspNetCore.Call; +namespace AgentCore.AspNetCore.Conversation; /// Which task an observer is watching, so it logs the right line. internal enum ConnectionTaskKind @@ -12,14 +12,14 @@ internal enum ConnectionTaskKind /// The loop that writes the transport. WriteLoop, - /// The wait for the call to end: its words reach store 1, then its session goes. + /// The wait for the conversation to end: its words reach store 1, then its session goes. SessionClose, } /// /// Awaits the loops and turns of one connection, and never lets a fault go unobserved. /// -/// Names the call in a log line. A function, because the id arrives mid-call. +/// Names the conversation in a log line. A function, because the id arrives mid-conversation. /// Logs that a task passed its teardown deadline. /// Logs a fault this observer could not classify. /// @@ -28,7 +28,7 @@ internal enum ConnectionTaskKind /// to fall through to . It must not throw. /// internal sealed class ConnectionTaskObserver( - Func callId, + Func conversationId, Action logTimeout, Action logFault, Func classify) @@ -43,7 +43,7 @@ internal sealed class ConnectionTaskObserver( /// A task that completes once has been observed. /// /// A cancellation raised by the connection's own token is teardown that connection asked for - /// itself, so it stays quiet. Anything else is the silence a voice call must never answer with, + /// itself, so it stays quiet. Anything else is the silence a voice conversation must never answer with, /// per the house rule in . /// public async Task ObserveAsync(Task task, ConnectionTaskKind kind, TimeSpan? timeout = null) @@ -65,7 +65,7 @@ public async Task ObserveAsync(Task task, ConnectionTaskKind kind, TimeSpan? tim } catch (TimeoutException) when (timeout is not null) { - SafeLog(() => logTimeout(callId(), DisplayName(kind))); + SafeLog(() => logTimeout(conversationId(), DisplayName(kind))); // Task.WaitAsync removes its own continuation from task once the timeout fires, rather // than leaving one behind to observe a later fault: a probe confirmed this directly. So @@ -86,7 +86,7 @@ public async Task ObserveAsync(Task task, ConnectionTaskKind kind, TimeSpan? tim TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } - catch (Exception fault) when (SafeClassify(fault, kind, callId())) + catch (Exception fault) when (SafeClassify(fault, kind, conversationId())) { // The adapter recognised this one and logged it in its own words. It sits here, after // the two clauses above and before the general one below, because a cause a vendor can @@ -99,11 +99,11 @@ public async Task ObserveAsync(Task task, ConnectionTaskKind kind, TimeSpan? tim } } - /// Runs one log call, and never lets it break the teardown sequence around it. - /// The call to make, already bound to its logger and its arguments. + /// Runs one log conversation, and never lets it break the teardown sequence around it. + /// The conversation to make, already bound to its logger and its arguments. /// /// aggregates and rethrows a provider's own fault, so - /// even a line whose only job is to report a defect can itself throw. Every log call teardown + /// even a line whose only job is to report a defect can itself throw. Every log conversation teardown /// makes — cancelling the token, the close, an observed fault, a teardown timeout — sits behind /// this guard for that reason; logging exists to help diagnose a defect, and must never become a /// second one that stops the store removal or the rest of teardown from running. @@ -148,13 +148,13 @@ private void LogFault(ConnectionTaskKind kind, Exception? fault) return; } - SafeLog(() => logFault(kind, callId(), fault)); + SafeLog(() => logFault(kind, conversationId(), fault)); } /// Runs classify behind the same guard uses. /// The exception the adapter gets first refusal on. /// Which task faulted. - /// The call the fault belongs to. + /// The conversation the fault belongs to. /// /// when the adapter handled itself, and /// when it did not — including when it threw. diff --git a/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs b/src/AgentCore.AspNetCore/Conversation/ConversationEndpointRouteBuilderExtensions.cs similarity index 85% rename from src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs rename to src/AgentCore.AspNetCore/Conversation/ConversationEndpointRouteBuilderExtensions.cs index d50b0701..7ce63829 100644 --- a/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs +++ b/src/AgentCore.AspNetCore/Conversation/ConversationEndpointRouteBuilderExtensions.cs @@ -8,13 +8,13 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -namespace AgentCore.AspNetCore.Call; +namespace AgentCore.AspNetCore.Conversation; /// -/// Maps the inbound call route, with the URL naming the entry, onto whichever transport the +/// Maps the inbound conversation route, with the URL naming the entry, onto whichever transport the /// document names. /// -public static class CallEndpointRouteBuilderExtensions +public static class ConversationEndpointRouteBuilderExtensions { /// The route parameter that names the entry, as {entry} in a pattern. public const string EntryRouteParameter = "entry"; @@ -52,7 +52,7 @@ public static IEndpointConventionBuilder MapCall(this IEndpointRouteBuilder endp } /// Reads the entry the URL names, off the {entry} route parameter. - /// The request on a call route. + /// The request on a conversation route. /// The entry key, or the empty string when the route carries none. public static string EntryOf(HttpContext http) { @@ -70,14 +70,14 @@ private static Task DispatchAsync(HttpContext http, string pattern) return NotRoutedAsync(http, pattern, "this host registered no AgentCore services"); } - if (boot.CallHandler is not { } handler) + if (boot.ConversationHandler is not { } handler) { - return NotRoutedAsync(http, pattern, boot.CallUnroutable ?? "this host routes no inbound call"); + return NotRoutedAsync(http, pattern, boot.ConversationUnroutable ?? "this host routes no inbound conversation"); } var entry = EntryOf(http); - return boot.Entries.CallSessions.ContainsKey(entry) + return boot.Entries.ConversationSessions.ContainsKey(entry) ? handler(http) : UnknownEntryAsync(http, EntryRegistry.UnknownEntryMessage(entry, boot.Entries.Entries)); } @@ -85,11 +85,11 @@ private static Task DispatchAsync(HttpContext http, string pattern) private static async Task NotRoutedAsync(HttpContext http, string pattern, string reason) { var logger = (http.RequestServices.GetService() ?? NullLoggerFactory.Instance) - .CreateLogger(typeof(CallEndpointRouteBuilderExtensions).FullName!); + .CreateLogger(typeof(ConversationEndpointRouteBuilderExtensions).FullName!); - CallRouteLog.RouteNotMapped(logger, pattern, reason); + ConversationRouteLog.RouteNotMapped(logger, pattern, reason); - await WriteProblemAsync(http, StatusCodes.Status503ServiceUnavailable, "This host routes no inbound call.", reason, pattern) + await WriteProblemAsync(http, StatusCodes.Status503ServiceUnavailable, "This host routes no inbound conversation.", reason, pattern) .ConfigureAwait(false); } diff --git a/src/AgentCore.AspNetCore/Call/CallRouteLog.cs b/src/AgentCore.AspNetCore/Conversation/ConversationRouteLog.cs similarity index 61% rename from src/AgentCore.AspNetCore/Call/CallRouteLog.cs rename to src/AgentCore.AspNetCore/Conversation/ConversationRouteLog.cs index e34d067d..3bd1b11d 100644 --- a/src/AgentCore.AspNetCore/Call/CallRouteLog.cs +++ b/src/AgentCore.AspNetCore/Conversation/ConversationRouteLog.cs @@ -1,33 +1,33 @@ using Microsoft.Extensions.Logging; -namespace AgentCore.AspNetCore.Call; +namespace AgentCore.AspNetCore.Conversation; -/// The lines the call route writes while the host starts. +/// The lines the conversation route writes while the host starts. /// /// Source-generated by , as CA1848 asks. Silently leaving a /// route unmapped is how a deployment loses every call to a 404 with nothing to read, so each /// reason says so once. /// -internal static partial class CallRouteLog +internal static partial class ConversationRouteLog { - /// The host registered no call adapter, or loaded no document. - /// The logger of the map-time gate, not of any call. + /// The host registered no conversation adapter, or loaded no document. + /// The logger of the map-time gate, not of any conversation. /// The route this host asked for and did not get. /// What was missing, in the words a reader can act on. [LoggerMessage( EventId = 1, Level = LogLevel.Information, - Message = "the call route '{Pattern}' is not mapped: {Reason}.")] + Message = "the conversation route '{Pattern}' is not mapped: {Reason}.")] public static partial void RouteNotMapped(ILogger logger, string pattern, string reason); /// The document named a vendor this process dials out to, which owns no route. - /// The logger of the map-time gate, not of any call. - /// The providers.call.kind the document named. + /// The logger of the map-time gate, not of any conversation. + /// The providers.conversation.kind the document named. /// The route this host asked for and did not get. [LoggerMessage( EventId = 2, Level = LogLevel.Information, - Message = "providers.call names '{Kind}', which this process dials out to rather than " - + "being dialled in to, so the call route '{Pattern}' is not mapped.")] + Message = "providers.conversation names '{Kind}', which this process dials out to rather than " + + "being dialled in to, so the conversation route '{Pattern}' is not mapped.")] public static partial void DialOutVendorMapsNoRoute(ILogger logger, string kind, string pattern); } diff --git a/src/AgentCore.AspNetCore/Conversation/ConversationSeams.cs b/src/AgentCore.AspNetCore/Conversation/ConversationSeams.cs new file mode 100644 index 00000000..fcff8ac8 --- /dev/null +++ b/src/AgentCore.AspNetCore/Conversation/ConversationSeams.cs @@ -0,0 +1,11 @@ +using AgentCore.Application.Providers; + +namespace AgentCore.AspNetCore.Conversation; + +/// The names the conversation seam uses in every failure it raises. +internal static class ConversationSeams +{ + /// The providers.conversation seam. + public static readonly VendorSeam Conversation = + new("providers.conversation", "/providers/conversation/kind", "options.UseConversation(...)"); +} diff --git a/src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs b/src/AgentCore.AspNetCore/Conversation/ConversationTurnArbiter.cs similarity index 84% rename from src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs rename to src/AgentCore.AspNetCore/Conversation/ConversationTurnArbiter.cs index e07d3ea5..b6af0bc8 100644 --- a/src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs +++ b/src/AgentCore.AspNetCore/Conversation/ConversationTurnArbiter.cs @@ -1,29 +1,29 @@ using AgentCore.Application.Ports; -namespace AgentCore.AspNetCore.Call; +namespace AgentCore.AspNetCore.Conversation; /// -/// Decides which turn of one call may speak, and which one a barge-in cuts short. +/// Decides which turn of one conversation may speak, and which one a barge-in cuts short. /// /// /// /// The first of the two barge-in gates lives here: once a turn is marked interrupted this class -/// stops handing its fragments to . The last gate, immediately +/// stops handing its fragments to . The last gate, immediately /// before the wire, belongs to the port's own implementation and is expressed in that /// implementation's private vocabulary, so no turn id of this class ever crosses the port. /// /// -internal sealed class CallTurnArbiter +internal sealed class ConversationTurnArbiter { // Not readonly, and volatile for the same reason the connection's own session field is: a - // repeated setup frame replaces the call this arbiter runs turns against, and every turn that + // repeated setup frame replaces the conversation this arbiter runs turns against, and every turn that // starts after it must run against the replacement. One arbiter serves the whole connection, // across as many sessions as the vendor names, because "one turn at a time" is a property of // the transport and not of any one session: a second arbiter would carry its own _turnActive, // its own held prompt, and its own ids, and a prompt arriving while the replaced session's turn // still ran would start a second turn writing into the same channel. private volatile IConversationPort _session; - private readonly ICallOutputPort _output; + private readonly IConversationOutputPort _output; private readonly ConnectionTaskObserver _observer; private readonly Action _logPromptHeld; private readonly Action _logPendingPromptDropped; @@ -64,29 +64,29 @@ internal sealed class CallTurnArbiter private bool _turnActive; private string? _pendingPrompt; - /// What a voice caller hears when a tool waits on an approval the call cannot take. + /// What a voice caller hears when a tool waits on an approval the conversation cannot take. internal const string PendingApprovalNotice = - "That action needs a human approval, which this call can't take."; + "That action needs a human approval, which this conversation can't take."; - /// Builds the arbiter one call runs its turns through. - /// The call this arbiter runs turns against, until names another. + /// Builds the arbiter one conversation runs its turns through. + /// The conversation this arbiter runs turns against, until names another. /// Where a turn's reply goes, one fragment at a time. /// Watches a turn's task, and never lets its fault go unobserved. /// - /// Logs that one prompt was held until the turn in flight ends, given the id of the call it was + /// Logs that one prompt was held until the turn in flight ends, given the id of the conversation it was /// held for. Called once per held prompt, from inside the turn lock. /// /// - /// Logs that a further prompt was dropped because one was already held, given the id of the call + /// Logs that a further prompt was dropped because one was already held, given the id of the conversation /// it was dropped for. Called at most once per connection, from inside the turn lock. /// /// /// Cancelled once, for any reason the transport is going away. Every turn reads it, and no /// held prompt starts a turn after it fires. /// - public CallTurnArbiter( + public ConversationTurnArbiter( IConversationPort session, - ICallOutputPort output, + IConversationOutputPort output, ConnectionTaskObserver observer, Action logPromptHeld, Action logPendingPromptDropped, @@ -120,10 +120,10 @@ public Task CurrentTurn } } - /// Points this arbiter at another call, keeping every turn it is already running. - /// The call every turn started from now on runs against. + /// Points this arbiter at another conversation, keeping every turn it is already running. + /// The conversation every turn started from now on runs against. /// - /// For the one caller that needs it: a transport whose vendor names the call a second time on + /// For the one caller that needs it: a transport whose vendor names the conversation a second time on /// one connection. Only the session moves. _turnActive, the held prompt, the ids, and the /// log-once flag all stay exactly where they are, because "one turn at a time" and "one held /// prompt, logged once" are promises this connection makes for its whole life and not for one @@ -135,14 +135,14 @@ public Task CurrentTurn /// Starts a turn for what the caller just said, or holds it until the turn in flight ends. /// What the caller said. /// - /// The turn this call started, or a completed task when the prompt was held or dropped. It + /// The turn this conversation started, or a completed task when the prompt was held or dropped. It /// reports only completion: a turn's own fault stays on , which the /// next turn and teardown both already observe through . /// public Task StartTurnAsync(string text) { - // Read once, here, so the turn this call starts and the line it may log about holding the - // prompt both name the call the setup frame most recently gave this connection. + // Read once, here, so the turn this conversation starts and the line it may log about holding the + // prompt both name the conversation the setup frame most recently gave this connection. var session = _session; Task justFinished; @@ -153,14 +153,14 @@ public Task StartTurnAsync(string text) // The caller finished a second sentence before the agent spoke. There is no // interrupt frame for this, because the vendor never truncated anything, so there // is no heard text to record. IConversationPort throws on a second turn of one - // call, and a throw here would drop it, so one prompt is held and runs once the + // conversation, and a throw here would drop it, so one prompt is held and runs once the // turn in flight ends. Item 6a of section 11 draws the line at one: a queue of // held prompts would answer questions the caller has already moved past, so a // third prompt is dropped instead of queued behind the first. // // _turnActive, not _turn.IsCompleted: RunPendingPrompt runs inside RunTurnAsync's // own finally, strictly before that turn's Task itself transitions to completed, so - // a check against IsCompleted here could see "no turn running" for a call whose own + // a check against IsCompleted here could see "no turn running" for a conversation whose own // RunPendingPrompt had already run and found nothing pending — losing this prompt // outright, since nothing would ever come back to run it. _turnActive is cleared by // RunPendingPrompt in that same lock acquisition instead, so this check and that @@ -168,14 +168,14 @@ public Task StartTurnAsync(string text) if (_pendingPrompt is null) { _pendingPrompt = text; - _logPromptHeld(session.CallId); + _logPromptHeld(session.ConversationId); } else if (!_loggedPendingPromptDropped) { - // Log once for the call, not once for the frame. Same rule as the + // Log once for the conversation, not once for the frame. Same rule as the // unknown-frame line. _loggedPendingPromptDropped = true; - _logPendingPromptDropped(session.CallId); + _logPendingPromptDropped(session.ConversationId); } return Task.CompletedTask; @@ -192,20 +192,20 @@ public Task StartTurnAsync(string text) /// The text the caller actually heard, as the transport reported it. /// How much of the reply played, as the transport reported it. /// - /// when the call recorded the barge-in, against the running turn or + /// when the conversation recorded the barge-in, against the running turn or /// against the turn that finished last, and when there was nothing to /// record it against. /// /// /// Synchronous, and it stays synchronous. It marks the interrupted id, decides /// cutsRunningTurn, and calls before anything - /// awaits, and it hands 's task to the observer rather + /// awaits, and it hands 's task to the observer rather /// than awaiting it: this runs on the read loop, and a read loop that blocks cannot receive the /// next frame. /// public bool Interrupt(string heardText, TimeSpan playedDuration) { - // Read once, here, so the record goes to the call the setup frame most recently named — the + // Read once, here, so the record goes to the conversation the setup frame most recently named — the // same field, read at the same point, as when this method still lived on the connection. var session = _session; @@ -215,7 +215,7 @@ public bool Interrupt(string heardText, TimeSpan playedDuration) // Mark before cancelling. Every project that solves this race does it in this order: // a token already past the guard in RunTurnAsync must find its own id already marked // interrupted right here, not a cancellation that is still on its way to the model - // call. + // conversation. // // _spokenTurnId is what is marked, and never _turnId. The two differ exactly when a // held prompt fired: turn N finishes streaming, RunPendingPrompt starts turn N+1 inside @@ -233,7 +233,7 @@ public bool Interrupt(string heardText, TimeSpan playedDuration) Interlocked.Exchange(ref _interruptedTurnId, spoken); } - // The same comparison the mark above rests on, carried across the seam. CallSession + // The same comparison the mark above rests on, carried across the seam. ConversationSession // cannot reach it: it decides from whether the *running* turn is audible to it, and a // turn is audible to it the moment it hands over any content at all — a tool call, a // line of reasoning — none of which is a word the transport ever spoke. So turn N+1 can @@ -242,7 +242,7 @@ public bool Interrupt(string heardText, TimeSpan playedDuration) // both ids are known and already under the lock that guards them, is what puts the heard // text on turn N instead of on a turn nobody has heard one word of. // - // Zero answers false as well. Nothing of this call has reached the transport, so there + // Zero answers false as well. Nothing of this conversation has reached the transport, so there // is no running turn the caller was hearing, and cutting one short would destroy a reply // against nothing — the same rule the mark above already follows by staying put. cutsRunningTurn = spoken != 0 && spoken == Interlocked.Read(ref _turnId); @@ -265,14 +265,14 @@ public bool Interrupt(string heardText, TimeSpan playedDuration) } /// Observes the turn that just ended, then starts the next one and follows it to its end. - /// The call the turn this starts runs against. + /// The conversation the turn this starts runs against. /// What the caller said. - /// The turn this call read out of . - /// A task that completes when the turn this call starts completes. + /// The turn this conversation read out of . + /// A task that completes when the turn this conversation starts completes. private async Task StartAfterAsync(IConversationPort session, string text, Task justFinished) { - // A call runs many turns, and CurrentTurn only ever holds the most recent one. Observing the - // finished turn here is what stops a turn that faulted mid-call from being silently + // A conversation runs many turns, and CurrentTurn only ever holds the most recent one. Observing the + // finished turn here is what stops a turn that faulted mid-conversation from being silently // replaced by the next one before anything looks at it. The in-flight guard above only // proved _turnActive was false, not that justFinished itself has completed: RunPendingPrompt // clears _turnActive from inside RunTurnAsync's own finally, strictly before that turn's @@ -280,7 +280,7 @@ private async Task StartAfterAsync(IConversationPort session, string text, Task // while justFinished is still finishing the last step of its own async state machine. This // await can therefore still yield here, but only for as long as that tail takes to unwind — // microseconds — which is why it is safe to await inline rather than fire-and-forget. Only - // the very last turn of the call still relies on teardown's own observation. + // the very last turn of the conversation still relies on teardown's own observation. await _observer.ObserveAsync(justFinished, ConnectionTaskKind.Turn).ConfigureAwait(false); Task started; @@ -313,8 +313,8 @@ private async Task StartAfterAsync(IConversationPort session, string text, Task /// Runs one turn end to end, and streams its reply to the output port. /// - /// The call this turn runs against. Passed in rather than read off the field, so a turn already - /// in flight when names another call still finishes on the one it started on. + /// The conversation this turn runs against. Passed in rather than read off the field, so a turn already + /// in flight when names another conversation still finishes on the one it started on. /// /// What the caller said. /// The id this turn's output is marked with. @@ -341,10 +341,10 @@ private async Task RunTurnAsync(IConversationPort session, string text, long tur // interrupted. // // continue, not return: abandoning the enumeration here would dispose - // CallSession's own iterator from the outside, which unwinds it past the code that + // ConversationSession's own iterator from the outside, which unwinds it past the code that // records the interruption on LastTurn rather than through it. Session.Interrupt // already asked the model call to stop; this loop still has to drain whatever - // update that call already had in flight so CallSession reaches its own ending on + // update that call already had in flight so ConversationSession reaches its own ending on // its own terms. Every update after the raised id is read and thrown away instead // of queued, which is what keeps the queue itself from growing on a barge-in. if (Interlocked.Read(ref _interruptedTurnId) == turnId) @@ -369,7 +369,7 @@ private async Task RunTurnAsync(IConversationPort session, string text, long tur { if (session.LastTurn?.Approvals is { Count: > 0 }) { - // A tool waits on a human answer, and a voice call has no surface to give one. + // A tool waits on a human answer, and a voice conversation has no surface to give one. // Say so instead of hanging in the silence the pending turn speaks. await _output.SpeakAsync(PendingApprovalNotice, _connectionToken).ConfigureAwait(false); } @@ -382,9 +382,9 @@ private async Task RunTurnAsync(IConversationPort session, string text, long tur } catch (OperationCanceledException) { - // CallSession absorbs a barge-in's own cancellation internally and ends the turn + // ConversationSession absorbs a barge-in's own cancellation internally and ends the turn // normally, so what reaches here is the connection's own teardown token instead. The - // call itself goes on; only this turn stops. + // conversation itself goes on; only this turn stops. } finally { @@ -408,7 +408,7 @@ private void RunPendingPrompt() { // The connection is tearing down, so a fresh turn here would speak after the transport // stopped reading, and teardown's own read of CurrentTurn (also under this lock) may - // already have captured the task this call is inside of — leaving a turn nothing waits + // already have captured the task this conversation is inside of — leaving a turn nothing waits // for. The caller's last sentence goes unanswered either way once the socket is gone. if (_pendingPrompt is not { } held || _connectionToken.IsCancellationRequested) { @@ -420,7 +420,7 @@ private void RunPendingPrompt() var turnId = Interlocked.Increment(ref _turnId); // Read here and not captured when the prompt was held: a setup frame that named another - // call in between makes that call the one to answer, which is the rule the connection + // conversation in between makes that call the one to answer, which is the rule the connection // followed when this method still lived there. _turn = RunTurnAsync(_session, held, turnId); } diff --git a/src/AgentCore.AspNetCore/Conversation/IConversationTransportAdapter.cs b/src/AgentCore.AspNetCore/Conversation/IConversationTransportAdapter.cs new file mode 100644 index 00000000..a2a595f6 --- /dev/null +++ b/src/AgentCore.AspNetCore/Conversation/IConversationTransportAdapter.cs @@ -0,0 +1,20 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using Microsoft.AspNetCore.Http; + +namespace AgentCore.AspNetCore.Conversation; + +/// +/// A conversation vendor this process is dialled in to, which therefore owns an inbound route. +/// +public interface IConversationTransportAdapter : IConversationAdapter +{ + /// Builds the handler the conversation route answers every entry with. + /// The providers.conversation block, including its limits. + /// + /// The delegate the conversation route runs. The URL names the entry, and the route has already + /// refused one the document does not declare; the handler reads it with + /// . + /// + RequestDelegate CreateHandler(ConversationProviderConfiguration configuration); +} diff --git a/src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs b/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs similarity index 95% rename from src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs rename to src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs index f2c5b6e1..c753c765 100644 --- a/src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs +++ b/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs @@ -3,7 +3,7 @@ using System.Text.Json; using System.Threading.Channels; -namespace AgentCore.AspNetCore.Call; +namespace AgentCore.AspNetCore.Conversation; /// What reading one inbound message produced. /// The parsed frame, or when none was read. @@ -27,7 +27,7 @@ namespace AgentCore.AspNetCore.Call; /// What one pump may do, and for how long. /// The largest inbound message the pump accepts, in bytes. -/// How long the pump waits with no inbound message before it ends the call. +/// How long the pump waits with no inbound message before it ends the conversation. /// How long the close handshake may take before the socket is aborted. /// /// Builds the exception the pump throws when the peer broke the contract. The adapter supplies it, @@ -35,14 +35,14 @@ namespace AgentCore.AspNetCore.Call; /// still recognise it. /// /// -/// Logs a discriminator no case matched. The pump calls it once for the call, not once for the +/// Logs a discriminator no case matched. The pump calls it once for the conversation, not once for the /// frame, and passes the name; the line itself names the vendor, which is why it is a callback. /// /// -/// Logs a known discriminator whose body would not bind, on the same once-for-the-call rule as +/// Logs a known discriminator whose body would not bind, on the same once-for-the-conversation rule as /// . /// -/// Logs that the idle deadline, rather than teardown, ended the call. +/// Logs that the idle deadline, rather than teardown, ended the conversation. internal sealed record JsonWebSocketPumpOptions( int MaxFrameBytes, TimeSpan IdleTimeout, @@ -57,7 +57,7 @@ internal sealed record JsonWebSocketPumpOptions( /// /// /// -/// Moved out of the Telnyx connection with its comments intact. Every duplex call adapter reads +/// Moved out of the Telnyx connection with its comments intact. Every duplex conversation adapter reads /// one message at a time off a socket that fragments where it likes, sends from exactly one task /// because a WebSocket supports one send at a time, and closes on a bounded deadline — and none of /// that names a vendor. The three seams that would have are delegates: the parse, the exception @@ -87,7 +87,7 @@ internal sealed class JsonWebSocketPump( private bool _loggedUnknownFrame; private bool _loggedRefusedFrameBody; - /// Reads whole messages off the socket until the call ends, and hands each one over. + /// Reads whole messages off the socket until the conversation ends, and hands each one over. /// Reads one reassembled message, and never throws on what the peer sent. /// /// Takes one parsed frame. It is awaited, so a caller that must not block the loop — a turn, for @@ -95,7 +95,7 @@ internal sealed class JsonWebSocketPump( /// /// A task that completes when the socket, the idle deadline, or teardown ends the loop. /// - /// Returns rather than throws for every ordinary end of a call, including the idle deadline, so + /// Returns rather than throws for every ordinary end of a conversation, including the idle deadline, so /// a caller reading for its close status sees a fault only when /// something actually went wrong. /// @@ -118,7 +118,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) ValueWebSocketReceiveResult result; // The vendor never reconnects, so a socket with no inbound frame for IdleTimeout is - // a call that already ended, not a fault. The first receive of every message races + // a conversation that already ended, not a fault. The first receive of every message races // the deadline rather than being cancelled by one: a probe against a real Kestrel // WebSocket confirmed that cancelling ReceiveAsync's own token while it is pending // aborts the socket outright — WebSocketState.Aborted — which then makes the @@ -165,7 +165,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) // The receive won the race. Cancelling idling's own token here, rather than // leaving it to expire on its own after IdleTimeout, releases the timer behind it - // now instead of leaving one pending per message for as long as a busy call keeps + // now instead of leaving one pending per message for as long as a busy conversation keeps // sending faster than IdleTimeout — CancelAfter is never involved, so this touches // nothing outside this one local source. await idleCancel.CancelAsync().ConfigureAwait(false); @@ -221,7 +221,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) "the relay sent a frame this endpoint cannot parse."); } - // Log once for the call, not once for the frame. Section 3.1. + // Log once for the conversation, not once for the frame. Section 3.1. if (outcome.UnknownType is { } unmodelled) { if (!_loggedUnknownFrame) @@ -234,7 +234,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) { // A known type whose body will not bind. Section 7.1 treats a vendor that // changes a frame exactly as it treats one that adds a frame: the frame is - // refused, and the call goes on. + // refused, and the conversation goes on. _loggedRefusedFrameBody = true; options.LogRefusedFrameBody(outcome.RefusedType!); } @@ -260,7 +260,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) } } - /// Sends whatever the caller queues, one item at a time, until the call ends. + /// Sends whatever the caller queues, one item at a time, until the conversation ends. /// Whatever the caller queues. This pump never looks inside one. /// The queue the caller's own writers fill. /// @@ -334,7 +334,7 @@ public async Task CloseAsync(WebSocketCloseStatus status, string? description) try { // CloseOutputAsync, never CloseAsync. CloseAsync waits for the peer close frame, and a - // call that already dropped never sends one. + // conversation that already dropped never sends one. await socket .CloseOutputAsync(status, TruncateForCloseFrame(description), closeDeadline.Token) .ConfigureAwait(false); @@ -348,7 +348,7 @@ await socket } catch (WebSocketException) { - // The far end already went away. That is the end of a call, not a fault. + // The far end already went away. That is the end of a conversation, not a fault. } } @@ -375,7 +375,7 @@ await socket /// let a second renter receive the same array, and the first receive's own bytes then landed /// in it once the peer actually sent something, overwriting whatever the second renter had put /// there. is shared with every other read loop in this - /// process, including one on a completely different call, so that corruption is not confined + /// process, including one on a completely different conversation, so that corruption is not confined /// to this connection. Deferring the return until itself finishes /// — successfully, faulted, or cancelled, it makes no difference — is what keeps the array out /// of the pool for exactly as long as something can still write to it, never shorter. @@ -392,7 +392,7 @@ private static void ObserveAbandonedReceive(Task re // clearArray: true. The array still holds the caller's own words, and the pool it // goes back to is shared with Kestrel and with every other read loop in this - // process. D23 makes the audit chain the record of a call; a pooled buffer that + // process. D23 makes the audit chain the record of a conversation; a pooled buffer that // hands a transcript to the next renter is not a record, it is a leak. ArrayPool.Shared.Return(buffer, clearArray: true); }, diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index abcfae5a..dd59ada7 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -1,5 +1,5 @@ using AgentCore.Application.Audit; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; @@ -60,7 +60,7 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers, /// Gets the registry that compiled the document, and would compile it again. internal CompiledAgentRegistry CompiledRegistry => Started.Graph.Registry; - /// Gets the compiled entries, keyed by entry name. Every call shares them. + /// Gets the compiled entries, keyed by entry name. Every conversation shares them. internal IReadOnlyDictionary CompiledEntries => Started.Graph.Entries; /// Gets the factory the compile table asks for every agent and for the extractor. @@ -72,8 +72,8 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers, /// Gets the registry the compile table reads. internal ToolRegistry Tools => Started.Tools; - /// Gets the backing every call's row and every word of it is kept in. - internal CallRepository Calls => Started.Calls; + /// Gets the backing every conversation's row and every word of it is kept in. + internal Conversations Conversations => Started.Conversations; /// Gets the registry the turn loop reads, and the offline golden set alike. internal EvaluatorRegistry Evaluators => Started.Evaluators; @@ -93,14 +93,14 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers, /// Gets the blob store, or when the document names none. internal IBlobStore? Blobs => Started.Blobs; - /// Gets what the call route runs, or when no call routes here. - internal RequestDelegate? CallHandler => Started.CallHandler; + /// Gets what the conversation route runs, or when no conversation routes here. + internal RequestDelegate? ConversationHandler => Started.ConversationHandler; - /// Gets why no call routes here, or when calls route. - internal string? CallUnroutable => Started.CallUnroutable; + /// Gets why no conversation routes here, or when conversations route. + internal string? ConversationUnroutable => Started.ConversationUnroutable; - /// Gets the call transports the host registered, or if it registered none. - internal IReadOnlyList? CallAdapters => Started.CallAdapters; + /// Gets the conversation transports the host registered, or if it registered none. + internal IReadOnlyList? ConversationAdapters => Started.ConversationAdapters; /// Gets the speech vendors the host registered, or if it registered none. internal IReadOnlyList? SpeechAdapters => Started.SpeechAdapters; @@ -146,7 +146,7 @@ internal T Release(T resource) /// Loads the document, opens everything it names, and compiles it. /// Cancels the secret reads and the adapter builds. - /// A task that completes when the graph is ready to take a call. + /// A task that completes when the graph is ready to take a conversation. /// /// The options name no document, name two, or bind no chat client adapter. /// @@ -219,11 +219,11 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) ConfigurationValidator.ValidateSkillToolNames(configuration); - var store = Track(await CallStartup + var store = Track(await ConversationStartup .OpenAsync(configuration, _options, _loggers, cancellationToken) .ConfigureAwait(false)); - CallRepository calls = new(store, blobs); + Conversations conversations = new(store, blobs); var evaluators = await EvaluationStartup .CreateRegistryAsync(configuration, _options, cancellationToken) @@ -234,7 +234,7 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) configuration, chatClients, tools.Registry, - calls, + conversations, evaluators, knowledge, skills, @@ -245,9 +245,9 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) secrets) .ConfigureAwait(false); - var seams = CallSeamStartup.Build(configuration, _options); + var seams = ConversationSeamStartup.Build(configuration, _options); - var call = await CallSessionStartup + var conversation = await ConversationSessionStartup .OpenAsync(this, configuration, _options, graph, _loggers, cancellationToken) .ConfigureAwait(false); @@ -256,14 +256,14 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) secrets, telemetry, tools.Registry, - calls, + conversations, blobs, evaluators, graph, - call.Entries, - call.Queue, + conversation.Entries, + conversation.Queue, knowledge, - seams.Call, + seams.Conversation, seams.Speech, seams.Handler, seams.Unroutable); @@ -326,17 +326,17 @@ private sealed record BootState( ResolvedSecrets Secrets, ITelemetrySession? Telemetry, ToolRegistry Tools, - CallRepository Calls, + Conversations Conversations, IBlobStore? Blobs, EvaluatorRegistry Evaluators, CompiledGraph Graph, EntryRegistry Entries, QueuedAuditSink AuditQueue, IKnowledgeRetrievalPort? Knowledge, - IReadOnlyList? CallAdapters, + IReadOnlyList? ConversationAdapters, IReadOnlyList? SpeechAdapters, - RequestDelegate? CallHandler, - string? CallUnroutable); + RequestDelegate? ConversationHandler, + string? ConversationUnroutable); } /// Every line writes itself, below what each startup step logs. diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBootService.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBootService.cs index 49591fdc..5d693759 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBootService.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBootService.cs @@ -8,7 +8,7 @@ internal sealed class AgentCoreBootService(AgentCoreBoot boot) : IHostedLifecycl { /// Loads the document and opens everything it names. /// Cancels the secret reads and the adapter builds. - /// A task that completes when the graph is ready to take a call. + /// A task that completes when the graph is ready to take a conversation. public Task StartingAsync(CancellationToken cancellationToken) => boot.BootAsync(cancellationToken).AsTask(); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index 512f0730..b5ea3e26 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -16,7 +16,7 @@ public sealed class AgentCoreOptions { private readonly List> _toolSources = []; - private readonly List _observers = []; + private readonly List _observers = []; /// Gets the path of the configuration document, or . public string? ConfigurationPath { get; set; } @@ -66,8 +66,8 @@ public sealed class AgentCoreOptions /// Gets the audit sink vendors the host registered, or . internal IReadOnlyList? AuditSinks { get; private set; } - /// Gets the call store vendors the host registered, or . - internal IReadOnlyList? CallStores { get; private set; } + /// Gets the conversation store vendors the host registered, or . + internal IReadOnlyList? ConversationStores { get; private set; } /// Gets the blob store vendors the host registered, or . internal IReadOnlyList? BlobStores { get; private set; } @@ -81,39 +81,39 @@ public sealed class AgentCoreOptions /// Gets the skills source a host bound directly, or . internal AgentSkillsSource? SkillsSource { get; private set; } - /// Gets the call transports this host supports, or . - internal IReadOnlyList? CallAdapters { get; private set; } + /// Gets the conversation transports this host supports, or . + internal IReadOnlyList? ConversationAdapters { get; private set; } - /// Gets the folder under which every call gets its own workspace, or . + /// Gets the folder under which every conversation gets its own workspace, or . internal string? WorkspaceRoot { get; private set; } /// Gets the extra tool sources, in the order the registry asks them. internal IReadOnlyList> ToolSources => _toolSources; /// Gets the observers the host registered, in the order it registered them. - internal IReadOnlyList Observers => _observers; + internal IReadOnlyList Observers => _observers; /// Gets the store opener the host bound, or for the in-memory default. - internal Func? CallSessions { get; private set; } + internal Func? ConversationSessions { get; private set; } /// Binds the session store, one per entry. /// /// Opens the store for one entry. It takes the entry name and the factory that builds that - /// entry's sessions, and it runs once per entry the document declares. Each call must return a + /// entry's sessions, and it runs once per entry the document declares. Each conversation must return a /// distinct store: two entries that share one store let a vendor call id arriving on both /// entries read one call through two shapes. /// - /// These options, so a host chains its calls. - public AgentCoreOptions UseCallSessions(Func open) + /// These options, so a host chains its conversations. + public AgentCoreOptions UseConversationSessions(Func open) { ArgumentNullException.ThrowIfNull(open); - CallSessions = open; + ConversationSessions = open; return this; } /// Binds the vendor adapters, and the document picks one by each entry's kind. /// One adapter for each vendor this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseChatClients(params IChatClientAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -124,7 +124,7 @@ public AgentCoreOptions UseChatClients(params IChatClientAdapter[] adapters) /// Binds the adapter that turns a model reference into a chat client. /// Builds the adapter from the loaded document, without a wait. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseChatClients(Func chatClients) { ArgumentNullException.ThrowIfNull(chatClients); @@ -133,7 +133,7 @@ public AgentCoreOptions UseChatClients(FuncBinds the adapter that turns a model reference into a chat client, with a wait. /// Builds the adapter from the loaded document. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseChatClients(Func> chatClients) { ArgumentNullException.ThrowIfNull(chatClients); @@ -143,7 +143,7 @@ public AgentCoreOptions UseChatClients(FuncBinds the embedding vendors, and the document picks one by providers.embeddings.kind. /// One adapter for each embedding vendor this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseEmbeddings(params IEmbeddingGeneratorAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -153,7 +153,7 @@ public AgentCoreOptions UseEmbeddings(params IEmbeddingGeneratorAdapter[] adapte /// Binds the knowledge vendors, and the document picks one by providers.knowledge.kind. /// One adapter for each knowledge vendor this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseKnowledgeStores(params IKnowledgeStoreAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -163,7 +163,7 @@ public AgentCoreOptions UseKnowledgeStores(params IKnowledgeStoreAdapter[] adapt /// Binds the adapter that beats the providers.knowledge.kind registry. /// Builds the adapter from the loaded document. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseKnowledgeRetrieval(Func retrieval) { ArgumentNullException.ThrowIfNull(retrieval); @@ -200,7 +200,7 @@ public AgentCoreOptions UseKnowledgeCitationFormatters(params IKnowledgeCitation /// Binds the moderation vendors, and the document picks one by kind. /// The vendors this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseModeration(params IModerationAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -210,7 +210,7 @@ public AgentCoreOptions UseModeration(params IModerationAdapter[] adapters) /// Binds the telemetry vendors, and the document picks one by kind. /// The vendors this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseTelemetry(params ITelemetryAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -220,7 +220,7 @@ public AgentCoreOptions UseTelemetry(params ITelemetryAdapter[] adapters) /// Binds the audit sink vendors, and the document picks one by kind. /// The vendors this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseAuditSinks(params IAuditSinkAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -228,19 +228,19 @@ public AgentCoreOptions UseAuditSinks(params IAuditSinkAdapter[] adapters) return this; } - /// Binds the call store vendors, and the document picks one by kind. + /// Binds the conversation store vendors, and the document picks one by kind. /// The vendors this host supports. - /// These options, so a host chains its calls. - public AgentCoreOptions UseCallStores(params ICallStoreAdapter[] adapters) + /// These options, so a host chains its conversations. + public AgentCoreOptions UseConversationStores(params IConversationStoreAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); - CallStores = adapters; + ConversationStores = adapters; return this; } /// Binds the blob store vendors, and the document picks one by providers.blobs.kind. /// The vendors this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseBlobStores(params IBlobStoreAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -248,13 +248,13 @@ public AgentCoreOptions UseBlobStores(params IBlobStoreAdapter[] adapters) return this; } - /// Binds the host's own readings of a call, beside the three this library keeps. + /// Binds the host's own readings of a conversation, beside the three this library keeps. /// - /// What the host wants told about every call. Each one takes every fact, in the order the call + /// What the host wants told about every conversation. Each one takes every fact, in the order the conversation /// produced it. An empty set is legal and registers nothing. /// - /// These options, so a host chains its calls. - public AgentCoreOptions UseObservers(params ICallObserver[] observers) + /// These options, so a host chains its conversations. + public AgentCoreOptions UseObservers(params IConversationObserver[] observers) { ArgumentNullException.ThrowIfNull(observers); _observers.AddRange(observers); @@ -263,7 +263,7 @@ public AgentCoreOptions UseObservers(params ICallObserver[] observers) /// Binds the speech vendors, and the document picks one by kind. /// The vendors this host supports. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions UseSpeech(params ISpeechAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); @@ -289,13 +289,13 @@ public AgentCoreOptions UseSkills(AgentSkillsSource source) return this; } - /// Lists the vendors that may carry a call, so providers.call.kind can pick one. + /// Lists the vendors that may carry a conversation, so providers.conversation.kind can pick one. /// The transports this host supports. - /// These options, so a host chains its calls. - public AgentCoreOptions UseCall(params ICallAdapter[] adapters) + /// These options, so a host chains its conversations. + public AgentCoreOptions UseConversation(params IConversationAdapter[] adapters) { ArgumentNullException.ThrowIfNull(adapters); - CallAdapters = adapters; + ConversationAdapters = adapters; return this; } @@ -306,7 +306,7 @@ public AgentCoreOptions UseCall(params ICallAdapter[] adapters) /// , the composition root closes it when the host stops. Do not return an /// instance the host still needs after that. /// - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. public AgentCoreOptions AddToolSource(Func toolSource) { ArgumentNullException.ThrowIfNull(toolSource); @@ -315,8 +315,8 @@ public AgentCoreOptions AddToolSource(Func toolSo } /// - /// Binds the folder under which every call gets its own workspace directory, - /// <root>/<callId>/, created with the call and deleted when the call ends. + /// Binds the folder under which every conversation gets its own workspace directory, + /// <root>/<conversationId>/, created with the conversation and deleted when the conversation ends. /// public AgentCoreOptions UseWorkspace(string root) { @@ -328,7 +328,7 @@ public AgentCoreOptions UseWorkspace(string root) /// Registers one host delegate behind a binds: name. /// The name a binds: field writes, such as CreateCase. /// The delegate the tool calls. - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. /// The name is already registered. public AgentCoreOptions Bind(string name, ToolBinding binding) { @@ -341,10 +341,10 @@ public AgentCoreOptions Bind(string name, ToolBinding binding) /// /// The method the tool calls. Its parameters are the arguments the model fills, and their JSON /// Schema, so the declaration writes no parameters:. A parameter of type - /// is filled by the runtime with the call the turn belongs to, and + /// is filled by the runtime with the conversation the turn belongs to, and /// is not exposed to the model. /// - /// These options, so a host chains its calls. + /// These options, so a host chains its conversations. /// The name is already registered. public AgentCoreOptions Bind(string name, Delegate method) { diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs index b9c72656..f5df141b 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs @@ -1,5 +1,5 @@ using AgentCore.Application.Audit; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Evaluation; using AgentCore.Application.Ports; @@ -20,10 +20,10 @@ namespace AgentCore.AspNetCore.DependencyInjection; /// public static class AgentCoreServiceCollectionExtensions { - /// Registers everything a call needs, and loads the document when the host starts. + /// Registers everything a conversation needs, and loads the document when the host starts. /// The service collection of the host. /// Binds the document and the adapters the document names. - /// The same collection, so a host chains its calls. + /// The same collection, so a host chains its conversations. public static IServiceCollection AddAgentCore( this IServiceCollection services, Action configure) @@ -45,14 +45,15 @@ public static IServiceCollection AddAgentCore( services.AddSingleton(Boot(boot => boot.ChatClients)); services.AddSingleton(Boot(boot => boot.Guards)); services.AddSingleton(Boot(boot => boot.Tools)); - services.AddSingleton(Boot(boot => boot.Calls)); - services.AddSingleton(provider => provider.GetRequiredService()); + services.AddSingleton(Boot(boot => boot.Conversations)); + services.AddSingleton(provider => provider.GetRequiredService()); + services.AddSingleton(provider => provider.GetRequiredService()); services.AddSingleton(Boot(boot => boot.Entries)); - services.AddSingleton(provider => provider.GetRequiredService()); + services.AddSingleton(provider => provider.GetRequiredService()); services.AddSingleton(Boot(boot => boot.AuditQueue)); services.TryAddSingleton(provider => - new AgentCoreAgentSessionStore(provider.GetRequiredService())); + new AgentCoreAgentSessionStore(provider.GetRequiredService())); services.TryAddSingleton(provider => provider.GetRequiredService()); @@ -63,21 +64,21 @@ public static IServiceCollection AddAgentCore( services.AddSingleton(Boot(boot => boot.Telemetry!)); services.AddSingleton(Boot(boot => boot.Knowledge!)); services.AddSingleton(Boot(boot => boot.Blobs!)); - services.AddSingleton(Boot(boot => boot.CallAdapters!)); + services.AddSingleton(Boot(boot => boot.ConversationAdapters!)); services.AddSingleton(Boot(boot => boot.SpeechAdapters!)); services.TryAddSingleton(provider => provider.GetRequiredService>().Value.TimeProvider ?? TimeProvider.System); - services.AddHostedService(provider => new CallSessionSweeper( + services.AddHostedService(provider => new ConversationSessionSweeper( provider, provider.GetRequiredService(), - provider.GetService()?.CreateLogger() - ?? NullLogger.Instance)); + provider.GetService()?.CreateLogger() + ?? NullLogger.Instance)); - services.TryAddSingleton(provider => new ChatCallTitler( - provider.GetRequiredService(), + services.TryAddSingleton(provider => new ChatConversationTitler( + provider.GetRequiredService(), provider.GetRequiredService() .GetChatClient(provider.GetRequiredService().Titler?.Model))); @@ -92,9 +93,9 @@ public static IServiceCollection AddAgentCore( return services; } - /// Registers WebSocket options that suit a phone call rather than a browser tab. + /// Registers WebSocket options that suit a phone conversation rather than a browser tab. /// The service collection of the host. - /// The same collection, so a host chains its calls. + /// The same collection, so a host chains its conversations. public static IServiceCollection AddAgentCoreWebSockets(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); @@ -109,7 +110,7 @@ public static IServiceCollection AddAgentCoreWebSockets(this IServiceCollection /// Reads one thing out of the boot, once the host has started it. /// What the caller is registering. /// Picks it off the started boot. - /// A factory the container calls on first resolve. + /// A factory the container conversations on first resolve. private static Func Boot(Func read) where T : class => provider => diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ChatClientStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ChatClientStartup.cs index c0de2c81..2644ec58 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ChatClientStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ChatClientStartup.cs @@ -6,7 +6,7 @@ namespace AgentCore.AspNetCore.DependencyInjection; /// /// It is built from the document and the resolved secrets and from nothing else, so it can be built /// before the tools. That ordering is what lets a shipped agent hold its own model rather than -/// looking one up at call time. +/// looking one up at conversation time. /// internal static class ChatClientStartup { diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs index 0aef3b6f..4e4f0186 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -16,21 +16,21 @@ namespace AgentCore.AspNetCore.DependencyInjection; /// The factory the compile table asks for every agent and for the extractor. /// The shared evaluator. It holds no state of its own. /// The registry that compiled the document, and would compile it again. -/// The compiled entries, keyed by entry name. Every call shares them. +/// The compiled entries, keyed by entry name. Every conversation shares them. internal readonly record struct CompiledGraph( IChatClientFactory ChatClients, GuardEvaluator Guards, CompiledAgentRegistry Registry, IReadOnlyDictionary Entries); -/// Step 5: compile the document once, so every call shares the result. +/// Step 5: compile the document once, so every conversation shares the result. internal static class CompilationStartup { /// Compiles every entry of the document against the tools and the chat clients already built. /// The loaded document. /// The factory step 3c built, which the compile table asks for every agent and for the extractor. /// The registry step 4 built. - /// The store every call's row and every word of it is kept in. + /// The store every conversation's row and every word of it is kept in. /// /// The registry the moderator comes out of. R3 puts moderation in the chat pipeline of every /// compiled agent, so it is bound here rather than on the session factory. @@ -48,7 +48,7 @@ internal static ValueTask CompileAsync( AgentCoreConfiguration configuration, IChatClientFactory chatClients, ToolRegistry tools, - ICallStore calls, + IConversationStore conversations, EvaluatorRegistry evaluators, IKnowledgeRetrievalPort? knowledge, SkillCatalog? skills, @@ -68,7 +68,7 @@ internal static ValueTask CompileAsync( Tools = tools, Guards = guards, Moderation = PromptModerator.FromRegistry(evaluators), - CallStore = calls, + ConversationStore = conversations, Knowledge = knowledge, Skills = skills, Citations = citations, diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationSeamStartup.cs similarity index 59% rename from src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs rename to src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationSeamStartup.cs index e6008eca..2639ed8f 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationSeamStartup.cs @@ -1,15 +1,15 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using AgentCore.Application.Providers; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using Microsoft.AspNetCore.Http; namespace AgentCore.AspNetCore.DependencyInjection.Startup; -/// What the call seam produced while the host started. -/// The transports registered. +/// What the conversation seam produced while the host started. +/// The transports registered. /// /// The vendors registered, selected by nothing. /// providers.speech names the recognition vendor and the synthesis vendor, but no code in @@ -19,44 +19,44 @@ namespace AgentCore.AspNetCore.DependencyInjection.Startup; /// /// /// What the MapCall route runs for every entry, or when this -/// document routes no inbound call — the host registered no transport, wrote no -/// providers.call block, or named a vendor this process dials out to, which has no inbound URL. +/// document routes no inbound conversation — the host registered no transport, wrote no +/// providers.conversation block, or named a vendor this process dials out to, which has no inbound URL. /// /// /// Why is , in the words a deployer can act on, or -/// when calls route. +/// when conversations route. /// -internal readonly record struct CallSeamAdapters( - IReadOnlyList? Call, +internal readonly record struct ConversationSeamAdapters( + IReadOnlyList? Conversation, IReadOnlyList? Speech, RequestDelegate? Handler, string? Unroutable); -/// The two provider blocks a call arrives on: providers.call and providers.speech. -internal static class CallSeamStartup +/// The two provider blocks a conversation arrives on: providers.conversation and providers.speech. +internal static class ConversationSeamStartup { /// Checks the two blocks agree, and hands back the vendor lists and the handler to register. /// The loaded document. It carries both provider blocks. /// The options the host filled. It carries the registered vendors. /// The two lists and the handler, each one or when the host registered none. - internal static CallSeamAdapters Build( + internal static ConversationSeamAdapters Build( AgentCoreConfiguration configuration, AgentCoreOptions options) { - if (options.CallAdapters is not { } callAdapters) + if (options.ConversationAdapters is not { } conversationAdapters) { - return new CallSeamAdapters( - null, options.Speech, null, "this host registered no call adapter"); + return new ConversationSeamAdapters( + null, options.Speech, null, "this host registered no conversation adapter"); } // Registering a vendor is what turns this seam on. A host that registered none is not asked // what its document says, exactly as telemetry, knowledge, and moderation are not read when // a host registered no adapter for them. - var callEntry = configuration.Providers?.Call - ?? throw MissingCallBlock(); + var conversationEntry = configuration.Providers?.Conversation + ?? throw MissingConversationBlock(); - var selectedCall = VendorAdapterSelector.Select( - callEntry.Kind, callAdapters, CallSeams.Call); + var selectedConversation = VendorAdapterSelector.Select( + conversationEntry.Kind, conversationAdapters, ConversationSeams.Conversation); var speechEntry = configuration.Providers?.Speech ?? throw MissingSpeechBlock(); @@ -64,47 +64,47 @@ internal static CallSeamAdapters Build( // Read here, and not only where the route is mapped. Agreement between two document entries // is a document fact: it is true or false whether or not anything is routed, so a host that // forgets app.MapCall() still learns its document contradicts itself. - CallSpeechPairing.Validate(callEntry, speechEntry, selectedCall); + ConversationSpeechPairing.Validate(conversationEntry, speechEntry, selectedConversation); - // Built here and not where the route is mapped, so an unusable limit in providers.call stops - // the host rather than the first call that arrives on it. A vendor this process dials out to + // Built here and not where the route is mapped, so an unusable limit in providers.conversation stops + // the host rather than the first conversation that arrives on it. A vendor this process dials out to // has no inbound URL, and that is not a failure: it is the other half of the seam working. - if (selectedCall is not ICallTransportAdapter transport) + if (selectedConversation is not IConversationTransportAdapter transport) { - return new CallSeamAdapters( - callAdapters, + return new ConversationSeamAdapters( + conversationAdapters, options.Speech, null, - $"'{selectedCall.Kind}' is a vendor this process dials out to, so it answers no inbound route"); + $"'{selectedConversation.Kind}' is a vendor this process dials out to, so it answers no inbound route"); } - return new CallSeamAdapters(callAdapters, options.Speech, transport.CreateHandler(callEntry), null); + return new ConversationSeamAdapters(conversationAdapters, options.Speech, transport.CreateHandler(conversationEntry), null); } - /// Refuses a configuration that turned the call seam on and named no transport. + /// Refuses a configuration that turned the conversation seam on and named no transport. /// The failure to throw, pointed at the block that is missing. - private static ConfigurationLoadException MissingCallBlock() + private static ConfigurationLoadException MissingConversationBlock() => new(new ConfigurationError { - Pointer = "/providers/call", + Pointer = "/providers/conversation", Message = - "This host registered a call transport with options.UseCall(...), and this " - + "configuration writes no providers.call block for a kind to be picked from. A " - + "document that writes a providers section names both call and speech, because the " + "This host registered a conversation transport with options.UseConversation(...), and this " + + "configuration writes no providers.conversation block for a kind to be picked from. A " + + "document that writes a providers section names both conversation and speech, because the " + "schema requires them there; a document that writes no providers section at all is " + "valid, and so is a configuration a host built in code, which passes through no " - + "schema. Write providers.call: { kind: ... }, or drop the options.UseCall(...) call.", + + "schema. Write providers.conversation: { kind: ... }, or drop the options.UseConversation(...) call.", Check = ConfigurationCheck.ReferenceResolution, }); - /// Refuses a configuration whose call transport has no speech block to be paired with. + /// Refuses a configuration whose conversation transport has no speech block to be paired with. /// The failure to throw, pointed at the block that is missing. private static ConfigurationLoadException MissingSpeechBlock() => new(new ConfigurationError { Pointer = "/providers/speech", Message = - "This configuration names providers.call and no providers.speech, so there is " + "This configuration names providers.conversation and no providers.speech, so there is " + "nothing to check the transport against: a transport that carries text is itself " + "the recognizer, and one that carries audio needs a speech vendor named. A " + "document that writes a providers section names both, because the schema requires " diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationSessionStartup.cs similarity index 73% rename from src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs rename to src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationSessionStartup.cs index 4fad9998..32318ed9 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationSessionStartup.cs @@ -9,14 +9,14 @@ namespace AgentCore.AspNetCore.DependencyInjection.Startup; -/// Everything the call seam opened: the audit chain, and one session factory per entry. +/// Everything the conversation seam opened: the audit chain, and one session factory per entry. /// One factory, one agent, and one session store per entry, keyed by entry name. /// The queue that answers the audit port, not the store behind it. -internal readonly record struct CallSessionSeam( +internal readonly record struct ConversationSessionSeam( EntryRegistry Entries, QueuedAuditSink Queue); -/// The seam a call arrives on: the audit queue, the observers, and one session factory per entry. -internal static class CallSessionStartup +/// The seam a conversation arrives on: the audit queue, the observers, and one session factory per entry. +internal static class ConversationSessionStartup { /// Opens the audit store the document names and builds one session factory per entry over it. /// The owner the audit chain is tracked against. @@ -26,7 +26,7 @@ internal static class CallSessionStartup /// The factory the session and the audit queue take their loggers from. /// Cancels the store open. /// The per-entry seams, and the queue in front of the store. - internal static async ValueTask OpenAsync( + internal static async ValueTask OpenAsync( AgentCoreBoot boot, AgentCoreConfiguration configuration, AgentCoreOptions options, @@ -49,7 +49,7 @@ internal static async ValueTask OpenAsync( QueuedAuditSink auditSink = boot.Track(new QueuedAuditSink(store, loggers.CreateLogger())); - var sessionLogger = loggers.CreateLogger(); + var sessionLogger = loggers.CreateLogger(); if (options.WorkspaceRoot is { } root) { @@ -67,19 +67,19 @@ internal static async ValueTask OpenAsync( } } - var observers = CallObservers.Standard(auditSink, sessionLogger, options.Observers); + var observers = ConversationObservers.Standard(auditSink, sessionLogger, options.Observers); var timeProvider = options.TimeProvider ?? TimeProvider.System; - Dictionary factories = new(StringComparer.Ordinal); + Dictionary factories = new(StringComparer.Ordinal); Dictionary agents = new(StringComparer.Ordinal); - Dictionary sessions = new(StringComparer.Ordinal); + Dictionary sessions = new(StringComparer.Ordinal); foreach (var (entryName, compiled) in graph.Entries) { - CallSessionFactory factory = new( + ConversationSessionFactory factory = new( compiled, graph.Guards, - CallSessionFactory.CreateExtractor(compiled, graph.ChatClients), + ConversationSessionFactory.CreateExtractor(compiled, graph.ChatClients), options.TimeProvider, sessionLogger, observers, @@ -87,11 +87,11 @@ internal static async ValueTask OpenAsync( factories[entryName] = factory; agents[entryName] = new AgentCoreAgent(factory, entryName); - sessions[entryName] = options.CallSessions?.Invoke(entryName, factory) - ?? new InMemoryCallSessions( - factory, InMemoryCallSessions.DefaultIdleTimeout, timeProvider); + sessions[entryName] = options.ConversationSessions?.Invoke(entryName, factory) + ?? new InMemoryConversationSessions( + factory, InMemoryConversationSessions.DefaultIdleTimeout, timeProvider); } - return new CallSessionSeam(new EntryRegistry(factories, agents, sessions), auditSink); + return new ConversationSessionSeam(new EntryRegistry(factories, agents, sessions), auditSink); } } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationStartup.cs similarity index 59% rename from src/AgentCore.AspNetCore/DependencyInjection/Startup/CallStartup.cs rename to src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationStartup.cs index 1fef4e1f..b6f3d2a9 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConversationStartup.cs @@ -1,5 +1,5 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using Microsoft.Extensions.Logging; @@ -7,31 +7,31 @@ namespace AgentCore.AspNetCore.DependencyInjection.Startup; /// Step 4c: open the store 0 backing the document names, before the document is compiled. -internal static class CallStartup +internal static class ConversationStartup { - /// Opens the store providers.calls names, or the built-in one. - /// The loaded document. It carries providers.calls. - /// The options the host filled. It carries the call store vendors. + /// Opens the store providers.conversations names, or the built-in one. + /// The loaded document. It carries providers.conversations. + /// The options the host filled. It carries the conversation store vendors. /// The factory the defaulting warning is written through. /// Cancels the store open. /// The store, which is never . - internal static async ValueTask OpenAsync( + internal static async ValueTask OpenAsync( AgentCoreConfiguration configuration, AgentCoreOptions options, ILoggerFactory loggers, CancellationToken cancellationToken) { - ICallStore store = await CallStoreFactory + IConversationStore store = await ConversationStoreFactory .OpenAsync( configuration, options.SecretResolver, - options.CallStores ?? [], + options.ConversationStores ?? [], cancellationToken) .ConfigureAwait(false); - if (store is InMemoryCallStore && configuration.Providers?.Calls is null) + if (store is InMemoryConversationStore && configuration.Providers?.Conversations is null) { - StartupLog.CallStoreDefaulted(loggers.CreateLogger()); + StartupLog.ConversationStoreDefaulted(loggers.CreateLogger()); } return store; diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs index 763c532a..8edb9ec3 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/EntryRegistry.cs @@ -7,39 +7,39 @@ namespace AgentCore.AspNetCore.DependencyInjection.Startup; /// /// Each entry compiles its own shape over the shared pool, so each entry gets its own /// session factory and its own store: a vendor call id arriving on two routes opens two -/// isolated calls rather than one call read through two shapes. The audit chain, the +/// isolated conversations rather than one conversation read through two shapes. The audit chain, the /// observers, and the workspace root are shared across entries, because they describe the /// deployment rather than the shape. Agents are named by entry key. /// -internal sealed class EntryRegistry : ICallSessionRegistry +internal sealed class EntryRegistry : IConversationSessionRegistry { /// Creates the registry over the per-entry seams. /// The session factories, keyed by entry name. /// The agent shims, keyed by entry name. - /// The session stores, keyed by entry name. + /// The session stores, keyed by entry name. public EntryRegistry( - IReadOnlyDictionary factories, + IReadOnlyDictionary factories, IReadOnlyDictionary agents, - IReadOnlyDictionary callSessions) + IReadOnlyDictionary conversationSessions) { ArgumentNullException.ThrowIfNull(factories); ArgumentNullException.ThrowIfNull(agents); - ArgumentNullException.ThrowIfNull(callSessions); + ArgumentNullException.ThrowIfNull(conversationSessions); Factories = factories; Agents = agents; - CallSessions = callSessions; - Entries = callSessions.Keys.ToArray(); + ConversationSessions = conversationSessions; + Entries = conversationSessions.Keys.ToArray(); } /// Gets the session factories, keyed by entry name. - public IReadOnlyDictionary Factories { get; } + public IReadOnlyDictionary Factories { get; } /// Gets the agent shims, keyed by entry name. public IReadOnlyDictionary Agents { get; } /// Gets the session stores, keyed by entry name. - public IReadOnlyDictionary CallSessions { get; } + public IReadOnlyDictionary ConversationSessions { get; } /// public IReadOnlyCollection Entries { get; } @@ -48,7 +48,7 @@ public EntryRegistry( /// The entry key a route named. /// The factory for that entry. /// The entry is not declared. - public ICallSessionFactory ForFactory(string entry) + public IConversationSessionFactory ForFactory(string entry) => For(Factories, entry); /// Reads one entry's agent shim. @@ -59,8 +59,8 @@ public AgentCoreAgent ForAgent(string entry) => For(Agents, entry); /// - public ICallSessions ForSessions(string entry) - => For(CallSessions, entry); + public IConversationSessions ForSessions(string entry) + => For(ConversationSessions, entry); /// Builds the failure text for an entry nothing declares, in one place. /// The entry key a route named. diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs index 67b1080c..93c97a05 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs @@ -66,7 +66,7 @@ internal static async ValueTask BuildAsync( if (configuration.Mcp.Count > 0 && options.ToolSources.Count == 0) { throw ToolSourceError.Fail( - "the document declares mcp:, and nothing registered a tool source to connect to it. Call " + "the document declares mcp:, and nothing registered a tool source to connect to it. Conversation " + "AddAgentCoreHost (AgentCore.Hosting), or register one yourself with " + "options.AddToolSource(...)."); } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/StartupLog.cs b/src/AgentCore.AspNetCore/DependencyInjection/StartupLog.cs index 27d09b20..0941a635 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/StartupLog.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/StartupLog.cs @@ -17,14 +17,14 @@ internal static partial class StartupLog + "providers.audit.kind, or write kind: memory to say this was meant.")] public static partial void AuditSinkDefaulted(ILogger logger); - /// The document named no providers.calls, so the in-process store was opened. + /// The document named no providers.conversations, so the in-process store was opened. /// The factory's logger for the in-process store. [LoggerMessage( EventId = 3, Level = LogLevel.Warning, - Message = "the document names no providers.calls, so a call's row and the words of every " - + "call are kept in this process. That store is not durable, it grows without a bound, " - + "and no retention window applies to it. Name a durable providers.calls.kind, or write " + Message = "the document names no providers.conversations, so a conversation's row and the words of every " + + "conversation are kept in this process. That store is not durable, it grows without a bound, " + + "and no retention window applies to it. Name a durable providers.conversations.kind, or write " + "kind: memory to say this was meant.")] - public static partial void CallStoreDefaulted(ILogger logger); + public static partial void ConversationStoreDefaulted(ILogger logger); } diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs index 431d083d..42fff0ed 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs @@ -57,21 +57,21 @@ internal static class ResponsesAgentCore } /// Builds the metadata one finished turn files onto its answer. - /// The call the turn ran on. + /// The conversation the turn ran on. /// The finished turn. /// String pairs: the protocol's metadata holds strings only, and at most 16. - internal static IDictionary TurnMetadata(CallSession call, TurnResult turn) + internal static IDictionary TurnMetadata(ConversationSession conversation, TurnResult turn) { Dictionary metadata = new(StringComparer.Ordinal) { - ["call_id"] = call.CallId, + ["call_id"] = conversation.ConversationId, ["turn_index"] = turn.TurnIndex.ToString(System.Globalization.CultureInfo.InvariantCulture), ["stage_before"] = turn.StageBefore, ["stage_after"] = turn.StageAfter, ["is_terminal"] = turn.IsTerminal ? "true" : "false", }; - if (call.LastReplyMessageId is { } messageId) + if (conversation.LastReplyMessageId is { } messageId) { metadata["message_id"] = messageId; } @@ -92,8 +92,8 @@ internal static IDictionary TurnMetadata(CallSession call, TurnR /// Answers where one turn hangs, in the shape the turn loop reads. /// What the client said, or for a plain turn. /// The origin, or when the turn appends. - internal static CallTurnOrigin? OriginOf(ResponsesRequestInfo? info) - => info is null ? null : new CallTurnOrigin(info.MessageId, info.ParentId) { NamesParent = info.NamesParent }; + internal static ConversationTurnOrigin? OriginOf(ResponsesRequestInfo? info) + => info is null ? null : new ConversationTurnOrigin(info.MessageId, info.ParentId) { NamesParent = info.NamesParent }; private static string ApprovalsJson(TurnResult turn) { @@ -114,7 +114,7 @@ private static string ApprovalsJson(TurnResult turn) /// Where the client says its turn belongs and what it answers, beside the OpenAI shape. /// What the client calls the message it is sending. -/// What the client calls the message this one hangs off. Null starts the call afresh. +/// What the client calls the message this one hangs off. Null starts the conversation afresh. /// Whether the body carried parent_id at all. /// The approval answer this turn carries, or when it holds words. internal sealed record ResponsesRequestInfo( diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index f7dbf5d5..9370cafe 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -16,7 +16,7 @@ namespace AgentCore.AspNetCore.Endpoints; /// /// The Responses path: an OpenAI-compatible POST /v1/{entry}/responses over the turn loop, -/// with the call continuing across requests through the session store. +/// with the conversation continuing across requests through the session store. /// public static class ResponsesEndpointRouteBuilderExtensions { @@ -65,7 +65,7 @@ public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder return endpoints.MapPost(pattern, HandleAsync); } - /// Runs one turn of one call, and files the session under the ids the answer carries. + /// Runs one turn of one conversation, and files the session under the ids the answer carries. private static async Task HandleAsync(HttpContext http) { var cancellationToken = http.RequestAborted; @@ -108,7 +108,7 @@ await ResponsesRequestReader.WriteErrorAsync( { // An approval answer carries no words, only the request it answers — and the // protocol parse refuses a turn with no input. The continuation still names the - // call, so read it off the body and run the answer alone. + // conversation, so read it off the body and run the answer alone. if (agentcore?.Approval is null) { await ResponsesRequestReader.WriteErrorAsync( @@ -141,8 +141,8 @@ await ResponsesRequestReader.WriteErrorAsync( var sessions = http.RequestServices.GetRequiredService(); - // The continuation this turn hangs off, or null for the first turn of a call. - // A conversation id names the call itself; a response id names one past turn of it. + // The continuation this turn hangs off, or null for the first turn of a conversation. + // A conversation id names the conversation itself; a response id names one past turn of it. // The helper prefers the response chain over the conversation, exactly as the // protocol treats them as mutually exclusive; the refused-parse fallback reads // the same precedence off the body. @@ -163,7 +163,7 @@ await ResponsesRequestReader.WriteErrorAsync( var known = key is not null && await sessions.ContainsAsync(key, cancellationToken).ConfigureAwait(false); - var namesNewCall = key is not null + var namesNewConversation = key is not null && !known && string.Equals(key, conversationId, StringComparison.Ordinal) && conversationId is not null @@ -177,7 +177,7 @@ await ResponsesRequestReader.WriteErrorAsync( await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, - "an approval answer names the call it resumes. Send it with the conversation " + "an approval answer names the conversation it resumes. Send it with the conversation " + "or previous response id the asking turn answered with.", InvalidRequestError, "missing_session", @@ -188,11 +188,11 @@ await ResponsesRequestReader.WriteErrorAsync( conversationId = ResponsesRequestReader.NewConversationId(); session = await agent.CreateSessionAsync(conversationId, cancellationToken).ConfigureAwait(false); } - else if (namesNewCall) + else if (namesNewConversation) { - // Unknown conversation with words: start the call under that id, so the conversation, - // the call, and the continuation key are one id. Unknown response ids stay 404 below: - // they name a turn, not a call. + // Unknown conversation with words: start the conversation under that id, so the conversation, + // the conversation, and the continuation key are one id. Unknown response ids stay 404 below: + // they name a turn, not a conversation. session = await agent.CreateSessionAsync(key, cancellationToken).ConfigureAwait(false); } else if (known) @@ -218,11 +218,11 @@ await ResponsesRequestReader.WriteErrorAsync( { // Either an unknown response id — a turn no answer ever carried — or an unknown // conversation beside an approval-only body the parse refused. A conversation with words - // reaches the namesNewCall branch; an approval never starts a call. + // reaches the namesNewConversation branch; an approval never starts a conversation. await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status404NotFound, - $"no call opens under '{key}'. Send the request with neither a conversation nor a " + $"no conversation opens under '{key}'. Send the request with neither a conversation nor a " + "previous response id to start one.", InvalidRequestError, "continuation_not_found", @@ -231,7 +231,7 @@ await ResponsesRequestReader.WriteErrorAsync( return; } - if (session.GetService() is not { } call) + if (session.GetService() is not { } conversation) { throw new InvalidOperationException( "The session is not one this agent created, so it names no call to run."); @@ -253,15 +253,15 @@ await ResponsesRequestReader.WriteErrorAsync( return; } - // Async: a resumed call has run no turn in this process, so its ledger session — + // Async: a resumed conversation has run no turn in this process, so its ledger session — // and the queue the suspending turn filed — is still closed. This opens it first. - if (await call.TryCreateApprovalAnswerAsync(approval.RequestId, approval.Approved, cancellationToken).ConfigureAwait(false) is not { } answer) + if (await conversation.TryCreateApprovalAnswerAsync(approval.RequestId, approval.Approved, cancellationToken).ConfigureAwait(false) is not { } answer) { await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status409Conflict, - $"the call queues no approval under id '{approval.RequestId}'. It was " - + "answered already, belongs to another call, or was never asked.", + $"the conversation queues no approval under id '{approval.RequestId}'. It was " + + "answered already, belongs to another conversation, or was never asked.", InvalidRequestError, "no_pending_approval", cancellationToken).ConfigureAwait(false); @@ -299,7 +299,7 @@ await ResponsesRequestReader.WriteErrorAsync( // Only the stream has a frame to carry a drawing, so only the stream gets a screen. Binding // one on the whole-reply branch would let the tool report a picture the caller never sees. // Set per request, not once: the session outlives a request and the branch can differ per turn. - call.SetHasScreen(streaming); + conversation.SetHasScreen(streaming); if (CallerTimeZone.Parse(http.Request.Headers[TimeZoneHeaderName]) is { } zone) { @@ -312,18 +312,18 @@ await ResponsesRequestReader.WriteErrorAsync( { // The dialect is opt-in by the member only our clients send: an OpenAI SDK // never carries agentcore, so its stream stays the framework's pure shapes. - await ResponsesTurnStream.WriteAsync(http, agent, sessions, session, call, input, origin, responseId, conversationId, agentcore is not null, cancellationToken) + await ResponsesTurnStream.WriteAsync(http, agent, sessions, session, conversation, input, origin, responseId, conversationId, agentcore is not null, cancellationToken) .ConfigureAwait(false); } else { - await ResponsesTurnReply.WriteAsync(http, agent, sessions, session, call, input, origin, responseId, conversationId, cancellationToken) + await ResponsesTurnReply.WriteAsync(http, agent, sessions, session, conversation, input, origin, responseId, conversationId, cancellationToken) .ConfigureAwait(false); } } catch (InvalidOperationException exception) { - // The turn loop refuses a turn on a finished call, and refuses a second turn while one + // The turn loop refuses a turn on a finished conversation, and refuses a second turn while one // runs. Both are a caller mistake and neither is a defect of this host. await ResponsesRequestReader.WriteErrorAsync( http, diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs index 91913b7b..467ba580 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs @@ -17,14 +17,14 @@ internal static async Task WriteAsync( AgentCoreAgent agent, AgentCoreAgentSessionStore sessions, AgentSession session, - CallSession call, + ConversationSession conversation, ChatMessage input, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, string responseId, string? conversationId, CancellationToken cancellationToken) { - var turn = await call + var turn = await conversation .RunTurnMessageAtOriginAsync(input, origin, cancellationToken) .ConfigureAwait(false); @@ -46,7 +46,7 @@ await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, con var node = JsonNode.Parse(rendered.GetRawText())!.AsObject(); JsonObject metadata = node["metadata"]?.AsObject() ?? []; - foreach (var (name, value) in ResponsesAgentCore.TurnMetadata(call, turn)) + foreach (var (name, value) in ResponsesAgentCore.TurnMetadata(conversation, turn)) { metadata[name] = value; } diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs index 3ef41c27..ce60a653 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs @@ -1,6 +1,6 @@ using System.Text.Json; using System.Text.Json.Nodes; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Runtime; using AgentCore.Application.Tools; using AgentCore.AspNetCore.Sessions; @@ -31,9 +31,9 @@ internal static async Task WriteAsync( AgentCoreAgent agent, AgentCoreAgentSessionStore sessions, AgentSession session, - CallSession call, + ConversationSession conversation, ChatMessage input, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, string responseId, string? conversationId, bool dialect, @@ -44,12 +44,12 @@ internal static async Task WriteAsync( http.Response.Headers.CacheControl = "no-cache"; // The headers leave before the turn ends, so this one names the stage the turn speaks in. - http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = call.Stage; + http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = conversation.Stage; // One turn's worth of ids: the pairing dies with the stream. ToolCallNames toolNames = new(); - var updates = StreamAgentUpdatesAsync(http, agent, call, input, origin, dialect, toolNames, cancellationToken); + var updates = StreamAgentUpdatesAsync(http, agent, conversation, input, origin, dialect, toolNames, cancellationToken); await foreach (var frame in OpenAIResponses .WriteResponseStreamAsync(updates, responseId, conversationId, cancellationToken) @@ -65,7 +65,7 @@ await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, con .ConfigureAwait(false); } - /// Runs one streaming turn on the call, wrapping each update with the agent's id. + /// Runs one streaming turn on the conversation, wrapping each update with the agent's id. /// /// The framework converter sees every update untouched: it ignores the contents it /// knows nothing of, so dialect lines duplicate nothing and pure streams lose nothing. @@ -73,16 +73,16 @@ await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, con private static async IAsyncEnumerable StreamAgentUpdatesAsync( HttpContext http, AgentCoreAgent agent, - CallSession call, + ConversationSession conversation, ChatMessage input, - CallTurnOrigin? origin, + ConversationTurnOrigin? origin, bool dialect, ToolCallNames toolNames, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) { TurnStreamFiles files = new(); - await foreach (var update in call + await foreach (var update in conversation .RunTurnMessageStreamingAtOriginAsync(input, origin, cancellationToken) .ConfigureAwait(false)) { @@ -103,9 +103,9 @@ private static async IAsyncEnumerable StreamAgentUpdatesAsy { // The enumeration above ends only after the run has finished, and the publish tool ran // inside it: by here the bytes are in the store or never will be. - var calls = http.RequestServices.GetRequiredService(); + var conversations = http.RequestServices.GetRequiredService(); - await foreach (var part in files.ResolveAsync(calls, call.CallId, cancellationToken).ConfigureAwait(false)) + await foreach (var part in files.ResolveAsync(conversations, conversation.ConversationId, cancellationToken).ConfigureAwait(false)) { await WritePartLineAsync(http, part, cancellationToken).ConfigureAwait(false); } diff --git a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs index 7a4735e2..0a13c50e 100644 --- a/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamFiles.cs @@ -1,6 +1,6 @@ using AgentCore.Application.Transcript; using System.Runtime.CompilerServices; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using Microsoft.Extensions.AI; namespace AgentCore.AspNetCore.Endpoints; @@ -20,13 +20,13 @@ internal void Note(ChatResponseUpdate update) } /// Links every noted file the store kept, in the order they were noted. - /// The door to the stored call. - /// The call that owns the files. + /// The door to the stored conversation. + /// The conversation that owns the files. /// Cancels the lookups. /// One part for each file the store holds. internal async IAsyncEnumerable ResolveAsync( - CallRepository calls, - string callId, + Conversations conversations, + string conversationId, [EnumeratorCancellation] CancellationToken cancellationToken) { if (_files.Count == 0) @@ -34,8 +34,8 @@ internal async IAsyncEnumerable ResolveAsync( yield break; } - var links = await calls - .LinkFilesAsync(callId, [new ChatMessage(ChatRole.Assistant, [.. _files])], cancellationToken) + var links = await conversations + .LinkFilesAsync(conversationId, [new ChatMessage(ChatRole.Assistant, [.. _files])], cancellationToken) .ConfigureAwait(false); foreach (var (blob, url) in links) diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index c5df04e9..18309e78 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -1,7 +1,7 @@ #nullable enable -AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions -AgentCore.AspNetCore.Call.ICallTransportAdapter -AgentCore.AspNetCore.Call.ICallTransportAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! configuration) -> Microsoft.AspNetCore.Http.RequestDelegate! +AgentCore.AspNetCore.Conversation.ConversationEndpointRouteBuilderExtensions +AgentCore.AspNetCore.Conversation.IConversationTransportAdapter +AgentCore.AspNetCore.Conversation.IConversationTransportAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration! configuration) -> Microsoft.AspNetCore.Http.RequestDelegate! AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.AgentCoreHttpClients(System.Net.Http.HttpMessageHandler? primaryHandler = null, Microsoft.Extensions.Logging.ILoggerFactory? loggers = null) -> void AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.CreateClient(string! name) -> System.Net.Http.HttpClient! @@ -24,9 +24,9 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.SecretResolver.set -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.TimeProvider.get -> System.TimeProvider? AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.TimeProvider.set -> void AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseAuditSinks(params AgentCore.Application.Ports.IAuditSinkAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! -AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseCall(params AgentCore.Application.Ports.ICallAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! -AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseCallSessions(System.Func! open) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! -AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseCallStores(params AgentCore.Application.Ports.ICallStoreAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseConversation(params AgentCore.Application.Ports.IConversationAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseConversationSessions(System.Func! open) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseConversationStores(params AgentCore.Application.Ports.IConversationStoreAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseChatClients(System.Func! chatClients) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseChatClients(System.Func>! chatClients) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseChatClients(params AgentCore.Application.Ports.IChatClientAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! @@ -37,7 +37,7 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseKnowledgeQueryAnaly AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseKnowledgeRetrieval(System.Func! retrieval) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseKnowledgeStores(params AgentCore.Application.Ports.IKnowledgeStoreAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseModeration(params AgentCore.Application.Ports.IModerationAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! -AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseObservers(params AgentCore.Application.Ports.ICallObserver![]! observers) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseObservers(params AgentCore.Application.Ports.IConversationObserver![]! observers) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseSkills(Microsoft.Agents.AI.AgentSkillsSource! source) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseSkills(string! path) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseSpeech(params AgentCore.Application.Ports.ISpeechAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! @@ -49,31 +49,31 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup.Configuration.get -> A AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup.Secrets.get -> AgentCore.Application.Secrets.ResolvedSecrets! AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore -AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.AgentCoreAgentSessionStore(AgentCore.Application.Ports.ICallStore! calls) -> void +AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.AgentCoreAgentSessionStore(AgentCore.Application.Ports.IConversationStore! conversations) -> void AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.ContainsAsync(string! sessionStoreId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask override AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.DeleteSessionAsync(Microsoft.Agents.AI.AIAgent! agent, string! sessionStoreId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask override AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.GetSessionAsync(Microsoft.Agents.AI.AIAgent! agent, string! sessionStoreId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask override AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.SaveSessionAsync(Microsoft.Agents.AI.AIAgent! agent, string! sessionStoreId, Microsoft.Agents.AI.AgentSession! session, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter -AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.CarriesText.get -> bool -AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! configuration) -> Microsoft.AspNetCore.Http.RequestDelegate! -AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.Kind.get -> string! -AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.TelnyxRelayCallAdapter() -> void +AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayConversationAdapter +AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayConversationAdapter.CarriesText.get -> bool +AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayConversationAdapter.CreateHandler(AgentCore.Application.Configuration.Schema.ConversationProviderConfiguration! configuration) -> Microsoft.AspNetCore.Http.RequestDelegate! +AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayConversationAdapter.Kind.get -> string! +AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayConversationAdapter.TelnyxRelayConversationAdapter() -> void AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter.Kind.get -> string! AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter.TelnyxRelaySpeechAdapter() -> void -const AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.DefaultPattern = "/v1/{entry}/call" -> string! -const AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.EntryRouteParameter = "entry" -> string! +const AgentCore.AspNetCore.Conversation.ConversationEndpointRouteBuilderExtensions.DefaultPattern = "/v1/{entry}/call" -> string! +const AgentCore.AspNetCore.Conversation.ConversationEndpointRouteBuilderExtensions.EntryRouteParameter = "entry" -> string! const AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.MaxAttempts = 3 -> int const AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.PipelineName = "agentcore-http" -> string! const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.DefaultPattern = "/v1/{entry}/responses" -> string! const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.EntryRouteParameter = "entry" -> string! const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.StageHeaderName = "X-AgentCore-Stage" -> string! -const AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayCallAdapter.TelnyxRelayKind = "telnyx-relay" -> string! +const AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelayConversationAdapter.TelnyxRelayKind = "telnyx-relay" -> string! const AgentCore.AspNetCore.Vendors.TelnyxRelay.TelnyxRelaySpeechAdapter.TelnyxRelayKind = "telnyx-relay" -> string! -static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.EntryOf(Microsoft.AspNetCore.Http.HttpContext! http) -> string! -static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! -static AgentCore.AspNetCore.Call.CallEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! +static AgentCore.AspNetCore.Conversation.ConversationEndpointRouteBuilderExtensions.EntryOf(Microsoft.AspNetCore.Http.HttpContext! http) -> string! +static AgentCore.AspNetCore.Conversation.ConversationEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! +static AgentCore.AspNetCore.Conversation.ConversationEndpointRouteBuilderExtensions.MapCall(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! static AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions.AddAgentCore(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions.AddAgentCoreWebSockets(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.MapResponses(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! diff --git a/src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs b/src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs index 5b2bea98..9e906baf 100644 --- a/src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs +++ b/src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs @@ -5,19 +5,19 @@ namespace AgentCore.AspNetCore.Sessions; /// -/// The framework's session seam over the continuation map that lives in the call store. +/// The framework's session seam over the continuation map that lives in the conversation store. /// public sealed class AgentCoreAgentSessionStore : AgentSessionStore { - private readonly ICallStore _calls; + private readonly IConversationStore _conversations; - /// Creates the seam over one call store. - /// The store the continuation ids open onto. + /// Creates the seam over one conversation store. + /// The store the continuation ids open onto. /// The store is . - public AgentCoreAgentSessionStore(ICallStore calls) + public AgentCoreAgentSessionStore(IConversationStore conversations) { - ArgumentNullException.ThrowIfNull(calls); - _calls = calls; + ArgumentNullException.ThrowIfNull(conversations); + _conversations = conversations; } /// Reads whether anything is filed under one continuation id. @@ -28,7 +28,7 @@ public async ValueTask ContainsAsync(string sessionStoreId, CancellationTo { ArgumentNullException.ThrowIfNull(sessionStoreId); - return await _calls.GetContinuationAsync(sessionStoreId, cancellationToken).ConfigureAwait(false) + return await _conversations.GetContinuationAsync(sessionStoreId, cancellationToken).ConfigureAwait(false) is not null; } @@ -43,7 +43,7 @@ public override async ValueTask SaveSessionAsync( var envelope = await agent .SerializeSessionAsync(session, cancellationToken: cancellationToken) .ConfigureAwait(false); - await _calls.SaveContinuationAsync(sessionStoreId, envelope, cancellationToken).ConfigureAwait(false); + await _conversations.SaveContinuationAsync(sessionStoreId, envelope, cancellationToken).ConfigureAwait(false); } /// @@ -53,7 +53,7 @@ public override async ValueTask GetSessionAsync( ArgumentNullException.ThrowIfNull(agent); ArgumentNullException.ThrowIfNull(sessionStoreId); - var envelope = await _calls.GetContinuationAsync(sessionStoreId, cancellationToken).ConfigureAwait(false); + var envelope = await _conversations.GetContinuationAsync(sessionStoreId, cancellationToken).ConfigureAwait(false); if (envelope is null) { return await agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); @@ -71,6 +71,6 @@ public override ValueTask DeleteSessionAsync( ArgumentNullException.ThrowIfNull(agent); ArgumentNullException.ThrowIfNull(sessionStoreId); - return _calls.DeleteContinuationAsync(sessionStoreId, cancellationToken); + return _conversations.DeleteContinuationAsync(sessionStoreId, cancellationToken); } } diff --git a/src/AgentCore.AspNetCore/Sessions/CallSessionSweeper.cs b/src/AgentCore.AspNetCore/Sessions/ConversationSessionSweeper.cs similarity index 83% rename from src/AgentCore.AspNetCore/Sessions/CallSessionSweeper.cs rename to src/AgentCore.AspNetCore/Sessions/ConversationSessionSweeper.cs index caf3d641..053793a6 100644 --- a/src/AgentCore.AspNetCore/Sessions/CallSessionSweeper.cs +++ b/src/AgentCore.AspNetCore/Sessions/ConversationSessionSweeper.cs @@ -7,10 +7,10 @@ namespace AgentCore.AspNetCore.Sessions; /// -/// Runs the idle sweep of every for as long as the host is up. +/// Runs the idle sweep of every for as long as the host is up. /// -internal sealed class CallSessionSweeper( - IServiceProvider services, TimeProvider timeProvider, ILogger logger) : BackgroundService +internal sealed class ConversationSessionSweeper( + IServiceProvider services, TimeProvider timeProvider, ILogger logger) : BackgroundService { /// How often the sweep runs. private static readonly TimeSpan Interval = TimeSpan.FromMinutes(5); @@ -29,9 +29,9 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) try { List? faults = null; - foreach (var store in entries.CallSessions.Values) + foreach (var store in entries.ConversationSessions.Values) { - if (store is not InMemoryCallSessions memory) + if (store is not InMemoryConversationSessions memory) { continue; } @@ -54,14 +54,14 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } catch (Exception fault) when (fault is not OperationCanceledException) { - CallSessionSweeperLog.SweepFaulted(logger, fault); + ConversationSessionSweeperLog.SweepFaulted(logger, fault); } } } } /// Every line the idle sweep writes. -internal static partial class CallSessionSweeperLog +internal static partial class ConversationSessionSweeperLog { /// A sweep could not end one or more of the sessions it visited. /// The logger of the sweeper. diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs index 1e0d8dc3..6f5f8157 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs @@ -2,10 +2,10 @@ using System.Runtime.CompilerServices; using System.Text.Json; using System.Threading.Channels; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.Domain.Audit; using Microsoft.AspNetCore.Http; @@ -16,7 +16,7 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// -/// One socket, one call. +/// One socket, one conversation. /// /// /// @@ -39,11 +39,11 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// frames onto and nothing else. /// /// -/// One object fills both halves of the call's , because one socket +/// One object fills both halves of the conversation's , because one socket /// carries both directions for this vendor. Nothing above the ports can tell, and nothing may ask. -/// The speaking side is below: every reply reaches the write loop +/// The speaking side is below: every reply reaches the write loop /// through . The last of the two barge-in gates is this class's business -/// and nobody else's — speaks in turn ids and never hands one over, +/// and nobody else's — speaks in turn ids and never hands one over, /// so this class keeps a monotonic reply generation instead, stamps every item it queues with the /// generation it was queued under, and raises that generation in . The write /// loop then drops any item at or below the raised one, which is the same comparison the turn ids @@ -54,10 +54,10 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// arbiter had already decided to speak, but which only reaches after /// raised the generation, is stamped with the new one and reaches the /// caller. A port carries no reply identity to tell that fragment from the first fragment of the -/// next reply, and the window is the few instructions between the arbiter's own check and that call. +/// next reply, and the window is the few instructions between the arbiter's own check and that conversation. /// /// -internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort +internal sealed class TelnyxRelayConnection : IConversationInputPort, IConversationOutputPort { private readonly TelnyxRelayOptions _options; @@ -90,17 +90,17 @@ internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort // promises one consumer for the life of the port, and this is what a second call trips over. private int _listening; - private volatile CallSession? _session; + private volatile ConversationSession? _session; // Resolved once per socket from the stamped entry, then cached: every session open, touch, // and close on this connection answers on the same entry. - private volatile ICallSessions? _entrySessions; + private volatile IConversationSessions? _entrySessions; - private const string BeforeSetupCallId = "(before setup)"; + private const string BeforeSetupConversationId = "(before setup)"; // volatile for the same reason _session is: the read loop assigns it when the setup frame // arrives, and teardown reads it from another task to find the last turn. - private volatile CallTurnArbiter? _arbiter; + private volatile ConversationTurnArbiter? _arbiter; private bool _loggedPromptBeforeSetup; @@ -110,7 +110,7 @@ internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort /// Reads this socket's entry session store, resolved once from the URL's entry. /// The store for the entry the URL named. - private ICallSessions EntrySessions() + private IConversationSessions EntrySessions() => _entrySessions ?? throw new InvalidOperationException("This socket resolved no session store."); @@ -120,10 +120,10 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt _logger = logger; - // A dropped socket ends this call, and so does the host shutting down. Both stop the read + // A dropped socket ends this conversation, and so does the host shutting down. Both stop the read // loop, the write loop, and any turn the same way, through the one token everything below // reads. IHostApplicationLifetime is resolved here, from the request's own provider, and - // never at MapTelnyxRelay time: nothing is bound to it until a call actually arrives. + // never at MapTelnyxRelay time: nothing is bound to it until a conversation actually arrives. _lifetime = http.RequestServices.GetRequiredService(); _cancellation = CancellationTokenSource.CreateLinkedTokenSource( @@ -133,7 +133,7 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt _connectionToken = _cancellation.Token; // AddAgentCore registers this from options.TimeProvider, or TimeProvider.System when the - // host bound none — the same clock CallSessionFactory already reads for callDurationSeconds. + // host bound none — the same clock ConversationSessionFactory already reads for conversationDurationSeconds. // Resolving it here, rather than reading TimeProvider.System directly, is what lets a test // own the idle deadline below by binding that one option. var timeProvider = http.RequestServices.GetRequiredService(); @@ -147,13 +147,13 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt }); // The observer is vendor-free, so the two faults that are the relay's own doing reach it - // through ClassifyTelnyxFault rather than through a catch clause of its own. The call id is + // through ClassifyTelnyxFault rather than through a catch clause of its own. The conversation id is // a function because the session only exists once the setup frame has arrived, which is // after this constructor and after some of the lines the observer logs. _observer = new ConnectionTaskObserver( - () => _session?.CallId ?? BeforeSetupCallId, - (callId, taskName) => TelnyxRelayLog.TeardownTimedOut(_logger, callId, taskName), - (kind, callId, fault) => LogFault(kind, callId, fault), + () => _session?.ConversationId ?? BeforeSetupConversationId, + (conversationId, taskName) => TelnyxRelayLog.TeardownTimedOut(_logger, conversationId, taskName), + (kind, conversationId, fault) => LogFault(kind, conversationId, fault), ClassifyTelnyxFault); // The pump owns the socket from here on: the read loop, the write loop, and the one close @@ -161,7 +161,7 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt // that would have are the delegates below — the exception the pump raises when the relay // breaks the contract, so DetermineCloseStatus still recognises it off the read loop's own // task, and the three log lines that name the relay by name. Each log callback closes over - // _session for the same reason the observer's own callId does: the id only exists once the + // _session for the same reason the observer's own conversationId does: the id only exists once the // setup frame has arrived, which is after this constructor. _pump = new JsonWebSocketPump( socket, @@ -170,14 +170,14 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt _options.IdleTimeout, _options.CloseTimeout, (status, message) => new RelayProtocolException(status, message), - frameType => TelnyxRelayLog.UnknownFrameType(_logger, frameType, _session?.CallId ?? BeforeSetupCallId), - frameType => TelnyxRelayLog.FrameBodyRefused(_logger, frameType, _session?.CallId ?? BeforeSetupCallId), - () => TelnyxRelayLog.IdleTimeoutReached(_logger, _session?.CallId ?? BeforeSetupCallId)), + frameType => TelnyxRelayLog.UnknownFrameType(_logger, frameType, _session?.ConversationId ?? BeforeSetupConversationId), + frameType => TelnyxRelayLog.FrameBodyRefused(_logger, frameType, _session?.ConversationId ?? BeforeSetupConversationId), + () => TelnyxRelayLog.IdleTimeoutReached(_logger, _session?.ConversationId ?? BeforeSetupConversationId)), timeProvider, _connectionToken); } - /// Runs one call to its end. + /// Runs one conversation to its end. /// The request that carried the handshake. /// The accepted socket. /// What the endpoint may do. @@ -195,7 +195,7 @@ public static Task RunAsync(HttpContext http, WebSocket socket, TelnyxRelayOptio TelnyxRelayConnection connection = new(http, socket, options, logger); connection._entrySessions = http.RequestServices .GetRequiredService() - .Entries.ForSessions(CallEndpointRouteBuilderExtensions.EntryOf(http)); + .Entries.ForSessions(ConversationEndpointRouteBuilderExtensions.EntryOf(http)); return connection.RunAsync(); } @@ -204,7 +204,7 @@ private async Task RunAsync() { // Both loops belong to the pump, and both seams into this class are named methods rather // than bodies: ParseFrame is the vendor's own reader, and DispatchAsync is what one parsed - // frame means to this call. The cast is safe because ParseFrame is the only thing that ever + // frame means to this conversation. The cast is safe because ParseFrame is the only thing that ever // puts a frame into a FrameOutcome, and it only ever puts a RelayFrame there. var reading = _pump.ReadLoopAsync(ParseFrame, frame => DispatchAsync((RelayFrame)frame)); var writing = _pump.WriteLoopAsync(_outbound.Reader, EncodeOutbound); @@ -216,7 +216,7 @@ private async Task RunAsync() finally { // The disposal below must run on every exit from here down, including a throw out of - // Cancel() itself or ICallSessions.CloseAsync: _cancellation links to ApplicationStopping, + // Cancel() itself or IConversationSessions.CloseAsync: _cancellation links to ApplicationStopping, // which lives for the whole process, and only Dispose() releases that registration. try { @@ -226,7 +226,7 @@ private async Task RunAsync() // method returns. Cancel() itself is guarded: it runs with throwOnFirstException: // false, so every callback still runs and both loops are already cancelled before a // callback fault can reach this catch, and losing the rest of teardown below would - // otherwise strand this call in the store for the life of the process. + // otherwise strand this conversation in the store for the life of the process. try { await _cancellation.CancelAsync().ConfigureAwait(false); @@ -235,7 +235,7 @@ private async Task RunAsync() { ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.CancellationFaulted( _logger, - _session?.CallId ?? BeforeSetupCallId, + _session?.ConversationId ?? BeforeSetupConversationId, fault)); } @@ -252,7 +252,7 @@ private async Task RunAsync() // chat client that ignores its token altogether, such as BlockingChatClient in the test // fakes — must not be able to wedge teardown forever. // - // The last turn is read through CallTurnArbiter.CurrentTurn, which takes the same + // The last turn is read through ConversationTurnArbiter.CurrentTurn, which takes the same // lock every writer of it takes, and never off a field directly: the arbiter's own // RunPendingPrompt can reassign it from a turn's own task, off the read loop, so // teardown here is no longer the only writer's own reader. That property's remarks @@ -292,7 +292,7 @@ private async Task RunAsync() { ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.CloseFaulted( _logger, - _session?.CallId ?? BeforeSetupCallId, + _session?.ConversationId ?? BeforeSetupConversationId, fault)); } @@ -301,13 +301,13 @@ private async Task RunAsync() if (_session is { } session) { // The chain closes before the session leaves the store, and never after: §11 - // item 6 makes call.ended the last event of every call, and the session is what + // item 6 makes conversation.ended the last event of every conversation, and the session is what // writes it. The reason comes from the status just decided rather than from a // second reading of the same tasks, so the vendor's close frame and the audit - // row can never disagree about how this call ended. A call that already closed + // row can never disagree about how this conversation ended. A conversation that already closed // its own chain from a terminal stage answers false here and keeps the - // agent.completed it wrote: EndCall is idempotent, and nothing on this path may - // give one call two endings. + // agent.completed it wrote: EndConversation is idempotent, and nothing on this path may + // give one conversation two endings. // // Guarded for the same reason CloseAsync above is. §7.1 forbids teardown // throwing out of the request handler, and the close below must run whatever @@ -316,28 +316,28 @@ private async Task RunAsync() // handed to observers that swallow their own faults and the reason is a member // of a closed set this class picks itself, so the only cause left is the clock // the session reads; a missing last event is a gap in one chain, and losing the - // rest of teardown would be a leak in every call after it. + // rest of teardown would be a leak in every conversation after it. try { - _ = session.EndCall(EndReasonOf(status)); + _ = session.EndConversation(EndReasonOf(status)); } catch (Exception fault) { - ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.CallEndFaulted( + ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.ConversationEndFaulted( _logger, - session.CallId, + session.ConversationId, fault)); } - // Closing waits for the words this call still owes store 1 and only then drops - // the session; ICallSessions.CloseAsync owns that order. + // Closing waits for the words this conversation still owes store 1 and only then drops + // the session; IConversationSessions.CloseAsync owns that order. // // Bounded and swallowed for the same reason the close above is: a store that - // stops answering must cost this call its last rows, not wedge teardown and + // stops answering must cost this conversation its last rows, not wedge teardown and // strand the session in the store for the life of the process. await _observer .ObserveAsync( - CloseSessionAsync(session.CallId), + CloseSessionAsync(session.ConversationId), ConnectionTaskKind.SessionClose, _options.CloseTimeout) .ConfigureAwait(false); @@ -350,12 +350,12 @@ await _observer } } - /// Ends one call, as a task the observer can bound and watch. - /// The call that ended. + /// Ends one conversation, as a task the observer can bound and watch. + /// The conversation that ended. /// A task that completes once the words are written and the session is gone. - private async Task CloseSessionAsync(string callId) + private async Task CloseSessionAsync(string conversationId) { - await EntrySessions().CloseAsync(callId, CancellationToken.None).ConfigureAwait(false); + await EntrySessions().CloseAsync(conversationId, CancellationToken.None).ConfigureAwait(false); } /// Works out the status and the description the vendor sees on the close frame. @@ -383,7 +383,7 @@ private async Task CloseSessionAsync(string callId) /// /// /// The checks are ordered by how specific each cause is. A - /// names exactly why the endpoint refused the call, so it wins over everything else. A turn or + /// names exactly why the endpoint refused the conversation, so it wins over everything else. A turn or /// the write loop faulting with anything other than its own cancellation is this connection's /// own defect, not the caller's or the vendor's, so either counts before the host-stopping check /// below even notices that is, by this point in teardown, always @@ -395,7 +395,7 @@ private async Task CloseSessionAsync(string callId) /// this cancelled too." A dropped socket with no close frame — /// — and a read loop that simply /// returned once it saw the relay's own close frame both fall through to the same default: an - /// ordinary end of call. + /// ordinary end of conversation. /// /// /// The check only catches a write loop that has already faulted at @@ -440,14 +440,14 @@ private async Task CloseSessionAsync(string callId) } /// Reads the ending one close status reports, as one member of the closed set. - /// What already decided this call closes with. + /// What already decided this conversation closes with. /// The reason the last event of the chain carries. /// /// - /// §11 item 6 and T55/T56 ask every call to end its chain in call.ended with a reason from + /// §11 item 6 and T55/T56 ask every call to end its chain in conversation.ended with a reason from /// the closed set of four, and only this adapter can supply two of them: the turn loop closes its - /// own chain with when the stage machine reaches a - /// terminal stage, and belongs to the Call Control + /// own chain with when the stage machine reaches a + /// terminal stage, and belongs to the Conversation Control /// path of §4.3 that voice slice 2 adds and this build does not have. What is left for a socket /// that ended is the caller, or a fault. /// @@ -460,15 +460,15 @@ private async Task CloseSessionAsync(string callId) /// is a hang-up, not a fault, and that /// is the load-bearing decision here. A socket that stopped with no close frame is what /// already folds into - /// alongside a read loop that saw the relay's own close frame — its remarks call both "an ordinary - /// end of call" — and what already logs through - /// at Information rather than as a defect. + /// alongside a read loop that saw the relay's own close frame — its remarks conversation both "an ordinary + /// end of conversation" — and what already logs through + /// at Information rather than as a defect. /// This method agrees with both, and it has to: a caller who hangs up and a caller whose phone /// loses signal look identical on this socket, the vendor never reconnects either of them, and - /// the audit table would be worth very little if the ordinary way a call ends were counted as a - /// system fault. §7.1's rule that a bad frame must never drop a call points the same way — the - /// adapter's default reading of an ended socket is the call ending, not the endpoint failing. - /// The one place this reading is contradicted is the remark on + /// the audit table would be worth very little if the ordinary way a conversation ends were counted as a + /// system fault. §7.1's rule that a bad frame must never drop a conversation points the same way — the + /// adapter's default reading of an ended socket is the conversation ending, not the endpoint failing. + /// The one place this reading is contradicted is the remark on /// itself, which lists "a dropped relay socket" among its causes; that sentence predates the /// close-status reasoning above, and it is left alone here rather than edited, because the enum is /// the core's and this decision is the adapter's. @@ -478,38 +478,38 @@ private async Task CloseSessionAsync(string callId) /// IdleTimeout returns rather than throwing, so it reaches /// and is recorded as a hang-up — which is /// exactly what already says a silent socket is: - /// a call that is already over. + /// a conversation that is already over. /// /// - /// Everything else is , and that includes two endings worth + /// Everything else is , and that includes two endings worth /// naming. A protocol violation closes with the status - /// carries: the relay broke the contract and this endpoint refused the call, which no caller + /// carries: the relay broke the contract and this endpoint refused the conversation, which no caller /// chose. A host that stops closes with : - /// the process went away underneath a live call, which no caller chose either. Neither is a + /// the process went away underneath a live conversation, which no caller chose either. Neither is a /// hang-up, neither is the agent finishing, and neither is a transfer, so within a set of four /// the honest answer is the fault — recorded as one rather than quietly counted as a caller who /// decided to leave. /// /// - private static CallEndReason EndReasonOf(WebSocketCloseStatus status) + private static ConversationEndReason EndReasonOf(WebSocketCloseStatus status) => status is WebSocketCloseStatus.NormalClosure - ? CallEndReason.CallerHungUp - : CallEndReason.Faulted; + ? ConversationEndReason.CallerHungUp + : ConversationEndReason.Faulted; /// Logs the two faults that are the vendor's doing rather than this endpoint's defect. /// The exception a loop or a turn ended with. /// Which task faulted. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// /// when this method logged itself, and /// to leave it to . /// /// - /// The classify hook calls before its own general clause. + /// The classify hook conversations before its own general clause. /// Both causes below name a vendor type, which is why they stay here rather than moving into /// that observer with the rest of the teardown machinery. /// - private bool ClassifyTelnyxFault(Exception fault, ConnectionTaskKind kind, string callId) + private bool ClassifyTelnyxFault(Exception fault, ConnectionTaskKind kind, string conversationId) { switch (fault) { @@ -520,14 +520,14 @@ private bool ClassifyTelnyxFault(Exception fault, ConnectionTaskKind kind, strin // other malformed-input line in this file (PromptBeforeSetup, FrameRefused, // MalformedInterruptFrame) already logs at Warning, and LogFault's generic path // would otherwise report this at Error, the same level as an unhandled bug. - TelnyxRelayLog.RelayProtocolViolation(_logger, callId, protocol.Message); + TelnyxRelayLog.RelayProtocolViolation(_logger, conversationId, protocol.Message); return true; case WebSocketException { WebSocketErrorCode: WebSocketError.ConnectionClosedPrematurely } when kind == ConnectionTaskKind.ReadLoop: - // The call dropped with no close frame. Section "close statuses" of task 7: that is - // an ordinary end of a call, not a fault, so it is worth a line but not an error one. - TelnyxRelayLog.CallDroppedWithNoCloseFrame(_logger, callId); + // The conversation dropped with no close frame. Section "close statuses" of task 7: that is + // an ordinary end of a conversation, not a fault, so it is worth a line but not an error one. + TelnyxRelayLog.ConversationDroppedWithNoCloseFrame(_logger, conversationId); return true; default: @@ -537,7 +537,7 @@ private bool ClassifyTelnyxFault(Exception fault, ConnectionTaskKind kind, strin /// Logs the fault of a read loop, a turn, or a write loop, whichever names. /// Which task faulted. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// The cause. /// /// The logFault hook of , which calls it from @@ -546,24 +546,24 @@ private bool ClassifyTelnyxFault(Exception fault, ConnectionTaskKind kind, strin /// to catch a throw, so the observer wraps every call to this method in /// ; nothing here has to guard itself again. /// - private void LogFault(ConnectionTaskKind kind, string callId, Exception fault) + private void LogFault(ConnectionTaskKind kind, string conversationId, Exception fault) { switch (kind) { case ConnectionTaskKind.Turn: - TelnyxRelayLog.TurnFaulted(_logger, callId, fault); + TelnyxRelayLog.TurnFaulted(_logger, conversationId, fault); break; case ConnectionTaskKind.WriteLoop: - TelnyxRelayLog.WriteLoopFaulted(_logger, callId, fault); + TelnyxRelayLog.WriteLoopFaulted(_logger, conversationId, fault); break; case ConnectionTaskKind.SessionClose: - TelnyxRelayLog.CallCloseFaulted(_logger, callId, fault); + TelnyxRelayLog.ConversationCloseFaulted(_logger, conversationId, fault); break; default: - TelnyxRelayLog.ReadLoopFaulted(_logger, callId, fault); + TelnyxRelayLog.ReadLoopFaulted(_logger, conversationId, fault); break; } } @@ -594,13 +594,13 @@ private static FrameOutcome ParseFrame(ReadOnlySpan utf8) /// The encode seam of , which runs it immediately before /// its one send. The gate below stays here, on this side of that seam, because a stale item is /// stale in this connection's own vocabulary and in no transport's. The writer belongs to that - /// loop and is reused for every frame of the call, so nothing here keeps it, flushes it, or + /// loop and is reused for every frame of the conversation, so nothing here keeps it, flushes it, or /// holds what it wrote: the bytes are the loop's to send and the loop's to overwrite. /// private bool EncodeOutbound(OutboundItem item, Utf8JsonWriter writer) { // The write loop is the last gate, immediately before the one SendAsync call the pump - // makes for this connection. CallTurnArbiter's own check only narrows the race — it cannot + // makes for this connection. ConversationTurnArbiter's own check only narrows the race — it cannot // stop a token already past it at the moment a barge-in raises the reply generation: // one already queued, one a bounded channel's backpressure was about to release into the gap // StopAsync's own drain just made, or one this loop had already dequeued and was about to @@ -613,7 +613,7 @@ private bool EncodeOutbound(OutboundItem item, Utf8JsonWriter writer) // // >=, not ==. _replyGeneration and every item's own Generation both only ever increase, // so "the highest generation a barge-in has cut off is at or above this item's own" is - // the question that actually matches a call across two barge-ins: with == alone, an item of + // the question that actually matches a conversation across two barge-ins: with == alone, an item of // generation N already dequeued here, then gated after a second, later barge-in raises // the mark to N+1, would compare N+1 != N, pass, and reach the caller — exactly the // straggler this gate exists to stop. With no interrupt at all _replyGeneration stays @@ -630,7 +630,7 @@ private bool EncodeOutbound(OutboundItem item, Utf8JsonWriter writer) // The same options SerializeToUtf8Bytes was given, and the same bytes: TelnyxRelayJson sets // no encoder and no indentation, so a default Utf8JsonWriter escapes and lays out this frame - // exactly as the writer JsonSerializer used to build per call did. + // exactly as the writer JsonSerializer used to build per conversation did. JsonSerializer.Serialize(writer, item.Frame, item.Frame.GetType(), TelnyxRelayJson.Options); return true; } @@ -640,7 +640,7 @@ private async Task DispatchAsync(RelayFrame frame) switch (frame) { case RelayFrame.Setup setup: - await StartCallAsync(setup).ConfigureAwait(false); + await StartConversationAsync(setup).ConfigureAwait(false); break; case RelayFrame.Prompt { Last: true } prompt: @@ -663,21 +663,21 @@ private async Task DispatchAsync(RelayFrame frame) case RelayFrame.Error error: // The vendor refused a frame this endpoint sent. That is our defect. - TelnyxRelayLog.FrameRefused(_logger, _session?.CallId ?? BeforeSetupCallId, error.Description); + TelnyxRelayLog.FrameRefused(_logger, _session?.ConversationId ?? BeforeSetupConversationId, error.Description); break; } } - private async Task StartCallAsync(RelayFrame.Setup setup) + private async Task StartConversationAsync(RelayFrame.Setup setup) { var sessions = EntrySessions(); - // One socket carries one call, and the vendor sends one setup frame. A second one replaces - // the session rather than refusing the socket, because section 7.1 forbids dropping a call - // over a frame the vendor got wrong, and because the vendor's latest word about the call is + // One socket carries one conversation, and the vendor sends one setup frame. A second one replaces + // the session rather than refusing the socket, because section 7.1 forbids dropping a conversation + // over a frame the vendor got wrong, and because the vendor's latest word about the conversation is // the one to answer. The first session is closed here and not left behind: teardown only // ever closes the session this connection currently holds, so this is the last moment - // anything waits for the words the replaced call still owed store 1. + // anything waits for the words the replaced conversation still owed store 1. // CancellationToken.None, because the close must still run while the connection is // tearing down. if (_session is { } replaced) @@ -685,29 +685,29 @@ private async Task StartCallAsync(RelayFrame.Setup setup) if (!_loggedSecondSetup) { _loggedSecondSetup = true; - TelnyxRelayLog.SecondSetupFrame(_logger, replaced.CallId); + TelnyxRelayLog.SecondSetupFrame(_logger, replaced.ConversationId); } // Teardown will later close the session that replaced this one and never this one, so // this is the last moment anything can wait for the writes it queued. Bounded and - // swallowed by the observer, so a store that stopped answering costs the replaced call + // swallowed by the observer, so a store that stopped answering costs the replaced conversation // its last rows rather than stalling the read loop for the rest of the connection. // Through CloseSessionAsync, and never CloseAsync(...).AsTask(): a store that throws // synchronously throws before AsTask() is ever reached, so the observer would not see - // it and §7.1's rule against dropping a call over a bad frame would be broken by the + // it and §7.1's rule against dropping a conversation over a bad frame would be broken by the // very frame that rule is about. An async method turns that throw into the task the // observer bounds. await _observer .ObserveAsync( - CloseSessionAsync(replaced.CallId), + CloseSessionAsync(replaced.ConversationId), ConnectionTaskKind.SessionClose, _options.CloseTimeout) .ConfigureAwait(false); } - // callSessionId groups the legs of one logical call, so the id survives the warm transfer + // conversationSessionId groups the legs of one logical conversation, so the id survives the warm transfer // that slice 2 adds. A leg id would break there. - _session = await sessions.OpenAsync(setup.CallSessionId, _cancellation.Token).ConfigureAwait(false); + _session = await sessions.OpenAsync(setup.ConversationSessionId, _cancellation.Token).ConfigureAwait(false); // Built on the first setup frame and never again: a later one only tells the arbiter which // call to answer from now on. One socket runs one turn at a time, and that promise belongs @@ -728,12 +728,12 @@ await _observer // port belonging to a separate synthesizer, which is the whole of D8. // The two log callbacks are this vendor's own lines, bound here: the arbiter decides when a // prompt is held and when a further one is dropped, and names no log event of its own. - _arbiter = new CallTurnArbiter( + _arbiter = new ConversationTurnArbiter( _session, this, _observer, - callId => TelnyxRelayLog.PromptHeld(_logger, callId), - callId => TelnyxRelayLog.PendingPromptDropped(_logger, callId), + conversationId => TelnyxRelayLog.PromptHeld(_logger, conversationId), + conversationId => TelnyxRelayLog.PendingPromptDropped(_logger, conversationId), _connectionToken); } @@ -741,7 +741,7 @@ private async Task StartTurnAsync(string text) { if (_arbiter is not { } arbiter) { - // Log once for the call, not once for the frame. Same rule as the unknown-frame line. + // Log once for the conversation, not once for the frame. Same rule as the unknown-frame line. if (!_loggedPromptBeforeSetup) { _loggedPromptBeforeSetup = true; @@ -760,14 +760,14 @@ private async Task StartTurnAsync(string text) _ = arbiter.StartTurnAsync(text); } - /// Tells the store this call is still being had. + /// Tells the store this conversation is still being had. /// A task that completes once the store has been read. /// - /// This connection opens its session once and holds it for the whole call, so nothing else ever - /// reads it back. A store that expires an idle session counts a read as the one sign the call is - /// still live, so without this a call longer than that timeout is swept out from under the turn + /// This connection opens its session once and holds it for the whole conversation, so nothing else ever + /// reads it back. A store that expires an idle session counts a read as the one sign the conversation is + /// still live, so without this a conversation longer than that timeout is swept out from under the turn /// about to run: its words are flushed, its session is dropped, and every turn after it runs on - /// an object no close can reach. A call nobody speaks on is ended by this socket's own + /// an object no close can reach. A conversation nobody speaks on is ended by this socket's own /// IdleTimeout instead, which is a real end and closes the chain. /// The result is not used. It is the read itself that matters, and the session this connection /// holds is the one the arbiter must keep running whatever the store answers. @@ -779,16 +779,16 @@ private async Task KeepSessionAliveAsync() return; } - // §7.1 forbids dropping a call over one frame, and this runs on the read loop. A store that - // throws costs this call its place in the sweep, never the call itself. + // §7.1 forbids dropping a conversation over one frame, and this runs on the read loop. A store that + // throws costs this conversation its place in the sweep, never the conversation itself. try { - _ = await EntrySessions().TryGetAsync(session.CallId, _connectionToken).ConfigureAwait(false); + _ = await EntrySessions().TryGetAsync(session.ConversationId, _connectionToken).ConfigureAwait(false); } catch (Exception fault) when (fault is not OperationCanceledException) { ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.SessionTouchFaulted( - _logger, session.CallId, fault)); + _logger, session.ConversationId, fault)); } } @@ -800,10 +800,10 @@ private void HandleInterrupt(RelayFrame.Interrupt interrupt) } // Section 7.1's rule for an unknown frame type and for a prompt before setup applies here - // too: a frame the vendor got wrong must not drop the call. System.Text.Json enforces + // too: a frame the vendor got wrong must not drop the conversation. System.Text.Json enforces // neither a missing property nor a negative number at run time, so a frame missing // utteranceUntilInterrupt, or carrying a negative durationUntilInterruptMs, would otherwise - // reach CallSession.Interrupt's own ArgumentNullException or ArgumentOutOfRangeException + // reach ConversationSession.Interrupt's own ArgumentNullException or ArgumentOutOfRangeException // uncaught and take the read loop down with it. Nothing here clamps the duration — a clamp // is an estimate, and D28 exists to keep estimates out of this path. This guard stays here, // and never moves into the arbiter: validating these two values is reading a vendor frame. @@ -812,7 +812,7 @@ private void HandleInterrupt(RelayFrame.Interrupt interrupt) if (!_loggedMalformedInterrupt) { _loggedMalformedInterrupt = true; - TelnyxRelayLog.MalformedInterruptFrame(_logger, session.CallId); + TelnyxRelayLog.MalformedInterruptFrame(_logger, session.ConversationId); } return; @@ -824,10 +824,10 @@ private void HandleInterrupt(RelayFrame.Interrupt interrupt) interrupt.UtteranceUntilInterrupt, TimeSpan.FromMilliseconds(interrupt.DurationUntilInterruptMs)); - // Logged last, once the raised id, the call to Interrupt, and the drain behind - // ICallOutputPort.StopAsync have all already happened, so this line is proof the whole + // Logged last, once the raised id, the conversation to Interrupt, and the drain behind + // IConversationOutputPort.StopAsync have all already happened, so this line is proof the whole // guard is in place — never the words the caller said or heard. - TelnyxRelayLog.InterruptReceived(_logger, session.CallId); + TelnyxRelayLog.InterruptReceived(_logger, session.ConversationId); } /// @@ -865,13 +865,13 @@ public ValueTask StopAsync(CancellationToken cancellationToken = default) /// /// /// This stream yields nothing today, and that is deliberate rather than a defect. The - /// read loop still drives DispatchAsync directly, so every inbound frame of this call + /// read loop still drives DispatchAsync directly, so every inbound frame of this conversation /// already reaches the arbiter by that path; rerouting it through this stream is a later change /// that no current caller needs. Until then this half of the channel exists so the shape is /// honest — one object really does fill both slots — and it completes when the connection does, - /// so an await foreach over it ends with the call rather than at once. A consumer that + /// so an await foreach over it ends with the conversation rather than at once. A consumer that /// cancels its own read gets instead, which is the rule - /// sets for every implementation of this port. + /// sets for every implementation of this port. /// /// /// One consumer for the life of the port, and the guard is here rather than inside the iterator @@ -879,7 +879,7 @@ public ValueTask StopAsync(CancellationToken cancellationToken = default) /// otherwise hand back a stream that throws late, or never at all if nobody enumerates it. /// /// - public IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default) + public IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default) { if (Interlocked.CompareExchange(ref _listening, 1, 0) != 0) { @@ -894,15 +894,15 @@ public IAsyncEnumerable ListenAsync(CancellationToken cancellationTok /// Nothing to release here, and disposing a port must not tear this connection down. The /// channel, the linked cancellation source, and the socket all belong to RunAsync, which /// releases them in its own teardown once the last turn has stopped writing — and for this - /// vendor the call ends when that method returns, not when whoever holds the - /// lets go of it. + /// vendor the conversation ends when that method returns, not when whoever holds the + /// lets go of it. /// public ValueTask DisposeAsync() => ValueTask.CompletedTask; /// Yields nothing, and completes when this connection ends. /// Ends the stream early, ahead of the connection itself. /// An empty stream, deliberately. 's remarks say why. - private async IAsyncEnumerable ListenCoreAsync( + private async IAsyncEnumerable ListenCoreAsync( [EnumeratorCancellation] CancellationToken cancellationToken) { // Linked, so the caller's own token ends the stream too, and built from the captured @@ -915,8 +915,8 @@ private async IAsyncEnumerable ListenCoreAsync( } catch (OperationCanceledException) { - // Which token fired is the whole difference, and ICallInputPort.ListenAsync settles - // it: the connection ending is the ordinary end of the call and completes this stream, + // Which token fired is the whole difference, and IConversationInputPort.ListenAsync settles + // it: the connection ending is the ordinary end of the conversation and completes this stream, // while the consumer's own cancellation throws, as any cancelled await does. Rethrown // through the caller's token rather than by letting the linked one out, so the exception // names the token the caller actually cancelled. Both fired at once counts as diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayContracts.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayContracts.cs index 6dda5a64..525003ad 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayContracts.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayContracts.cs @@ -16,25 +16,25 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// internal abstract record RelayFrame { - /// The first frame of a call. It names every id the call will need. + /// The first frame of a conversation. It names every id the conversation will need. /// The relay session. - /// The call, in the vendor vocabulary. + /// The conversation, in the vendor vocabulary. /// - /// The handle the Call Control API accepts. Slice 2 needs it for the conference warm transfer + /// The handle the Conversation Control API accepts. Slice 2 needs it for the conference warm transfer /// of section 4.3, and this frame is the only place it reaches the socket. /// - /// - /// The group of legs that belong to one logical call. It becomes the AgentCore call id, + /// + /// The group of legs that belong to one logical conversation. It becomes the AgentCore conversation id, /// because it survives a transfer and a single leg id does not. /// /// The caller number. /// The number the caller dialled. - /// Per-call values the host attached, or null. + /// Per-conversation values the host attached, or null. internal sealed record Setup( string SessionId, string CallSid, string CallControlId, - string CallSessionId, + string ConversationSessionId, string From, string To, IReadOnlyDictionary? CustomParameters) : RelayFrame; @@ -62,7 +62,7 @@ internal sealed record Interrupt(string UtteranceUntilInterrupt, int DurationUnt internal sealed record Dtmf(string Digit) : RelayFrame; /// The vendor refused a frame this application sent. - /// Why it refused. This reports our defect, not a call fault. + /// Why it refused. This reports our defect, not a conversation fault. internal sealed record Error(string Description) : RelayFrame; } @@ -80,7 +80,7 @@ internal sealed record RelayToken(string Token, bool Last) public string Type { get; } = "text"; } -/// Hands the call back to the vendor, outbound. +/// Hands the conversation back to the vendor, outbound. /// Anything the next step should read, or null. internal sealed record RelayEnd(string? HandoffData) { diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConversationAdapter.cs similarity index 81% rename from src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs rename to src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConversationAdapter.cs index fbc22198..48e7e23e 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallAdapter.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConversationAdapter.cs @@ -1,12 +1,12 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using Microsoft.AspNetCore.Http; namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// -/// The Telnyx Conversation Relay as a call transport: it owns the socket and speaks Telnyx frames. +/// The Telnyx Conversation Relay as a conversation transport: it owns the socket and speaks Telnyx frames. /// /// /// @@ -15,13 +15,13 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// providers.speech.stt and providers.speech.tts, must name this same vendor. /// /// -/// This owns only the route. TelnyxRelayConnection is still what a call runs on, and -/// TelnyxRelayCallChannelFactory is still what hands out its two ports. +/// This owns only the route. TelnyxRelayConnection is still what a conversation runs on, and +/// TelnyxRelayConversationChannelFactory is still what hands out its two ports. /// /// -public sealed class TelnyxRelayCallAdapter : ICallTransportAdapter +public sealed class TelnyxRelayConversationAdapter : IConversationTransportAdapter { - /// The one providers.call.kind value this vendor answers to. + /// The one providers.conversation.kind value this vendor answers to. public const string TelnyxRelayKind = "telnyx-relay"; /// The longest delay Task.Delay, CancelAfter, and Task.WaitAsync all accept. @@ -41,7 +41,7 @@ public sealed class TelnyxRelayCallAdapter : ICallTransportAdapter public bool CarriesText => true; /// - public RequestDelegate CreateHandler(CallProviderConfiguration configuration) + public RequestDelegate CreateHandler(ConversationProviderConfiguration configuration) { ArgumentNullException.ThrowIfNull(configuration); @@ -50,7 +50,7 @@ public RequestDelegate CreateHandler(CallProviderConfiguration configuration) } /// Turns the document's limits into the options the endpoint runs on. - /// The providers.call block. + /// The providers.conversation block. /// The options, with the shipped default kept for every value the document omits. /// /// A value would be refused at run time by Task.Delay, CancelAfter, or @@ -61,7 +61,7 @@ public RequestDelegate CreateHandler(CallProviderConfiguration configuration) /// because the value came from a document rather than /// from a C# caller, and a reader needs the line to fix rather than a property name. /// - internal static TelnyxRelayOptions BuildOptions(CallProviderConfiguration configuration) + internal static TelnyxRelayOptions BuildOptions(ConversationProviderConfiguration configuration) { ArgumentNullException.ThrowIfNull(configuration); @@ -71,7 +71,7 @@ internal static TelnyxRelayOptions BuildOptions(CallProviderConfiguration config { // Every frame is measured against this before it is written into the message buffer. // Zero or less would refuse the first byte of every message forever, which is not a - // limit — it is a call nobody could ever place. + // limit — it is a conversation nobody could ever place. if (frame <= 0) { throw Fail("maxFrameBytes", $"must be positive, and it is {frame}."); @@ -94,7 +94,7 @@ internal static TelnyxRelayOptions BuildOptions(CallProviderConfiguration config } /// Turns whole seconds from the document into the span a bounded wait accepts. - /// The providers.call field the value came from, for the pointer. + /// The providers.conversation field the value came from, for the pointer. /// The whole seconds the document wrote. /// The span, or for -1. private static TimeSpan ToTimeSpan(string field, int seconds) @@ -119,14 +119,14 @@ private static TimeSpan ToTimeSpan(string field, int seconds) } /// Builds the one failure every check here raises, pointed at the field. - /// The providers.call field that is wrong. + /// The providers.conversation field that is wrong. /// What is wrong with it, in the words a reader can act on. /// The failure to throw. private static ConfigurationLoadException Fail(string field, string problem) => new(new ConfigurationError { - Pointer = $"/providers/call/{field}", - Message = $"providers.call.{field} {problem}", + Pointer = $"/providers/conversation/{field}", + Message = $"providers.conversation.{field} {problem}", Check = ConfigurationCheck.ReferenceResolution, }); } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConversationChannelFactory.cs similarity index 68% rename from src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs rename to src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConversationChannelFactory.cs index 8055de62..da0caaf1 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConversationChannelFactory.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Ports; namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; @@ -8,10 +8,10 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// /// Which of the two shapes this is, and why. A relay connection is born from an accepted /// WebSocket rather than from a caller, so there is no moment at which something above asks this -/// factory to go and open a call: by the time a channel could exist, the socket is already up and +/// factory to go and open a conversation: by the time a channel could exist, the socket is already up and /// the connection already owns it. The other shape on offer was to reach the connection through -/// , and that context carries a call id and the host's own -/// per-call values and no vendor field at all — which is exactly what makes D8 hold, and exactly +/// , and that context carries a conversation id and the host's own +/// per-conversation values and no vendor field at all — which is exactly what makes D8 hold, and exactly /// why it cannot smuggle a connection through. So the entry point stays /// , /// app.MapCall() is untouched, and this factory is built with the connection it hands out. @@ -27,21 +27,21 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// behind it, and so the bundled case is written down as the ordinary one rather than the exception. /// /// -/// The connection that accepted this call's socket, and that is both halves of it. -internal sealed class TelnyxRelayCallChannelFactory(TelnyxRelayConnection connection) : ICallChannelFactory +/// The connection that accepted this conversation's socket, and that is both halves of it. +internal sealed class TelnyxRelayConversationChannelFactory(TelnyxRelayConnection connection) : IConversationChannelFactory { /// /// - /// is read for nothing, and the call id in it least of all: this - /// vendor names the call on its own setup frame, and the connection is already answering that - /// call by the time anything here could run. A future factory that really does open a call — + /// is read for nothing, and the conversation id in it least of all: this + /// vendor names the conversation on its own setup frame, and the connection is already answering that + /// conversation by the time anything here could run. A future factory that really does open a conversation — /// the split adapter's — is where those values start to matter. /// - public ValueTask OpenAsync( - CallChannelContext context, + public ValueTask OpenAsync( + ConversationChannelContext context, CancellationToken cancellationToken = default) { // The same object in both slots. Nothing above this line can tell, and nothing may ask. - return ValueTask.FromResult(new CallChannel(connection, connection)); + return ValueTask.FromResult(new ConversationChannel(connection, connection)); } } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs index 88077c5c..05ac9dc9 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayEndpoints.cs @@ -11,23 +11,23 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// /// /// This is the second inbound adapter onto , and -/// the first one that carries a call. The /v1/responses endpoint is the other. Both +/// the first one that carries a conversation. The /v1/responses endpoint is the other. Both /// read the same contract, so D8 holds and the core never learns a vendor frame schema. /// /// /// Nothing here decides whether this transport is in use. The composition root reads -/// providers.call while the host starts, picks the one transport it names, and asks it for a -/// handler through ; -/// +/// providers.conversation while the host starts, picks the one transport it names, and asks it for a +/// handler through ; +/// /// owns only the route string. This type maps whatever it is handed, and it is -/// so that is the only thing that +/// so that is the only thing that /// hands it anything, apart from the test host, through InternalsVisibleTo: a host names its /// route once and changes vendors in the document. /// /// -/// The host owns the WebSocket middleware, and its defaults suit a browser rather than a call. -/// Call app.UseWebSockets with a KeepAliveInterval and a KeepAliveTimeout of -/// about 20 seconds. The shipped default is two minutes with no timeout, which lets a dead call +/// The host owns the WebSocket middleware, and its defaults suit a browser rather than a conversation. +/// Conversation app.UseWebSockets with a KeepAliveInterval and a KeepAliveTimeout of +/// about 20 seconds. The shipped default is two minutes with no timeout, which lets a dead conversation /// hold a session for two minutes. /// /// @@ -39,7 +39,7 @@ internal static class TelnyxRelayEndpointRouteBuilderExtensions /// reaches this value. It is kept because the relay suite maps its host through /// directly and needs one route string both sides agree on. /// - public const string DefaultPattern = "/v1/{" + Call.CallEndpointRouteBuilderExtensions.EntryRouteParameter + "}/telnyx/relay"; + public const string DefaultPattern = "/v1/{" + Conversation.ConversationEndpointRouteBuilderExtensions.EntryRouteParameter + "}/telnyx/relay"; /// Maps the socket on one route, with the limits the host chose. /// The route builder of the host. @@ -47,8 +47,8 @@ internal static class TelnyxRelayEndpointRouteBuilderExtensions /// What the endpoint may do, and for how long. /// The mapped endpoint, so a host adds its own conventions. /// - /// The options are not checked here. is what - /// builds them out of providers.call, and it refuses a value Task.Delay, + /// The options are not checked here. is what + /// builds them out of providers.conversation, and it refuses a value Task.Delay, /// CancelAfter, or Task.WaitAsync would reject before that value is ever written /// into a — with a /// naming the field of diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayFrameReader.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayFrameReader.cs index 7e4ead33..b14dc09c 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayFrameReader.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayFrameReader.cs @@ -13,16 +13,16 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// and nothing in the vendor contract promises that. /// /// -/// A vendor that adds a frame must not be able to drop a call, so an unmodelled type is refused -/// and named rather than thrown. The caller logs the name once for the call, not once for the +/// A vendor that adds a frame must not be able to drop a conversation, so an unmodelled type is refused +/// and named rather than thrown. The caller logs the name once for the conversation, not once for the /// frame, per section 3.1. /// /// /// A vendor that changes a frame must not be able to drop one either, and section 7.1 draws /// no line between the two. A known type whose body will not bind is therefore a third /// answer, apart from both "here is your frame" and "these bytes are not readable at all": the -/// frame is refused, the socket lives, and the call goes on. Two shapes reach it from the live -/// wire — a decimal durationUntilInterruptMs, which would otherwise end a call at the exact +/// frame is refused, the socket lives, and the conversation goes on. Two shapes reach it from the live +/// wire — a decimal durationUntilInterruptMs, which would otherwise end a conversation at the exact /// moment of a barge-in, and a non-string value inside customParameters, which would /// otherwise end it on the setup frame before it began. /// @@ -95,7 +95,7 @@ public static bool TryRead( catch (JsonException) { // The type is one this build knows, so the bytes are readable and only a field is - // wrong. Section 7.1: that is a refused frame, never a refused call. + // wrong. Section 7.1: that is a refused frame, never a refused conversation. refusedType = name; return false; } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayJson.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayJson.cs index 0ac6142c..b0ba31d0 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayJson.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayJson.cs @@ -8,7 +8,7 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// /// /// gives camelCase names and case-insensitive reads, -/// which is exactly what the vendor sends and expects. One shared instance avoids the per-call +/// which is exactly what the vendor sends and expects. One shared instance avoids the per-conversation /// options cache that a fresh instance would rebuild for every frame. /// internal static class TelnyxRelayJson diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayLog.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayLog.cs index f6a732fc..e32851d5 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayLog.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayLog.cs @@ -9,24 +9,24 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// /// The methods are source-generated by , so a line that nobody /// listens to costs one level check and allocates nothing. CA1848 asks for exactly this shape -/// rather than a direct call on . +/// rather than a direct conversation on . /// /// /// No line here carries what the caller said or pressed. The audit chain of D23 is the record of a -/// call, and a log is not; a keypad in particular carries card numbers, PINs, and dates of birth. +/// conversation, and a log is not; a keypad in particular carries card numbers, PINs, and dates of birth. /// /// internal static partial class TelnyxRelayLog { - /// Section 3.1. An unmodelled frame type, logged once for the call. + /// Section 3.1. An unmodelled frame type, logged once for the conversation. /// The logger of the connection. /// The type value no case matched. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. [LoggerMessage( EventId = 1, Level = LogLevel.Information, - Message = "the relay sent an unmodelled frame type '{FrameType}' on call {CallId}.")] - public static partial void UnknownFrameType(ILogger logger, string frameType, string callId); + Message = "the relay sent an unmodelled frame type '{FrameType}' on conversation {ConversationId}.")] + public static partial void UnknownFrameType(ILogger logger, string frameType, string conversationId); /// The caller pressed one key. The key itself never reaches a log line. /// The logger of the connection. @@ -38,15 +38,15 @@ internal static partial class TelnyxRelayLog /// The vendor refused a frame this endpoint sent. That is our defect. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// Why the vendor refused it. [LoggerMessage( EventId = 3, Level = LogLevel.Warning, - Message = "the relay refused a frame on call {CallId}: {Description}")] - public static partial void FrameRefused(ILogger logger, string callId, string description); + Message = "the relay refused a frame on conversation {ConversationId}: {Description}")] + public static partial void FrameRefused(ILogger logger, string conversationId, string description); - /// A prompt arrived before any setup frame, logged once for the call. + /// A prompt arrived before any setup frame, logged once for the conversation. /// The logger of the connection. [LoggerMessage( EventId = 4, @@ -56,37 +56,37 @@ internal static partial class TelnyxRelayLog /// The read loop ended in a fault rather than a clean close. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// The cause. /// - /// states the house rule: on a voice call, silence is + /// states the house rule: on a voice conversation, silence is /// the failure, so this line makes sure a read loop fault is never silent. It fires for anything /// the read loop throws other than the two causes that have their own, quieter case: a /// logs through at /// Warning instead, because it is a protocol violation this endpoint already refused and closed /// on, not an unhandled defect; and a dropped socket with no close frame logs through - /// at Information. Everything else reaching this line + /// at Information. Everything else reaching this line /// is this endpoint's own bug. /// [LoggerMessage( EventId = 5, Level = LogLevel.Error, - Message = "the relay read loop of call {CallId} ended in a fault.")] - public static partial void ReadLoopFaulted(ILogger logger, string callId, Exception exception); + Message = "the relay read loop of conversation {ConversationId} ended in a fault.")] + public static partial void ReadLoopFaulted(ILogger logger, string conversationId, Exception exception); /// A turn faulted rather than finishing or being cancelled by the connection itself. /// The logger of the connection. - /// The id of the call. + /// The id of the conversation. /// The cause. [LoggerMessage( EventId = 6, Level = LogLevel.Error, - Message = "a turn of call {CallId} faulted.")] - public static partial void TurnFaulted(ILogger logger, string callId, Exception exception); + Message = "a turn of conversation {ConversationId} faulted.")] + public static partial void TurnFaulted(ILogger logger, string conversationId, Exception exception); /// The write loop ended in a fault rather than a clean close. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// The cause. /// /// The write loop is the only task that touches the socket, so its fault — typically a @@ -97,12 +97,12 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 7, Level = LogLevel.Error, - Message = "the relay write loop of call {CallId} ended in a fault.")] - public static partial void WriteLoopFaulted(ILogger logger, string callId, Exception exception); + Message = "the relay write loop of conversation {ConversationId} ended in a fault.")] + public static partial void WriteLoopFaulted(ILogger logger, string conversationId, Exception exception); /// A bounded teardown wait expired before the task it was watching stopped. /// The logger of the connection. - /// The id of the call. + /// The id of the conversation. /// Which task did not stop in time, for example "the last turn". /// /// Cancellation reaches a well-behaved task, but this line is not proof of one that ignored its @@ -114,28 +114,28 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 8, Level = LogLevel.Error, - Message = "{What} of call {CallId} did not stop before the close timeout.")] - public static partial void TeardownTimedOut(ILogger logger, string callId, string what); + Message = "{What} of conversation {ConversationId} did not stop before the close timeout.")] + public static partial void TeardownTimedOut(ILogger logger, string conversationId, string what); /// The close handshake faulted for a reason other than its own deadline or a dead peer. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// The cause. /// /// Logged and swallowed rather than left to propagate, because a throw here must not skip the /// write-loop observation or the session close that follow it in RunAsync. A close that - /// never runs leaves the call to wait out its idle timeout, and nothing waits for the words its + /// never runs leaves the conversation to wait out its idle timeout, and nothing waits for the words its /// last turn still owed store 1. /// [LoggerMessage( EventId = 9, Level = LogLevel.Error, - Message = "the close handshake of call {CallId} faulted.")] - public static partial void CloseFaulted(ILogger logger, string callId, Exception exception); + Message = "the close handshake of conversation {ConversationId} faulted.")] + public static partial void CloseFaulted(ILogger logger, string conversationId, Exception exception); /// Cancelling the connection's own token faulted, from a registered callback. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// The cause. /// /// Logged and swallowed rather than left to propagate, because Cancel() runs with @@ -146,12 +146,12 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 10, Level = LogLevel.Error, - Message = "cancelling the connection token of call {CallId} faulted.")] - public static partial void CancellationFaulted(ILogger logger, string callId, Exception exception); + Message = "cancelling the connection token of conversation {ConversationId} faulted.")] + public static partial void CancellationFaulted(ILogger logger, string conversationId, Exception exception); - /// A third final prompt arrived while one turn ran, logged once for the call. + /// A third final prompt arrived while one turn ran, logged once for the conversation. /// The logger of the connection. - /// The id of the call. + /// The id of the conversation. /// /// Item 6a of section 11 holds one pending prompt so a caller's second sentence is not lost. /// A third would queue a prompt behind a question the caller has already moved past, so it is @@ -160,58 +160,58 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 11, Level = LogLevel.Information, - Message = "a further prompt arrived on call {CallId} while one turn was already held. It is dropped.")] - public static partial void PendingPromptDropped(ILogger logger, string callId); + Message = "a further prompt arrived on conversation {ConversationId} while one turn was already held. It is dropped.")] + public static partial void PendingPromptDropped(ILogger logger, string conversationId); /// The relay reported a barge-in. Never the words the caller said. /// The logger of the connection. - /// The id of the call. + /// The id of the conversation. [LoggerMessage( EventId = 12, Level = LogLevel.Information, - Message = "the relay reported a barge-in on call {CallId}.")] - public static partial void InterruptReceived(ILogger logger, string callId); + Message = "the relay reported a barge-in on conversation {ConversationId}.")] + public static partial void InterruptReceived(ILogger logger, string conversationId); - /// A malformed interrupt frame was refused. Section 7.1: a bad frame must not drop the call. + /// A malformed interrupt frame was refused. Section 7.1: a bad frame must not drop the conversation. /// The logger of the connection. - /// The id of the call. + /// The id of the conversation. /// /// Fires when utteranceUntilInterrupt is missing or durationUntilInterruptMs is - /// negative, logged once for the call the same way an unmodelled frame type is. + /// negative, logged once for the conversation the same way an unmodelled frame type is. /// [LoggerMessage( EventId = 13, Level = LogLevel.Warning, - Message = "the relay sent a malformed interrupt frame on call {CallId}. It is dropped.")] - public static partial void MalformedInterruptFrame(ILogger logger, string callId); + Message = "the relay sent a malformed interrupt frame on conversation {ConversationId}. It is dropped.")] + public static partial void MalformedInterruptFrame(ILogger logger, string conversationId); /// A second final prompt arrived while one turn ran, and is held for when it ends. /// The logger of the connection. - /// The id of the call. + /// The id of the conversation. [LoggerMessage( EventId = 14, Level = LogLevel.Information, - Message = "a further prompt arrived on call {CallId} while one turn ran. It is held.")] - public static partial void PromptHeld(ILogger logger, string callId); + Message = "a further prompt arrived on conversation {ConversationId} while one turn ran. It is held.")] + public static partial void PromptHeld(ILogger logger, string conversationId); - /// The relay dropped the socket with no close frame. Task 7: an ordinary end of a call. + /// The relay dropped the socket with no close frame. Task 7: an ordinary end of a conversation. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// /// Fires instead of for exactly one cause: a /// whose code is /// . The vendor - /// never reconnects, so this is a finished call, not a defect this endpoint owns. + /// never reconnects, so this is a finished conversation, not a defect this endpoint owns. /// [LoggerMessage( EventId = 15, Level = LogLevel.Information, - Message = "call {CallId} ended without a close frame from the relay.")] - public static partial void CallDroppedWithNoCloseFrame(ILogger logger, string callId); + Message = "conversation {ConversationId} ended without a close frame from the relay.")] + public static partial void ConversationDroppedWithNoCloseFrame(ILogger logger, string conversationId); /// The read loop refused a frame and the connection is closing because of it. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// /// The fixed, vendor-free message carries — never the /// bytes the relay actually sent. @@ -227,14 +227,14 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 16, Level = LogLevel.Warning, - Message = "the relay read loop of call {CallId} closed the socket over a protocol violation: {Reason}")] - public static partial void RelayProtocolViolation(ILogger logger, string callId, string reason); + Message = "the relay read loop of conversation {ConversationId} closed the socket over a protocol violation: {Reason}")] + public static partial void RelayProtocolViolation(ILogger logger, string conversationId, string reason); - /// No inbound frame arrived within IdleTimeout. Task 8: an ordinary end of a call. + /// No inbound frame arrived within IdleTimeout. Task 8: an ordinary end of a conversation. /// The logger of the connection. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// - /// The vendor never reconnects, so a silent socket is a call that is already over, not a fault + /// The vendor never reconnects, so a silent socket is a conversation that is already over, not a fault /// this endpoint owns. This fires only when the idle deadline itself is the cause: the read /// loop checks that the connection's own teardown token has not also fired before it logs this /// line, so a socket closed for some other reason never gets this one instead. @@ -242,16 +242,16 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 17, Level = LogLevel.Information, - Message = "call {CallId} ended: no inbound frame arrived before the idle deadline.")] - public static partial void IdleTimeoutReached(ILogger logger, string callId); + Message = "conversation {ConversationId} ended: no inbound frame arrived before the idle deadline.")] + public static partial void IdleTimeoutReached(ILogger logger, string conversationId); - /// A frame of a known type carried a field that would not bind, logged once for the call. + /// A frame of a known type carried a field that would not bind, logged once for the conversation. /// The logger of the connection. /// The type value whose body was refused. - /// The id of the call, or a placeholder before setup. + /// The id of the conversation, or a placeholder before setup. /// /// Section 7.1 gives a vendor that adds a frame and a vendor that changes one the same rule: - /// neither may drop a call. A decimal durationUntilInterruptMs and a non-string value in + /// neither may drop a conversation. A decimal durationUntilInterruptMs and a non-string value in /// customParameters both reach here. This is the vendor's defect and not this endpoint's, /// so it logs at Warning, beside and /// , and never at the Error level a bug of ours gets. The @@ -261,63 +261,63 @@ internal static partial class TelnyxRelayLog [LoggerMessage( EventId = 18, Level = LogLevel.Warning, - Message = "the relay sent a '{FrameType}' frame on call {CallId} whose body this build cannot " - + "read. It is dropped, and the call continues.")] - public static partial void FrameBodyRefused(ILogger logger, string frameType, string callId); + Message = "the relay sent a '{FrameType}' frame on conversation {ConversationId} whose body this build cannot " + + "read. It is dropped, and the conversation continues.")] + public static partial void FrameBodyRefused(ILogger logger, string frameType, string conversationId); - /// A second setup frame arrived on one socket, logged once for the call. + /// A second setup frame arrived on one socket, logged once for the conversation. /// The logger of the connection. - /// The id of the call the first setup frame started. + /// The id of the conversation the first setup frame started. /// - /// One socket carries one call, and the vendor sends one setup. A second one is the - /// vendor's defect, and section 7.1 forbids dropping a call over one, so the frame replaces the + /// One socket carries one conversation, and the vendor sends one setup. A second one is the + /// vendor's defect, and section 7.1 forbids dropping a conversation over one, so the frame replaces the /// session rather than refusing the socket. The first session is closed as it goes, because /// teardown only ever closes the session the connection currently holds — so this is the last - /// moment anything waits for the words the replaced call still owed store 1. + /// moment anything waits for the words the replaced conversation still owed store 1. /// [LoggerMessage( EventId = 19, Level = LogLevel.Warning, - Message = "the relay sent a second setup frame on call {CallId}. The first session is " + Message = "the relay sent a second setup frame on conversation {ConversationId}. The first session is " + "released and the new one replaces it.")] - public static partial void SecondSetupFrame(ILogger logger, string callId); + public static partial void SecondSetupFrame(ILogger logger, string conversationId); - /// Closing the audit chain of a call faulted, so that call has no call.ended event. + /// Closing the audit chain of a conversation faulted, so that call has no conversation.ended event. /// The logger of the connection. - /// The id of the call whose chain did not close. + /// The id of the conversation whose chain did not close. /// The cause. /// /// This is worth an Error line and not a quieter one. §9 makes the chain of D23 the only - /// long-term record of a call, and §11 item 6 says every chain ends in call.ended, so a + /// long-term record of a conversation, and §11 item 6 says every chain ends in conversation.ended, so a /// chain that stops without one is a permanent gap in that record rather than a passing /// inconvenience. Logged and swallowed all the same: §7.1 forbids teardown throwing out of the /// request handler, and the session close that follows it in RunAsync must still run — a - /// close that never runs leaves the call to wait out its idle timeout with its last words never + /// close that never runs leaves the conversation to wait out its idle timeout with its last words never /// waited for. /// [LoggerMessage( EventId = 20, Level = LogLevel.Error, - Message = "the audit chain of call {CallId} could not be closed, so it has no call.ended event.")] - public static partial void CallEndFaulted(ILogger logger, string callId, Exception exception); + Message = "the audit chain of conversation {ConversationId} could not be closed, so it has no conversation.ended event.")] + public static partial void ConversationEndFaulted(ILogger logger, string conversationId, Exception exception); - /// The session of a call could not be closed at the end of that call. + /// The session of a conversation could not be closed at the end of that conversation. /// The logger. - /// The id of the call. + /// The id of the conversation. /// The cause. [LoggerMessage( EventId = 22, Level = LogLevel.Error, - Message = "the session of call {CallId} could not be closed, so its last words may never reach store 1 and it waits out the idle timeout.")] - public static partial void CallCloseFaulted(ILogger logger, string callId, Exception exception); + Message = "the session of conversation {ConversationId} could not be closed, so its last words may never reach store 1 and it waits out the idle timeout.")] + public static partial void ConversationCloseFaulted(ILogger logger, string conversationId, Exception exception); - /// The store could not be told that a call is still being had. + /// The store could not be told that a conversation is still being had. /// The logger. - /// The id of the call. + /// The id of the conversation. /// The cause. [LoggerMessage( EventId = 23, Level = LogLevel.Warning, - Message = "the store could not be read for call {CallId}, so that call may be dropped by the idle sweep while it is still running.")] - public static partial void SessionTouchFaulted(ILogger logger, string callId, Exception exception); + Message = "the store could not be read for conversation {ConversationId}, so that call may be dropped by the idle sweep while it is still running.")] + public static partial void SessionTouchFaulted(ILogger logger, string conversationId, Exception exception); } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs index 5992eec0..58c8dd95 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayOptions.cs @@ -4,7 +4,7 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// What the relay endpoint may do, and for how long. /// /// -/// Every default here is chosen for a phone call. A call is short, it is quiet in bytes, and a +/// Every default here is chosen for a phone conversation. A conversation is short, it is quiet in bytes, and a /// dead one must be noticed in seconds rather than minutes. /// internal sealed class TelnyxRelayOptions @@ -20,9 +20,9 @@ internal sealed class TelnyxRelayOptions /// Gets or sets how long teardown gives a stuck task before it moves on. /// /// Every wait that could otherwise wedge a connection shares this one bound: how long the last - /// turn of a call may take to unwind once teardown cancels it, how long the close handshake may - /// take before the socket is aborted, and how long the words of a call may take to reach store 1 - /// before its session is dropped. A telephony call that already dropped never answers a close + /// turn of a conversation may take to unwind once teardown cancels it, how long the close handshake may + /// take before the socket is aborted, and how long the words of a conversation may take to reach store 1 + /// before its session is dropped. A telephony conversation that already dropped never answers a close /// frame, a chat client is not guaranteed to honour cancellation promptly, and a transcript /// store talks to a database, so each wait needs a bound or any one of them could wedge the /// connection forever. Because they run one after another rather than together, one wedged @@ -32,9 +32,9 @@ internal sealed class TelnyxRelayOptions /// public TimeSpan CloseTimeout { get; set; } = TimeSpan.FromSeconds(5); - /// Gets or sets how long the endpoint waits with no inbound frame before it ends the call. + /// Gets or sets how long the endpoint waits with no inbound frame before it ends the conversation. /// - /// The vendor never reconnects, so a silent socket is a call that is already over. The clock + /// The vendor never reconnects, so a silent socket is a conversation that is already over. The clock /// is a , resolved from the request's own service provider rather /// than a property of this class: /// when the host bound one, otherwise . A test that wants a diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelaySpeechAdapter.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelaySpeechAdapter.cs index b8f2ccd5..a1715e36 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelaySpeechAdapter.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelaySpeechAdapter.cs @@ -12,12 +12,12 @@ namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; /// service the process dials. A host registers this through /// AgentCoreOptions.UseSpeech, and a document that names it under providers.speech.stt /// and providers.speech.tts then selects it — both roles, because it sells both. The socket -/// itself belongs to providers.call, which app.MapCall() reads — and because this +/// itself belongs to providers.conversation, which app.MapCall() reads — and because this /// vendor bundles the pipe with the ears and the mouth, all three names must agree or the start /// fails. /// /// -/// It carries a kind and nothing else, because does. A relay call +/// It carries a kind and nothing else, because does. A relay conversation /// is born from a socket the host already accepted, so there is nothing here to create at selection /// time: the frames arriving on that socket are the channel. /// diff --git a/src/AgentCore.Domain/Audit/AuditEvent.cs b/src/AgentCore.Domain/Audit/AuditEvent.cs index 39b606ac..e708abd5 100644 --- a/src/AgentCore.Domain/Audit/AuditEvent.cs +++ b/src/AgentCore.Domain/Audit/AuditEvent.cs @@ -1,15 +1,15 @@ namespace AgentCore.Domain.Audit; /// -/// One append-only audit event. It is what a call wrote at one moment, and nothing edits it. +/// One append-only audit event. It is what a conversation wrote at one moment, and nothing edits it. /// public sealed record AuditEvent { private static readonly IReadOnlyDictionary EmptyPayload = new Dictionary(StringComparer.Ordinal); - /// Gets the id of the call the event belongs to. - public required string CallId { get; init; } + /// Gets the id of the conversation the event belongs to. + public required string ConversationId { get; init; } /// Gets what the event records. public required AuditEventKind Kind { get; init; } @@ -19,21 +19,21 @@ public sealed record AuditEvent /// /// Gets the zero-based index of the turn the event belongs to, or when the - /// event belongs to the call rather than to one turn. + /// event belongs to the conversation rather than to one turn. /// public int? TurnIndex { get; init; } - /// Gets the identity of the event. The call allocates it, and it never orders anything. + /// Gets the identity of the event. The conversation allocates it, and it never orders anything. /// /// It is a UUID v7, so it is unique without a round trip and an amendment can name the event it /// corrects the instant that event is raised. It is not an order: v7 is random within a - /// millisecond, and a turn raises three events inside one. The order of a call is the + /// millisecond, and a turn raises three events inside one. The order of a conversation is the /// sequence the store assigns, and nothing sorts by this value. /// public required Guid EventId { get; init; } /// - /// Gets the of the earlier event in the same call that this event corrects, + /// Gets the of the earlier event in the same conversation that this event corrects, /// or when the event corrects nothing. /// public Guid? AmendsEventId { get; init; } diff --git a/src/AgentCore.Domain/Audit/AuditEventKind.cs b/src/AgentCore.Domain/Audit/AuditEventKind.cs index 545f31b9..0b91f461 100644 --- a/src/AgentCore.Domain/Audit/AuditEventKind.cs +++ b/src/AgentCore.Domain/Audit/AuditEventKind.cs @@ -1,12 +1,12 @@ namespace AgentCore.Domain.Audit; /// -/// The closed set of things one call writes into the audit chain. +/// The closed set of things one conversation writes into the audit chain. /// public enum AuditEventKind { - /// A session of the call started. It is the first event of every session, not of every call. - CallStarted = 0, + /// A session of the conversation started. It is the first event of every session, not of every conversation. + ConversationStarted = 0, /// One turn ran to the end, and the caller heard the whole reply. TurnCompleted = 1, @@ -18,8 +18,8 @@ public enum AuditEventKind ToolFailed = 3, - /// The host ended the call. It is the last event of the session that ended it, not of the chain. - CallEnded = 5, + /// The host ended the conversation. It is the last event of the session that ended it, not of the chain. + ConversationEnded = 5, /// Moderation flagged what the CALLER said, so the agent refused to answer that turn. PromptFlagged = 6, diff --git a/src/AgentCore.Domain/Audit/AuditEventKinds.cs b/src/AgentCore.Domain/Audit/AuditEventKinds.cs index 1e6b8c50..582ac6d4 100644 --- a/src/AgentCore.Domain/Audit/AuditEventKinds.cs +++ b/src/AgentCore.Domain/Audit/AuditEventKinds.cs @@ -11,11 +11,11 @@ public static class AuditEventKinds /// The value is not a member of the closed set. public static string ToToken(AuditEventKind kind) => kind switch { - AuditEventKind.CallStarted => "call.started", + AuditEventKind.ConversationStarted => "conversation.started", AuditEventKind.TurnCompleted => "turn.completed", AuditEventKind.ReplyInterrupted => "reply.interrupted", AuditEventKind.ToolFailed => "tool.failed", - AuditEventKind.CallEnded => "call.ended", + AuditEventKind.ConversationEnded => "conversation.ended", AuditEventKind.PromptFlagged => "prompt.flagged", AuditEventKind.TurnSuperseded => "turn.superseded", _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "The audit event vocabulary is closed, and this value is not in it."), @@ -29,11 +29,11 @@ public static bool TryParse(string? token, out AuditEventKind kind) { switch (token) { - case "call.started": kind = AuditEventKind.CallStarted; return true; + case "conversation.started": kind = AuditEventKind.ConversationStarted; return true; case "turn.completed": kind = AuditEventKind.TurnCompleted; return true; case "reply.interrupted": kind = AuditEventKind.ReplyInterrupted; return true; case "tool.failed": kind = AuditEventKind.ToolFailed; return true; - case "call.ended": kind = AuditEventKind.CallEnded; return true; + case "conversation.ended": kind = AuditEventKind.ConversationEnded; return true; case "prompt.flagged": kind = AuditEventKind.PromptFlagged; return true; case "turn.superseded": kind = AuditEventKind.TurnSuperseded; return true; default: kind = default; return false; diff --git a/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs b/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs index 33dcac27..15ce395c 100644 --- a/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs +++ b/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs @@ -9,9 +9,9 @@ public static class AuditEventVocabulary /// Refuses an event the vocabulary does not permit. public static void Validate(AuditEvent auditEvent) { - if (string.IsNullOrEmpty(auditEvent.CallId)) + if (string.IsNullOrEmpty(auditEvent.ConversationId)) { - throw new ArgumentException("An audit event carries a call id.", nameof(auditEvent)); + throw new ArgumentException("An audit event carries a conversation id.", nameof(auditEvent)); } if (auditEvent.EventId == Guid.Empty) @@ -44,7 +44,7 @@ public static void Validate(AuditEvent auditEvent) RequirePromptFlagged(auditEvent); - RequireCallEnded(auditEvent); + RequireConversationEnded(auditEvent); foreach (KeyValuePair entry in auditEvent.Payload) { @@ -111,18 +111,18 @@ private static void RequirePromptFlagged(AuditEvent auditEvent) } - /// Refuses a call end that carries no reason from the closed set. - private static void RequireCallEnded(AuditEvent auditEvent) + /// Refuses a conversation end that carries no reason from the closed set. + private static void RequireConversationEnded(AuditEvent auditEvent) { // The reason is countable, so the chain refuses free text here. §9 makes this table the // only long-term record, and a report that counts the endings of one year reads the - // token. Detail belongs under another key. See CallEndReason. - if (auditEvent.Kind == AuditEventKind.CallEnded + // token. Detail belongs under another key. See ConversationEndReason. + if (auditEvent.Kind == AuditEventKind.ConversationEnded && (!auditEvent.Payload.TryGetValue(AuditPayloadKeys.EndReason, out string? endReason) - || !CallEndReasons.TryParse(endReason, out _))) + || !ConversationEndReasons.TryParse(endReason, out _))) { throw new ArgumentException( - $"A call.ended event carries '{AuditPayloadKeys.EndReason}', and the value is one token of the closed set. See CallEndReason.", + $"A conversation.ended event carries '{AuditPayloadKeys.EndReason}', and the value is one token of the closed set. See ConversationEndReason.", nameof(auditEvent)); } } diff --git a/src/AgentCore.Domain/Audit/AuditHash.cs b/src/AgentCore.Domain/Audit/AuditHash.cs index aa1a6acd..4e2151ee 100644 --- a/src/AgentCore.Domain/Audit/AuditHash.cs +++ b/src/AgentCore.Domain/Audit/AuditHash.cs @@ -80,7 +80,7 @@ public static AuditHash FromDigest(ReadOnlySpan digest) /// The text to hash. The empty string is legal and hashes to a full digest. /// The SHA-256 of the UTF-8 bytes of the text. /// - /// The spoken words of a call live in store 1, where they stay erasable, and the chain stores + /// The spoken words of a conversation live in store 1, where they stay erasable, and the chain stores /// this instead. The bytes are UTF-8 with no byte-order mark, which is the same input /// encode(sha256(convert_to(t, 'UTF8')), 'hex') reads in PostgreSQL, so a reviewer can /// recompute the proof in either place. diff --git a/src/AgentCore.Domain/Audit/AuditPayloadKeys.cs b/src/AgentCore.Domain/Audit/AuditPayloadKeys.cs index db7eb833..61a72d06 100644 --- a/src/AgentCore.Domain/Audit/AuditPayloadKeys.cs +++ b/src/AgentCore.Domain/Audit/AuditPayloadKeys.cs @@ -60,7 +60,7 @@ public static class AuditPayloadKeys public const string ModerationCategories = "moderationCategories"; /// - /// Why the call ended. + /// Why the conversation ended. /// public const string EndReason = "endReason"; diff --git a/src/AgentCore.Domain/Audit/CallEndReason.cs b/src/AgentCore.Domain/Audit/ConversationEndReason.cs similarity index 70% rename from src/AgentCore.Domain/Audit/CallEndReason.cs rename to src/AgentCore.Domain/Audit/ConversationEndReason.cs index 082cd099..f3b0fc0b 100644 --- a/src/AgentCore.Domain/Audit/CallEndReason.cs +++ b/src/AgentCore.Domain/Audit/ConversationEndReason.cs @@ -1,22 +1,22 @@ namespace AgentCore.Domain.Audit; /// -/// The closed set of ways one call ends. +/// The closed set of ways one conversation ends. /// /// /// /// The set is closed for the reason the chain exists. D23 makes the audit table the record of the -/// call, and D26 buys 14 days of free retention on every other signal, so §9 calls this chain the +/// conversation, and D26 buys 14 days of free retention on every other signal, so §9 calls this chain the /// only long-term record. A report written years later reads this table and nothing else. A /// free-text reason cannot be counted: one path writes /// hangup, a second writes caller hung up, and a third writes HANGUP, and the /// three are one fact under three names. /// /// -/// Section 4 names every way a call ends, and there are four. The caller hangs up, and only the +/// Section 4 names every way a conversation ends, and there are four. The caller hangs up, and only the /// vendor adapter sees it. The stage machine reaches a terminal stage, and the agent finished the -/// work. The agent hands the call to a human through the conference pattern of section 4.3, which is -/// item 5 of section 11. Or a fault ends the call. +/// work. The agent hands the conversation to a human through the conference pattern of section 4.3, which is +/// item 5 of section 11. Or a fault ends the conversation. /// /// /// A caller that holds more detail puts it in another payload key. The vendor hang-up cause, the @@ -25,20 +25,20 @@ namespace AgentCore.Domain.Audit; /// /// /// The set is small on purpose, and it stays small. A new reason is a change to this enum, a change -/// to , and a new row in the public API file. +/// to , and a new row in the public API file. /// /// -public enum CallEndReason +public enum ConversationEndReason { /// The caller hung up. /// - /// Only the telephony adapter sees this, because the hang-up arrives on a Call Control webhook + /// Only the telephony adapter sees this, because the hang-up arrives on a Conversation Control webhook /// and never on the relay socket. The vendor reports a cause with it, and that cause is detail /// beside the reason rather than the reason. /// CallerHungUp = 0, - /// The stage machine reached a terminal stage, and the agent finished the call. + /// The stage machine reached a terminal stage, and the agent finished the conversation. /// /// The turn loop closes the chain itself here, because it is the only place that knows the stage /// the machine reached. The event carries that stage under @@ -46,18 +46,18 @@ public enum CallEndReason /// AgentCompleted = 1, - /// The call went to a human through the conference pattern. + /// The conversation went to a human through the conference pattern. /// - /// Section 11, item 5, and section 4.3: the adapter joins the call to a conference and never + /// Section 11, item 5, and section 4.3: the adapter joins the conversation to a conference and never /// sends the Telnyx transfer command, which costs $0.10 for each invocation (T27). The - /// call leaves the agent at this point, so this is the last event of its chain. + /// conversation leaves the agent at this point, so this is the last event of its chain. /// TransferredToHuman = 2, - /// A fault ended the call. + /// A fault ended the conversation. /// /// This is the ending section 8.7 works to prevent, so it is rare. A tool that fails and a run - /// that answers with no text both speak the fallback line and keep the call, and neither reaches + /// that answers with no text both speak the fallback line and keep the conversation, and neither reaches /// here. A dropped relay socket and a stage that names no agent do. /// Faulted = 3, diff --git a/src/AgentCore.Domain/Audit/CallEndReasons.cs b/src/AgentCore.Domain/Audit/ConversationEndReasons.cs similarity index 58% rename from src/AgentCore.Domain/Audit/CallEndReasons.cs rename to src/AgentCore.Domain/Audit/ConversationEndReasons.cs index 14b94117..af580f16 100644 --- a/src/AgentCore.Domain/Audit/CallEndReasons.cs +++ b/src/AgentCore.Domain/Audit/ConversationEndReasons.cs @@ -1,11 +1,11 @@ namespace AgentCore.Domain.Audit; /// -/// The wire token of each . +/// The wire token of each . /// /// /// -/// The call.ended payload holds this token under , and +/// The conversation.ended payload holds this token under , and /// never the .NET member name, and never the numeric value of the enum. This is the treatment /// already gives an event kind, and it is the same argument: a rename /// of a C# member must not change a hash PostgreSQL already stored, and the CHECK constraint @@ -18,22 +18,22 @@ namespace AgentCore.Domain.Audit; /// /// /// A token reads <who ended it>.<what they did>. caller.hangup takes the -/// vendor's own word, because the Call Control webhook that reports it is named call.hangup +/// vendor's own word, because the Conversation Control webhook that reports it is named conversation.hangup /// and the adapter maps one to the other. /// /// -public static class CallEndReasons +public static class ConversationEndReasons { /// Reads the wire token of one reason. /// The reason to name. - /// The token the call.ended payload writes. + /// The token the conversation.ended payload writes. /// The value is not a member of the closed set. - public static string ToToken(CallEndReason reason) => reason switch + public static string ToToken(ConversationEndReason reason) => reason switch { - CallEndReason.CallerHungUp => "caller.hangup", - CallEndReason.AgentCompleted => "agent.completed", - CallEndReason.TransferredToHuman => "agent.transferred", - CallEndReason.Faulted => "call.faulted", + ConversationEndReason.CallerHungUp => "caller.hangup", + ConversationEndReason.AgentCompleted => "agent.completed", + ConversationEndReason.TransferredToHuman => "agent.transferred", + ConversationEndReason.Faulted => "conversation.faulted", _ => throw new ArgumentOutOfRangeException(nameof(reason), reason, "The end-reason vocabulary is closed, and this value is not in it."), }; @@ -41,14 +41,14 @@ public static class CallEndReasons /// The token a stored row holds. /// The reason, when the token is known. /// when the token names a reason. - public static bool TryParse(string? token, out CallEndReason reason) + public static bool TryParse(string? token, out ConversationEndReason reason) { switch (token) { - case "caller.hangup": reason = CallEndReason.CallerHungUp; return true; - case "agent.completed": reason = CallEndReason.AgentCompleted; return true; - case "agent.transferred": reason = CallEndReason.TransferredToHuman; return true; - case "call.faulted": reason = CallEndReason.Faulted; return true; + case "caller.hangup": reason = ConversationEndReason.CallerHungUp; return true; + case "agent.completed": reason = ConversationEndReason.AgentCompleted; return true; + case "agent.transferred": reason = ConversationEndReason.TransferredToHuman; return true; + case "conversation.faulted": reason = ConversationEndReason.Faulted; return true; default: reason = default; return false; } } diff --git a/src/AgentCore.Domain/Audit/ToolFailureKind.cs b/src/AgentCore.Domain/Audit/ToolFailureKind.cs index 003c3034..8191b548 100644 --- a/src/AgentCore.Domain/Audit/ToolFailureKind.cs +++ b/src/AgentCore.Domain/Audit/ToolFailureKind.cs @@ -5,8 +5,8 @@ namespace AgentCore.Domain.Audit; /// /// /// -/// The set is closed for the reason gives. D23 makes the audit table the -/// record of the call and §9 makes it the only long-term record, so a report written years later +/// The set is closed for the reason gives. D23 makes the audit table the +/// record of the conversation and §9 makes it the only long-term record, so a report written years later /// counts these two facts apart and reads nothing else. Free text cannot be counted. /// /// diff --git a/src/AgentCore.Domain/Audit/ToolFailureKinds.cs b/src/AgentCore.Domain/Audit/ToolFailureKinds.cs index 0206956b..583faf87 100644 --- a/src/AgentCore.Domain/Audit/ToolFailureKinds.cs +++ b/src/AgentCore.Domain/Audit/ToolFailureKinds.cs @@ -7,7 +7,7 @@ namespace AgentCore.Domain.Audit; /// /// The tool.failed payload holds this token under , /// and never the .NET member name, and never the numeric value of the enum. This is the treatment -/// already gives an end reason, and it is the same argument: a rename of a +/// already gives an end reason, and it is the same argument: a rename of a /// C# member must not change a hash PostgreSQL already stored, and the CHECK constraint of D23 /// recomputes the same SHA-256 inside the engine, where no enum exists. /// @@ -16,7 +16,7 @@ namespace AgentCore.Domain.Audit; /// /// /// A token reads tool.<what happened to it>, which is the -/// <subject>.<what happened> shape uses. The tokens are +/// <subject>.<what happened> shape uses. The tokens are /// deliberately NOT the framework's NotFound and Exception: those name a C# enum whose /// stability Microsoft does not promise, and a stored row must not depend on it. /// diff --git a/src/AgentCore.Domain/PublicAPI.Unshipped.txt b/src/AgentCore.Domain/PublicAPI.Unshipped.txt index aca4a783..3e7ffc36 100644 --- a/src/AgentCore.Domain/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Domain/PublicAPI.Unshipped.txt @@ -4,8 +4,8 @@ AgentCore.Domain.Audit.AuditEvent.$() -> AgentCore.Domain.Audit.AuditEven AgentCore.Domain.Audit.AuditEvent.AmendsEventId.get -> System.Guid? AgentCore.Domain.Audit.AuditEvent.AmendsEventId.init -> void AgentCore.Domain.Audit.AuditEvent.AuditEvent() -> void -AgentCore.Domain.Audit.AuditEvent.CallId.get -> string! -AgentCore.Domain.Audit.AuditEvent.CallId.init -> void +AgentCore.Domain.Audit.AuditEvent.ConversationId.get -> string! +AgentCore.Domain.Audit.AuditEvent.ConversationId.init -> void AgentCore.Domain.Audit.AuditEvent.Equals(AgentCore.Domain.Audit.AuditEvent? other) -> bool AgentCore.Domain.Audit.AuditEvent.EventId.get -> System.Guid AgentCore.Domain.Audit.AuditEvent.EventId.init -> void @@ -18,8 +18,8 @@ AgentCore.Domain.Audit.AuditEvent.Payload.init -> void AgentCore.Domain.Audit.AuditEvent.TurnIndex.get -> int? AgentCore.Domain.Audit.AuditEvent.TurnIndex.init -> void AgentCore.Domain.Audit.AuditEventKind -AgentCore.Domain.Audit.AuditEventKind.CallEnded = 5 -> AgentCore.Domain.Audit.AuditEventKind -AgentCore.Domain.Audit.AuditEventKind.CallStarted = 0 -> AgentCore.Domain.Audit.AuditEventKind +AgentCore.Domain.Audit.AuditEventKind.ConversationEnded = 5 -> AgentCore.Domain.Audit.AuditEventKind +AgentCore.Domain.Audit.AuditEventKind.ConversationStarted = 0 -> AgentCore.Domain.Audit.AuditEventKind AgentCore.Domain.Audit.AuditEventKind.PromptFlagged = 6 -> AgentCore.Domain.Audit.AuditEventKind AgentCore.Domain.Audit.AuditEventKind.ReplyInterrupted = 2 -> AgentCore.Domain.Audit.AuditEventKind AgentCore.Domain.Audit.AuditEventKind.ToolFailed = 3 -> AgentCore.Domain.Audit.AuditEventKind @@ -32,12 +32,12 @@ AgentCore.Domain.Audit.AuditHash.$() -> AgentCore.Domain.Audit.AuditHash! AgentCore.Domain.Audit.AuditHash.Equals(AgentCore.Domain.Audit.AuditHash? other) -> bool AgentCore.Domain.Audit.AuditHash.Value.get -> string! AgentCore.Domain.Audit.AuditPayloadKeys -AgentCore.Domain.Audit.CallEndReason -AgentCore.Domain.Audit.CallEndReason.AgentCompleted = 1 -> AgentCore.Domain.Audit.CallEndReason -AgentCore.Domain.Audit.CallEndReason.CallerHungUp = 0 -> AgentCore.Domain.Audit.CallEndReason -AgentCore.Domain.Audit.CallEndReason.Faulted = 3 -> AgentCore.Domain.Audit.CallEndReason -AgentCore.Domain.Audit.CallEndReason.TransferredToHuman = 2 -> AgentCore.Domain.Audit.CallEndReason -AgentCore.Domain.Audit.CallEndReasons +AgentCore.Domain.Audit.ConversationEndReason +AgentCore.Domain.Audit.ConversationEndReason.AgentCompleted = 1 -> AgentCore.Domain.Audit.ConversationEndReason +AgentCore.Domain.Audit.ConversationEndReason.CallerHungUp = 0 -> AgentCore.Domain.Audit.ConversationEndReason +AgentCore.Domain.Audit.ConversationEndReason.Faulted = 3 -> AgentCore.Domain.Audit.ConversationEndReason +AgentCore.Domain.Audit.ConversationEndReason.TransferredToHuman = 2 -> AgentCore.Domain.Audit.ConversationEndReason +AgentCore.Domain.Audit.ConversationEndReasons AgentCore.Domain.Audit.ToolFailureKind AgentCore.Domain.Audit.ToolFailureKind.Faulted = 1 -> AgentCore.Domain.Audit.ToolFailureKind AgentCore.Domain.Audit.ToolFailureKind.Undeclared = 0 -> AgentCore.Domain.Audit.ToolFailureKind @@ -112,9 +112,9 @@ AgentCore.Domain.TurnResult AgentCore.Domain.TurnResult.$() -> AgentCore.Domain.TurnResult! AgentCore.Domain.TurnResult.Approvals.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Domain.TurnResult.Approvals.init -> void -AgentCore.Domain.TurnResult.CallId.get -> string! -AgentCore.Domain.TurnResult.CallId.init -> void -AgentCore.Domain.TurnResult.Deconstruct(out string! CallId, out int TurnIndex, out string! StageBefore, out string! StageAfter, out string! ReplyText, out bool IsTerminal, out string? ExtractionFailure, out string? Failure, out System.TimeSpan? InterruptedAfter, out System.DateTimeOffset EndedAt) -> void +AgentCore.Domain.TurnResult.ConversationId.get -> string! +AgentCore.Domain.TurnResult.ConversationId.init -> void +AgentCore.Domain.TurnResult.Deconstruct(out string! ConversationId, out int TurnIndex, out string! StageBefore, out string! StageAfter, out string! ReplyText, out bool IsTerminal, out string? ExtractionFailure, out string? Failure, out System.TimeSpan? InterruptedAfter, out System.DateTimeOffset EndedAt) -> void AgentCore.Domain.TurnResult.EndedAt.get -> System.DateTimeOffset AgentCore.Domain.TurnResult.EndedAt.init -> void AgentCore.Domain.TurnResult.Equals(AgentCore.Domain.TurnResult? other) -> bool @@ -134,7 +134,7 @@ AgentCore.Domain.TurnResult.StageBefore.get -> string! AgentCore.Domain.TurnResult.StageBefore.init -> void AgentCore.Domain.TurnResult.TurnIndex.get -> int AgentCore.Domain.TurnResult.TurnIndex.init -> void -AgentCore.Domain.TurnResult.TurnResult(string! CallId, int TurnIndex, string! StageBefore, string! StageAfter, string! ReplyText, bool IsTerminal, string? ExtractionFailure, string? Failure = null, System.TimeSpan? InterruptedAfter = null, System.DateTimeOffset EndedAt = default(System.DateTimeOffset)) -> void +AgentCore.Domain.TurnResult.TurnResult(string! ConversationId, int TurnIndex, string! StageBefore, string! StageAfter, string! ReplyText, bool IsTerminal, string? ExtractionFailure, string? Failure = null, System.TimeSpan? InterruptedAfter = null, System.DateTimeOffset EndedAt = default(System.DateTimeOffset)) -> void const AgentCore.Domain.Audit.AuditHash.Length = 64 -> int const AgentCore.Domain.Audit.AuditPayloadKeys.DurationUntilInterruptMs = "durationUntilInterruptMs" -> string! const AgentCore.Domain.Audit.AuditPayloadKeys.EndReason = "endReason" -> string! @@ -181,8 +181,8 @@ static AgentCore.Domain.Audit.AuditHash.Parse(string! value) -> AgentCore.Domain static AgentCore.Domain.Audit.AuditHash.TryParse(string? value, out AgentCore.Domain.Audit.AuditHash? hash) -> bool static AgentCore.Domain.Audit.AuditHash.operator !=(AgentCore.Domain.Audit.AuditHash? left, AgentCore.Domain.Audit.AuditHash? right) -> bool static AgentCore.Domain.Audit.AuditHash.operator ==(AgentCore.Domain.Audit.AuditHash? left, AgentCore.Domain.Audit.AuditHash? right) -> bool -static AgentCore.Domain.Audit.CallEndReasons.ToToken(AgentCore.Domain.Audit.CallEndReason reason) -> string! -static AgentCore.Domain.Audit.CallEndReasons.TryParse(string? token, out AgentCore.Domain.Audit.CallEndReason reason) -> bool +static AgentCore.Domain.Audit.ConversationEndReasons.ToToken(AgentCore.Domain.Audit.ConversationEndReason reason) -> string! +static AgentCore.Domain.Audit.ConversationEndReasons.TryParse(string? token, out AgentCore.Domain.Audit.ConversationEndReason reason) -> bool static AgentCore.Domain.Audit.ToolFailureKinds.ToToken(AgentCore.Domain.Audit.ToolFailureKind kind) -> string! static AgentCore.Domain.Audit.ToolFailureKinds.TryParse(string? token, out AgentCore.Domain.Audit.ToolFailureKind kind) -> bool static AgentCore.Domain.Knowledge.KnowledgeCard.operator !=(AgentCore.Domain.Knowledge.KnowledgeCard? left, AgentCore.Domain.Knowledge.KnowledgeCard? right) -> bool diff --git a/src/AgentCore.Domain/TurnResult.cs b/src/AgentCore.Domain/TurnResult.cs index 6d1a0c6c..36298664 100644 --- a/src/AgentCore.Domain/TurnResult.cs +++ b/src/AgentCore.Domain/TurnResult.cs @@ -1,7 +1,7 @@ namespace AgentCore.Domain; /// -/// What one finished turn did to one call. +/// What one finished turn did to one conversation. /// /// /// @@ -16,7 +16,7 @@ namespace AgentCore.Domain; /// A failed turn is reported the same way. Section 8.7 gives the turn loop two failures it must /// survive: a run that returns an empty reply after 40 tool rounds, and a tool that fails four times /// in a row. Both end the turn with a spoken fallback, both fill , and neither -/// drops the call. +/// drops the conversation. /// /// /// is always the text the caller heard. It is the fallback when the turn @@ -25,7 +25,7 @@ namespace AgentCore.Domain; /// item 6a reads them and never computes them. /// /// -/// The id of the call this turn belongs to. +/// The id of the conversation this turn belongs to. /// The zero-based index of the turn that just ran. /// /// The stage the turn ran in. It is empty when the document declares no policy:. @@ -39,7 +39,7 @@ namespace AgentCore.Domain; /// is set, and the truncated reply when /// is set. /// -/// Whether the stage after the turn ends the call. +/// Whether the stage after the turn ends the conversation. /// /// The reason the extractor produced nothing, or when it ran or did not run. /// @@ -55,12 +55,12 @@ namespace AgentCore.Domain; /// The moment the turn ended, read from the clock the turn loop was given. The audit chain of D23 /// stamps occurred_at from it. The sink runs behind a bounded Channel and a background /// writer, so a writer that read its own clock would stamp the event one enqueue late and a slow -/// queue would move the record of the call. The turn loop reads the clock once, when the turn ends, +/// queue would move the record of the conversation. The turn loop reads the clock once, when the turn ends, /// and every event of that turn carries the same moment. A record a caller builds by hand and leaves /// unset reads default. /// public sealed record TurnResult( - string CallId, + string ConversationId, int TurnIndex, string StageBefore, string StageAfter, diff --git a/src/AgentCore.Hosting/AgentCore.Hosting.csproj b/src/AgentCore.Hosting/AgentCore.Hosting.csproj index 579773e8..3bda8a3d 100644 --- a/src/AgentCore.Hosting/AgentCore.Hosting.csproj +++ b/src/AgentCore.Hosting/AgentCore.Hosting.csproj @@ -2,7 +2,7 @@ true - The batteries-included host: every vendor seam bound and every route mapped, in two calls. + The batteries-included host: every vendor seam bound and every route mapped, in two conversations. agent;ai;voice;chat;hosting diff --git a/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs b/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs index 8445fb96..6f6532c5 100644 --- a/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs +++ b/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs @@ -4,7 +4,7 @@ using AgentCore.Hosting.Secrets; using AgentCore.Infrastructure.Audit.Postgres; using AgentCore.Infrastructure.Blobs.S3; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Embeddings.OpenAI; using AgentCore.Infrastructure.Evaluation.OpenAiModeration; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; @@ -20,7 +20,7 @@ namespace AgentCore.Hosting; /// -/// Registers everything AgentCore needs to run, in one call. +/// Registers everything AgentCore needs to run, in one conversation. /// public static class AgentCoreHostBuilderExtensions { @@ -44,7 +44,7 @@ public static class AgentCoreHostBuilderExtensions /// this library does not name, or to replace the document, the secret resolver, the logger /// factory, or any vendor seam. /// - /// The same builder, so a host chains its calls. + /// The same builder, so a host chains its conversations. /// is . public static WebApplicationBuilder AddAgentCoreHost( this WebApplicationBuilder builder, @@ -113,8 +113,8 @@ private static void Configure( // providers.telemetry.kind picks the adapter. options.UseTelemetry(new GrafanaOtlpTelemetryAdapter()); - // providers.call.kind picks one. - options.UseCall(new TelnyxRelayCallAdapter()); + // providers.conversation.kind picks one. + options.UseConversation(new TelnyxRelayConversationAdapter()); // The speech vendor. options.UseSpeech(new TelnyxRelaySpeechAdapter()); @@ -130,8 +130,8 @@ private static void Configure( // providers.audit.kind picks the adapter. options.UseAuditSinks(new PostgresAuditSinkAdapter()); - // providers.calls.kind picks the adapter. - options.UseCallStores(new PostgresCallStoreAdapter()); + // providers.conversations.kind picks the adapter. + options.UseConversationStores(new PostgresConversationStoreAdapter()); // providers.blobs.kind picks the adapter. options.UseBlobStores(new S3BlobStoreAdapter()); diff --git a/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs b/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs index 2130a943..85c73739 100644 --- a/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs +++ b/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs @@ -1,4 +1,4 @@ -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.Endpoints; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -6,28 +6,28 @@ namespace AgentCore.Hosting; /// -/// Maps every route AgentCore answers on, in one call. +/// Maps every route AgentCore answers on, in one conversation. /// public static class AgentCoreHostEndpointExtensions { /// The route the liveness check answers on. public const string HealthPattern = "/health"; - /// Installs the WebSocket middleware and maps health, the Responses endpoint, and the call socket. + /// Installs the WebSocket middleware and maps health, the Responses endpoint, and the conversation socket. /// The application to map on. /// /// The route the OpenAI-compatible Responses endpoint answers on, with {entry} naming /// the entry, or for /// . /// - /// - /// The route the call socket answers on, with {entry} naming the entry, or - /// for . + /// + /// The route the conversation socket answers on, with {entry} naming the entry, or + /// for . /// - /// The same application, so a host chains its calls. + /// The same application, so a host chains its conversations. /// is . public static WebApplication MapAgentCoreHost( - this WebApplication app, string? responsesPattern = null, string? callPattern = null) + this WebApplication app, string? responsesPattern = null, string? conversationPattern = null) { ArgumentNullException.ThrowIfNull(app); @@ -37,7 +37,7 @@ public static WebApplication MapAgentCoreHost( app.MapResponses(responsesPattern ?? ResponsesEndpointRouteBuilderExtensions.DefaultPattern); - app.MapCall(callPattern ?? CallEndpointRouteBuilderExtensions.DefaultPattern); + app.MapCall(conversationPattern ?? ConversationEndpointRouteBuilderExtensions.DefaultPattern); return app; } diff --git a/src/AgentCore.Hosting/PublicAPI.Unshipped.txt b/src/AgentCore.Hosting/PublicAPI.Unshipped.txt index 4d3e4ad2..c37f0072 100644 --- a/src/AgentCore.Hosting/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Hosting/PublicAPI.Unshipped.txt @@ -7,4 +7,4 @@ const AgentCore.Hosting.AgentCoreHostBuilderExtensions.DefaultConfigurationPath const AgentCore.Hosting.AgentCoreHostBuilderExtensions.McpHttpClientName = "agentcore.mcp" -> string! const AgentCore.Hosting.AgentCoreHostEndpointExtensions.HealthPattern = "/health" -> string! static AgentCore.Hosting.AgentCoreHostBuilderExtensions.AddAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplicationBuilder! builder, System.Action? configure = null) -> Microsoft.AspNetCore.Builder.WebApplicationBuilder! -static AgentCore.Hosting.AgentCoreHostEndpointExtensions.MapAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplication! app, string? responsesPattern = null, string? callPattern = null) -> Microsoft.AspNetCore.Builder.WebApplication! +static AgentCore.Hosting.AgentCoreHostEndpointExtensions.MapAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplication! app, string? responsesPattern = null, string? conversationPattern = null) -> Microsoft.AspNetCore.Builder.WebApplication! diff --git a/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj b/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj index 1796d2fb..5a4ee52d 100644 --- a/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj +++ b/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj @@ -2,7 +2,7 @@ true - Outbound adapters: OpenAI, Qdrant, Telnyx call control, Postgres, B2. + Outbound adapters: OpenAI, Qdrant, Telnyx conversation control, Postgres, B2. agent;ai;openai;telnyx;qdrant;postgres diff --git a/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs b/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs index d49e0e0d..3af62ab6 100644 --- a/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs +++ b/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs @@ -16,16 +16,16 @@ internal sealed class PostgresAuditSink : IAuditSinkPort, IAsyncDisposable { private const string Schema = PostgresSchema.SchemaName; - /// Serialises the writers of one call so two of them cannot pick the same sequence. + /// Serialises the writers of one conversation so two of them cannot pick the same sequence. internal const string LockSql = "SELECT pg_advisory_xact_lock(hashtext($1))"; - /// Appends one call's run, numbering only the rows that will actually survive. + /// Appends one conversation's run, numbering only the rows that will actually survive. internal const string AppendSql = $""" INSERT INTO {Schema}.audit_event ( - call_id, event_id, sequence, kind, occurred_at, turn_index, amends_event_id, payload) + conversation_id, event_id, sequence, kind, occurred_at, turn_index, amends_event_id, payload) SELECT $1, d.event_id, - coalesce((SELECT max(sequence) FROM {Schema}.audit_event WHERE call_id = $1), -1) + coalesce((SELECT max(sequence) FROM {Schema}.audit_event WHERE conversation_id = $1), -1) + row_number() OVER (ORDER BY d.position), d.kind, d.occurred_at, d.turn_index, d.amends_event_id, d.payload FROM unnest($2::uuid[], $3::text[], $4::timestamptz[], @@ -33,8 +33,8 @@ FROM unnest($2::uuid[], $3::text[], $4::timestamptz[], WITH ORDINALITY AS d(event_id, kind, occurred_at, turn_index, amends_event_id, payload, position) WHERE NOT EXISTS ( - SELECT 1 FROM {Schema}.audit_event e WHERE e.call_id = $1 AND e.event_id = d.event_id) - ON CONFLICT (call_id, event_id) DO NOTHING + SELECT 1 FROM {Schema}.audit_event e WHERE e.conversation_id = $1 AND e.event_id = d.event_id) + ON CONFLICT (conversation_id, event_id) DO NOTHING """; private readonly NpgsqlDataSource _dataSource; @@ -78,21 +78,21 @@ public async ValueTask AppendManyAsync( await using var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); await using NpgsqlBatch batch = new(connection, transaction); - // Grouped, because the queue in front of this sink batches across calls, and a call is the - // unit the sequence counts within. Ordered by call id, because two transactions that each - // hold two calls would otherwise be able to take the two locks in opposite orders and wait - // on each other forever. Best effort, and only that: the lock is on hashtext(call_id), so a + // Grouped, because the queue in front of this sink batches across conversations, and a conversation is the + // unit the sequence counts within. Ordered by conversation id, because two transactions that each + // hold two conversations would otherwise be able to take the two locks in opposite orders and wait + // on each other forever. Best effort, and only that: the lock is on hashtext(conversation_id), so a // consistent order on ids is a consistent order on locks only while the hash is injective // over the ids in play. See the remarks on LockSql for what a collision costs. - foreach (var call in auditEvents - .GroupBy(item => item.CallId, StringComparer.Ordinal) + foreach (var conversation in auditEvents + .GroupBy(item => item.ConversationId, StringComparer.Ordinal) .OrderBy(group => group.Key, StringComparer.Ordinal)) { NpgsqlBatchCommand lockCommand = new(LockSql); - lockCommand.Parameters.Add(new NpgsqlParameter { Value = call.Key }); + lockCommand.Parameters.Add(new NpgsqlParameter { Value = conversation.Key }); batch.BatchCommands.Add(lockCommand); - batch.BatchCommands.Add(AppendCommand(call.Key, [.. call])); + batch.BatchCommands.Add(AppendCommand(conversation.Key, [.. conversation])); } // One round trip for the run. A durable insert is ~13 ms, so twenty apart cost 260 ms and @@ -111,7 +111,7 @@ public async ValueTask AppendManyAsync( "csharpsquid", "S3265", Justification = "Npgsql documents Array combined with an element type via bit OR, and the enum omits Flags only upstream.")] - private static NpgsqlBatchCommand AppendCommand(string callId, IReadOnlyList run) + private static NpgsqlBatchCommand AppendCommand(string conversationId, IReadOnlyList run) { NpgsqlBatchCommand command = new(AppendSql); @@ -121,7 +121,7 @@ private static NpgsqlBatchCommand AppendCommand(string callId, IReadOnlyList item.EventId)]; - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); command.Parameters.Add(new NpgsqlParameter { TypedValue = [.. distinct.Select(item => item.EventId)], diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs deleted file mode 100644 index 98dc83d4..00000000 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System.Text.Json; -using AgentCore.Application.Calls; -using AgentCore.Application.Transcript; -using Microsoft.Extensions.AI; -using Npgsql; -using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreSql; - -namespace AgentCore.Infrastructure.Calls.Postgres; - -/// How a Postgres row becomes a or , and back. -internal static class PostgresCallRows -{ - /// - /// One call's row from , whose ninth column is the state a - /// resume reads back and whose tenth is its ordinal counter. - /// - internal static CallRecord Read(NpgsqlDataReader reader) => - ReadListing(reader) with - { - State = reader.IsDBNull(8) ? null : ReadState(reader.GetString(8)), - NextOrdinal = reader.GetInt32(9), - }; - - /// Reads one call's resume blob, or nothing when the blob cannot be read. - /// The JSON in call.state. - /// The state, or when it did not parse into one. - internal static CallSessionState? ReadState(string blob) - { - try - { - return JsonSerializer.Deserialize(blob, CallStateJson.Options); - } - catch (JsonException) - { - return null; - } - } - - /// - /// One call's row from , which projects - /// alone. It has no ninth or tenth column to read, so - /// and are left at their - /// defaults — and 0 — rather than paying for what a listing never shows. - /// - internal static CallRecord ReadListing(NpgsqlDataReader reader) => - new( - reader.GetString(0), - reader.IsDBNull(1) ? null : reader.GetString(1), - ToStatus(reader.GetString(2)), - reader.IsDBNull(3) ? null : reader.GetString(3), - reader.IsDBNull(4) ? null : JsonDocument.Parse(reader.GetString(4)).RootElement.Clone(), - reader.GetFieldValue(5), - reader.IsDBNull(7) ? null : reader.GetFieldValue(7)); - - internal static string ToText(CallStatus status) => status == CallStatus.Archived ? Archived : Regular; - - internal static CallStatus ToStatus(string text) => - text == Archived ? CallStatus.Archived : CallStatus.Regular; - - internal static string Serialise(ChatMessage message) - => JsonSerializer.Serialize(message, TranscriptJson.Options); - - internal static ChatMessage Deserialise(string content) - => JsonSerializer.Deserialize(content, TranscriptJson.Options) - ?? throw new InvalidOperationException("A call_message row holds JSON null in content."); -} diff --git a/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationRows.cs b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationRows.cs new file mode 100644 index 00000000..45559047 --- /dev/null +++ b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationRows.cs @@ -0,0 +1,66 @@ +using System.Text.Json; +using AgentCore.Application.Conversation; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Npgsql; +using static AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreSql; + +namespace AgentCore.Infrastructure.Conversation.Postgres; + +/// How a Postgres row becomes a or , and back. +internal static class PostgresConversationRows +{ + /// + /// One conversation's row from , whose ninth column is the state a + /// resume reads back and whose tenth is its ordinal counter. + /// + internal static ConversationRecord Read(NpgsqlDataReader reader) => + ReadListing(reader) with + { + State = reader.IsDBNull(8) ? null : ReadState(reader.GetString(8)), + NextOrdinal = reader.GetInt32(9), + }; + + /// Reads one conversation's resume blob, or nothing when the blob cannot be read. + /// The JSON in conversation.state. + /// The state, or when it did not parse into one. + internal static ConversationSessionState? ReadState(string blob) + { + try + { + return JsonSerializer.Deserialize(blob, ConversationStateJson.Options); + } + catch (JsonException) + { + return null; + } + } + + /// + /// One conversation's row from , which projects + /// alone. It has no ninth or tenth column to read, so + /// and are left at their + /// defaults — and 0 — rather than paying for what a listing never shows. + /// + internal static ConversationRecord ReadListing(NpgsqlDataReader reader) => + new( + reader.GetString(0), + reader.IsDBNull(1) ? null : reader.GetString(1), + ToStatus(reader.GetString(2)), + reader.IsDBNull(3) ? null : reader.GetString(3), + reader.IsDBNull(4) ? null : JsonDocument.Parse(reader.GetString(4)).RootElement.Clone(), + reader.GetFieldValue(5), + reader.IsDBNull(7) ? null : reader.GetFieldValue(7)); + + internal static string ToText(ConversationStatus status) => status == ConversationStatus.Archived ? Archived : Regular; + + internal static ConversationStatus ToStatus(string text) => + text == Archived ? ConversationStatus.Archived : ConversationStatus.Regular; + + internal static string Serialise(ChatMessage message) + => JsonSerializer.Serialize(message, TranscriptJson.Options); + + internal static ChatMessage Deserialise(string content) + => JsonSerializer.Deserialize(content, TranscriptJson.Options) + ?? throw new InvalidOperationException("A conversation_message row holds JSON null in content."); +} diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStore.cs similarity index 69% rename from src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs rename to src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStore.cs index e0b8db82..edb3fb87 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs +++ b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStore.cs @@ -1,79 +1,79 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Ports; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Npgsql; using NpgsqlTypes; -using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallRows; -using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreSql; +using static AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationRows; +using static AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreSql; -namespace AgentCore.Infrastructure.Calls.Postgres; +namespace AgentCore.Infrastructure.Conversation.Postgres; -/// The store, in PostgreSQL: a call, who may see it, and its words. -internal sealed class PostgresCallStore : ICallStore, IAsyncDisposable +/// The store, in PostgreSQL: a conversation, who may see it, and its words. +internal sealed class PostgresConversationStore : IConversationStore, IAsyncDisposable { private readonly NpgsqlDataSource _dataSource; /// Creates the store over a data source it then owns. /// The pool every statement runs on. Disposing the store disposes it. /// The data source is . - public PostgresCallStore(NpgsqlDataSource dataSource) + public PostgresConversationStore(NpgsqlDataSource dataSource) { ArgumentNullException.ThrowIfNull(dataSource); _dataSource = dataSource; } /// - public async ValueTask CreateAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask CreateAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using (var command = _dataSource.CreateCommand(CreateSql)) { - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } - return await GetAsync(callId, cancellationToken).ConfigureAwait(false) - ?? throw new InvalidOperationException($"Store 0 lost call '{callId}' between its write and its read."); + return await GetAsync(conversationId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException($"Store 0 lost conversation '{conversationId}' between its write and its read."); } /// - public async ValueTask GetAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask GetAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using var command = _dataSource.CreateCommand(GetSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); return await reader.ReadAsync(cancellationToken).ConfigureAwait(false) ? Read(reader) : null; } /// - public ValueTask RenameAsync(string callId, string title, CancellationToken cancellationToken = default) + public ValueTask RenameAsync(string conversationId, string title, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); ArgumentNullException.ThrowIfNull(title); - return AmendAsync(RenameSql, callId, new NpgsqlParameter { Value = title }, cancellationToken); + return AmendAsync(RenameSql, conversationId, new NpgsqlParameter { Value = title }, cancellationToken); } /// - public ValueTask SetStatusAsync(string callId, CallStatus status, CancellationToken cancellationToken = default) + public ValueTask SetStatusAsync(string conversationId, ConversationStatus status, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); - return AmendAsync(StatusSql, callId, new NpgsqlParameter { Value = ToText(status) }, cancellationToken); + return AmendAsync(StatusSql, conversationId, new NpgsqlParameter { Value = ToText(status) }, cancellationToken); } /// public ValueTask SetCustomAsync( - string callId, JsonElement? custom, CancellationToken cancellationToken = default) + string conversationId, JsonElement? custom, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); NpgsqlParameter parameter = new() { @@ -81,14 +81,14 @@ public ValueTask SetCustomAsync( Value = custom is { } element ? element.GetRawText() : DBNull.Value, }; - return AmendAsync(CustomSql, callId, parameter, cancellationToken); + return AmendAsync(CustomSql, conversationId, parameter, cancellationToken); } /// public ValueTask SetExternalIdAsync( - string callId, string? externalId, CancellationToken cancellationToken = default) + string conversationId, string? externalId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); NpgsqlParameter parameter = new() { @@ -96,35 +96,35 @@ public ValueTask SetExternalIdAsync( Value = externalId is null ? DBNull.Value : externalId, }; - return AmendAsync(ExternalIdSql, callId, parameter, cancellationToken); + return AmendAsync(ExternalIdSql, conversationId, parameter, cancellationToken); } /// - public async ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask DeleteAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using var command = _dataSource.CreateCommand(DeleteSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); await using var continuation = _dataSource.CreateCommand(DeleteContinuationSql); - continuation.Parameters.Add(new NpgsqlParameter { Value = callId }); + continuation.Parameters.Add(new NpgsqlParameter { Value = conversationId }); await continuation.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } /// - public async ValueTask ListAsync( + public async ValueTask ListAsync( string principalKey, string? after, int limit, - CallStatus? status = null, + ConversationStatus? status = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(principalKey); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limit); - var hasCursor = CallCursor.TryDecode(after, out var sortAt, out var cursorId); + var hasCursor = ConversationCursor.TryDecode(after, out var sortAt, out var cursorId); await using var command = _dataSource.CreateCommand(ListSql); command.Parameters.Add(new NpgsqlParameter { Value = principalKey }); @@ -145,7 +145,7 @@ public async ValueTask ListAsync( }); command.Parameters.Add(new NpgsqlParameter { Value = limit }); - List rows = []; + List rows = []; DateTimeOffset lastSortAt = default; await using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false)) @@ -158,10 +158,10 @@ public async ValueTask ListAsync( } var next = rows.Count == limit - ? CallCursor.Encode(lastSortAt, rows[^1].CallId) + ? ConversationCursor.Encode(lastSortAt, rows[^1].ConversationId) : null; - return new CallPage(rows, next); + return new ConversationPage(rows, next); } /// @@ -202,14 +202,14 @@ public async ValueTask SweepAsync( /// public async ValueTask AttachPrincipalAsync( - string callId, string principalKey, string role, CancellationToken cancellationToken = default) + string conversationId, string principalKey, string role, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); ArgumentNullException.ThrowIfNull(principalKey); ArgumentNullException.ThrowIfNull(role); await using var command = _dataSource.CreateCommand(AttachSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); command.Parameters.Add(new NpgsqlParameter { Value = principalKey }); command.Parameters.Add(new NpgsqlParameter { Value = role }); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); @@ -217,13 +217,13 @@ public async ValueTask AttachPrincipalAsync( /// public async ValueTask DetachPrincipalAsync( - string callId, string principalKey, CancellationToken cancellationToken = default) + string conversationId, string principalKey, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); ArgumentNullException.ThrowIfNull(principalKey); await using var command = _dataSource.CreateCommand(DetachSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); command.Parameters.Add(new NpgsqlParameter { Value = principalKey }); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } @@ -233,10 +233,10 @@ public async ValueTask DetachPrincipalAsync( public ValueTask DisposeAsync() => _dataSource.DisposeAsync(); private async ValueTask AmendAsync( - string sql, string callId, NpgsqlParameter value, CancellationToken cancellationToken) + string sql, string conversationId, NpgsqlParameter value, CancellationToken cancellationToken) { await using var command = _dataSource.CreateCommand(sql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); command.Parameters.Add(value); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } @@ -246,13 +246,13 @@ private async ValueTask AmendAsync( "csharpsquid", "S3265", Justification = "Npgsql documents Array combined with an element type via bit OR, and the enum omits Flags only upstream.")] - public async ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, + public async ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); ArgumentNullException.ThrowIfNull(messages); if (messages.Count == 0) @@ -264,7 +264,7 @@ public async ValueTask> AppendAsync( await using NpgsqlBatch batch = new(connection); NpgsqlBatchCommand appendCommand = new(AppendSql); - appendCommand.Parameters.Add(new NpgsqlParameter { Value = callId }); + appendCommand.Parameters.Add(new NpgsqlParameter { Value = conversationId }); appendCommand.Parameters.Add(new NpgsqlParameter { TypedValue = [.. messages.Select(message => message.TurnIndex)], @@ -287,10 +287,10 @@ public async ValueTask> AppendAsync( if (state is not null) { NpgsqlBatchCommand stateCommand = new(StateSql); - stateCommand.Parameters.Add(new NpgsqlParameter { Value = callId }); + stateCommand.Parameters.Add(new NpgsqlParameter { Value = conversationId }); stateCommand.Parameters.Add(new NpgsqlParameter { - Value = JsonSerializer.Serialize(state, CallStateJson.Options), + Value = JsonSerializer.Serialize(state, ConversationStateJson.Options), NpgsqlDbType = NpgsqlDbType.Jsonb, }); @@ -312,26 +312,26 @@ public async ValueTask> AppendAsync( if (written.Count == 0) { - throw new InvalidOperationException($"Store 0 holds no call '{callId}' to append words to."); + throw new InvalidOperationException($"Store 0 holds no conversation '{conversationId}' to append words to."); } return [.. messages.Select(draft => { var (ordinal, turnIndex) = written[draft.MessageId]; - return new CallMessage(callId, ordinal, turnIndex, draft.Content, draft.MessageId); + return new ConversationMessage(conversationId, ordinal, turnIndex, draft.Content, draft.MessageId); })]; } /// public async ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); ArgumentException.ThrowIfNullOrEmpty(messageId); ArgumentNullException.ThrowIfNull(content); await using var command = _dataSource.CreateCommand(RewriteSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); command.Parameters.Add(new NpgsqlParameter { Value = messageId }); command.Parameters.Add(new NpgsqlParameter { Value = Serialise(content), NpgsqlDbType = NpgsqlDbType.Jsonb }); @@ -339,22 +339,22 @@ public async ValueTask RewriteAsync( } /// - /// The call id is . - public async ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) + /// The conversation id is . + public async ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using var command = _dataSource.CreateCommand(ReadSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); - List rows = []; + List rows = []; await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) { - rows.Add(new CallMessage( - callId, + rows.Add(new ConversationMessage( + conversationId, reader.GetInt32(0), reader.GetInt32(1), Deserialise(reader.GetString(2)), @@ -365,14 +365,14 @@ public async ValueTask> ReadAsync( } /// - /// The call id is . + /// The conversation id is . public async ValueTask TruncateAsync( - string callId, int fromOrdinal, CancellationToken cancellationToken = default) + string conversationId, int fromOrdinal, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using var command = _dataSource.CreateCommand(TruncateSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); command.Parameters.Add(new NpgsqlParameter { Value = fromOrdinal }); return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); @@ -380,12 +380,12 @@ public async ValueTask TruncateAsync( /// /// The continuation id is . - public async ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using var command = _dataSource.CreateCommand(EraseSql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } @@ -433,12 +433,12 @@ public async ValueTask DeleteContinuationAsync(string continuationId, Cancellati } - /// Reads one call's spoken turns beside the hashes the audit chain holds for them. - /// The call to check. + /// Reads one conversation's spoken turns beside the hashes the audit chain holds for them. + /// The conversation to check. /// Cancels the read. /// One row for each spoken turn, oldest turn first. - /// The call id is . + /// The conversation id is . public Task> ReadSpokenTurnsAsync( - string callId, CancellationToken cancellationToken = default) - => PostgresCallVerification.ReadSpokenTurnsAsync(_dataSource, callId, cancellationToken); + string conversationId, CancellationToken cancellationToken = default) + => PostgresConversationVerification.ReadSpokenTurnsAsync(_dataSource, conversationId, cancellationToken); } diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreAdapter.cs b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStoreAdapter.cs similarity index 65% rename from src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreAdapter.cs rename to src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStoreAdapter.cs index 6a533c62..be25fd5f 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreAdapter.cs +++ b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStoreAdapter.cs @@ -3,12 +3,12 @@ using AgentCore.Infrastructure.Database.Postgres; using Npgsql; -namespace AgentCore.Infrastructure.Calls.Postgres; +namespace AgentCore.Infrastructure.Conversation.Postgres; /// -/// The postgres call vendor behind . +/// The postgres conversation vendor behind . /// -public sealed class PostgresCallStoreAdapter : ICallStoreAdapter +public sealed class PostgresConversationStoreAdapter : IConversationStoreAdapter { /// /// The one kind value this adapter serves. @@ -21,7 +21,7 @@ public sealed class PostgresCallStoreAdapter : ICallStoreAdapter public string Kind => ProviderKind; /// - public async ValueTask OpenAsync( + public async ValueTask OpenAsync( VendorProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default) @@ -29,10 +29,10 @@ public async ValueTask OpenAsync( NpgsqlDataSource dataSource = await PostgresDataSourceFactory .OpenMigratedAsync( secrets, - "A call's row in providers.calls is written to PostgreSQL.", + "A conversation's row in providers.conversations is written to PostgreSQL.", cancellationToken) .ConfigureAwait(false); - return new PostgresCallStore(dataSource); + return new PostgresConversationStore(dataSource); } } diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStoreSql.cs similarity index 56% rename from src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs rename to src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStoreSql.cs index 7598ada4..585eb842 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs +++ b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationStoreSql.cs @@ -1,9 +1,9 @@ using AgentCore.Infrastructure.Database.Postgres; -namespace AgentCore.Infrastructure.Calls.Postgres; +namespace AgentCore.Infrastructure.Conversation.Postgres; -/// Every statement runs. -internal static class PostgresCallStoreSql +/// Every statement runs. +internal static class PostgresConversationStoreSql { private const string Schema = PostgresSchema.SchemaName; @@ -19,63 +19,63 @@ internal static class PostgresCallStoreSql /// internal const string Projection = $""" - c.call_id, c.title, c.status, c.external_id, c.custom, c.created_at, + c.conversation_id, c.title, c.status, c.external_id, c.custom, c.created_at, {SortAt} AS sort_at, m.last_message_at """; internal const string ActivityJoin = $""" LEFT JOIN LATERAL ( - SELECT max(updated_at) AS last_message_at FROM {Schema}.call_message x WHERE x.call_id = c.call_id + SELECT max(updated_at) AS last_message_at FROM {Schema}.conversation_message x WHERE x.conversation_id = c.conversation_id ) m ON true """; internal const string CreateSql = - $"INSERT INTO {Schema}.call (call_id) VALUES ($1) ON CONFLICT (call_id) DO NOTHING"; + $"INSERT INTO {Schema}.conversation (conversation_id) VALUES ($1) ON CONFLICT (conversation_id) DO NOTHING"; - /// One call's row, with the session state a resume reads back and its ordinal counter. + /// One conversation's row, with the session state a resume reads back and its ordinal counter. internal static readonly string GetSql = - $"SELECT {Projection}, c.state, c.next_ordinal FROM {Schema}.call c {ActivityJoin} WHERE c.call_id = $1"; + $"SELECT {Projection}, c.state, c.next_ordinal FROM {Schema}.conversation c {ActivityJoin} WHERE c.conversation_id = $1"; internal const string StateSql = - $"UPDATE {Schema}.call SET state = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.conversation SET state = $2, updated_at = now() WHERE conversation_id = $1"; internal const string RenameSql = - $"UPDATE {Schema}.call SET title = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.conversation SET title = $2, updated_at = now() WHERE conversation_id = $1"; internal const string StatusSql = - $"UPDATE {Schema}.call SET status = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.conversation SET status = $2, updated_at = now() WHERE conversation_id = $1"; internal const string CustomSql = - $"UPDATE {Schema}.call SET custom = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.conversation SET custom = $2, updated_at = now() WHERE conversation_id = $1"; internal const string ExternalIdSql = - $"UPDATE {Schema}.call SET external_id = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.conversation SET external_id = $2, updated_at = now() WHERE conversation_id = $1"; - internal const string DeleteSql = $"DELETE FROM {Schema}.call WHERE call_id = $1"; + internal const string DeleteSql = $"DELETE FROM {Schema}.conversation WHERE conversation_id = $1"; internal const string AttachSql = $""" - INSERT INTO {Schema}.call_principal (call_id, principal_key, role) + INSERT INTO {Schema}.conversation_principal (conversation_id, principal_key, role) VALUES ($1, $2, $3) - ON CONFLICT (principal_key, call_id) DO NOTHING + ON CONFLICT (principal_key, conversation_id) DO NOTHING """; internal const string DetachSql = - $"DELETE FROM {Schema}.call_principal WHERE call_id = $1 AND principal_key = $2"; + $"DELETE FROM {Schema}.conversation_principal WHERE conversation_id = $1 AND principal_key = $2"; - /// One page of one principal's calls. + /// One page of one principal's conversations. internal static readonly string ListSql = $""" SELECT {Projection} - FROM {Schema}.call_principal p - JOIN {Schema}.call c USING (call_id) + FROM {Schema}.conversation_principal p + JOIN {Schema}.conversation c USING (conversation_id) {ActivityJoin} WHERE p.principal_key = $1 AND ($2::text IS NULL OR c.status = $2) AND ($3::timestamptz IS NULL - OR ({SortAt}, c.call_id) < ($3, $4)) - ORDER BY sort_at DESC, c.call_id DESC + OR ({SortAt}, c.conversation_id) < ($3, $4)) + ORDER BY sort_at DESC, c.conversation_id DESC LIMIT $5 """; @@ -84,41 +84,41 @@ ON CONFLICT (principal_key, call_id) DO NOTHING /// doubles as the count the whole batch numbers from: cardinality($5::text[]) is how many /// ordinals mark reserves, and RETURNING on the UPDATE sees the bumped /// next_ordinal, so subtracting that same count back off it gives the first one this batch - /// may use. A null element of $2 (turn_index) takes the call's own next turn index instead + /// may use. A null element of $2 (turn_index) takes the conversation's own next turn index instead /// of naming one, which is what an append from outside any turn asks for. /// internal const string AppendSql = $""" WITH mark AS ( - UPDATE {Schema}.call + UPDATE {Schema}.conversation SET next_ordinal = next_ordinal + cardinality($5::text[]), updated_at = now() - WHERE call_id = $1 + WHERE conversation_id = $1 RETURNING next_ordinal - cardinality($5::text[]) AS first, coalesce((state ->> 'nextTurnIndex')::int, 0) AS next_turn_index ) - INSERT INTO {Schema}.call_message (call_id, ordinal, turn_index, role, content, message_id) + INSERT INTO {Schema}.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id) SELECT $1, mark.first + d.position - 1, coalesce(d.turn_index, mark.next_turn_index), d.role, d.content, d.message_id FROM mark, unnest($2::int[], $3::text[], $4::jsonb[], $5::text[]) WITH ORDINALITY AS d(turn_index, role, content, message_id, position) RETURNING ordinal, turn_index, message_id """; - /// Reads one whole call. + /// Reads one whole conversation. internal const string ReadSql = $""" SELECT ordinal, turn_index, content, message_id - FROM {Schema}.call_message WHERE call_id = $1 ORDER BY ordinal + FROM {Schema}.conversation_message WHERE conversation_id = $1 ORDER BY ordinal """; - /// Withdraws the tail of a call, from one ordinal onward. + /// Withdraws the tail of a conversation, from one ordinal onward. internal const string TruncateSql = - $"DELETE FROM {Schema}.call_message WHERE call_id = $1 AND ordinal >= $2"; + $"DELETE FROM {Schema}.conversation_message WHERE conversation_id = $1 AND ordinal >= $2"; internal const string RewriteSql = $""" - UPDATE {Schema}.call_message SET content = $3, updated_at = now() - WHERE call_id = $1 AND message_id = $2 + UPDATE {Schema}.conversation_message SET content = $3, updated_at = now() + WHERE conversation_id = $1 AND message_id = $2 """; - internal const string EraseSql = $"DELETE FROM {Schema}.call_message WHERE call_id = $1"; + internal const string EraseSql = $"DELETE FROM {Schema}.conversation_message WHERE conversation_id = $1"; /// Files one session envelope under one continuation id, replacing any envelope already there. internal const string SaveContinuationSql = @@ -136,55 +136,55 @@ ON CONFLICT (store_id) DO UPDATE SET envelope = EXCLUDED.envelope $"DELETE FROM {Schema}.response_continuation WHERE store_id = $1"; /// - /// Reads what store 1 holds for each spoken turn of one call, beside what store 3 proves. + /// Reads what store 1 holds for each spoken turn of one conversation, beside what store 3 proves. /// internal const string VerifySql = $$""" WITH spoken AS ( - SELECT DISTINCT ON (call_id, turn_index) - call_id, turn_index, + SELECT DISTINCT ON (conversation_id, turn_index) + conversation_id, turn_index, (SELECT coalesce(string_agg(part ->> 'text', '' ORDER BY position), '') FROM jsonb_array_elements(content -> 'contents') WITH ORDINALITY AS element(part, position) WHERE part ->> '$type' = 'text') AS words - FROM {{Schema}}.call_message - WHERE call_id = $1 + FROM {{Schema}}.conversation_message + WHERE conversation_id = $1 AND role = 'assistant' AND content -> 'contents' @> '[{"$type": "text"}]' - ORDER BY call_id, turn_index, ordinal DESC + ORDER BY conversation_id, turn_index, ordinal DESC ), completed AS ( - SELECT DISTINCT ON (call_id, turn_index) call_id, turn_index, payload + SELECT DISTINCT ON (conversation_id, turn_index) conversation_id, turn_index, payload FROM {{Schema}}.audit_event - WHERE call_id = $1 AND kind = 'turn.completed' - ORDER BY call_id, turn_index, sequence DESC + WHERE conversation_id = $1 AND kind = 'turn.completed' + ORDER BY conversation_id, turn_index, sequence DESC ) SELECT m.turn_index, m.words, a.payload ->> 'replyTextSha256' - FROM spoken m JOIN completed a USING (call_id, turn_index) + FROM spoken m JOIN completed a USING (conversation_id, turn_index) ORDER BY m.turn_index """; - /// Deletes one batch of calls that have aged out whole. + /// Deletes one batch of conversations that have aged out whole. internal static readonly string SweepContinuationsSql = $""" DELETE FROM {Schema}.response_continuation WHERE store_id IN ( - SELECT call_id FROM ( - SELECT c.call_id - FROM {Schema}.call c + SELECT conversation_id FROM ( + SELECT c.conversation_id + FROM {Schema}.conversation c {ActivityJoin} WHERE {SortAt} < now() - $1 LIMIT $2 ) q) """; - /// Deletes one batch of calls that have aged out whole. + /// Deletes one batch of conversations that have aged out whole. internal static readonly string SweepSql = $""" - DELETE FROM {Schema}.call - WHERE call_id IN ( - SELECT call_id FROM ( - SELECT c.call_id - FROM {Schema}.call c + DELETE FROM {Schema}.conversation + WHERE conversation_id IN ( + SELECT conversation_id FROM ( + SELECT c.conversation_id + FROM {Schema}.conversation c {ActivityJoin} WHERE {SortAt} < now() - $1 LIMIT $2 diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationVerification.cs similarity index 67% rename from src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs rename to src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationVerification.cs index 705c13d4..a6806d0c 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs +++ b/src/AgentCore.Infrastructure/Conversation/Postgres/PostgresConversationVerification.cs @@ -1,24 +1,24 @@ using Npgsql; -using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreSql; +using static AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreSql; -namespace AgentCore.Infrastructure.Calls.Postgres; +namespace AgentCore.Infrastructure.Conversation.Postgres; /// Reads store 1's words beside the hashes store 3 holds for them, for a retroactive check. -internal static class PostgresCallVerification +internal static class PostgresConversationVerification { - /// Reads one call's spoken turns beside the hashes the audit chain holds for them. + /// Reads one conversation's spoken turns beside the hashes the audit chain holds for them. /// The pool the read runs on. - /// The call to check. + /// The conversation to check. /// Cancels the read. /// One row for each spoken turn, oldest turn first. - /// The call id is . + /// The conversation id is . public static async Task> ReadSpokenTurnsAsync( - NpgsqlDataSource dataSource, string callId, CancellationToken cancellationToken = default) + NpgsqlDataSource dataSource, string conversationId, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(conversationId); await using var command = dataSource.CreateCommand(VerifySql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); List turns = []; diff --git a/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql b/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql index a808386d..df870e7c 100644 --- a/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql +++ b/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql @@ -1,8 +1,8 @@ -- The whole AgentCore schema. One migration, applied to a database that has none of it. -- -- Order inside the file is the order the objects need: the role first, because every grant names it; --- the schema next, because every table below lives in it; call before call_message, because the --- words are a child of the call they belong to; the continuation map beside them, because a resume +-- the schema next, because every table below lives in it; conversation before conversation_message, because the +-- words are a child of the conversation they belong to; the continuation map beside them, because a resume -- must never find the key without the words; audit_event last, with the triggers that refuse to -- let it change. @@ -40,24 +40,24 @@ GRANT USAGE ON SCHEMA agentcore TO agentcore_writer; GRANT SELECT ON agentcore.schema_migration TO agentcore_writer; --- Store 0 — what a call is, apart from its words. One row per thread in a caller's list. +-- Store 0 — what a conversation is, apart from its words. One row per thread in a caller's list. -- --- This table comes first because call_message hangs off it. A call exists before it has words, and +-- This table comes first because conversation_message hangs off it. A conversation exists before it has words, and -- deleting it takes the words with it: one statement, one transaction, no ordering to get wrong. -- -- audit_event is deliberately NOT a child. The triggers at the foot of this file refuse every DELETE -- on it, so a cascade could not run even if one were declared. The trail outlives the conversation --- on purpose, and relates to a call by call_id convention alone. -CREATE TABLE agentcore.call ( - call_id text PRIMARY KEY, +-- on purpose, and relates to a conversation by conversation_id convention alone. +CREATE TABLE agentcore.conversation ( + conversation_id text PRIMARY KEY, title text NULL, status text NOT NULL DEFAULT 'regular', external_id text NULL, custom jsonb NULL, - -- What the SESSION of a call holds and nothing else does: the stage, whether the machine - -- finished, the slots the writers filled, and the turn-index mark that says how far the call's - -- own session has got. Not the words — those are call_message. Written in the same batch as the + -- What the SESSION of a conversation holds and nothing else does: the stage, whether the machine + -- finished, the slots the writers filled, and the turn-index mark that says how far the conversation's + -- own session has got. Not the words — those are conversation_message. Written in the same batch as the -- turn's words, so a crash cannot land one without the other. -- -- The ordinal mark is not here. next_ordinal, below, holds it instead: an append can come from @@ -65,48 +65,48 @@ CREATE TABLE agentcore.call ( -- itself owns, not a value inside session state that only the session ever writes. -- -- The turn-index mark stays here on purpose. An edit deletes the rows it replaces, so the largest - -- turn index still in call_message is smaller than the largest ever issued, and a session that + -- turn index still in conversation_message is smaller than the largest ever issued, and a session that -- recomputed it from the surviving rows would hand the next turn a place a deleted row already -- stood in. state jsonb NULL, - -- The call's next free message ordinal: a store-owned counter that numbers every appended row, + -- The conversation's next free message ordinal: a store-owned counter that numbers every appended row, -- whether the append comes from the session or from a host outside any turn. next_ordinal integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT call_status_check CHECK (status IN ('regular', 'archived')) + CONSTRAINT conversation_status_check CHECK (status IN ('regular', 'archived')) ); --- Who may see a call. principal_key is opaque: this schema never joins it to a user table, and the --- consumer's identity model stays the consumer's. A call carries as many keys as are attached, so a --- tenant key can be attached when the call starts and a person's key when identity is learned. -CREATE TABLE agentcore.call_principal ( - call_id text NOT NULL REFERENCES agentcore.call(call_id) ON DELETE CASCADE, +-- Who may see a conversation. principal_key is opaque: this schema never joins it to a user table, and the +-- consumer's identity model stays the consumer's. A conversation carries as many keys as are attached, so a +-- tenant key can be attached when the conversation starts and a person's key when identity is learned. +CREATE TABLE agentcore.conversation_principal ( + conversation_id text NOT NULL REFERENCES agentcore.conversation(conversation_id) ON DELETE CASCADE, principal_key text NOT NULL, role text NOT NULL, attached_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (principal_key, call_id) + PRIMARY KEY (principal_key, conversation_id) ); -- The listing filters by principal, so principal leads the primary key. This index serves the other --- direction, which reading and detaching one call's claims use. -CREATE INDEX call_principal_call_idx ON agentcore.call_principal (call_id); +-- direction, which reading and detaching one conversation's claims use. +CREATE INDEX conversation_principal_conversation_idx ON agentcore.conversation_principal (conversation_id); -- No index on title. Searching the list is the consumer's, and a consumer who wants substring match -- adds their own GIN index over pg_trgm rather than paying for one nobody asked for. -GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.call, agentcore.call_principal TO agentcore_writer; +GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.conversation, agentcore.conversation_principal TO agentcore_writer; --- Store 1 — the words of a call. One row per message, never one JSON blob per call. +-- Store 1 — the words of a conversation. One row per message, never one JSON blob per conversation. -- --- A child of call. The row must exist before a word may be written against it, which is what stops --- a call accumulating words no listing can reach. -CREATE TABLE agentcore.call_message ( - call_id text NOT NULL REFERENCES agentcore.call(call_id) ON DELETE CASCADE, +-- A child of conversation. The row must exist before a word may be written against it, which is what stops +-- a conversation accumulating words no listing can reach. +CREATE TABLE agentcore.conversation_message ( + conversation_id text NOT NULL REFERENCES agentcore.conversation(conversation_id) ON DELETE CASCADE, ordinal integer NOT NULL, turn_index integer NOT NULL, role text NOT NULL, @@ -125,33 +125,33 @@ CREATE TABLE agentcore.call_message ( created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (call_id, ordinal), + PRIMARY KEY (conversation_id, ordinal), - -- What the id -> ordinal lookup an edit does reads, and what stops two rows of one call + -- What the id -> ordinal lookup an edit does reads, and what stops two rows of one conversation -- answering to one name. - CONSTRAINT call_message_message_id_unique UNIQUE (call_id, message_id) + CONSTRAINT conversation_message_message_id_unique UNIQUE (conversation_id, message_id) ); -CREATE INDEX call_message_updated_at_idx ON agentcore.call_message (updated_at); -CREATE INDEX call_message_turn_idx ON agentcore.call_message (call_id, turn_index); -CREATE INDEX call_message_retention_idx ON agentcore.call_message (call_id, updated_at DESC); +CREATE INDEX conversation_message_updated_at_idx ON agentcore.conversation_message (updated_at); +CREATE INDEX conversation_message_turn_idx ON agentcore.conversation_message (conversation_id, turn_index); +CREATE INDEX conversation_message_retention_idx ON agentcore.conversation_message (conversation_id, updated_at DESC); --- Retention deletes the call itself and reaches these rows through the cascade, so it needs no +-- Retention deletes the conversation itself and reaches these rows through the cascade, so it needs no -- privilege of its own here. -GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.call_message TO agentcore_writer; +GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.conversation_message TO agentcore_writer; -- The Responses continuation map: one serialized agent session per opaque id. -- --- A conversation id or a response id names no call and carries no state. This +-- A conversation id or a response id names no conversation and carries no state. This -- table is what it opens: the session envelope an AIAgent wrote, filed under --- the id the protocol handed out. It lives in this database beside the calls --- rather than anywhere else because the envelope names a call whose words live --- in call_message: splitting the key from the words across databases would let +-- the id the protocol handed out. It lives in this database beside the conversations +-- rather than anywhere else because the envelope names a conversation whose words live +-- in conversation_message: splitting the key from the words across databases would let -- a resume find one without the other. -- --- No foreign key to call. A continuation outlives the turns that filed it, and --- a swept call must not take the row that proves what its id once opened; an +-- No foreign key to conversation. A continuation outlives the turns that filed it, and +-- a swept conversation must not take the row that proves what its id once opened; an -- unknown id already fails closed at lookup, which is the only integrity this -- table needs. CREATE TABLE agentcore.response_continuation ( @@ -166,19 +166,19 @@ REVOKE ALL ON agentcore.response_continuation FROM PUBLIC; REVOKE ALL ON agentcore.response_continuation FROM agentcore_writer; GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.response_continuation TO agentcore_writer; --- Store 3 — the append-only record of what happened on a call. +-- Store 3 — the append-only record of what happened on a conversation. -- -- Two numbers, two owners, and the split is the point. event_id is IDENTITY and the CALL allocates -- it: an amendment has to name the event it corrects the instant that event is raised, so waiting --- for a store is not available. sequence is ORDER and the STORE allocates it: a per-call counter --- held by a session restarts at zero on the second session of one call, which is what a chat page +-- for a store is not available. sequence is ORDER and the STORE allocates it: a per-conversation counter +-- held by a session restarts at zero on the second session of one conversation, which is what a chat page -- reload is, and two app instances have no counter to share at all. -- -- Nothing sorts by event_id. UUID v7 is random within a millisecond and one turn raises three events -- inside one, so id order is not time order. Read the chain by sequence. CREATE TABLE agentcore.audit_event ( write_position bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, - call_id text NOT NULL, + conversation_id text NOT NULL, event_id uuid NOT NULL, sequence bigint NOT NULL, kind text NOT NULL, @@ -187,17 +187,17 @@ CREATE TABLE agentcore.audit_event ( amends_event_id uuid NULL, payload jsonb NOT NULL DEFAULT '{}'::jsonb, - CONSTRAINT audit_event_call_sequence_unique UNIQUE (call_id, sequence), + CONSTRAINT audit_event_conversation_sequence_unique UNIQUE (conversation_id, sequence), -- What makes a replayed batch a no-op instead of a duplicate. QueuedAuditSink logs and drops a -- batch today rather than retrying it, so nothing exercises this yet — but the day a retry is -- added, it must be safe by construction, not by care, and this constraint is what makes it so. - CONSTRAINT audit_event_call_event_unique UNIQUE (call_id, event_id) + CONSTRAINT audit_event_conversation_event_unique UNIQUE (conversation_id, event_id) ); --- No index for reading one call's chain is declared here, and that is not an omission: --- audit_event_call_sequence_unique is (call_id, sequence), so the constraint's own index already --- serves every "this call, in order" read. A second index on the same two columns in the same order +-- No index for reading one conversation's chain is declared here, and that is not an omission: +-- audit_event_conversation_sequence_unique is (conversation_id, sequence), so the constraint's own index already +-- serves every "this conversation, in order" read. A second index on the same two columns in the same order -- would only cost every insert a second write. -- Refusals 1, 2 and 3: the writer may only insert and read. diff --git a/src/AgentCore.Infrastructure/Database/Postgres/PostgresDataSourceFactory.cs b/src/AgentCore.Infrastructure/Database/Postgres/PostgresDataSourceFactory.cs index 1303eff8..87f67519 100644 --- a/src/AgentCore.Infrastructure/Database/Postgres/PostgresDataSourceFactory.cs +++ b/src/AgentCore.Infrastructure/Database/Postgres/PostgresDataSourceFactory.cs @@ -25,7 +25,7 @@ internal static class PostgresDataSourceFactory /// The connection string resolves to nothing. /// /// This runs once, while the host starts, so a missing credential or an unreachable database stops - /// the host and never a call. + /// the host and never a conversation. /// internal static async ValueTask OpenMigratedAsync( ISecretResolverPort? secrets, diff --git a/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs b/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs index f5687599..a440ed38 100644 --- a/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs +++ b/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs @@ -49,7 +49,7 @@ private static string Read(string version) /// Applies every migration the database has not seen yet. /// A data source whose role may create the agentcore schema and tables in it. /// Cancels the work. - /// The versions this call applied, oldest first. Empty when the schema was current. + /// The versions this conversation applied, oldest first. Empty when the schema was current. /// /// The connecting role also needs CREATEROLE the first time, because migration 001 creates /// agentcore_writer. The running system connects as a member of that role, not as this one. diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs index f49b6271..e36b523d 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs @@ -18,14 +18,14 @@ internal interface IQdrantSearchChannel { /// Sends one fused query. /// The query. - /// Cancels the call. The store links its deadline into this. + /// Cancels the conversation. The store links its deadline into this. /// The scored points, best first. Task> QueryAsync(SearchQuery query, CancellationToken cancellationToken); /// Fetches whole points by key, in one call. /// The collection. /// The keys. - /// Cancels the call. + /// Cancels the conversation. /// The points that exist. An unknown key is left out; it does not throw. Task> RetrieveAsync( string collection, IReadOnlyList ids, CancellationToken cancellationToken); @@ -34,7 +34,7 @@ Task> RetrieveAsync( /// The collection. /// What the points must match. /// The most points to return. - /// Cancels the call. + /// Cancels the conversation. /// The points that matched. An empty result is not an error. Task> ScrollAsync( string collection, Filter filter, uint limit, CancellationToken cancellationToken); diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs index f891f41b..ea95300e 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs @@ -75,11 +75,11 @@ public async Task> ScrollAsync( /// /// Runs one gRPC call and converts a client-side cancellation into . /// - private static async Task RunAsync(Func> call, CancellationToken cancellationToken) + private static async Task RunAsync(Func> conversation, CancellationToken cancellationToken) { try { - return await call().ConfigureAwait(false); + return await conversation().ConfigureAwait(false); } catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled && cancellationToken.IsCancellationRequested) { diff --git a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt index c4b9fbe0..5a4f965c 100644 --- a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt @@ -3,10 +3,10 @@ AgentCore.Infrastructure.Audit.Postgres.PostgresAuditSinkAdapter AgentCore.Infrastructure.Audit.Postgres.PostgresAuditSinkAdapter.Kind.get -> string! AgentCore.Infrastructure.Audit.Postgres.PostgresAuditSinkAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask AgentCore.Infrastructure.Audit.Postgres.PostgresAuditSinkAdapter.PostgresAuditSinkAdapter() -> void -AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreAdapter -AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreAdapter.Kind.get -> string! -AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreAdapter.PostgresCallStoreAdapter() -> void +AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreAdapter +AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreAdapter.Kind.get -> string! +AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreAdapter.OpenAsync(AgentCore.Application.Configuration.Schema.VendorProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreAdapter.PostgresConversationStoreAdapter() -> void AgentCore.Infrastructure.Database.Postgres.PostgresSchema AgentCore.Infrastructure.Embeddings.OpenAI.OpenAiEmbeddingGeneratorAdapter AgentCore.Infrastructure.Embeddings.OpenAI.OpenAiEmbeddingGeneratorAdapter.CreateGeneratorAsync(AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!>!> @@ -61,7 +61,7 @@ AgentCore.Infrastructure.Tools.McpToolSource.DisposeAsync() -> System.Threading. AgentCore.Infrastructure.Tools.McpToolSource.McpToolSource(AgentCore.Application.Secrets.ResolvedSecrets! secrets, System.Func? httpClients = null, Microsoft.Extensions.Logging.ILoggerFactory? loggers = null) -> void AgentCore.Infrastructure.Tools.McpToolSource.ProvideAsync(AgentCore.Application.Tools.Registry.ToolSourceContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> const AgentCore.Infrastructure.Audit.Postgres.PostgresAuditSinkAdapter.ProviderKind = "postgres" -> string! -const AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreAdapter.ProviderKind = "postgres" -> string! +const AgentCore.Infrastructure.Conversation.Postgres.PostgresConversationStoreAdapter.ProviderKind = "postgres" -> string! const AgentCore.Infrastructure.Embeddings.OpenAI.OpenAiEmbeddingGeneratorAdapter.ApiKeySecretName = "openai-api-key" -> string! const AgentCore.Infrastructure.Embeddings.OpenAI.OpenAiEmbeddingGeneratorAdapter.ApiKeyVariableName = "OPENAI_API_KEY" -> string! const AgentCore.Infrastructure.Embeddings.OpenAI.OpenAiEmbeddingGeneratorAdapter.ProviderKind = "openai" -> string! diff --git a/src/AgentCore.Infrastructure/Telemetry/Grafana/GrafanaOtlpTelemetryAdapter.cs b/src/AgentCore.Infrastructure/Telemetry/Grafana/GrafanaOtlpTelemetryAdapter.cs index ce3ad26a..a2299711 100644 --- a/src/AgentCore.Infrastructure/Telemetry/Grafana/GrafanaOtlpTelemetryAdapter.cs +++ b/src/AgentCore.Infrastructure/Telemetry/Grafana/GrafanaOtlpTelemetryAdapter.cs @@ -37,7 +37,7 @@ namespace AgentCore.Infrastructure.Telemetry.Grafana; /// adapter project for signals the framework already produces. /// /// -/// T61 is enforced twice, and this is the second place. The library keeps no call id on a +/// T61 is enforced twice, and this is the second place. The library keeps no conversation id on a /// metric attribute; this keeps the export interval at a minute or more, because Grafana Cloud bills /// the greater of active series and data points a minute. The floor lives on /// , so a document cannot diff --git a/src/AgentCore.Infrastructure/Tools/HttpToolSource.cs b/src/AgentCore.Infrastructure/Tools/HttpToolSource.cs index d6fd31f6..77471a15 100644 --- a/src/AgentCore.Infrastructure/Tools/HttpToolSource.cs +++ b/src/AgentCore.Infrastructure/Tools/HttpToolSource.cs @@ -99,7 +99,7 @@ internal HttpTool( { if (!TryFillUrl(arguments, out var url, out var missing)) { - return Failed($"the call filled no '{missing}', and the URL needs it."); + return Failed($"the conversation filled no '{missing}', and the URL needs it."); } using HttpRequestMessage message = new(new HttpMethod(_request.Method), url); diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpLog.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpLog.cs index e555d1bf..49f134a1 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpLog.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpLog.cs @@ -35,9 +35,9 @@ public static partial void ConnectAttemptFailed( [LoggerMessage( EventId = 101, Level = LogLevel.Warning, - Message = "MCP server {Server}: the call to '{Tool}' failed on the connection. " + Message = "MCP server {Server}: the conversation to '{Tool}' failed on the connection. " + "Reconnecting once and repeating it.")] - public static partial void CallFailedReconnecting(ILogger logger, string server, string tool, Exception error); + public static partial void ConversationFailedReconnecting(ILogger logger, string server, string tool, Exception error); /// A connection would not close cleanly. /// The logger of the session. @@ -69,7 +69,7 @@ public static partial void ConnectAttemptFailed( EventId = 105, Level = LogLevel.Warning, Message = "MCP server {Server}: changed the arguments of {Drifted}. The model keeps the schema it " - + "was given at boot, because rewriting a prompt during a live call is worse than a stale " + + "was given at boot, because rewriting a prompt during a live conversation is worse than a stale " + "one. Restart this service to pick the new schema up.")] public static partial void ToolSchemasDrifted(ILogger logger, string server, string drifted); diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs index 9fa11612..0ea93d08 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs @@ -127,15 +127,15 @@ public async ValueTask> OpenAsync( throw last!; } - /// Calls one tool, reconnecting once if the connection has died since the last call. + /// Calls one tool, reconnecting once if the connection has died since the last conversation. /// The name the server offers the tool under, never the served id. /// The arguments the model filled. - /// Cancels the call. + /// Cancels the conversation. /// Whatever the server answered, error results included. /// The server has stopped offering the tool. /// The session is closed. /// - /// One reconnect and one repeat, so a server that died between two turns of a telephone call + /// One reconnect and one repeat, so a server that died between two turns of a telephone conversation /// costs the caller a pause rather than the turn. A second failure is the caller's answer: a /// server that is down stays down, and repeating past that only spends the call timeout. /// @@ -168,7 +168,7 @@ public async ValueTask CallAsync( died = ex; } - McpLog.CallFailedReconnecting(_log, _server.Id, toolName, died); + McpLog.ConversationFailedReconnecting(_log, _server.Id, toolName, died); var reopened = await ReconnectAsync(client, cancellationToken).ConfigureAwait(false); @@ -189,18 +189,18 @@ private static async ValueTask SendAsync( IReadOnlyDictionary arguments, CancellationToken cancellationToken) { - var call = client.CallToolAsync(toolName, arguments, cancellationToken: cancellationToken).AsTask(); - var finished = await Task.WhenAny(call, client.Completion).ConfigureAwait(false); + var conversation = client.CallToolAsync(toolName, arguments, cancellationToken: cancellationToken).AsTask(); + var finished = await Task.WhenAny(conversation, client.Completion).ConfigureAwait(false); - if (ReferenceEquals(finished, call)) + if (ReferenceEquals(finished, conversation)) { - return await call.ConfigureAwait(false); + return await conversation.ConfigureAwait(false); } - // The call is never going to be answered now, but it is still a live task holding an + // The conversation is never going to be answered now, but it is still a live task holding an // exception nobody has looked at. Observing it keeps that from surfacing later as an // unhandled fault on a finalizer thread, with no context left to say where it came from. - Observe(call); + Observe(conversation); throw Ended(await client.Completion.ConfigureAwait(false)); } @@ -213,7 +213,7 @@ private static void Observe(Task task) TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - /// Turns a finished session into the exception the call itself never threw. + /// Turns a finished session into the exception the conversation itself never threw. private static IOException Ended(ClientCompletionDetails details) { var why = details.Exception?.Message ?? "it closed the connection"; @@ -342,7 +342,7 @@ private async ValueTask ReconnectAsync(McpClient dead, CancellationTo { ObjectDisposedException.ThrowIf(_disposed, this); - // Two calls can fail against one dead client at once. The first through here replaces it; + // Two conversations can fail against one dead client at once. The first through here replaces it; // the second must use that replacement rather than open a third connection. if (!ReferenceEquals(_client, dead)) { @@ -361,8 +361,8 @@ private async ValueTask ReconnectAsync(McpClient dead, CancellationTo /// Returns the live connection, opening one if the session has none. /// /// A client whose has already finished is replaced before it - /// is handed out, rather than after a call has been spent discovering it. That is the ordinary - /// case for a stdio server whose child crashed between two turns of a call. + /// is handed out, rather than after a conversation has been spent discovering it. That is the ordinary + /// case for a stdio server whose child crashed between two turns of a conversation. /// private async ValueTask CurrentAsync(CancellationToken cancellationToken) { diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs index f3f0756a..86659e0e 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs @@ -7,7 +7,7 @@ // Only the server's declared properties cross the wire (see _declared). The invoking client files // the turn into every call's arguments and the turn carries delegates, which the MCP SDK's argument // serializer cannot hold — forwarding everything faulted every call. Revisit if the SDK ever lets a -// call exclude entries, or if the turn stops riding along in tool arguments. +// conversation exclude entries, or if the turn stops riding along in tool arguments. namespace AgentCore.Infrastructure.Tools.Mcp; diff --git a/src/AgentCore.Infrastructure/Tools/McpToolSource.cs b/src/AgentCore.Infrastructure/Tools/McpToolSource.cs index 5e693e85..d275ecaa 100644 --- a/src/AgentCore.Infrastructure/Tools/McpToolSource.cs +++ b/src/AgentCore.Infrastructure/Tools/McpToolSource.cs @@ -93,7 +93,7 @@ private static async ValueTask Open( /// A server cannot be reached within its own retry and timeout; an allow: entry names a /// tool the server does not offer, is empty, or writes "*" alongside another entry or with /// an as:; or a kept tool has no description. Every one of these names the server id, so a - /// deployer knows which mcp: entry is wrong. On any failure, every session this call + /// deployer knows which mcp: entry is wrong. On any failure, every session this conversation /// already opened is closed before the exception leaves — a partly-booted document leaves no /// child process behind. /// diff --git a/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs b/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs deleted file mode 100644 index f62f9946..00000000 --- a/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs +++ /dev/null @@ -1,249 +0,0 @@ -using AgentCore.Application.Audit.Memory; -using AgentCore.Application.Audit; -using AgentCore.Application.Runtime; -using AgentCore.Domain.Audit; -using Xunit; -using Xunit.Sdk; - -namespace AgentCore.Application.Tests.Audit; - -/// -/// The one place that knows both vocabularies: a neutral fact of a call, and a row of the chain of D23. -/// -public sealed class AuditCallObserverTests -{ - private const string CallId = "call-1"; - - private static readonly DateTimeOffset Moment = new(2026, 8, 15, 9, 30, 0, TimeSpan.Zero); - - /// The six kinds that are counted or logged or both, and stored nowhere. - public static TheoryData DiagnosticKinds => - [ - CallEventKind.ModerationUnavailable, - CallEventKind.ModerationClean, - CallEventKind.EmptyReply, - CallEventKind.ExtractionFailed, - CallEventKind.TranscriptWriteFailed, - CallEventKind.StateRestorePartial, - CallEventKind.TranscriptResyncFailed, - ]; - - /// Every kind, once, across the two tables above. - [Fact] - public void TheTwoTables_BetweenThemNameEveryKind() - { - IEnumerable named = - [ - .. DiagnosticKinds.Select(row => (CallEventKind)((ITheoryDataRow)row).GetData()[0]!), - .. StoredKinds.Select(row => (CallEventKind)((ITheoryDataRow)row).GetData()[0]!), - ]; - - Assert.Equal([.. Enum.GetValues().Order()], [.. named.Order()]); - } - - /// The seven kinds the store keeps, beside the token each one writes. - public static TheoryData StoredKinds => - new() - { - { CallEventKind.CallStarted, AuditEventKind.CallStarted }, - { CallEventKind.PromptFlagged, AuditEventKind.PromptFlagged }, - { CallEventKind.ToolFailed, AuditEventKind.ToolFailed }, - { CallEventKind.TurnCompleted, AuditEventKind.TurnCompleted }, - { CallEventKind.ReplyInterrupted, AuditEventKind.ReplyInterrupted }, - { CallEventKind.CallEnded, AuditEventKind.CallEnded }, - { CallEventKind.TurnSuperseded, AuditEventKind.TurnSuperseded }, - }; - - [Theory] - [MemberData(nameof(DiagnosticKinds))] - public async Task AFactWithNoEventId_WritesNoRow(CallEventKind kind) - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - - // A diagnostic-only event leaves EventId null precisely because it takes no row. - await observer.OnCallEventAsync(Event(kind), TestContext.Current.CancellationToken); - - Assert.Empty(sink.Events); - } - - [Theory] - [MemberData(nameof(StoredKinds))] - public async Task AStoredFact_BecomesARowOfItsOwnKind(CallEventKind kind, AuditEventKind expected) - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - - await observer.OnCallEventAsync( - Event(kind, eventId: Guid.CreateVersion7(), amends: Guid.CreateVersion7()), - TestContext.Current.CancellationToken); - - var written = Assert.Single(sink.Events); - Assert.Equal(expected, written.Kind); - } - - [Fact] - public async Task ItCopiesTheIdentityStraightThrough() - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - var id = Guid.CreateVersion7(); - - await observer.OnCallEventAsync( - new CallEvent - { - CallId = CallId, - Kind = CallEventKind.CallStarted, - OccurredAt = DateTimeOffset.UnixEpoch, - EventId = id, - }, - CancellationToken.None); - - Assert.Equal(id, Assert.Single(sink.EventsOf(CallId)).EventId); - } - - [Fact] - public async Task ItCopiesTheAmendmentStraightThrough() - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - var turn = Guid.CreateVersion7(); - var cut = Guid.CreateVersion7(); - - await observer.OnCallEventAsync( - new CallEvent - { - CallId = CallId, - Kind = CallEventKind.ReplyInterrupted, - OccurredAt = DateTimeOffset.UnixEpoch, - EventId = cut, - AmendsEventId = turn, - TurnIndex = 0, - Payload = new Dictionary(StringComparer.Ordinal) - { - [AuditPayloadKeys.UtteranceUntilInterruptSha256] = AuditHash.OfText("heard").Value, - [AuditPayloadKeys.DurationUntilInterruptMs] = "120", - }, - }, - CancellationToken.None); - - var written = Assert.Single(sink.EventsOf(CallId)); - Assert.Equal(cut, written.EventId); - Assert.Equal(turn, written.AmendsEventId); - } - - [Fact] - public async Task AFactThatCorrectsNothing_LeavesTheAmendmentUnset() - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - - await observer.OnCallEventAsync( - Event(CallEventKind.TurnCompleted, eventId: Guid.CreateVersion7()), - TestContext.Current.CancellationToken); - - Assert.Null(Assert.Single(sink.Events).AmendsEventId); - } - - [Fact] - public async Task TheRow_CarriesTheCallTheTurnAndTheMomentUnchanged() - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - Dictionary payload = new(StringComparer.Ordinal) - { - [AuditPayloadKeys.ReplyTextSha256] = AuditHash.OfText("hello there.").Value, - [AuditPayloadKeys.StageBefore] = "greeting", - [AuditPayloadKeys.StageAfter] = "triage", - }; - - await observer.OnCallEventAsync( - Event(CallEventKind.TurnCompleted, eventId: Guid.CreateVersion7(), turnIndex: 5, payload: payload), - TestContext.Current.CancellationToken); - - var written = Assert.Single(sink.Events); - Assert.Equal(CallId, written.CallId); - Assert.Equal(5, written.TurnIndex); - Assert.Equal(Moment, written.OccurredAt); - Assert.Equal(payload, written.Payload); - } - - [Fact] - public async Task AFactAboutTheCallItself_CarriesNoTurn() - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - - await observer.OnCallEventAsync( - Event(CallEventKind.CallStarted, eventId: Guid.CreateVersion7()), - TestContext.Current.CancellationToken); - - Assert.Null(Assert.Single(sink.Events).TurnIndex); - } - - [Fact] - public async Task ManyFacts_ReachTheSinkInTheOrderTheCallRaisedThem() - { - InMemoryAuditSink sink = new(); - AuditCallObserver observer = new(sink); - var token = TestContext.Current.CancellationToken; - - await observer.OnCallEventAsync(Event(CallEventKind.CallStarted, eventId: Guid.CreateVersion7()), token); - - // The two diagnostic facts between them take no identity, so they write no row. - await observer.OnCallEventAsync(Event(CallEventKind.ModerationClean), token); - await observer.OnCallEventAsync( - Event(CallEventKind.TurnCompleted, eventId: Guid.CreateVersion7(), turnIndex: 0), token); - await observer.OnCallEventAsync(Event(CallEventKind.EmptyReply, turnIndex: 0), token); - await observer.OnCallEventAsync(Event(CallEventKind.CallEnded, eventId: Guid.CreateVersion7()), token); - - Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.TurnCompleted, AuditEventKind.CallEnded], - sink.EventsOf(CallId).Select(item => item.Kind).ToArray()); - } - - [Fact] - public void NoSink_IsRefused() => Assert.Throws(() => new AuditCallObserver(null!)); - - [Fact] - public async Task NoEvent_IsRefused() - => await Assert.ThrowsAsync(async () => - await new AuditCallObserver(new InMemoryAuditSink()) - .OnCallEventAsync(null!, TestContext.Current.CancellationToken)); - - private static CallEvent Event( - CallEventKind kind, - Guid? eventId = null, - int? turnIndex = null, - Guid? amends = null, - IReadOnlyDictionary? payload = null) => new() - { - CallId = CallId, - Kind = kind, - OccurredAt = Moment, - EventId = eventId, - TurnIndex = turnIndex, - AmendsEventId = amends, - Payload = payload ?? RequiredPayload(kind), - }; - - /// - /// The payload each kind must carry to be a legal event, per . - /// - private static Dictionary RequiredPayload(CallEventKind kind) => kind switch - { - CallEventKind.ReplyInterrupted => new Dictionary(StringComparer.Ordinal) - { - [AuditPayloadKeys.UtteranceUntilInterruptSha256] = AuditHash.OfText("the belt ships").Value, - }, - CallEventKind.PromptFlagged => new Dictionary(StringComparer.Ordinal) - { - [AuditPayloadKeys.ModerationCategories] = "harassment", - }, - CallEventKind.CallEnded => new Dictionary(StringComparer.Ordinal) - { - [AuditPayloadKeys.EndReason] = CallEndReasons.ToToken(CallEndReason.CallerHungUp), - }, - _ => new Dictionary(StringComparer.Ordinal), - }; -} diff --git a/tests/AgentCore.Application.Tests/Audit/AuditConversationObserverTests.cs b/tests/AgentCore.Application.Tests/Audit/AuditConversationObserverTests.cs new file mode 100644 index 00000000..59378be5 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Audit/AuditConversationObserverTests.cs @@ -0,0 +1,249 @@ +using AgentCore.Application.Audit.Memory; +using AgentCore.Application.Audit; +using AgentCore.Application.Runtime; +using AgentCore.Domain.Audit; +using Xunit; +using Xunit.Sdk; + +namespace AgentCore.Application.Tests.Audit; + +/// +/// The one place that knows both vocabularies: a neutral fact of a conversation, and a row of the chain of D23. +/// +public sealed class AuditConversationObserverTests +{ + private const string ConversationId = "conversation-1"; + + private static readonly DateTimeOffset Moment = new(2026, 8, 15, 9, 30, 0, TimeSpan.Zero); + + /// The six kinds that are counted or logged or both, and stored nowhere. + public static TheoryData DiagnosticKinds => + [ + ConversationEventKind.ModerationUnavailable, + ConversationEventKind.ModerationClean, + ConversationEventKind.EmptyReply, + ConversationEventKind.ExtractionFailed, + ConversationEventKind.TranscriptWriteFailed, + ConversationEventKind.StateRestorePartial, + ConversationEventKind.TranscriptResyncFailed, + ]; + + /// Every kind, once, across the two tables above. + [Fact] + public void TheTwoTables_BetweenThemNameEveryKind() + { + IEnumerable named = + [ + .. DiagnosticKinds.Select(row => (ConversationEventKind)((ITheoryDataRow)row).GetData()[0]!), + .. StoredKinds.Select(row => (ConversationEventKind)((ITheoryDataRow)row).GetData()[0]!), + ]; + + Assert.Equal([.. Enum.GetValues().Order()], [.. named.Order()]); + } + + /// The seven kinds the store keeps, beside the token each one writes. + public static TheoryData StoredKinds => + new() + { + { ConversationEventKind.ConversationStarted, AuditEventKind.ConversationStarted }, + { ConversationEventKind.PromptFlagged, AuditEventKind.PromptFlagged }, + { ConversationEventKind.ToolFailed, AuditEventKind.ToolFailed }, + { ConversationEventKind.TurnCompleted, AuditEventKind.TurnCompleted }, + { ConversationEventKind.ReplyInterrupted, AuditEventKind.ReplyInterrupted }, + { ConversationEventKind.ConversationEnded, AuditEventKind.ConversationEnded }, + { ConversationEventKind.TurnSuperseded, AuditEventKind.TurnSuperseded }, + }; + + [Theory] + [MemberData(nameof(DiagnosticKinds))] + public async Task AFactWithNoEventId_WritesNoRow(ConversationEventKind kind) + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + + // A diagnostic-only event leaves EventId null precisely because it takes no row. + await observer.OnConversationEventAsync(Event(kind), TestContext.Current.CancellationToken); + + Assert.Empty(sink.Events); + } + + [Theory] + [MemberData(nameof(StoredKinds))] + public async Task AStoredFact_BecomesARowOfItsOwnKind(ConversationEventKind kind, AuditEventKind expected) + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + + await observer.OnConversationEventAsync( + Event(kind, eventId: Guid.CreateVersion7(), amends: Guid.CreateVersion7()), + TestContext.Current.CancellationToken); + + var written = Assert.Single(sink.Events); + Assert.Equal(expected, written.Kind); + } + + [Fact] + public async Task ItCopiesTheIdentityStraightThrough() + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + var id = Guid.CreateVersion7(); + + await observer.OnConversationEventAsync( + new ConversationEvent + { + ConversationId = ConversationId, + Kind = ConversationEventKind.ConversationStarted, + OccurredAt = DateTimeOffset.UnixEpoch, + EventId = id, + }, + CancellationToken.None); + + Assert.Equal(id, Assert.Single(sink.EventsOf(ConversationId)).EventId); + } + + [Fact] + public async Task ItCopiesTheAmendmentStraightThrough() + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + var turn = Guid.CreateVersion7(); + var cut = Guid.CreateVersion7(); + + await observer.OnConversationEventAsync( + new ConversationEvent + { + ConversationId = ConversationId, + Kind = ConversationEventKind.ReplyInterrupted, + OccurredAt = DateTimeOffset.UnixEpoch, + EventId = cut, + AmendsEventId = turn, + TurnIndex = 0, + Payload = new Dictionary(StringComparer.Ordinal) + { + [AuditPayloadKeys.UtteranceUntilInterruptSha256] = AuditHash.OfText("heard").Value, + [AuditPayloadKeys.DurationUntilInterruptMs] = "120", + }, + }, + CancellationToken.None); + + var written = Assert.Single(sink.EventsOf(ConversationId)); + Assert.Equal(cut, written.EventId); + Assert.Equal(turn, written.AmendsEventId); + } + + [Fact] + public async Task AFactThatCorrectsNothing_LeavesTheAmendmentUnset() + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + + await observer.OnConversationEventAsync( + Event(ConversationEventKind.TurnCompleted, eventId: Guid.CreateVersion7()), + TestContext.Current.CancellationToken); + + Assert.Null(Assert.Single(sink.Events).AmendsEventId); + } + + [Fact] + public async Task TheRow_CarriesTheConversationTheTurnAndTheMomentUnchanged() + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + Dictionary payload = new(StringComparer.Ordinal) + { + [AuditPayloadKeys.ReplyTextSha256] = AuditHash.OfText("hello there.").Value, + [AuditPayloadKeys.StageBefore] = "greeting", + [AuditPayloadKeys.StageAfter] = "triage", + }; + + await observer.OnConversationEventAsync( + Event(ConversationEventKind.TurnCompleted, eventId: Guid.CreateVersion7(), turnIndex: 5, payload: payload), + TestContext.Current.CancellationToken); + + var written = Assert.Single(sink.Events); + Assert.Equal(ConversationId, written.ConversationId); + Assert.Equal(5, written.TurnIndex); + Assert.Equal(Moment, written.OccurredAt); + Assert.Equal(payload, written.Payload); + } + + [Fact] + public async Task AFactAboutTheConversationItself_CarriesNoTurn() + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + + await observer.OnConversationEventAsync( + Event(ConversationEventKind.ConversationStarted, eventId: Guid.CreateVersion7()), + TestContext.Current.CancellationToken); + + Assert.Null(Assert.Single(sink.Events).TurnIndex); + } + + [Fact] + public async Task ManyFacts_ReachTheSinkInTheOrderTheConversationRaisedThem() + { + InMemoryAuditSink sink = new(); + AuditConversationObserver observer = new(sink); + var token = TestContext.Current.CancellationToken; + + await observer.OnConversationEventAsync(Event(ConversationEventKind.ConversationStarted, eventId: Guid.CreateVersion7()), token); + + // The two diagnostic facts between them take no identity, so they write no row. + await observer.OnConversationEventAsync(Event(ConversationEventKind.ModerationClean), token); + await observer.OnConversationEventAsync( + Event(ConversationEventKind.TurnCompleted, eventId: Guid.CreateVersion7(), turnIndex: 0), token); + await observer.OnConversationEventAsync(Event(ConversationEventKind.EmptyReply, turnIndex: 0), token); + await observer.OnConversationEventAsync(Event(ConversationEventKind.ConversationEnded, eventId: Guid.CreateVersion7()), token); + + Assert.Equal( + [AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted, AuditEventKind.ConversationEnded], + sink.EventsOf(ConversationId).Select(item => item.Kind).ToArray()); + } + + [Fact] + public void NoSink_IsRefused() => Assert.Throws(() => new AuditConversationObserver(null!)); + + [Fact] + public async Task NoEvent_IsRefused() + => await Assert.ThrowsAsync(async () => + await new AuditConversationObserver(new InMemoryAuditSink()) + .OnConversationEventAsync(null!, TestContext.Current.CancellationToken)); + + private static ConversationEvent Event( + ConversationEventKind kind, + Guid? eventId = null, + int? turnIndex = null, + Guid? amends = null, + IReadOnlyDictionary? payload = null) => new() + { + ConversationId = ConversationId, + Kind = kind, + OccurredAt = Moment, + EventId = eventId, + TurnIndex = turnIndex, + AmendsEventId = amends, + Payload = payload ?? RequiredPayload(kind), + }; + + /// + /// The payload each kind must carry to be a legal event, per . + /// + private static Dictionary RequiredPayload(ConversationEventKind kind) => kind switch + { + ConversationEventKind.ReplyInterrupted => new Dictionary(StringComparer.Ordinal) + { + [AuditPayloadKeys.UtteranceUntilInterruptSha256] = AuditHash.OfText("the belt ships").Value, + }, + ConversationEventKind.PromptFlagged => new Dictionary(StringComparer.Ordinal) + { + [AuditPayloadKeys.ModerationCategories] = "harassment", + }, + ConversationEventKind.ConversationEnded => new Dictionary(StringComparer.Ordinal) + { + [AuditPayloadKeys.EndReason] = ConversationEndReasons.ToToken(ConversationEndReason.CallerHungUp), + }, + _ => new Dictionary(StringComparer.Ordinal), + }; +} diff --git a/tests/AgentCore.Application.Tests/Audit/AuditSinkFactoryTests.cs b/tests/AgentCore.Application.Tests/Audit/AuditSinkFactoryTests.cs index ba0b1617..3151946e 100644 --- a/tests/AgentCore.Application.Tests/Audit/AuditSinkFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Audit/AuditSinkFactoryTests.cs @@ -42,7 +42,7 @@ public async Task NoAuditBlock_GetsTheInProcessSinkAndAsksNoAdapter() [adapter], TestContext.Current.CancellationToken); - // The whole point of the seam. A document that chose no store still records the call, so the + // The whole point of the seam. A document that chose no store still records the conversation, so the // events of D23 have somewhere to go and a host with no database still starts. Assert.IsType(sink); Assert.Equal(0, adapter.Opens); @@ -137,7 +137,7 @@ public async Task AKindNoAdapterServes_FailsTheStartAndNamesWhatIsRegistered() TestContext.Current.CancellationToken)); // A document that asked for something this host cannot give. The failure belongs to the - // start and never to a call, which is what item 9 of section 11 asks for. + // start and never to a conversation, which is what item 9 of section 11 asks for. Assert.Contains("postgres", failure.Message, StringComparison.Ordinal); Assert.Contains("'fake'", failure.Message, StringComparison.Ordinal); Assert.Equal("/providers/audit/kind", failure.Errors[0].Pointer); @@ -176,7 +176,7 @@ public async Task TwoAdaptersOnOneKind_FailTheStart() /// /// The raw string in ExampleDocument strips its common indentation, so inside /// providers: a key sits at two spaces and its own keys at four. Every line is written here - /// rather than by the caller, because YAML indentation written by hand at a call site is how the + /// rather than by the caller, because YAML indentation written by hand at a conversation site is how the /// first draft of the telemetry tests failed. /// private static string Document(params string[] entries) diff --git a/tests/AgentCore.Application.Tests/Audit/CallSessionAuditTests.cs b/tests/AgentCore.Application.Tests/Audit/ConversationSessionAuditTests.cs similarity index 77% rename from tests/AgentCore.Application.Tests/Audit/CallSessionAuditTests.cs rename to tests/AgentCore.Application.Tests/Audit/ConversationSessionAuditTests.cs index 5a4fc1e4..04d2b1e4 100644 --- a/tests/AgentCore.Application.Tests/Audit/CallSessionAuditTests.cs +++ b/tests/AgentCore.Application.Tests/Audit/ConversationSessionAuditTests.cs @@ -24,7 +24,7 @@ namespace AgentCore.Application.Tests.Audit; /// The session is the only place that knows the turn index, both stages, and the identity a later /// amendment must name, so it is the only place that produces an event. /// -public sealed class CallSessionAuditTests +public sealed class ConversationSessionAuditTests { private const string PolicyYaml = """ @@ -41,7 +41,7 @@ public sealed class CallSessionAuditTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller" } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -73,59 +73,59 @@ public sealed class CallSessionAuditTests // The events, and the identity a later amendment names. // ------------------------------------------------------------------------------------------- [Fact] - public void ANewSession_WritesTheCallStartedEvent() + public void ANewSession_WritesTheConversationStartedEvent() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); - var started = Assert.Single(sink.EventsOf("call-1")); - Assert.Equal(AuditEventKind.CallStarted, started.Kind); + var started = Assert.Single(sink.EventsOf("conversation-1")); + Assert.Equal(AuditEventKind.ConversationStarted, started.Kind); Assert.NotEqual(Guid.Empty, started.EventId); Assert.Null(started.TurnIndex); Assert.Null(started.AmendsEventId); - Assert.Equal(session.CallId, started.CallId); + Assert.Equal(session.ConversationId, started.ConversationId); } [Fact] - public async Task ASecondSessionOfOneCall_CollidesWithNothing() + public async Task ASecondSessionOfOneConversation_CollidesWithNothing() { using SequencedChatClient reply = new("hello there.", "still here."); using SequencedChatClient fill = new(StayingNull, StayingNull); InMemoryAuditSink sink = new(); // One factory, so both sessions share one compiled agent and one store — which is what a host - // holds, and what makes the second session a resume rather than a different call. + // holds, and what makes the second session a resume rather than a different conversation. var factory = Build(PolicyYaml, reply, fill, auditSink: sink); - var first = factory.Create("call-1"); + var first = factory.Create("conversation-1"); await first.RunTurnAsync("hello", TestContext.Current.CancellationToken); await first.FlushTranscriptAsync(); - var second = factory.Create("call-1"); + var second = factory.Create("conversation-1"); await second.RunTurnAsync("still there?", TestContext.Current.CancellationToken); await second.FlushTranscriptAsync(); - var written = sink.EventsOf("call-1"); + var written = sink.EventsOf("conversation-1"); // The shape is the assertion, and both halves of it are the point. // // ARRIVAL: before this change the second session restarted its counter at zero, store 3 - // refused every event it raised, and a resumed call lost its whole audit trail. The proof of + // refused every event it raised, and a resumed conversation lost its whole audit trail. The proof of // the fix is that the second session's two events are HERE — distinctness proves nothing, // because InMemoryAuditSink enforces no key and Guid.CreateVersion7 is unique by // construction, so that assertion passed just as well over the two events that never arrived. // - // A SECOND call.started: a session opening onto a call that already has words raises one, and - // it is kept rather than suppressed. See AuditEventKind.CallStarted for why. This is where + // A SECOND conversation.started: a session opening onto a conversation that already has words raises one, and + // it is kept rather than suppressed. See AuditEventKind.ConversationStarted for why. This is where // that decision is visible, so a build that quietly stopped raising it fails here. Assert.Equal( [ - AuditEventKind.CallStarted, + AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted, - AuditEventKind.CallStarted, + AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted, ], written.Select(item => item.Kind).ToArray()); @@ -142,13 +142,13 @@ public async Task AFinishedTurn_WritesOneTurnCompletedEventWithBothStages() using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); TestTimeProvider clock = new(); - var session = Build(PolicyYaml, reply, fill, timeProvider: clock, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, timeProvider: clock, auditSink: sink).Create("conversation-1"); clock.Advance(TimeSpan.FromSeconds(12)); var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - var completed = Assert.Single(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.TurnCompleted); - Assert.Same(completed, sink.EventsOf("call-1")[1]); + var completed = Assert.Single(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.TurnCompleted); + Assert.Same(completed, sink.EventsOf("conversation-1")[1]); Assert.Equal(0, completed.TurnIndex); Assert.Equal(AuditHash.OfText("hello there.").Value, completed.Payload[AuditPayloadKeys.ReplyTextSha256]); Assert.Equal("greeting", completed.Payload[AuditPayloadKeys.StageBefore]); @@ -166,7 +166,7 @@ public async Task ABargeIn_WritesASecondEventThatAmendsTheTurnEvent() using ScriptedChatClient reply = new("hello", " there.") { GateAfterFirstFragment = true }; using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); // The streaming shape, because only an audible turn is cut in flight: the caller heard the // first fragment, then spoke over the rest. A turn that never streamed is never audible and @@ -180,12 +180,12 @@ public async Task ABargeIn_WritesASecondEventThatAmendsTheTurnEvent() Assert.False(await updates.MoveNextAsync()); } - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); var completed = Assert.Single(events, item => item.Kind == AuditEventKind.TurnCompleted); var cut = Assert.Single(events, item => item.Kind == AuditEventKind.ReplyInterrupted); // T23: the chain is append-only, so an amendment is a second event that references the first. - var chain = sink.EventsOf("call-1"); + var chain = sink.EventsOf("conversation-1"); Assert.Equal(completed.EventId, cut.AmendsEventId); Assert.True(chain.ToList().IndexOf(cut) > chain.ToList().IndexOf(completed)); Assert.Equal(completed.TurnIndex, cut.TurnIndex); @@ -201,19 +201,19 @@ public async Task TheFourthConsecutiveToolFailure_WritesAToolFailedEventBeforeTh { using LoopingToolCallingChatClient reply = new(); InMemoryAuditSink sink = new(); - var session = Build(ToolYaml, reply, null, new ThrowingToolBuilder().Create, auditSink: sink).Create("call-1"); + var session = Build(ToolYaml, reply, null, new ThrowingToolBuilder().Create, auditSink: sink).Create("conversation-1"); await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); var failures = events.Where(item => item.Kind == AuditEventKind.ToolFailed).ToArray(); var completed = Assert.Single(events, item => item.Kind == AuditEventKind.TurnCompleted); - // The kind is raised at two altitudes and both are here: one row for each call that failed, + // The kind is raised at two altitudes and both are here: one row for each conversation that failed, // and one for the turn that ended because of them. Five in all, and every one of them before // the turn event. Assert.Equal(5, failures.Length); - var order = sink.EventsOf("call-1").ToList(); + var order = sink.EventsOf("conversation-1").ToList(); Assert.All(failures, failure => Assert.True(order.IndexOf(failure) < order.IndexOf(completed))); Assert.All(failures, failure => Assert.Equal(0, failure.TurnIndex)); @@ -232,24 +232,24 @@ public async Task TheFourthConsecutiveToolFailure_WritesAToolFailedEventBeforeTh // The four call-level rows are the new fact, and each one names its tool. The fourth is the // one that spent the budget: the framework does not capture that exception at all, so it never // reaches CreateResponseMessages, and only the invocation hook sees it. - var calls = failures.Where(failure => failure.Payload.ContainsKey(AuditPayloadKeys.ToolCallId)).ToArray(); - Assert.Equal(4, calls.Length); - Assert.All(calls, call => Assert.Equal("lookup_order", call.Payload[AuditPayloadKeys.ToolName])); + var conversations = failures.Where(failure => failure.Payload.ContainsKey(AuditPayloadKeys.ToolCallId)).ToArray(); + Assert.Equal(4, conversations.Length); + Assert.All(conversations, conversation => Assert.Equal("lookup_order", conversation.Payload[AuditPayloadKeys.ToolName])); Assert.All( - calls, - call => Assert.Equal( + conversations, + conversation => Assert.Equal( ToolFailureKinds.ToToken(ToolFailureKind.Faulted), - call.Payload[AuditPayloadKeys.ToolFailureKind])); + conversation.Payload[AuditPayloadKeys.ToolFailureKind])); Assert.All( - calls, - call => Assert.Contains( + conversations, + conversation => Assert.Contains( ThrowingToolBuilder.Message, - call.Payload[AuditPayloadKeys.ToolError], + conversation.Payload[AuditPayloadKeys.ToolError], StringComparison.Ordinal)); - // Four calls, four ids, and none of them repeated. The name alone could never have told them + // Four conversations, four ids, and none of them repeated. The name alone could never have told them // apart, and the chain used to hold neither. - var ids = calls.Select(call => call.Payload[AuditPayloadKeys.ToolCallId]).ToArray(); + var ids = conversations.Select(conversation => conversation.Payload[AuditPayloadKeys.ToolCallId]).ToArray(); Assert.Equal(4, ids.Distinct(StringComparer.Ordinal).Count()); // The chain still verifies over every one of the new keys. @@ -257,21 +257,21 @@ public async Task TheFourthConsecutiveToolFailure_WritesAToolFailedEventBeforeTh } // ------------------------------------------------------------------------------------------- - // The facts of one tool call. §8.7 row six is the turn-level fact; these are the call-level ones. + // The facts of one tool call. §8.7 row six is the turn-level fact; these are the conversation-level ones. // ------------------------------------------------------------------------------------------- [Fact] - public async Task AToolThatFaults_NamesTheToolAndTheCallIdInTheChain() + public async Task AToolThatFaults_NamesTheToolAndTheConversationIdInTheChain() { // One failing round, then the model answers, so the turn ends normally and the only thing // that could ever have recorded the tool is the observer. using NamedToolCallingChatClient reply = new("lookup_order", "I could not reach the order system."); InMemoryAuditSink sink = new(); UnreachableEndpointToolBuilder tools = new(); - var session = Build(ToolYaml, reply, null, tools.Create, auditSink: sink).Create("call-1"); + var session = Build(ToolYaml, reply, null, tools.Create, auditSink: sink).Create("conversation-1"); var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); - var failed = Assert.Single(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.ToolFailed); + var failed = Assert.Single(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ToolFailed); Assert.Equal("lookup_order", failed.Payload[AuditPayloadKeys.ToolName]); Assert.Equal(reply.CallIds[0], failed.Payload[AuditPayloadKeys.ToolCallId]); Assert.Equal( @@ -296,11 +296,11 @@ public async Task AHallucinatedToolName_ReachesTheChain() using NamedToolCallingChatClient reply = new("lookup_ordar", "Let me try that again."); InMemoryAuditSink sink = new(); var session = Build(ToolYaml, reply, null, new StubToolBuilder("""{"status":"shipped"}""").Create, auditSink: sink) - .Create("call-1"); + .Create("conversation-1"); var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); - var failed = Assert.Single(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.ToolFailed); + var failed = Assert.Single(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ToolFailed); // The name recorded is the name the MODEL called, so a reader that joins it to tools[].id // finds nothing — which is the finding. @@ -323,11 +323,11 @@ public async Task TwoParallelCallsToTheSameTool_AreTwoDistinguishableRecords() using NamedToolCallingChatClient reply = new("lookup_order", "Both lookups failed.", callsPerTurn: 2); InMemoryAuditSink sink = new(); var session = Build(ToolYaml, reply, null, new UnreachableEndpointToolBuilder().Create, auditSink: sink) - .Create("call-1"); + .Create("conversation-1"); await session.RunTurnAsync("where are my two orders", TestContext.Current.CancellationToken); - var failures = sink.EventsOf("call-1").Where(item => item.Kind == AuditEventKind.ToolFailed).ToArray(); + var failures = sink.EventsOf("conversation-1").Where(item => item.Kind == AuditEventKind.ToolFailed).ToArray(); Assert.Equal(2, failures.Length); Assert.All(failures, failure => Assert.Equal("lookup_order", failure.Payload[AuditPayloadKeys.ToolName])); @@ -336,7 +336,7 @@ public async Task TwoParallelCallsToTheSameTool_AreTwoDistinguishableRecords() failures.Select(failure => failure.Payload[AuditPayloadKeys.ToolCallId]).Order(StringComparer.Ordinal).ToArray()); // Two records, and the chain still verifies over them. - Assert.All(sink.EventsOf("call-1"), AuditEventVocabulary.Validate); + Assert.All(sink.EventsOf("conversation-1"), AuditEventVocabulary.Validate); } [Fact] @@ -347,18 +347,18 @@ public async Task AToolWhoseFaultTheModelCanAnswer_WritesNoToolFailedEventAtAll( using NamedToolCallingChatClient reply = new("lookup_order", "That order is already closed."); InMemoryAuditSink sink = new(); var session = Build(ToolYaml, reply, null, new RefusedRequestToolBuilder().Create, auditSink: sink) - .Create("call-1"); + .Create("conversation-1"); var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); - Assert.DoesNotContain(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.ToolFailed); + Assert.DoesNotContain(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ToolFailed); Assert.Null(turn.Failure); Assert.Equal("That order is already closed.", turn.ReplyText); } - /// T44: one compiled agent serves every call, so nothing per call may live on it. + /// T44: one compiled agent serves every conversation, so nothing per conversation may live on it. [Fact] - public async Task TwoCallsAtOnce_DoNotPolluteEachOthersRecords() + public async Task TwoConversationsAtOnce_DoNotPolluteEachOthersRecords() { const int FanOut = 8; InMemoryAuditSink sink = new(); @@ -373,7 +373,7 @@ public async Task TwoCallsAtOnce_DoNotPolluteEachOthersRecords() await Task.WhenAll(Enumerable.Range(0, FanOut).Select(index => Task.Run( async () => { - var session = factory.Create($"call-{index}"); + var session = factory.Create($"conversation-{index}"); gate.SignalAndWait(token); await session.RunTurnAsync("where is my order", token).ConfigureAwait(false); }, @@ -381,33 +381,33 @@ await Task.WhenAll(Enumerable.Range(0, FanOut).Select(index => Task.Run( for (var index = 0; index < FanOut; index++) { - var events = sink.EventsOf($"call-{index}"); + var events = sink.EventsOf($"conversation-{index}"); - // Each call recorded exactly its own failure, under its own id, and its three events kept + // Each conversation recorded exactly its own failure, under its own id, and its three events kept // their own order. A record that had leaked between two flows would show up as a second // tool.failed here or as one of these kinds out of place. var failed = Assert.Single(events, item => item.Kind == AuditEventKind.ToolFailed); Assert.Equal("lookup_order", failed.Payload[AuditPayloadKeys.ToolName]); Assert.NotEmpty(failed.Payload[AuditPayloadKeys.ToolCallId]); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.ToolFailed, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.ToolFailed, AuditEventKind.TurnCompleted], events.Select(item => item.Kind).ToArray()); Assert.All(events, AuditEventVocabulary.Validate); } } [Fact] - public async Task ATerminalStage_ClosesTheChainWithOneCallEndedEvent() + public async Task ATerminalStage_ClosesTheChainWithOneConversationEndedEvent() { using SequencedChatClient reply = new("goodbye."); using SequencedChatClient fill = new(SaidGoodbye); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); await session.RunTurnAsync("goodbye", TestContext.Current.CancellationToken); Assert.True(session.IsComplete); - var ended = Assert.Single(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.CallEnded); + var ended = Assert.Single(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ConversationEnded); Assert.Null(ended.TurnIndex); // The reason is one token of the closed set, so a report can count it. The terminal stage is @@ -415,76 +415,76 @@ public async Task ATerminalStage_ClosesTheChainWithOneCallEndedEvent() Assert.Equal("agent.completed", ended.Payload[AuditPayloadKeys.EndReason]); Assert.Equal("close", ended.Payload[AuditPayloadKeys.StageAfter]); - // A hang-up frame that arrives after the machine already closed the call writes nothing. - Assert.False(session.EndCall(CallEndReason.CallerHungUp)); + // A hang-up frame that arrives after the machine already closed the conversation writes nothing. + Assert.False(session.EndConversation(ConversationEndReason.CallerHungUp)); } [Fact] - public void AHostThatEndsTheCall_ClosesTheChainOnce() + public void AHostThatEndsTheConversation_ClosesTheChainOnce() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); - Assert.True(session.EndCall(CallEndReason.CallerHungUp)); - Assert.False(session.EndCall(CallEndReason.CallerHungUp)); + Assert.True(session.EndConversation(ConversationEndReason.CallerHungUp)); + Assert.False(session.EndConversation(ConversationEndReason.CallerHungUp)); - var ended = Assert.Single(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.CallEnded); + var ended = Assert.Single(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ConversationEnded); Assert.Equal("caller.hangup", ended.Payload[AuditPayloadKeys.EndReason]); - // The machine never ran, so no stage closed the call and no stage rides on the event. + // The machine never ran, so no stage closed the conversation and no stage rides on the event. Assert.False(ended.Payload.ContainsKey(AuditPayloadKeys.StageAfter)); Assert.True(session.IsComplete); } - /// Section 11, item 5: the call goes to a human through the conference pattern. + /// Section 11, item 5: the conversation goes to a human through the conference pattern. [Fact] public void ATransferToAHuman_ClosesTheChainWithItsOwnReason() { using SequencedChatClient reply = new("one moment please."); using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); - // The adapter joins the call to a conference and never sends the transfer command (T27). - Assert.True(session.EndCall(CallEndReason.TransferredToHuman)); + // The adapter joins the conversation to a conference and never sends the transfer command (T27). + Assert.True(session.EndConversation(ConversationEndReason.TransferredToHuman)); - var ended = Assert.Single(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.CallEnded); + var ended = Assert.Single(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ConversationEnded); Assert.Equal("agent.transferred", ended.Payload[AuditPayloadKeys.EndReason]); } [Fact] - public void AReasonOutsideTheClosedSet_EndsNoCall() + public void AReasonOutsideTheClosedSet_EndsNoConversation() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); - Assert.Throws(() => session.EndCall((CallEndReason)99)); + Assert.Throws(() => session.EndConversation((ConversationEndReason)99)); - // Nothing moved. The call still runs, and the chain still holds only its first event. + // Nothing moved. The conversation still runs, and the chain still holds only its first event. Assert.False(session.IsComplete); - Assert.DoesNotContain(sink.EventsOf("call-1"), item => item.Kind == AuditEventKind.CallEnded); + Assert.DoesNotContain(sink.EventsOf("conversation-1"), item => item.Kind == AuditEventKind.ConversationEnded); } // ------------------------------------------------------------------------------------------- // Item 6: the chain the events form verifies. // ------------------------------------------------------------------------------------------- [Fact] - public async Task TheEventsOfOneCall_FormAChainThatVerifies() + public async Task TheEventsOfOneConversation_FormAChainThatVerifies() { using SequencedChatClient reply = new("hello there.", "goodbye."); using SequencedChatClient fill = new(StayingNull, SaidGoodbye); InMemoryAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); var token = TestContext.Current.CancellationToken; await session.RunTurnAsync("hi", token); await session.RunTurnAsync("goodbye", token); - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); // Four facts, four identities, none of them repeated. What orders them is // audit_event.sequence, which the store assigns and which this test never sees. @@ -504,7 +504,7 @@ public async Task TheTurn_FinishesWhileTheAppendIsStillOpen() using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); BlockingAuditSink sink = new(); - var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("call-1"); + var session = Build(PolicyYaml, reply, fill, auditSink: sink).Create("conversation-1"); // Section 7: a durable insert costs 13 ms at p50 and 32 ms at p99, against 91 nanoseconds to // enqueue. The turn therefore finishes with no append complete at all. @@ -512,9 +512,9 @@ public async Task TheTurn_FinishesWhileTheAppendIsStillOpen() Assert.Equal("hello there.", turn.ReplyText); - // The whole turn ran and returned while call.started is still inside the sink. The + // The whole turn ran and returned while conversation.started is still inside the sink. The // turn.completed event is queued behind it rather than racing past it, because the events of - // one call reach an observer in the order the call raised them, so exactly one has arrived. + // one conversation reach an observer in the order the conversation raised them, so exactly one has arrived. Assert.Single(sink.Events); sink.Release(); @@ -528,7 +528,7 @@ public async Task TheTurn_FinishesWhileTheAppendIsStillOpen() } Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted], sink.Events.Select(item => item.Kind).ToArray()); } @@ -539,11 +539,11 @@ public async Task ASinkThatRefusesAnEvent_IsLoggedAndTheTurnGoesOn() using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); var session = Build(PolicyYaml, reply, fill, auditSink: new ThrowingAuditSink(), logger: logger) - .Create("call-1"); + .Create("conversation-1"); var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // Audit is a record of the call and never a part of it. + // Audit is a record of the conversation and never a part of it. Assert.Equal("hello there.", turn.ReplyText); Assert.NotEmpty(logger.Of(5)); Assert.All(logger.Of(5), line => Assert.Equal(LogLevel.Error, line.Level)); @@ -554,7 +554,7 @@ public async Task ASessionWithNoSink_RunsATurnAndThrowsNothing() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); - var session = Build(PolicyYaml, reply, fill).Create("call-1"); + var session = Build(PolicyYaml, reply, fill).Create("conversation-1"); var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -565,28 +565,28 @@ public async Task ASessionWithNoSink_RunsATurnAndThrowsNothing() // The in-memory sink. // ------------------------------------------------------------------------------------------- [Fact] - public async Task TheInMemorySink_KeepsTheCallsApart() + public async Task TheInMemorySink_KeepsTheConversationsApart() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); InMemoryAuditSink sink = new(); var factory = Build(PolicyYaml, reply, fill, auditSink: sink); - var first = factory.Create("call-1"); - var second = factory.Create("call-2"); + var first = factory.Create("conversation-1"); + var second = factory.Create("conversation-2"); await first.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // One sink serves every call, because a session names itself on every event. - Assert.Equal(2, sink.EventsOf("call-1").Count); - Assert.Single(sink.EventsOf("call-2")); + // One sink serves every conversation, because a session names itself on every event. + Assert.Equal(2, sink.EventsOf("conversation-1").Count); + Assert.Single(sink.EventsOf("conversation-2")); Assert.Equal(3, sink.Events.Count); - Assert.Equal("call-2", second.CallId); + Assert.Equal("conversation-2", second.ConversationId); } // ------------------------------------------------------------------------------------------- // Helpers. // ------------------------------------------------------------------------------------------- - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IChatClient? fill, @@ -595,7 +595,7 @@ private static CallSessionFactory Build( IAuditSinkPort? auditSink = null, ILogger? logger = null) { - // There is always a sink now: CallObservers.Standard takes a required one, because the + // There is always a sink now: ConversationObservers.Standard takes a required one, because the // composition root resolves providers.audit for every host and falls back to the in-process // memory kind. An optional parameter has to be a compile-time constant, so the default is // spelled here instead — a fact that does not care where its events land gets a fresh @@ -616,12 +616,12 @@ private static CallSessionFactory Build( Tools = TestToolRegistry.From(document, tools, TestContext.Current.CancellationToken), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), + ConversationSessionFactory.CreateExtractor(compiled, chatClients), timeProvider, logger, - CallObservers.Standard(sink, logger)); + ConversationObservers.Standard(sink, logger)); } } diff --git a/tests/AgentCore.Application.Tests/Audit/CallSessionModerationTests.cs b/tests/AgentCore.Application.Tests/Audit/ConversationSessionModerationTests.cs similarity index 87% rename from tests/AgentCore.Application.Tests/Audit/CallSessionModerationTests.cs rename to tests/AgentCore.Application.Tests/Audit/ConversationSessionModerationTests.cs index 14a61644..18f14ea9 100644 --- a/tests/AgentCore.Application.Tests/Audit/CallSessionModerationTests.cs +++ b/tests/AgentCore.Application.Tests/Audit/ConversationSessionModerationTests.cs @@ -34,7 +34,7 @@ namespace AgentCore.Application.Tests.Audit; /// amends nothing. /// /// -public sealed class CallSessionModerationTests +public sealed class ConversationSessionModerationTests { private const string PlainYaml = """ @@ -76,11 +76,11 @@ public async Task AFlaggedPrompt_WritesTheFlagBeforeTheTurnEvent() { InMemoryAuditSink sink = new(); var session = Build(PlainYaml, new SequencedChatClient("never spoken"), sink: sink, - moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); var flagged = Assert.Single(events, e => e.Kind == AuditEventKind.PromptFlagged); var completed = Assert.Single(events, e => e.Kind == AuditEventKind.TurnCompleted); @@ -96,11 +96,11 @@ public async Task AFlaggedPrompt_CarriesTheCategoriesInTheOrderTheEndpointReturn { InMemoryAuditSink sink = new(); var session = Build(PlainYaml, new SequencedChatClient("never spoken"), sink: sink, - moderation: ScriptedModerationEvaluator.Flagging("violence", "harassment")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("violence", "harassment")).Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); - var flagged = Assert.Single(sink.EventsOf("call-1"), e => e.Kind == AuditEventKind.PromptFlagged); + var flagged = Assert.Single(sink.EventsOf("conversation-1"), e => e.Kind == AuditEventKind.PromptFlagged); Assert.Equal("violence,harassment", flagged.Payload[AuditPayloadKeys.ModerationCategories]); } @@ -109,7 +109,7 @@ public async Task AFlaggedPrompt_NeverReachesTheModel() { var model = new SequencedChatClient("never spoken"); var session = Build(PlainYaml, model, moderation: ScriptedModerationEvaluator.Flagging("hate")) - .Create("call-1"); + .Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -121,7 +121,7 @@ public async Task AFlaggedPrompt_NeverReachesTheModel() public async Task AFlaggedPrompt_SpeaksTheRefusalLineAndNotTheFallback() { var session = Build(PlainYaml, new SequencedChatClient("never spoken"), - moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("conversation-1"); var result = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -133,7 +133,7 @@ public async Task AFlaggedPrompt_SpeaksTheRefusalLineAndNotTheFallback() public async Task AFlaggedPrompt_IsNotAFailure() { var session = Build(PlainYaml, new SequencedChatClient("never spoken"), - moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("conversation-1"); var result = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -146,11 +146,11 @@ public async Task AFlaggedPrompt_RecordsTheRefusalAsTheTextTheCallerHeard() { InMemoryAuditSink sink = new(); var session = Build(PlainYaml, new SequencedChatClient("never spoken"), sink: sink, - moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); - var completed = Assert.Single(sink.EventsOf("call-1"), e => e.Kind == AuditEventKind.TurnCompleted); + var completed = Assert.Single(sink.EventsOf("conversation-1"), e => e.Kind == AuditEventKind.TurnCompleted); Assert.Equal( AuditHash.OfText("I am sorry. I cannot help with that request.").Value, completed.Payload[AuditPayloadKeys.ReplyTextSha256]); @@ -163,7 +163,7 @@ public async Task AFlaggedPrompt_RunsNoExtractor() // carry the flagged content into the state document and into every later prompt. var fill = new SequencedChatClient("""{ "callerSaidGoodbye": true }"""); var session = Build(ExtractingYaml, new SequencedChatClient("never spoken"), fill: fill, - moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("hate")).Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -175,7 +175,7 @@ public async Task AFlaggedPrompt_IsLoggedOnceAndNeverCarriesTheWordsThatWereFlag { RecordingLogger logger = new(); var session = Build(PlainYaml, new SequencedChatClient("never spoken"), logger: logger, - moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("conversation-1"); await session.RunTurnAsync("the words that were flagged", TestContext.Current.CancellationToken); @@ -189,17 +189,17 @@ public async Task AFlaggedPrompt_IsLoggedOnceAndNeverCarriesTheWordsThatWereFlag } [Fact] - public async Task TheEventsOfAModeratedCall_FormAChainThatVerifies() + public async Task TheEventsOfAModeratedConversation_FormAChainThatVerifies() { InMemoryAuditSink sink = new(); var session = Build(PlainYaml, new SequencedChatClient("never spoken"), sink: sink, - moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.PromptFlagged, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.PromptFlagged, AuditEventKind.TurnCompleted], events.Select(e => e.Kind).ToArray()); Assert.All(events, AuditEventVocabulary.Validate); } @@ -213,7 +213,7 @@ public async Task ACleanPrompt_ReachesTheModelAndWritesNoFlag() InMemoryAuditSink sink = new(); var model = new SequencedChatClient("the ordinary reply"); var session = Build(PlainYaml, model, sink: sink, moderation: ScriptedModerationEvaluator.Clean()) - .Create("call-1"); + .Create("conversation-1"); var result = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); @@ -221,14 +221,14 @@ public async Task ACleanPrompt_ReachesTheModelAndWritesNoFlag() Assert.Equal("the ordinary reply", result.ReplyText); // The vocabulary holds no reply.cleared. A turn.completed that no flag precedes is the record. - Assert.DoesNotContain(sink.EventsOf("call-1"), e => e.Kind == AuditEventKind.PromptFlagged); + Assert.DoesNotContain(sink.EventsOf("conversation-1"), e => e.Kind == AuditEventKind.PromptFlagged); } [Fact] public async Task TheModeratedText_IsWhatTheCallerSaid() { var endpoint = ScriptedModerationEvaluator.Clean(); - var session = Build(PlainYaml, new SequencedChatClient("hello"), moderation: endpoint).Create("call-1"); + var session = Build(PlainYaml, new SequencedChatClient("hello"), moderation: endpoint).Create("conversation-1"); await session.RunTurnAsync("how do I reset the console", TestContext.Current.CancellationToken); @@ -242,13 +242,13 @@ public async Task AnEndpointThatDidNotAnswer_LetsTheTurnThrough() InMemoryAuditSink sink = new(); var model = new SequencedChatClient("the ordinary reply"); var session = Build(PlainYaml, model, sink: sink, moderation: ScriptedModerationEvaluator.Unanswered()) - .Create("call-1"); + .Create("conversation-1"); var result = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); Assert.Equal(1, model.Calls); Assert.Equal("the ordinary reply", result.ReplyText); - Assert.DoesNotContain(sink.EventsOf("call-1"), e => e.Kind == AuditEventKind.PromptFlagged); + Assert.DoesNotContain(sink.EventsOf("conversation-1"), e => e.Kind == AuditEventKind.PromptFlagged); } [Fact] @@ -258,7 +258,7 @@ public async Task AnEndpointThatThrows_LetsTheTurnThroughAndLogsOnce() var model = new SequencedChatClient("the ordinary reply"); var session = Build(PlainYaml, model, logger: logger, moderation: ScriptedModerationEvaluator.Throwing(new InvalidOperationException("boom"))) - .Create("call-1"); + .Create("conversation-1"); var result = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -275,13 +275,13 @@ public async Task AnEndpointThatFails_WritesNoFlagAndNeverTheWordUnknown() InMemoryAuditSink sink = new(); var session = Build(PlainYaml, new SequencedChatClient("the ordinary reply"), sink: sink, moderation: ScriptedModerationEvaluator.Throwing(new InvalidOperationException("boom"))) - .Create("call-1"); + .Create("conversation-1"); await session.RunTurnAsync("...", TestContext.Current.CancellationToken); // A missing fact is an absent event, never an event carrying "unknown". The chain rule would // refuse a prompt.flagged with no category anyway. - Assert.DoesNotContain(sink.EventsOf("call-1"), e => e.Kind == AuditEventKind.PromptFlagged); + Assert.DoesNotContain(sink.EventsOf("conversation-1"), e => e.Kind == AuditEventKind.PromptFlagged); } [Fact] @@ -289,12 +289,12 @@ public async Task ASessionWithNoModerator_RunsATurnAndWritesNoFlag() { InMemoryAuditSink sink = new(); var model = new SequencedChatClient("the ordinary reply"); - var session = Build(PlainYaml, model, sink: sink).Create("call-1"); + var session = Build(PlainYaml, model, sink: sink).Create("conversation-1"); var result = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); Assert.Equal("the ordinary reply", result.ReplyText); - Assert.Equal(2, sink.EventsOf("call-1").Count); + Assert.Equal(2, sink.EventsOf("conversation-1").Count); } // ------------------------------------------------------------------------------------------- @@ -306,7 +306,7 @@ public async Task AFlaggedPrompt_StreamsTheRefusalAndOpensNoModelStream() InMemoryAuditSink sink = new(); var model = new SequencedChatClient("never spoken"); var session = Build(PlainYaml, model, sink: sink, - moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("harassment")).Create("conversation-1"); List spoken = []; await foreach (var update in session.RunTurnStreamingAsync("...", TestContext.Current.CancellationToken)) @@ -316,14 +316,14 @@ public async Task AFlaggedPrompt_StreamsTheRefusalAndOpensNoModelStream() Assert.Equal(["I am sorry. I cannot help with that request."], spoken); Assert.Equal(0, model.Calls); - Assert.Contains(sink.EventsOf("call-1"), e => e.Kind == AuditEventKind.PromptFlagged); + Assert.Contains(sink.EventsOf("conversation-1"), e => e.Kind == AuditEventKind.PromptFlagged); } [Fact] public async Task ACleanPromptOnTheStreamingPath_ReachesTheModel() { var model = new SequencedChatClient("the ordinary reply"); - var session = Build(PlainYaml, model, moderation: ScriptedModerationEvaluator.Clean()).Create("call-1"); + var session = Build(PlainYaml, model, moderation: ScriptedModerationEvaluator.Clean()).Create("conversation-1"); await foreach (var _ in session.RunTurnStreamingAsync("hello", TestContext.Current.CancellationToken)) { @@ -336,7 +336,7 @@ public async Task ACleanPromptOnTheStreamingPath_ReachesTheModel() // ------------------------------------------------------------------------------------------- // Helpers. // ------------------------------------------------------------------------------------------- - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IChatClient? fill = null, @@ -344,7 +344,7 @@ private static CallSessionFactory Build( ILogger? logger = null, ScriptedModerationEvaluator? moderation = null) { - // There is always a sink now: CallObservers.Standard takes a required one, because the + // There is always a sink now: ConversationObservers.Standard takes a required one, because the // composition root resolves providers.audit for every host and falls back to the in-process // memory kind. An optional parameter has to be a compile-time constant, so the default is // spelled here instead — a fact that does not care where its events land gets a fresh @@ -367,12 +367,12 @@ private static CallSessionFactory Build( Moderation = moderation is null ? null : new PromptModerator(moderation), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), + ConversationSessionFactory.CreateExtractor(compiled, chatClients), timeProvider: null, logger, - CallObservers.Standard(auditSink, logger)); + ConversationObservers.Standard(auditSink, logger)); } } diff --git a/tests/AgentCore.Application.Tests/Audit/QueuedAuditSinkTests.cs b/tests/AgentCore.Application.Tests/Audit/QueuedAuditSinkTests.cs index 9264f1ab..9508de83 100644 --- a/tests/AgentCore.Application.Tests/Audit/QueuedAuditSinkTests.cs +++ b/tests/AgentCore.Application.Tests/Audit/QueuedAuditSinkTests.cs @@ -19,7 +19,7 @@ namespace AgentCore.Application.Tests.Audit; /// public sealed class QueuedAuditSinkTests { - private const string CallId = "call-1"; + private const string ConversationId = "conversation-1"; /// The id Log.AuditQueueFull carries. private const int AuditQueueFullEventId = 8; @@ -59,7 +59,7 @@ public async Task EveryEvent_ReachesTheInnerSink_InTheOrderItWasAppended() await sink.FlushAsync(TestContext.Current.CancellationToken); - // One reader drains the channel, so the chain of D23 reaches the store in the order the call + // One reader drains the channel, so the chain of D23 reaches the store in the order the conversation // produced it. That ordering is now a property of this class and not of each adapter. Assert.Equal(ids, inner.Events.Select(item => item.EventId).ToArray()); } @@ -126,7 +126,7 @@ public async Task AnInnerSinkThatRefuses_IsReportedAndTheQueueKeepsRunning() await sink.AppendAsync(Event(1), TestContext.Current.CancellationToken); await sink.DisposeAsync(); - // Audit is a record of the call and never a part of it. The store refused, the line says so, + // Audit is a record of the conversation and never a part of it. The store refused, the line says so, // and nothing was thrown at anyone. LogLine line = Assert.Single(logger.Of(AuditAppendFailedEventId)); Assert.Equal(ThrowingAuditSink.Message, line.Exception?.Message); @@ -167,7 +167,7 @@ public async Task AnAppendAfterDisposal_IsDroppedAndNeverThrows() private static AuditEvent Event(long sequence, Guid? eventId = null) => new() { - CallId = CallId, + ConversationId = ConversationId, EventId = eventId ?? Guid.CreateVersion7(), Kind = AuditEventKind.TurnCompleted, OccurredAt = DateTimeOffset.UnixEpoch.AddSeconds(sequence), diff --git a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs index 49659c2d..48d95719 100644 --- a/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Blobs/BlobStoreFactoryTests.cs @@ -10,7 +10,7 @@ namespace AgentCore.Application.Tests.Blobs; /// The blob vendor seam: providers.blobs, and what a document that names none gets. /// /// -/// Unlike the call store, there is no built-in kind. A document that names none gets +/// Unlike the conversation store, there is no built-in kind. A document that names none gets /// , and that null is what switches the capture provider off. /// public sealed class BlobStoreFactoryTests diff --git a/tests/AgentCore.Application.Tests/Calls/CallCursorTests.cs b/tests/AgentCore.Application.Tests/Calls/CallCursorTests.cs deleted file mode 100644 index 3e99ff12..00000000 --- a/tests/AgentCore.Application.Tests/Calls/CallCursorTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -using AgentCore.Application.Calls; -using Xunit; - -namespace AgentCore.Application.Tests.Calls; - -/// The opaque cursor a listing hands back and takes again. -public sealed class CallCursorTests -{ - [Fact] - public void Encode_ThenDecode_ReturnsBothValues() - { - // Arrange - DateTimeOffset sortAt = new(2026, 8, 30, 12, 34, 56, 789, TimeSpan.Zero); - - // Act - var cursor = CallCursor.Encode(sortAt, "call-1"); - var decoded = CallCursor.TryDecode(cursor, out var readAt, out var readId); - - // Assert - Assert.True(decoded); - Assert.Equal(sortAt, readAt); - Assert.Equal("call-1", readId); - } - - [Fact] - public void Encode_ACallIdHoldingTheSeparator_RoundTripsWhole() - { - // Arrange - const string CallId = "call|with|pipes"; - - // Act - var cursor = CallCursor.Encode(DateTimeOffset.UnixEpoch, CallId); - CallCursor.TryDecode(cursor, out _, out var readId); - - // Assert - Assert.Equal(CallId, readId); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("not-base64!")] - [InlineData("bm90LWEtY3Vyc29y")] - public void TryDecode_SomethingThatIsNotACursor_IsFalseAndNotAThrow(string? cursor) - { - // Act - var decoded = CallCursor.TryDecode(cursor, out _, out _); - - // Assert - Assert.False(decoded); - } -} diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs index 8f5ef78a..d597aaee 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs @@ -297,7 +297,7 @@ public void Rule16_ADelegatingDocument_CompilesOnceThroughTheRegistry() } [Fact] - public async Task Rule16_TwentySixSimultaneousCalls_ShareOneDelegatingAgent() + public async Task Rule16_TwentySixSimultaneousConversations_ShareOneDelegatingAgent() { const int fanOut = 26; @@ -315,7 +315,7 @@ public async Task Rule16_TwentySixSimultaneousCalls_ShareOneDelegatingAgent() var compiled = registry.GetOrCompile(document, "main", context); gate.SignalAndWait(token); - var reply = await compiled.Agent.RunAsync($"call {index}", cancellationToken: token) + var reply = await compiled.Agent.RunAsync($"conversation {index}", cancellationToken: token) .ConfigureAwait(false); return (compiled, reply.Text); }, diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs index 52a318b5..6c7828ab 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs @@ -36,7 +36,7 @@ public sealed class ClarificationWiringBindingTests value: everyone enum: [everyone] providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -68,7 +68,7 @@ public async Task TheDocumentsAmbiguityWiring_ReachesTheAgentsOwnBoundSearch() var port = new ScopedFakePort(); var turn = new TurnInvocation { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Knowledge = Scope(model: "*", audience: "everyone"), @@ -89,7 +89,7 @@ public async Task TheSlotsOwnDescription_ReachesTheNoteTheProbeWrites() var port = new ScopedFakePort(); var turn = new TurnInvocation { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Knowledge = Scope(model: "*", audience: "everyone"), diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs index 8ab739a7..04e7cea2 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs @@ -111,7 +111,7 @@ public async Task Compile_CompactionBlock_TrimsWhatTheModelSeesAcrossTurns() // AgentCoreChatHistoryProvider (this agent's ChatHistoryProvider, because SingleAgentRow sets // SessionCarriesHistory) reads store 1, which nothing here writes to, so it always hands back an // empty history and never grows the request on its own. The conversation this test measures is - // instead built by hand and re-sent whole on every turn — exactly the shape a resumed call + // instead built by hand and re-sent whole on every turn — exactly the shape a resumed conversation // replays, which is the case CompactionProvider's incremental path exists for. List conversation = []; var sizeBeforeTheLastCompaction = 0; diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs index 74c96e01..0b5efd2c 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs @@ -6,15 +6,15 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// -/// Rule 16 of section 11, and T44. A fan-out of 26 simultaneous calls against one compiled agent is -/// clean, and no code path compiles an agent for each call. +/// Rule 16 of section 11, and T44. A fan-out of 26 simultaneous conversations against one compiled agent is +/// clean, and no code path compiles an agent for each conversation. /// public sealed class CompiledAgentConcurrencyTests { private const int FanOut = 26; [Fact] - public async Task Rule16_TwentySixSimultaneousCalls_ShareOneCompiledAgent() + public async Task Rule16_TwentySixSimultaneousConversations_ShareOneCompiledAgent() { using ScriptedChatClient client = new("Hello", " from", " one", " agent."); var document = ConfigurationLoader.LoadYaml(CompileTableTests.OneAgentYaml); @@ -27,13 +27,13 @@ public async Task Rule16_TwentySixSimultaneousCalls_ShareOneCompiledAgent() var runs = Enumerable.Range(0, FanOut).Select(index => Task.Run( async () => { - // Every call asks the registry for the agent, exactly as the turn loop does. + // Every conversation asks the registry for the agent, exactly as the turn loop does. var compiled = registry.GetOrCompile(document, "main", context); // Nothing starts until all 26 are ready, so the fan-out is really simultaneous. gate.SignalAndWait(token); - var reply = await compiled.Agent.RunAsync($"call {index}", cancellationToken: token) + var reply = await compiled.Agent.RunAsync($"conversation {index}", cancellationToken: token) .ConfigureAwait(false); return (compiled, reply.Text); }, @@ -41,7 +41,7 @@ public async Task Rule16_TwentySixSimultaneousCalls_ShareOneCompiledAgent() var results = await Task.WhenAll(runs); - // No code path compiles an agent for each call. The compiled agent is a process singleton. + // No code path compiles an agent for each conversation. The compiled agent is a process singleton. Assert.Equal(1, registry.CompileCount); Assert.All(results, result => Assert.Same(results[0].compiled, result.compiled)); Assert.All(results, result => Assert.Equal(client.FullText, result.Text)); @@ -49,7 +49,7 @@ public async Task Rule16_TwentySixSimultaneousCalls_ShareOneCompiledAgent() } [Fact] - public async Task Rule16_TwentySixSimultaneousCalls_AreCleanAgainstOneGraphWrapper() + public async Task Rule16_TwentySixSimultaneousConversations_AreCleanAgainstOneGraphWrapper() { using ScriptedChatClient client = new("Hello", " from", " the", " graph."); var document = ConfigurationLoader.LoadYaml(CompileTableTests.ExplicitGraphYaml); @@ -64,7 +64,7 @@ public async Task Rule16_TwentySixSimultaneousCalls_AreCleanAgainstOneGraphWrapp async () => { gate.SignalAndWait(token); - var reply = await compiled.Agent.RunAsync($"call {index}", cancellationToken: token) + var reply = await compiled.Agent.RunAsync($"conversation {index}", cancellationToken: token) .ConfigureAwait(false); return reply.Text; }, @@ -72,7 +72,7 @@ public async Task Rule16_TwentySixSimultaneousCalls_AreCleanAgainstOneGraphWrapp var texts = await Task.WhenAll(runs); - // T44: nothing serializes inside the AsAIAgent() wrapper, so one wrapper serves every call. + // T44: nothing serializes inside the AsAIAgent() wrapper, so one wrapper serves every conversation. Assert.Equal(1, registry.CompileCount); Assert.All(texts, text => Assert.Contains("graph.", text, StringComparison.Ordinal)); } diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs index 64b7ceed..8836a01f 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs @@ -12,7 +12,7 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// AsAIAgent() and yields its first non-empty delta before the model finishes. /// /// -/// Every test here uses an offline . There is no network call and no +/// Every test here uses an offline . There is no network conversation and no /// API key anywhere in this file. /// public sealed class CompiledAgentRunTests diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs index ab9568de..2e2b7ef9 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs @@ -36,7 +36,7 @@ public sealed class ConfigurationCompilerModelFacingTests public async Task TheSecondRoundOfACompiledAgent_NeverForwardsARenderContentTheFirstRoundsToolAttached() { TurnRenders renders = new(); - var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Renders = renders }; + var turn = new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", Renders = renders }; RequestCapturingChatClient recorder = new(new ToolCallingChatClient("done.")); var document = ConfigurationLoader.LoadYaml(Yaml); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs index 84bb6867..f29c4b56 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs @@ -16,7 +16,7 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The files: block reaching a compiled agent as a , the -/// file_access_* tools it puts in front of the model, and the call folder it scopes to. +/// file_access_* tools it puts in front of the model, and the conversation folder it scopes to. /// #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. public sealed class FilesCompilationTests : IDisposable @@ -90,10 +90,10 @@ public async Task Compile_FilesWorkspaceWithARoot_GetsAFileAccessProviderAndTheE { using SequencedChatClient reply = new("hello there."); var agent = CompileOne(FilesYaml, reply, _root); - Assert.Contains(Providers(agent), provider => provider is CallFilesProvider); + Assert.Contains(Providers(agent), provider => provider is ConversationFilesProvider); var factory = BuildFactory(FilesYaml, _root, reply); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); var tools = reply.Options[^1]?.Tools?.OfType().ToArray() ?? []; @@ -108,11 +108,11 @@ public async Task Compile_FilesWorkspaceWithARoot_TheModelsInstructionsAreTruthf { using SequencedChatClient reply = new("hello there."); var factory = BuildFactory(FilesYaml, _root, reply); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); var instructions = reply.Options[^1]?.Instructions ?? string.Empty; - Assert.Contains("deleted when the call ends", instructions, StringComparison.Ordinal); + Assert.Contains("deleted when the conversation ends", instructions, StringComparison.Ordinal); Assert.DoesNotContain("persist beyond", instructions, StringComparison.Ordinal); } @@ -121,7 +121,7 @@ public async Task Compile_FilesWorkspaceWriteFalse_GetsOnlyTheFourReadOnlyTools( { using SequencedChatClient reply = new("hello there."); var factory = BuildFactory(ReadOnlyFilesYaml, _root, reply); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; @@ -158,7 +158,7 @@ public void Compile_FilesWorkspaceWithNoRoot_FailsNamingTheFilesPointer() } [Fact] - public async Task EndToEnd_WriteReadLsGrep_ThenEndCallDeletesTheFolder() + public async Task EndToEnd_WriteReadLsGrep_ThenEndConversationDeletesTheFolder() { var client = new SequencedToolCallClient( (FileAccessProvider.WriteToolName, Args(("fileName", "out.txt"), ("content", "hello"))), @@ -167,35 +167,35 @@ public async Task EndToEnd_WriteReadLsGrep_ThenEndCallDeletesTheFolder() (FileAccessProvider.GrepToolName, Args(("regexPattern", "hell")))); var factory = BuildFactory(FilesYaml, _root, client); - var session = factory.Create("call-1"); - var callFolder = session.Workspace!; + var session = factory.Create("conversation-1"); + var conversationFolder = session.Workspace!; await session.RunTurnAsync("write hello to out.txt", TestContext.Current.CancellationToken); Assert.Equal("hello", await File.ReadAllTextAsync( - Path.Combine(callFolder, "out.txt"), TestContext.Current.CancellationToken)); + Path.Combine(conversationFolder, "out.txt"), TestContext.Current.CancellationToken)); await session.RunTurnAsync("read out.txt", TestContext.Current.CancellationToken); Assert.Contains("hello", client.ToolResults[1]); await session.RunTurnAsync("list the folder", TestContext.Current.CancellationToken); Assert.Contains("out.txt", client.ToolResults[2]); - Assert.DoesNotContain("call-1", client.ToolResults[2], StringComparison.Ordinal); + Assert.DoesNotContain("conversation-1", client.ToolResults[2], StringComparison.Ordinal); await session.RunTurnAsync("grep for hell", TestContext.Current.CancellationToken); Assert.Contains("out.txt", client.ToolResults[3]); - session.EndCall(CallEndReason.CallerHungUp); - Assert.False(Directory.Exists(callFolder)); + session.EndConversation(ConversationEndReason.CallerHungUp); + Assert.False(Directory.Exists(conversationFolder)); } [Fact] - public async Task Escape_WriteOutsideTheCallFolder_CreatesNothingOutsideItAndDoesNotThrow() + public async Task Escape_WriteOutsideTheConversationFolder_CreatesNothingOutsideItAndDoesNotThrow() { var client = new SequencedToolCallClient( (FileAccessProvider.WriteToolName, Args(("fileName", "../escape.txt"), ("content", "leaked")))); var factory = BuildFactory(FilesYaml, _root, client); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); // The point of the assertion is that this completes at all: an escape attempt must not // throw out of RunTurnAsync. @@ -214,7 +214,7 @@ public async Task Escape_WriteOutsideTheCallFolder_CreatesNothingOutsideItAndDoe } [Fact] - public async Task TwoSessions_DifferentCallIds_SeeOnlyTheirOwnFile() + public async Task TwoSessions_DifferentConversationIds_SeeOnlyTheirOwnFile() { var clientA = new SequencedToolCallClient( (FileAccessProvider.WriteToolName, Args(("fileName", "out.txt"), ("content", "A")))); @@ -222,11 +222,11 @@ public async Task TwoSessions_DifferentCallIds_SeeOnlyTheirOwnFile() (FileAccessProvider.WriteToolName, Args(("fileName", "out.txt"), ("content", "B")))); var factoryA = BuildFactory(FilesYaml, _root, clientA); - var sessionA = factoryA.Create("call-a"); + var sessionA = factoryA.Create("conversation-a"); await sessionA.RunTurnAsync("write A", TestContext.Current.CancellationToken); var factoryB = BuildFactory(FilesYaml, _root, clientB); - var sessionB = factoryB.Create("call-b"); + var sessionB = factoryB.Create("conversation-b"); await sessionB.RunTurnAsync("write B", TestContext.Current.CancellationToken); var pathA = Path.Combine(sessionA.Workspace!, "out.txt"); @@ -254,7 +254,7 @@ private static void AssertSameNames(string[] expected, string[] actual) return args; } - private static CallSessionFactory BuildFactory(string yaml, string root, IChatClient? client = null) + private static ConversationSessionFactory BuildFactory(string yaml, string root, IChatClient? client = null) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new RoutingChatClientFactory(client ?? new SequencedChatClient("done")); @@ -263,7 +263,7 @@ private static CallSessionFactory BuildFactory(string yaml, string root, IChatCl document, new AgentCompilationContext(chatClients) { WorkspaceRoot = root })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: root); @@ -329,7 +329,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, - [new FunctionCallContent("call_" + Guid.NewGuid().ToString("N"), name, args)]) + [new FunctionCallContent("conversation_" + Guid.NewGuid().ToString("N"), name, args)]) { ResponseId = responseId, MessageId = responseId, diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs index 5577e89c..82a76883 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs @@ -24,7 +24,7 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// section 8.2 refuses to ship. /// /// -/// Every test here runs offline. There is no network call and no API key in this file. +/// Every test here runs offline. There is no network conversation and no API key in this file. /// /// public sealed class GraphNoMatchTests @@ -56,7 +56,7 @@ public sealed class GraphNoMatchTests edges: - { from: route, to: escalated, when: wants_human } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -130,7 +130,7 @@ public async Task Row4_AGraphWhereAnEdgeGuardIsTrue_StillStreams() } [Fact] - public async Task Row4_ANoMatchInsideACall_SpeaksTheFallbackAndTheCallLives() + public async Task Row4_ANoMatchInsideAConversation_SpeaksTheFallbackAndTheConversationLives() { using Harness harness = new(); var session = harness.NewSession(); @@ -138,16 +138,16 @@ public async Task Row4_ANoMatchInsideACall_SpeaksTheFallbackAndTheCallLives() var turn = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); - // Section 8.7, sixth row. The run throws, the turn speaks the fallback, and the call lives. - // A live call therefore does not change: only a host that runs the compiled agent itself + // Section 8.7, sixth row. The run throws, the turn speaks the fallback, and the conversation lives. + // A live conversation therefore does not change: only a host that runs the compiled agent itself // reads the exception. - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); Assert.NotNull(turn.Failure); Assert.False(session.IsComplete); } [Fact] - public async Task Row4_ANoMatchInsideAStreamingCall_SpeaksTheFallbackAndTheCallLives() + public async Task Row4_ANoMatchInsideAStreamingConversation_SpeaksTheFallbackAndTheConversationLives() { using Harness harness = new(); var session = harness.NewSession(); @@ -160,7 +160,7 @@ public async Task Row4_ANoMatchInsideAStreamingCall_SpeaksTheFallbackAndTheCallL } Assert.NotNull(session.LastTurn); - Assert.Equal(CallSession.FallbackReply, session.LastTurn!.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, session.LastTurn!.ReplyText); Assert.NotNull(session.LastTurn.Failure); Assert.False(session.IsComplete); } @@ -176,7 +176,7 @@ private sealed class Harness : IDisposable private readonly ScriptedChatClient _router = new(string.Empty); private readonly ScriptedChatClient _human = new(EscalatedReply); private readonly AgentCoreConfiguration _document; - private readonly CallSessionFactory _sessions; + private readonly ConversationSessionFactory _sessions; /// Compiles the no-match graph once, over two offline models. public Harness() @@ -195,13 +195,13 @@ public Harness() Guards = guards, })["main"]; - _sessions = new CallSessionFactory(Compiled, guards); + _sessions = new ConversationSessionFactory(Compiled, guards); } - /// Gets the one compiled agent every call shares. + /// Gets the one compiled agent every conversation shares. public CompiledAgent Compiled { get; } - /// Builds the state of one call, with the slot the guard reads set. + /// Builds the state of one conversation, with the slot the guard reads set. /// What the guard wants_human reads. /// The state document. public StateDocument NewState(bool escalate) @@ -211,14 +211,14 @@ public StateDocument NewState(bool escalate) return state; } - /// Files one call's state on a bare run's options, the way the turn loop files it. + /// Files one conversation's state on a bare run's options, the way the turn loop files it. /// What the guard wants_human reads. /// Run options carrying the turn the graph-state wrapper reads. public ChatClientAgentRunOptions StateOptions(bool escalate) { TurnInvocation invocation = new() { - CallId = "test-call", + ConversationId = "test-conversation", TurnIndex = 0, Stage = string.Empty, State = NewState(escalate), @@ -233,9 +233,9 @@ public ChatClientAgentRunOptions StateOptions(bool escalate) }); } - /// Builds the session of one more call. + /// Builds the session of one more conversation. /// The session. - public CallSession NewSession() => _sessions.Create(); + public ConversationSession NewSession() => _sessions.Create(); public void Dispose() { diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs index c0cf08be..51615ed8 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs @@ -16,28 +16,28 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// /// Two rules pull apart here. T44 makes the compiled agent a process singleton, so one graph serves -/// every call and no code path compiles one for each call. A guarded edge reads the state of one -/// call, and each call owns its own state document. The graph-state wrapper files the turn's +/// every conversation and no code path compiles one for each conversation. A guarded edge reads the state of one +/// conversation, and each conversation owns its own state document. The graph-state wrapper files the turn's /// snapshot on the run and a gate executor reads it back, so the compiled graph captures nothing -/// per call and concurrent calls never share it. +/// per conversation and concurrent conversations never share it. /// /// -/// Every test here runs offline. There is no network call and no API key in this file. +/// Every test here runs offline. There is no network conversation and no API key in this file. /// /// public sealed class GuardedGraphEdgeTests { private const int FanOut = 26; - /// The text of the node a call reaches when the guard wants_human holds. + /// The text of the node a conversation reaches when the guard wants_human holds. private const string EscalatedReply = "ESCALATED"; - /// The text of the node a call reaches when the guard stays_with_bot holds. + /// The text of the node a conversation reaches when the guard stays_with_bot holds. private const string HandledReply = "HANDLED"; /// /// One start node and two guarded exits. Check 5 of section 8.5 proves the two guards exclusive - /// over the state domain, so exactly one edge fires for each call. + /// over the state domain, so exactly one edge fires for each conversation. /// internal const string GuardedGraphYaml = """ @@ -63,7 +63,7 @@ public sealed class GuardedGraphEdgeTests - { from: route, to: escalated, when: wants_human } - { from: route, to: handled, when: stays_with_bot } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -132,13 +132,13 @@ public async Task AGuardedEdge_TakesTheEdgeTheStateNamesWhileStreaming() } [Fact] - public async Task Rule16_TwentySixSimultaneousCalls_EachTakeTheirOwnEdgeThroughOneCompiledGraph() + public async Task Rule16_TwentySixSimultaneousConversations_EachTakeTheirOwnEdgeThroughOneCompiledGraph() { using Harness harness = new(); var token = TestContext.Current.CancellationToken; using Barrier gate = new(FanOut); - var calls = Enumerable.Range(0, FanOut).Select(index => Task.Run( + var conversations = Enumerable.Range(0, FanOut).Select(index => Task.Run( async () => { var escalate = index % 2 == 0; @@ -148,17 +148,17 @@ public async Task Rule16_TwentySixSimultaneousCalls_EachTakeTheirOwnEdgeThroughO // Nothing starts until all 26 are ready, so the fan-out is really simultaneous. gate.SignalAndWait(token); - var turn = await session.RunTurnAsync($"call {index}", token).ConfigureAwait(false); + var turn = await session.RunTurnAsync($"conversation {index}", token).ConfigureAwait(false); return (Escalate: escalate, turn.ReplyText); }, token)); - var results = await Task.WhenAll(calls); + var results = await Task.WhenAll(conversations); - // Rule 16: one compiled agent, and no code path compiles one for each call. + // Rule 16: one compiled agent, and no code path compiles one for each conversation. Assert.Equal(1, harness.CompileCount); - // No call read the state of another one. Thirteen went each way, and none went both. + // No conversation read the state of another one. Thirteen went each way, and none went both. Assert.All(results, result => Assert.Contains( result.Escalate ? EscalatedReply : HandledReply, result.ReplyText, StringComparison.Ordinal)); Assert.All(results, result => Assert.DoesNotContain( @@ -263,7 +263,7 @@ private static string Flatten(Exception exception) /// One compiled graph, wired the way the composition root wires it. /// /// - /// The seam is the one AddAgentCore bind: the shared guard evaluator. Nothing per call + /// The seam is the one AddAgentCore bind: the shared guard evaluator. Nothing per conversation /// is captured: the turn's snapshot rides each run. /// private sealed class Harness : IDisposable @@ -272,7 +272,7 @@ private sealed class Harness : IDisposable private readonly ScriptedChatClient _human; private readonly ScriptedChatClient _bot = new(HandledReply); private readonly CompiledAgentRegistry _registry = new(); - private readonly CallSessionFactory _sessions; + private readonly ConversationSessionFactory _sessions; /// Compiles the guarded graph once, over three offline models. /// @@ -299,18 +299,18 @@ public Harness(bool holdEscalatedReply = false) Guards = guards, }); - _sessions = new CallSessionFactory(Compiled, guards); + _sessions = new ConversationSessionFactory(Compiled, guards); } - /// Gets the one compiled agent every call shares. + /// Gets the one compiled agent every conversation shares. public CompiledAgent Compiled { get; } /// Gets how many times the registry ran the compile table. public int CompileCount => _registry.CompileCount; - /// Builds the session of one more call. + /// Builds the session of one more conversation. /// The session. - public CallSession NewSession() => _sessions.Create(); + public ConversationSession NewSession() => _sessions.Create(); /// Lets the rest of the escalated reply flow. public void ReleaseEscalatedReply() => _human.OpenGate(); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs index 0142c44f..dfc5b2f1 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs @@ -265,8 +265,8 @@ public void Compile_ShellBlock_GetsAToolProviderAndAnEnvironmentProvider() var providers = Providers(Assert.Single(compiled.Agents.Values)); - Assert.Contains(providers, provider => provider is CallShellProvider); - Assert.Contains(providers, provider => provider is CallShellEnvironmentProvider); + Assert.Contains(providers, provider => provider is ConversationShellProvider); + Assert.Contains(providers, provider => provider is ConversationShellEnvironmentProvider); } finally { diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs index 662104ab..b0b5567e 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs @@ -49,7 +49,7 @@ public sealed class KnowledgeProviderBindingTests """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs index 7c48a4ed..17cbdf66 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs @@ -19,7 +19,7 @@ public sealed class KnowledgeProviderSchemaTests """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -36,7 +36,7 @@ public sealed class KnowledgeProviderSchemaTests """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -74,7 +74,7 @@ public sealed class KnowledgeProviderSchemaTests """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -152,7 +152,7 @@ public void ScopeTemplate_WithoutKeyPlaceholder_IsRejectedBySchemaValidation() """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs index c238fb07..30e04917 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs @@ -100,7 +100,7 @@ public async Task Compile_LoopWithMaxRoundsThreeAndOpenTodos_RunsThreeIterations // messages plus the evaluator's feedback while only the provider session state carries // over, so the open todo list keeps every iteration going. Three iterations at the // maxRounds: 3 cap, then the loop stops rather than running on. Without the wrap the - // single run would spend two model calls and call todos_add once. + // single run would spend two model calls and conversation todos_add once. Assert.Equal(3, client.Called.Count(name => name == "todos_add")); Assert.Equal(6, client.Calls); Assert.Contains("added", response.Text, StringComparison.Ordinal); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs index 9dd09c78..386f72c1 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs @@ -16,7 +16,7 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The memory: block reaching a compiled agent as a , the /// seven file_memory_* tools it puts in front of the model, and the working folder it binds -/// to the running call. +/// to the running conversation. /// public sealed class MemoryCompilationTests : IDisposable { @@ -104,12 +104,12 @@ public async Task Compile_MemoryWorkspaceWithARoot_GetsAFileMemoryProviderAndThe var agent = Assert.Single(compiled.Agents.Values); Assert.Contains(Providers(agent), provider => provider is FileMemoryProvider); - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); - // A turn must be open for the FileMemoryProvider's state initializer to read the call id off - // the session, so the tool list is read through a real call rather than agent.RunAsync + // A turn must be open for the FileMemoryProvider's state initializer to read the conversation id off + // the session, so the tool list is read through a real conversation rather than agent.RunAsync // directly, unlike the todos/mode providers in HarnessCompilationTests. await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -127,14 +127,14 @@ public async Task Compile_MemoryWorkspaceWithARoot_TheModelsInstructionsAreTruth var compiled = ConfigurationCompiler.CompileAll( document, new AgentCompilationContext(chatClients) { WorkspaceRoot = _root })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); var instructions = reply.Options[^1]?.Instructions ?? string.Empty; - Assert.Contains("deleted when the call ends", instructions, StringComparison.Ordinal); + Assert.Contains("deleted when the conversation ends", instructions, StringComparison.Ordinal); Assert.DoesNotContain("persist beyond", instructions, StringComparison.Ordinal); } @@ -169,32 +169,32 @@ public void Compile_MemoryWorkspaceWithNoRoot_FailsNamingTheMemoryPointer() } [Fact] - public async Task EndToEnd_TheModelWritesAFile_ItLandsUnderTheCallsFolder_AndIsGoneWhenTheCallEnds() + public async Task EndToEnd_TheModelWritesAFile_ItLandsUnderTheConversationsFolder_AndIsGoneWhenTheConversationEnds() { var factory = BuildFactory(MemoryYaml, _root); - var session = factory.Create("call-1"); - var callFolder = session.Workspace!; + var session = factory.Create("conversation-1"); + var conversationFolder = session.Workspace!; await session.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); - var notes = FindRecursive(callFolder, "notes.md"); + var notes = FindRecursive(conversationFolder, "notes.md"); Assert.NotEmpty(notes); Assert.Contains("hello", await File.ReadAllTextAsync(notes[0], TestContext.Current.CancellationToken)); - session.EndCall(CallEndReason.CallerHungUp); + session.EndConversation(ConversationEndReason.CallerHungUp); - Assert.False(Directory.Exists(callFolder)); + Assert.False(Directory.Exists(conversationFolder)); } [Fact] - public async Task TwoSessions_DifferentCallIds_WriteToDifferentFolders() + public async Task TwoSessions_DifferentConversationIds_WriteToDifferentFolders() { var factory = BuildFactory(MemoryYaml, _root); - var first = factory.Create("call-a"); + var first = factory.Create("conversation-a"); await first.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); - var second = factory.Create("call-b"); + var second = factory.Create("conversation-b"); await second.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); var firstNotes = FindRecursive(first.Workspace!, "notes.md"); @@ -206,10 +206,10 @@ public async Task TwoSessions_DifferentCallIds_WriteToDifferentFolders() } [Fact] - public async Task MidTurnEndCall_DuringAFileMemoryWrite_StillDeletesTheFolder_EvenWhenThePolicyIsNotTerminal() + public async Task MidTurnEndConversation_DuringAFileMemoryWrite_StillDeletesTheFolder_EvenWhenThePolicyIsNotTerminal() { var document = ConfigurationLoader.LoadYaml(MemoryPolicyYaml); - EndCallDuringToolChatClient chatClient = new( + EndConversationDuringToolChatClient chatClient = new( "hello there.", new Dictionary(StringComparer.Ordinal) { @@ -220,22 +220,22 @@ public async Task MidTurnEndCall_DuringAFileMemoryWrite_StillDeletesTheFolder_Ev var compiled = ConfigurationCompiler.CompileAll( document, new AgentCompilationContext(chatClients) { WorkspaceRoot = _root })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); - var session = factory.Create("call-1"); - var callFolder = session.Workspace!; + var session = factory.Create("conversation-1"); + var conversationFolder = session.Workspace!; // The callback fires from inside the model's response, before the framework runs the tool - // it just asked for — mid-turn, exactly where a mid-turn EndCall would land in production. - chatClient.BeforeToolCall = () => session.EndCall(CallEndReason.CallerHungUp); + // it just asked for — mid-turn, exactly where a mid-turn EndConversation would land in production. + chatClient.BeforeToolCall = () => session.EndConversation(ConversationEndReason.CallerHungUp); var turn = await session.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); Assert.False(turn.IsTerminal); - Assert.False(Directory.Exists(callFolder)); + Assert.False(Directory.Exists(conversationFolder)); } - private static CallSessionFactory BuildFactory(string yaml, string root) + private static ConversationSessionFactory BuildFactory(string yaml, string root) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new RoutingChatClientFactory(new ToolCallingChatClient( @@ -250,7 +250,7 @@ private static CallSessionFactory BuildFactory(string yaml, string root) document, new AgentCompilationContext(chatClients) { WorkspaceRoot = root })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: root); @@ -280,17 +280,17 @@ private static IEnumerable Providers(AIAgent agent) /// /// Like , but runs immediately /// before it emits the one tool call it makes — the model-side moment a mid-turn - /// EndCall lands at, before the framework has actually run the tool. + /// EndConversation lands at, before the framework has actually run the tool. /// - private sealed class EndCallDuringToolChatClient : IChatClient + private sealed class EndConversationDuringToolChatClient : IChatClient { - private const string CallId = "call_1"; + private const string ConversationId = "conversation_1"; private readonly string _reply; private readonly Dictionary _arguments; private bool _answered; - public EndCallDuringToolChatClient(string reply, Dictionary arguments) + public EndConversationDuringToolChatClient(string reply, Dictionary arguments) { _reply = reply; _arguments = arguments; @@ -318,7 +318,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, - [new FunctionCallContent(CallId, tool.Name, _arguments)]) + [new FunctionCallContent(ConversationId, tool.Name, _arguments)]) { ResponseId = responseId, MessageId = responseId, diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs index ddcaabb7..38937c05 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ShellOptionsCompilerTests.cs @@ -37,7 +37,7 @@ public void Load_ShellEnvWithASecretReference_BindsTheReferenceAndLeavesAPlainVa } [Fact] - public void Build_ShellEnvAndMaxOutputKb_ResolveIntoTheCallShellOptions() + public void Build_ShellEnvAndMaxOutputKb_ResolveIntoTheConversationShellOptions() { var root = Path.Combine(Path.GetTempPath(), "agentcore-shell-env-secret-" + Guid.NewGuid().ToString("N")); var item = new AgentConfiguration { Id = "only" }; diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs index ce94d873..84dd30eb 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs @@ -19,7 +19,7 @@ public sealed class ConfigurationBinderTests private const string Providers = """ providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -43,10 +43,10 @@ public void AMaxFrameSizeLargerThanABufferLength_FailsWithThePointerOfTheField() { var failure = Assert.Throws( () => ConfigurationLoader.LoadYaml( - Header + "providers:\n call: { kind: telnyx-relay, maxFrameBytes: 4294967296 }\n" + Header + "providers:\n conversation: { kind: telnyx-relay, maxFrameBytes: 4294967296 }\n" + " speech:\n stt: { kind: telnyx-relay }\n tts: { kind: telnyx-relay }\n")); - Assert.Contains(failure.Errors, error => error.Pointer == "/providers/call/maxFrameBytes"); + Assert.Contains(failure.Errors, error => error.Pointer == "/providers/conversation/maxFrameBytes"); } /// The export interval becomes a period in milliseconds, and the same bound applies. @@ -140,13 +140,13 @@ public void AWholeNumberKeyWrittenWithAFraction_FailsWithThePointerOfTheField(st "agents": { "items": [{ "id": "only" }] }, "entries": { "main": { "agent": "only" } }, "providers": { - "call": { "kind": "telnyx-relay", "idleTimeoutSeconds": {{written}} }, + "conversation": { "kind": "telnyx-relay", "idleTimeoutSeconds": {{written}} }, "speech": { "stt": { "kind": "telnyx-relay" }, "tts": { "kind": "telnyx-relay" } } } } """)); - Assert.Contains(failure.Errors, error => error.Pointer == "/providers/call/idleTimeoutSeconds"); + Assert.Contains(failure.Errors, error => error.Pointer == "/providers/conversation/idleTimeoutSeconds"); Assert.DoesNotContain("System.", failure.Message, StringComparison.Ordinal); } @@ -242,7 +242,7 @@ public void Bind_KnowledgeScopeWildcardAndFromState_ReadsBoth() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -278,7 +278,7 @@ public void Bind_AmbiguityBlock_ReadsDefaults() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -311,7 +311,7 @@ public void Bind_AmbiguityBlock_ReadsEveryField() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -343,7 +343,7 @@ public void Bind_AnUnknownAmbiguityKey_FailsCheckOne() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs index b2dd8e18..59a76ca8 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationLoaderTests.cs @@ -169,7 +169,7 @@ public void AnEmptyKnowledgeBlock_FailsTheLoadForKindAndCollection() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -190,7 +190,7 @@ public void AFieldsBlockNamingOneRole_LeavesEveryOtherRoleUnmapped() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -223,7 +223,7 @@ public void ABodyFieldSetToNull_FailsTheLoad() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -246,7 +246,7 @@ public void AKnowledgeProviderThatWritesEveryField_BindsThem() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -276,7 +276,7 @@ public void AKnowledgeProviderWithNoVector_BindsNullMeaningTheAnonymousVector() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -300,7 +300,7 @@ public void AKnowledgeProviderNamingAMapper_BindsIt() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -697,7 +697,7 @@ public void NoLinksBlock_LeavesLinksNullAndTheFeatureOff() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -720,7 +720,7 @@ public void ALinksBlockWithoutLookup_DefaultsToFilter() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs index b1cbac87..2154cb73 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs @@ -149,7 +149,7 @@ public void AToolWriterWithNoPath_FailsWithThePointerOfTheSlot() [InlineData("\" \"")] public void AFallbackReplyWithNoWords_FailsWithThePointerOfTheField(string written) { - // Section 8.7 asks for a spoken fallback, and a line with no words is silence on a call. + // Section 8.7 asks for a spoken fallback, and a line with no words is silence on a conversation. var failure = Assert.Throws( () => ConfigurationLoader.LoadYaml($"apiVersion: agentcore/v1\nfallbackReply: {written}\n")); @@ -162,7 +162,7 @@ public void AFallbackReplyWithNoWords_FailsWithThePointerOfTheField(string writt [InlineData("\" \"")] public void ARefusalReplyWithNoWords_FailsWithThePointerOfTheField(string written) { - // The refusal is spoken too, and a line with no words is silence on a call. + // The refusal is spoken too, and a line with no words is silence on a conversation. var failure = Assert.Throws( () => ConfigurationLoader.LoadYaml($"apiVersion: agentcore/v1\nrefusalReply: {written}\n")); @@ -245,7 +245,7 @@ public void AnUnknownKnowledgeKey_Fails() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -266,7 +266,7 @@ public void TheOldKnowledgeStoreKey_Fails() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -291,7 +291,7 @@ public void AKnowledgeProviderNamingOnlyKindAndCollection_PassesCheckOne() const string document = """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/CallSchemaTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConversationSchemaTests.cs similarity index 78% rename from tests/AgentCore.Application.Tests/Configuration/CallSchemaTests.cs rename to tests/AgentCore.Application.Tests/Configuration/ConversationSchemaTests.cs index 2b188175..2deaa08b 100644 --- a/tests/AgentCore.Application.Tests/Configuration/CallSchemaTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConversationSchemaTests.cs @@ -5,22 +5,22 @@ namespace AgentCore.Application.Tests.Configuration; /// -/// providers.call names the vendor that carries the call, and the limits of its socket. +/// providers.conversation names the vendor that carries the conversation, and the limits of its socket. /// /// /// The media plane is not providers.speech, which names recognition and synthesis one role -/// at a time, and it is not providers.telephony, which is call control. Section 8.2 asks a +/// at a time, and it is not providers.telephony, which is conversation control. Section 8.2 asks a /// document that writes a providers: section to name both the pipe and the ears, so the two /// blocks are required together — and the speech block requires both of its own roles in turn. /// -public sealed class CallSchemaTests +public sealed class ConversationSchemaTests { [Fact] - public void TheCallBlockBindsItsKindAndItsThreeKnobs() + public void TheConversationBlockBindsItsKindAndItsThreeKnobs() { var configuration = Load(""" providers: - call: + conversation: kind: telnyx-relay idleTimeoutSeconds: 30 closeTimeoutSeconds: 5 @@ -30,11 +30,11 @@ public void TheCallBlockBindsItsKindAndItsThreeKnobs() tts: { kind: telnyx-relay } """); - var call = configuration.Providers!.Call!; - Assert.Equal("telnyx-relay", call.Kind); - Assert.Equal(30, call.IdleTimeoutSeconds); - Assert.Equal(5, call.CloseTimeoutSeconds); - Assert.Equal(65536, call.MaxFrameBytes); + var conversation = configuration.Providers!.Conversation!; + Assert.Equal("telnyx-relay", conversation.Kind); + Assert.Equal(30, conversation.IdleTimeoutSeconds); + Assert.Equal(5, conversation.CloseTimeoutSeconds); + Assert.Equal(65536, conversation.MaxFrameBytes); } [Fact] @@ -42,20 +42,20 @@ public void TheThreeKnobsAreOptional() { var configuration = Load(""" providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } """); - var call = configuration.Providers!.Call!; - Assert.Null(call.IdleTimeoutSeconds); - Assert.Null(call.CloseTimeoutSeconds); - Assert.Null(call.MaxFrameBytes); + var conversation = configuration.Providers!.Conversation!; + Assert.Null(conversation.IdleTimeoutSeconds); + Assert.Null(conversation.CloseTimeoutSeconds); + Assert.Null(conversation.MaxFrameBytes); } [Fact] - public void AMissingCallBlockFailsTheLoad() + public void AMissingConversationBlockFailsTheLoad() { var failure = Assert.Throws( () => Load(""" @@ -66,7 +66,7 @@ public void AMissingCallBlockFailsTheLoad() """)); Assert.Equal(ConfigurationCheck.DocumentSchema, failure.Check); - Assert.Contains("call", failure.Message, StringComparison.Ordinal); + Assert.Contains("conversation", failure.Message, StringComparison.Ordinal); } [Fact] @@ -75,7 +75,7 @@ public void AMissingSpeechBlockFailsTheLoad() var failure = Assert.Throws( () => Load(""" providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } """)); Assert.Equal(ConfigurationCheck.DocumentSchema, failure.Check); @@ -83,12 +83,12 @@ public void AMissingSpeechBlockFailsTheLoad() } [Fact] - public void AnUnknownFieldUnderCallFailsTheLoad() + public void AnUnknownFieldUnderConversationFailsTheLoad() { var failure = Assert.Throws( () => Load(""" providers: - call: { kind: telnyx-relay, idleTimeoutSecnods: 30 } + conversation: { kind: telnyx-relay, idleTimeoutSecnods: 30 } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -104,13 +104,13 @@ public void InfiniteIsSpelledMinusOne() { var configuration = Load(""" providers: - call: { kind: telnyx-relay, idleTimeoutSeconds: -1 } + conversation: { kind: telnyx-relay, idleTimeoutSeconds: -1 } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } """); - Assert.Equal(-1, configuration.Providers!.Call!.IdleTimeoutSeconds); + Assert.Equal(-1, configuration.Providers!.Conversation!.IdleTimeoutSeconds); } [Fact] @@ -118,7 +118,7 @@ public void TheSpeechBlockBindsBothRoles() { var configuration = Load(""" providers: - call: { kind: sip } + conversation: { kind: sip } speech: stt: { kind: deepgram } tts: { kind: elevenlabs } @@ -135,7 +135,7 @@ public void ASpeechBlockWithoutRecognitionFailsTheLoad() var failure = Assert.Throws( () => Load(""" providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: tts: { kind: telnyx-relay } """)); @@ -150,7 +150,7 @@ public void ASpeechBlockWithoutSynthesisFailsTheLoad() var failure = Assert.Throws( () => Load(""" providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } """)); @@ -165,7 +165,7 @@ public void AnUnknownFieldUnderSpeechFailsTheLoad() var failure = Assert.Throws( () => Load(""" providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs index df3092e3..f9c31f61 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs @@ -168,11 +168,11 @@ internal static class ExampleDocument - { kind: openai, model: gpt-5.4-nano, as: fill } # the extractor, chosen on null discipline - { kind: openai, model: gpt-4.1, as: judge } # evaluation only, chosen on judgement - { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false } - call: { kind: telnyx-relay } # the pipe: who carries the call and owns /v1/{entry}/call + conversation: { kind: telnyx-relay } # the pipe: who carries the conversation and owns /v1/{entry}/call speech: # the ears and the mouth, named one role at a time - stt: { kind: telnyx-relay } # recognition. Bundled here, so it matches call - tts: { kind: telnyx-relay } # synthesis. Bundled here, so it matches call - telephony: { kind: telnyx } # dial, transfer, hang up. Not the pipe — that is call + stt: { kind: telnyx-relay } # recognition. Bundled here, so it matches conversation + tts: { kind: telnyx-relay } # synthesis. Bundled here, so it matches conversation + telephony: { kind: telnyx } # dial, transfer, hang up. Not the pipe — that is conversation moderation: { kind: openai } # reads what the CALLER said, before the model runs embeddings: { kind: openai, model: text-embedding-3-small } blobs: { kind: s3, endpoint: https://s3.us-east-005.backblazeb2.com, bucket: agentcore-files, region: us-east-005 } @@ -601,7 +601,7 @@ internal static class ExampleDocument "webSearch": false } ], - "call": { + "conversation": { "kind": "telnyx-relay" }, "speech": { diff --git a/tests/AgentCore.Application.Tests/Configuration/FacetResolveSchemaTests.cs b/tests/AgentCore.Application.Tests/Configuration/FacetResolveSchemaTests.cs index 061b71ec..01917b2e 100644 --- a/tests/AgentCore.Application.Tests/Configuration/FacetResolveSchemaTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/FacetResolveSchemaTests.cs @@ -18,7 +18,7 @@ public sealed class FacetResolveSchemaTests main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Configuration/McpConfigurationTests.cs b/tests/AgentCore.Application.Tests/Configuration/McpConfigurationTests.cs index 8cac1ce7..ba065db9 100644 --- a/tests/AgentCore.Application.Tests/Configuration/McpConfigurationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/McpConfigurationTests.cs @@ -180,7 +180,7 @@ public void AnHttpServerWithACommand_FailsTheLoad() /// A null allow: entry is check 1's job, and check 1 already refuses it (see /// and its neighbours). This test bypasses /// check 1 and binds a hand-built tree directly, the route 's - /// own failure branches exist for: without HandleNull, JsonSerializer never calls + /// own failure branches exist for: without HandleNull, JsonSerializer never conversations /// Read for a null token and simply stores a null reference in the list. /// [Fact] diff --git a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs index a6d0f093..1bc0e3f6 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs @@ -21,7 +21,7 @@ public sealed class ConfigurationValidatorTests private const string MinimalProviders = """ providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -33,7 +33,7 @@ public sealed class ConfigurationValidatorTests private const string SpeechOnlyProviders = """ providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -335,7 +335,7 @@ public void AnUnusedAgentToolNamingAnUndeclaredAgent_FailsCheckTwo() const string document = """ apiVersion: agentcore/v1 tools: - - { id: call_ghost, kind: agent, agent: ghost } + - { id: conversation_ghost, kind: agent, agent: ghost } agents: items: - { id: planner } @@ -391,7 +391,7 @@ public void TwoMcpEntriesSharingAnId_FailCheckTwoNamingTheId() // Check 2, knowledge scope: a state-built scope must not produce a filter nobody meant. // --------------------------------------------------------------------------------------------- // KnowledgeStartup skips the store factory for a host-supplied port, and returns null when - // KnowledgeStores is unset, but CallSession composes the scope regardless — so these are document + // KnowledgeStores is unset, but ConversationSession composes the scope regardless — so these are document // checks, not store checks. private static AgentCoreConfiguration Scoped( IReadOnlyList fromState, @@ -734,7 +734,7 @@ public void Evaluate_AmbiguityWithCustomMapper_Fails() [Fact] public void Evaluate_AmbiguityProbeDeadlineSecondsAboveTheTimerCeiling_Fails() { - // CancelAfter throws above int.MaxValue milliseconds, from a call site with no pointer. + // CancelAfter throws above int.MaxValue milliseconds, from a conversation site with no pointer. var ambiguity = new KnowledgeAmbiguityConfiguration { ProbeDeadlineSeconds = 3_000_000 }; var result = ConfigurationValidator.EvaluateStructure(OneFacetScope(ambiguity)); @@ -1029,7 +1029,7 @@ public void AReservedSlotReadInARule_PassesCheckFour() apiVersion: agentcore/v1 guards: inResolve: { "===": [ { var: stage }, "resolve" ] } - longCall: { ">=": [ { var: callDurationSeconds }, 90 ] } + longConversation: { ">=": [ { var: conversationDurationSeconds }, 90 ] } lateTurn: { ">": [ { var: turnIndex }, 4 ] } agents: items: @@ -1388,7 +1388,7 @@ public void AnAgentAsToolLoop_FailsCheckEightWithThePointerOfTheToolThatClosesIt Assert.Equal("/agents/items/1/tools/0", error.Pointer); Assert.Equal( "this tool runs the agent 'planner', and that closes the delegation cycle " - + "planner -> writer -> planner. The call would never return.", + + "planner -> writer -> planner. The conversation would never return.", error.Message); } diff --git a/tests/AgentCore.Application.Tests/Configuration/Validation/GuardEvaluatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/Validation/GuardEvaluatorTests.cs index 3d37ef26..37f72985 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Validation/GuardEvaluatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Validation/GuardEvaluatorTests.cs @@ -216,7 +216,7 @@ public void AGuardThatThrowsAtRunTime_IsFalseAndIsReportedOnce() (description, _) => failures.Add(description)); // 'and' is on the allow-list, so check 4 passes the rule. Its argument is not an array, and - // JsonLogic throws while it reads it. Section 8.7 calls that possible and not a defect. + // JsonLogic throws while it reads it. Section 8.7 conversations that possible and not a defect. var rule = JsonNode.Parse("""{ "and": 5 }""")!; Assert.False(evaluator.Evaluate(rule, State)); diff --git a/tests/AgentCore.Application.Tests/Configuration/Validation/ReasoningTemperatureCheckTests.cs b/tests/AgentCore.Application.Tests/Configuration/Validation/ReasoningTemperatureCheckTests.cs index ba78ead7..ef85943e 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Validation/ReasoningTemperatureCheckTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Validation/ReasoningTemperatureCheckTests.cs @@ -61,7 +61,7 @@ public void TheEffortOfAnotherEntry_DoesNotReachThisReference() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -88,7 +88,7 @@ public void ATitlerAndAToolAndTheAgentDefaults_AreCheckedToo() titler: model: { ref: reply, temperature: 0.2 } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -133,7 +133,7 @@ private static string Document(string? effort, string? temperature) main: agent: greeter providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Calls/.editorconfig b/tests/AgentCore.Application.Tests/Conversation/.editorconfig similarity index 100% rename from tests/AgentCore.Application.Tests/Calls/.editorconfig rename to tests/AgentCore.Application.Tests/Conversation/.editorconfig diff --git a/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs b/tests/AgentCore.Application.Tests/Conversation/ChatConversationTitlerTests.cs similarity index 59% rename from tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs rename to tests/AgentCore.Application.Tests/Conversation/ChatConversationTitlerTests.cs index 1d3f2e1a..1e718971 100644 --- a/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/ChatConversationTitlerTests.cs @@ -1,55 +1,55 @@ using System.Runtime.CompilerServices; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Ports; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; -/// Making a call's title from its words. -public sealed class ChatCallTitlerTests +/// Making a conversation's title from its words. +public sealed class ChatConversationTitlerTests { private static CancellationToken Token => TestContext.Current.CancellationToken; [Fact] - public async Task GenerateAsync_ACallWithWords_StreamsThePiecesAndStoresTheWhole() + public async Task GenerateAsync_AConversationWithWords_StreamsThePiecesAndStoresTheWhole() { // Arrange - var (titler, calls) = await BuildAsync("A squeaky ", "belt"); + var (titler, conversations) = await BuildAsync("A squeaky ", "belt"); // Act var pieces = await CollectAsync(titler.GenerateAsync("c1", Token)); // Assert Assert.Equal(["A squeaky ", "belt"], pieces); - Assert.Equal("A squeaky belt", (await calls.GetAsync("c1", Token))!.Title); + Assert.Equal("A squeaky belt", (await conversations.GetAsync("c1", Token))!.Title); } [Fact] - public async Task GenerateAsync_ACallWithNoWords_YieldsNothingAndLeavesTheTitleAlone() + public async Task GenerateAsync_AConversationWithNoWords_YieldsNothingAndLeavesTheTitleAlone() { // Arrange - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); - await calls.RenameAsync("c1", "kept", Token); - ChatCallTitler titler = new(calls, new StubChatClient("ignored")); + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); + await conversations.RenameAsync("c1", "kept", Token); + ChatConversationTitler titler = new(conversations, new StubChatClient("ignored")); // Act var pieces = await CollectAsync(titler.GenerateAsync("c1", Token)); // Assert Assert.Empty(pieces); - Assert.Equal("kept", (await calls.GetAsync("c1", Token))!.Title); + Assert.Equal("kept", (await conversations.GetAsync("c1", Token))!.Title); } [Fact] public async Task GenerateAsync_StoppedPartWay_LeavesTheTitleAlone() { // Arrange - var (titler, calls) = await BuildAsync("A squeaky ", "belt"); - await calls.RenameAsync("c1", "kept", Token); + var (titler, conversations) = await BuildAsync("A squeaky ", "belt"); + await conversations.RenameAsync("c1", "kept", Token); // Act await foreach (var _ in titler.GenerateAsync("c1", Token)) @@ -58,51 +58,51 @@ public async Task GenerateAsync_StoppedPartWay_LeavesTheTitleAlone() } // Assert - Assert.Equal("kept", (await calls.GetAsync("c1", Token))!.Title); + Assert.Equal("kept", (await conversations.GetAsync("c1", Token))!.Title); } [Fact] public async Task GenerateFromAsync_MessagesFromTheCaller_StreamsThePiecesAndStoresTheWhole() { // Arrange - // The call holds no messages at all, so a title here can only have come from the caller's. - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); - ChatCallTitler titler = new(calls, new StubChatClient("A squeaky ", "belt")); + // The conversation holds no messages at all, so a title here can only have come from the caller's. + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); + ChatConversationTitler titler = new(conversations, new StubChatClient("A squeaky ", "belt")); // Act var pieces = await CollectAsync(titler.GenerateFromAsync("c1", Said("my belt squeaks"), Token)); // Assert Assert.Equal(["A squeaky ", "belt"], pieces); - Assert.Equal("A squeaky belt", (await calls.GetAsync("c1", Token))!.Title); + Assert.Equal("A squeaky belt", (await conversations.GetAsync("c1", Token))!.Title); } [Fact] public async Task GenerateFromAsync_NoMessagesFromTheCaller_YieldsNothingAndLeavesTheTitleAlone() { // Arrange - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); - await calls.RenameAsync("c1", "kept", Token); - ChatCallTitler titler = new(calls, new StubChatClient("ignored")); + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); + await conversations.RenameAsync("c1", "kept", Token); + ChatConversationTitler titler = new(conversations, new StubChatClient("ignored")); // Act var pieces = await CollectAsync(titler.GenerateFromAsync("c1", [], Token)); // Assert Assert.Empty(pieces); - Assert.Equal("kept", (await calls.GetAsync("c1", Token))!.Title); + Assert.Equal("kept", (await conversations.GetAsync("c1", Token))!.Title); } [Fact] public async Task GenerateFromAsync_StoppedPartWay_LeavesTheTitleAlone() { // Arrange - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); - await calls.RenameAsync("c1", "kept", Token); - ChatCallTitler titler = new(calls, new StubChatClient("A squeaky ", "belt")); + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); + await conversations.RenameAsync("c1", "kept", Token); + ChatConversationTitler titler = new(conversations, new StubChatClient("A squeaky ", "belt")); // Act await foreach (var _ in titler.GenerateFromAsync("c1", Said("my belt squeaks"), Token)) @@ -111,16 +111,16 @@ public async Task GenerateFromAsync_StoppedPartWay_LeavesTheTitleAlone() } // Assert - Assert.Equal("kept", (await calls.GetAsync("c1", Token))!.Title); + Assert.Equal("kept", (await conversations.GetAsync("c1", Token))!.Title); } [Fact] - public async Task GenerateFromAsync_AnUnknownCall_YieldsNothingAndNeverAsksTheModel() + public async Task GenerateFromAsync_AnUnknownConversation_YieldsNothingAndNeverAsksTheModel() { // Arrange - InMemoryCallStore calls = new(); + InMemoryConversationStore conversations = new(); StubChatClient client = new("A squeaky belt"); - ChatCallTitler titler = new(calls, client); + ChatConversationTitler titler = new(conversations, client); // Act var pieces = await CollectAsync(titler.GenerateFromAsync("missing", Said("my belt squeaks"), Token)); @@ -134,10 +134,10 @@ public async Task GenerateFromAsync_AnUnknownCall_YieldsNothingAndNeverAsksTheMo public async Task GenerateFromAsync_MoreMessagesThanTheCap_SendsOnlyTheFirstSix() { // Arrange - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); StubChatClient client = new("A squeaky belt"); - ChatCallTitler titler = new(calls, client); + ChatConversationTitler titler = new(conversations, client); List many = [.. Enumerable.Range(0, 9).Select(n => new ChatMessage(ChatRole.User, $"m{n}"))]; // Act @@ -153,10 +153,10 @@ public async Task GenerateFromAsync_MoreMessagesThanTheCap_SendsOnlyTheFirstSix( public async Task GenerateFromAsync_Always_SendsTheInstructionAsTheSystemMessageAndTheWordsAsTheUser() { // Arrange - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); StubChatClient client = new("A squeaky belt"); - ChatCallTitler titler = new(calls, client); + ChatConversationTitler titler = new(conversations, client); // Act await CollectAsync(titler.GenerateFromAsync("c1", Said("my belt squeaks"), Token)); @@ -186,16 +186,16 @@ private static async Task> CollectAsync(IAsyncEnumerable st return pieces; } - private static async Task<(ChatCallTitler Titler, InMemoryCallStore Calls)> BuildAsync(params string[] pieces) + private static async Task<(ChatConversationTitler Titler, InMemoryConversationStore Conversations)> BuildAsync(params string[] pieces) { - InMemoryCallStore calls = new(); - await calls.CreateAsync("c1", Token); - await calls.AppendAsync( + InMemoryConversationStore conversations = new(); + await conversations.CreateAsync("c1", Token); + await conversations.AppendAsync( "c1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "my belt squeaks"), "m0")], + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "my belt squeaks"), "m0")], cancellationToken: Token); - return (new ChatCallTitler(calls, new StubChatClient(pieces)), calls); + return (new ChatConversationTitler(conversations, new StubChatClient(pieces)), conversations); } private sealed class StubChatClient(params string[] pieces) : IChatClient diff --git a/tests/AgentCore.Application.Tests/Calls/CallChannelTests.cs b/tests/AgentCore.Application.Tests/Conversation/ConversationChannelTests.cs similarity index 76% rename from tests/AgentCore.Application.Tests/Calls/CallChannelTests.cs rename to tests/AgentCore.Application.Tests/Conversation/ConversationChannelTests.cs index f8bbd00c..3ba30994 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallChannelTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/ConversationChannelTests.cs @@ -1,19 +1,19 @@ using AgentCore.Application.Ports; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; /// /// The channel pair, including the case where one object fills both slots. /// -public sealed class CallChannelTests +public sealed class ConversationChannelTests { [Fact] public async Task OneObjectInBothSlots_IsDisposedExactlyOnce() { var both = new CountingChannel(); - var channel = new CallChannel(both, both); + var channel = new ConversationChannel(both, both); await channel.DisposeAsync(); @@ -25,7 +25,7 @@ public async Task TwoDistinctObjects_AreEachDisposedOnce() { var input = new CountingChannel(); var output = new CountingChannel(); - var channel = new CallChannel(input, output); + var channel = new ConversationChannel(input, output); await channel.DisposeAsync(); @@ -37,7 +37,7 @@ public async Task TwoDistinctObjects_AreEachDisposedOnce() public async Task DisposingTwice_DisposesTheInnerPortsOnlyOnce() { var both = new CountingChannel(); - var channel = new CallChannel(both, both); + var channel = new ConversationChannel(both, both); await channel.DisposeAsync(); await channel.DisposeAsync(); @@ -46,11 +46,11 @@ public async Task DisposingTwice_DisposesTheInnerPortsOnlyOnce() } /// A port that fills either slot, or both, and counts its own disposals. - private sealed class CountingChannel : ICallInputPort, ICallOutputPort + private sealed class CountingChannel : IConversationInputPort, IConversationOutputPort { public int Disposals { get; private set; } - public IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default) + public IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public ValueTask SpeakAsync(string fragment, CancellationToken cancellationToken = default) diff --git a/tests/AgentCore.Application.Tests/Conversation/ConversationCursorTests.cs b/tests/AgentCore.Application.Tests/Conversation/ConversationCursorTests.cs new file mode 100644 index 00000000..f44913c7 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Conversation/ConversationCursorTests.cs @@ -0,0 +1,52 @@ +using AgentCore.Application.Conversation; +using Xunit; + +namespace AgentCore.Application.Tests.Conversation; + +/// The opaque cursor a listing hands back and takes again. +public sealed class ConversationCursorTests +{ + [Fact] + public void Encode_ThenDecode_ReturnsBothValues() + { + // Arrange + DateTimeOffset sortAt = new(2026, 8, 30, 12, 34, 56, 789, TimeSpan.Zero); + + // Act + var cursor = ConversationCursor.Encode(sortAt, "conversation-1"); + var decoded = ConversationCursor.TryDecode(cursor, out var readAt, out var readId); + + // Assert + Assert.True(decoded); + Assert.Equal(sortAt, readAt); + Assert.Equal("conversation-1", readId); + } + + [Fact] + public void Encode_AConversationIdHoldingTheSeparator_RoundTripsWhole() + { + // Arrange + const string ConversationId = "conversation|with|pipes"; + + // Act + var cursor = ConversationCursor.Encode(DateTimeOffset.UnixEpoch, ConversationId); + ConversationCursor.TryDecode(cursor, out _, out var readId); + + // Assert + Assert.Equal(ConversationId, readId); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("not-base64!")] + [InlineData("bm90LWEtY3Vyc29y")] + public void TryDecode_SomethingThatIsNotACursor_IsFalseAndNotAThrow(string? cursor) + { + // Act + var decoded = ConversationCursor.TryDecode(cursor, out _, out _); + + // Assert + Assert.False(decoded); + } +} diff --git a/tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs b/tests/AgentCore.Application.Tests/Conversation/ConversationSessionStateTests.cs similarity index 72% rename from tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs rename to tests/AgentCore.Application.Tests/Conversation/ConversationSessionStateTests.cs index 5264f22c..a64529c4 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/ConversationSessionStateTests.cs @@ -1,17 +1,17 @@ using System.Linq; using System.Text.Json; using System.Text.Json.Nodes; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; -public sealed class CallSessionStateTests +public sealed class ConversationSessionStateTests { [Fact] public void ItRoundTripsThroughJson() { - CallSessionState state = new() + ConversationSessionState state = new() { Stage = "collecting", IsComplete = false, @@ -29,11 +29,11 @@ public void ItRoundTripsThroughJson() }, }; - var json = JsonSerializer.Serialize(state, CallStateJson.Options); - var read = JsonSerializer.Deserialize(json, CallStateJson.Options); + var json = JsonSerializer.Serialize(state, ConversationStateJson.Options); + var read = JsonSerializer.Deserialize(json, ConversationStateJson.Options); Assert.NotNull(read); - Assert.Equal(CallSessionState.CurrentVersion, read.Version); + Assert.Equal(ConversationSessionState.CurrentVersion, read.Version); Assert.Equal("collecting", read.Stage); Assert.False(read.IsComplete); Assert.Equal("F63", read.Slots["model"]!.GetValue()); @@ -48,12 +48,12 @@ public void ItRoundTripsThroughJson() [Fact] public void ANewStateCarriesTheCurrentVersion() - => Assert.Equal(CallSessionState.CurrentVersion, new CallSessionState().Version); + => Assert.Equal(ConversationSessionState.CurrentVersion, new ConversationSessionState().Version); [Fact] public void ItRoundTripsProvidersThroughJson() { - CallSessionState state = new() + ConversationSessionState state = new() { Providers = new Dictionary(StringComparer.Ordinal) { @@ -63,8 +63,8 @@ public void ItRoundTripsProvidersThroughJson() }, }; - var json = JsonSerializer.Serialize(state, CallStateJson.Options); - var read = JsonSerializer.Deserialize(json, CallStateJson.Options); + var json = JsonSerializer.Serialize(state, ConversationStateJson.Options); + var read = JsonSerializer.Deserialize(json, ConversationStateJson.Options); Assert.NotNull(read); Assert.Equal(2, read.Providers.Count); @@ -79,8 +79,8 @@ public void ItRoundTripsProvidersThroughJson() [Fact] public void ABlobWithNoProvidersMember_DeserializesWithEmptyProviders() { - var read = JsonSerializer.Deserialize( - """{"version":1,"nextTurnIndex":0,"stage":"","isComplete":false}""", CallStateJson.Options); + var read = JsonSerializer.Deserialize( + """{"version":1,"nextTurnIndex":0,"stage":"","isComplete":false}""", ConversationStateJson.Options); Assert.NotNull(read); Assert.Empty(read.Providers); @@ -88,5 +88,5 @@ public void ABlobWithNoProvidersMember_DeserializesWithEmptyProviders() [Fact] public void ANewState_HasEmptyProviders() - => Assert.Empty(new CallSessionState().Providers); + => Assert.Empty(new ConversationSessionState().Providers); } diff --git a/tests/AgentCore.Application.Tests/Calls/CallSpeechPairingTests.cs b/tests/AgentCore.Application.Tests/Conversation/ConversationSpeechPairingTests.cs similarity index 64% rename from tests/AgentCore.Application.Tests/Calls/CallSpeechPairingTests.cs rename to tests/AgentCore.Application.Tests/Conversation/ConversationSpeechPairingTests.cs index e887e483..94051466 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallSpeechPairingTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/ConversationSpeechPairingTests.cs @@ -1,21 +1,21 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; -public sealed class CallSpeechPairingTests +public sealed class ConversationSpeechPairingTests { - private sealed class FakeCallAdapter(string kind, bool carriesText) : ICallAdapter + private sealed class FakeConversationAdapter(string kind, bool carriesText) : IConversationAdapter { public string Kind { get; } = kind; public bool CarriesText { get; } = carriesText; } - private static CallProviderConfiguration Call(string kind) => new() { Kind = kind }; + private static ConversationProviderConfiguration Conversation(string kind) => new() { Kind = kind }; private static SpeechProviderConfiguration Speech(string stt, string tts) => new() { @@ -26,29 +26,29 @@ private sealed class FakeCallAdapter(string kind, bool carriesText) : ICallAdapt [Fact] public void ATextCarryingTransportBesideItsOwnSpeechKindPasses() { - CallSpeechPairing.Validate( - Call("telnyx-relay"), + ConversationSpeechPairing.Validate( + Conversation("telnyx-relay"), Speech("telnyx-relay", "telnyx-relay"), - new FakeCallAdapter("telnyx-relay", carriesText: true)); + new FakeConversationAdapter("telnyx-relay", carriesText: true)); } [Fact] public void TheKindsMatchWithoutRegardToCase() { - CallSpeechPairing.Validate( - Call("telnyx-relay"), + ConversationSpeechPairing.Validate( + Conversation("telnyx-relay"), Speech("TELNYX-RELAY", "Telnyx-Relay"), - new FakeCallAdapter("telnyx-relay", carriesText: true)); + new FakeConversationAdapter("telnyx-relay", carriesText: true)); } [Fact] public void ATextCarryingTransportBesideAnotherRecognitionKindFailsTheStart() { var failure = Assert.Throws( - () => CallSpeechPairing.Validate( - Call("telnyx-relay"), + () => ConversationSpeechPairing.Validate( + Conversation("telnyx-relay"), Speech("deepgram", "telnyx-relay"), - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); Assert.Single(failure.Errors); Assert.Equal("/providers/speech/stt/kind", failure.Errors[0].Pointer); @@ -62,10 +62,10 @@ public void ATextCarryingTransportBesideAnotherRecognitionKindFailsTheStart() public void ATextCarryingTransportBesideAnotherSynthesisKindFailsTheStart() { var failure = Assert.Throws( - () => CallSpeechPairing.Validate( - Call("telnyx-relay"), + () => ConversationSpeechPairing.Validate( + Conversation("telnyx-relay"), Speech("telnyx-relay", "elevenlabs"), - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); Assert.Single(failure.Errors); Assert.Equal("/providers/speech/tts/kind", failure.Errors[0].Pointer); @@ -79,10 +79,10 @@ public void ATextCarryingTransportBesideAnotherSynthesisKindFailsTheStart() public void BothRolesMismatchedReportTwoErrors() { var failure = Assert.Throws( - () => CallSpeechPairing.Validate( - Call("telnyx-relay"), + () => ConversationSpeechPairing.Validate( + Conversation("telnyx-relay"), Speech("deepgram", "elevenlabs"), - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); Assert.Equal(2, failure.Errors.Count); Assert.Equal("/providers/speech/stt/kind", failure.Errors[0].Pointer); @@ -94,23 +94,23 @@ public void AnAudioCarryingTransportBesideTwoOtherSpeechKindsPasses() { // This is the split shape: a SIP leg carries audio, one vendor turns it into text, and // another turns text back into what the caller hears. - CallSpeechPairing.Validate( - Call("sip"), + ConversationSpeechPairing.Validate( + Conversation("sip"), Speech("deepgram", "elevenlabs"), - new FakeCallAdapter("sip", carriesText: false)); + new FakeConversationAdapter("sip", carriesText: false)); } [Fact] public void NullArgumentsAreRefused() { - var adapter = new FakeCallAdapter("telnyx-relay", carriesText: true); + var adapter = new FakeConversationAdapter("telnyx-relay", carriesText: true); var speech = Speech("telnyx-relay", "telnyx-relay"); Assert.Throws( - () => CallSpeechPairing.Validate(null!, speech, adapter)); + () => ConversationSpeechPairing.Validate(null!, speech, adapter)); Assert.Throws( - () => CallSpeechPairing.Validate(Call("telnyx-relay"), null!, adapter)); + () => ConversationSpeechPairing.Validate(Conversation("telnyx-relay"), null!, adapter)); Assert.Throws( - () => CallSpeechPairing.Validate(Call("telnyx-relay"), speech, null!)); + () => ConversationSpeechPairing.Validate(Conversation("telnyx-relay"), speech, null!)); } } diff --git a/tests/AgentCore.Application.Tests/Calls/CallStoreFactoryTests.cs b/tests/AgentCore.Application.Tests/Conversation/ConversationStoreFactoryTests.cs similarity index 63% rename from tests/AgentCore.Application.Tests/Calls/CallStoreFactoryTests.cs rename to tests/AgentCore.Application.Tests/Conversation/ConversationStoreFactoryTests.cs index bf37dd6f..a49dd546 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallStoreFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/ConversationStoreFactoryTests.cs @@ -1,37 +1,37 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using AgentCore.TestSupport; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; /// -/// The store vendor seam: providers.calls, and what a document that names none gets. +/// The store vendor seam: providers.conversations, and what a document that names none gets. /// /// -/// The answer is never : a call's row and its words must have somewhere to go +/// The answer is never : a conversation's row and its words must have somewhere to go /// whether or not a document chose where. These tests pin the parts that are this project's and not a vendor's -- /// that there is always a store, that memory is this library's own name, and that every other /// kind goes through the shared selector. /// -public sealed class CallStoreFactoryTests +public sealed class ConversationStoreFactoryTests { [Fact] - public async Task OpenAsync_NoCallsBlock_GetsTheInProcessStoreAndAsksNoAdapter() + public async Task OpenAsync_NoConversationsBlock_GetsTheInProcessStoreAndAsksNoAdapter() { // Arrange var configuration = ConfigurationLoader.LoadYaml(Document()); - FakeCallStoreAdapter adapter = new("postgres"); + FakeConversationStoreAdapter adapter = new("postgres"); // Act - var store = await CallStoreFactory.OpenAsync( + var store = await ConversationStoreFactory.OpenAsync( configuration, secrets: null, [adapter], TestContext.Current.CancellationToken); // Assert - Assert.IsType(store); + Assert.IsType(store); Assert.Equal(0, adapter.Opens); } @@ -42,11 +42,11 @@ public async Task OpenAsync_TheMemoryKind_GetsTheInProcessStoreWithNoAdapterRegi var configuration = ConfigurationLoader.LoadYaml(Document("kind: memory")); // Act - var store = await CallStoreFactory.OpenAsync( + var store = await ConversationStoreFactory.OpenAsync( configuration, secrets: null, [], TestContext.Current.CancellationToken); // Assert - Assert.IsType(store); + Assert.IsType(store); } [Fact] @@ -54,14 +54,14 @@ public async Task OpenAsync_AnAdapterClaimingTheMemoryKind_DoesNotTakeOverTheBui { // Arrange var configuration = ConfigurationLoader.LoadYaml(Document("kind: memory")); - FakeCallStoreAdapter impostor = new("memory"); + FakeConversationStoreAdapter impostor = new("memory"); // Act - var store = await CallStoreFactory.OpenAsync( + var store = await ConversationStoreFactory.OpenAsync( configuration, secrets: null, [impostor], TestContext.Current.CancellationToken); // Assert - Assert.IsType(store); + Assert.IsType(store); Assert.Equal(0, impostor.Opens); } @@ -70,11 +70,11 @@ public async Task OpenAsync_TheKind_PicksOneAdapterAndLeavesTheOthersAlone() { // Arrange var configuration = ConfigurationLoader.LoadYaml(Document("kind: fake")); - FakeCallStoreAdapter fake = new("fake"); - FakeCallStoreAdapter other = new("postgres"); + FakeConversationStoreAdapter fake = new("fake"); + FakeConversationStoreAdapter other = new("postgres"); // Act - var store = await CallStoreFactory.OpenAsync( + var store = await ConversationStoreFactory.OpenAsync( configuration, secrets: null, [other, fake], TestContext.Current.CancellationToken); // Assert @@ -87,16 +87,16 @@ public async Task OpenAsync_AKindNoAdapterServes_FailsTheStartAndNamesWhatIsRegi { // Arrange var configuration = ConfigurationLoader.LoadYaml(Document("kind: postgres")); - FakeCallStoreAdapter adapter = new("fake"); + FakeConversationStoreAdapter adapter = new("fake"); // Act var failure = await Assert.ThrowsAsync( - async () => await CallStoreFactory.OpenAsync( + async () => await ConversationStoreFactory.OpenAsync( configuration, secrets: null, [adapter], TestContext.Current.CancellationToken)); // Assert Assert.Contains("postgres", failure.Message, StringComparison.Ordinal); - Assert.Equal("/providers/calls/kind", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversations/kind", failure.Errors[0].Pointer); } [Fact] @@ -104,12 +104,12 @@ public async Task OpenAsync_TwoAdaptersOnOneKind_FailTheStart() { // Arrange var configuration = ConfigurationLoader.LoadYaml(Document("kind: postgres")); - FakeCallStoreAdapter[] both = - [new FakeCallStoreAdapter("postgres"), new FakeCallStoreAdapter("postgres")]; + FakeConversationStoreAdapter[] both = + [new FakeConversationStoreAdapter("postgres"), new FakeConversationStoreAdapter("postgres")]; // Act var failure = await Assert.ThrowsAsync( - async () => await CallStoreFactory.OpenAsync( + async () => await ConversationStoreFactory.OpenAsync( configuration, secrets: null, both, TestContext.Current.CancellationToken)); // Assert @@ -117,12 +117,12 @@ public async Task OpenAsync_TwoAdaptersOnOneKind_FailTheStart() Assert.Contains("stores", failure.Message, StringComparison.Ordinal); } - /// The providers.knowledge line the calls block is written after. + /// The providers.knowledge line the conversations block is written after. private const string KnowledgeLine = Configuration.ExampleDocument.LastProviderLine; - /// Builds the section 8.1 document with one calls block written into it. + /// Builds the section 8.1 document with one conversations block written into it. /// - /// The keys under providers.calls, one for each line and without indentation. No entry + /// The keys under providers.conversations, one for each line and without indentation. No entry /// at all leaves the block out, which is the case that must still produce a store. /// private static string Document(params string[] entries) @@ -130,20 +130,20 @@ private static string Document(params string[] entries) ? Configuration.ExampleDocument.Yaml : Configuration.ExampleDocument.Yaml.Replace( KnowledgeLine, - KnowledgeLine + "\n calls:\n" + string.Join("\n", entries.Select(entry => " " + entry)), + KnowledgeLine + "\n conversations:\n" + string.Join("\n", entries.Select(entry => " " + entry)), StringComparison.Ordinal); /// An adapter that opens nothing and records that it was asked. - private sealed class FakeCallStoreAdapter(string kind) : ICallStoreAdapter + private sealed class FakeConversationStoreAdapter(string kind) : IConversationStoreAdapter { public string Kind => kind; public int Opens { get; private set; } /// The store this adapter hands over. It is a different type from the built-in one. - public ICallStore Store { get; } = new FakeCallStore(); + public IConversationStore Store { get; } = new FakeConversationStore(); - public ValueTask OpenAsync( + public ValueTask OpenAsync( VendorProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default) @@ -154,5 +154,5 @@ public ValueTask OpenAsync( } /// A store that is a different type from the built-in one, and does nothing else. - private sealed class FakeCallStore() : DelegatingCallStore(new InMemoryCallStore()); + private sealed class FakeConversationStore() : DelegatingConversationStore(new InMemoryConversationStore()); } diff --git a/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs b/tests/AgentCore.Application.Tests/Conversation/ConversationsTests.cs similarity index 50% rename from tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs rename to tests/AgentCore.Application.Tests/Conversation/ConversationsTests.cs index bb147a2a..9a4fa5d7 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallRepositoryTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/ConversationsTests.cs @@ -1,16 +1,16 @@ using AgentCore.Application.Transcript; using AgentCore.Application.Blobs; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Ports; using AgentCore.Application.Tests.Fakes; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; -/// The one door to a stored call: its row, its words, and its files go together. -public sealed class CallRepositoryTests +/// The one door to a stored conversation: its row, its words, and its files go together. +public sealed class ConversationsTests { /// A reply whose files the capture kept, 3 bytes each. private static ChatMessage ReplyWith(params (string Name, string MediaType)[] kept) @@ -22,44 +22,79 @@ private static FileContent Kept(string name, string mediaType, long length = 3) private static FileContent Refused(string name) => new() { Name = name, FileId = "cfile_" + name }; - private static async Task KeepAsync(RecordingBlobStore blobs, string callId, string name, string mediaType) - => await blobs.PutAsync(new BlobWrite(callId, name, mediaType, new MemoryStream([1, 2, 3]), 3), TestContext.Current.CancellationToken); + private static async Task KeepAsync(RecordingBlobStore blobs, string conversationId, string name, string mediaType) + => await blobs.PutAsync(new BlobWrite(conversationId, name, mediaType, new MemoryStream([1, 2, 3]), 3), TestContext.Current.CancellationToken); [Fact] public async Task DeleteAsync_DeletesTheFilesAndTheRow() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); RecordingBlobStore blobs = new(); - CallRepository calls = new(store, blobs); + Conversations conversations = new(store, blobs); var token = TestContext.Current.CancellationToken; - await calls.CreateAsync("call-1", token); - await KeepAsync(blobs, "call-1", "chart.png", "image/png"); - await KeepAsync(blobs, "call-2", "keep.png", "image/png"); + await conversations.CreateAsync("conversation-1", token); + await KeepAsync(blobs, "conversation-1", "chart.png", "image/png"); + await KeepAsync(blobs, "conversation-2", "keep.png", "image/png"); // Act - await calls.DeleteAsync("call-1", token); + await conversations.DeleteAsync("conversation-1", token); // Assert - Assert.Null(await store.GetAsync("call-1", token)); - Assert.Equal([("call-2", "keep.png")], blobs.Blobs.Keys); + Assert.Null(await store.GetAsync("conversation-1", token)); + Assert.Equal([("conversation-2", "keep.png")], blobs.Blobs.Keys); } [Fact] public async Task DeleteAsync_NoBlobStore_DeletesTheRowAlone() { // Arrange - InMemoryCallStore store = new(); - CallRepository calls = new(store, blobs: null); + InMemoryConversationStore store = new(); + Conversations conversations = new(store, blobs: null); var token = TestContext.Current.CancellationToken; - await calls.CreateAsync("call-1", token); + await conversations.CreateAsync("conversation-1", token); // Act - await calls.DeleteAsync("call-1", token); + await conversations.DeleteAsync("conversation-1", token); // Assert - Assert.Null(await store.GetAsync("call-1", token)); - Assert.False(calls.KeepsFiles); + Assert.Null(await store.GetAsync("conversation-1", token)); + } + + [Fact] + public async Task LoadAsync_ReturnsTheRowTheWordsAndOneLinkPerKeptFile() + { + // Arrange + CountingBlobStore blobs = new(); + Conversations conversations = new(new InMemoryConversationStore(), blobs); + var token = TestContext.Current.CancellationToken; + await conversations.CreateAsync("conversation-1", token); + await conversations.AppendMessageAsync("conversation-1", new ChatMessage(ChatRole.User, "chart it"), token); + await conversations.AppendMessageAsync("conversation-1", ReplyWith(("chart.png", "image/png")), token); + + // Act + var stored = await conversations.LoadAsync("conversation-1", token); + + // Assert + Assert.NotNull(stored); + Assert.Equal("conversation-1", stored.Conversation.ConversationId); + Assert.Equal(["chart it", "see"], stored.Messages.Select(message => message.Content.Text)); + var link = Assert.Single(stored.Files); + Assert.Equal(new BlobRef("conversation-1", "chart.png", "image/png", 3), link.Blob); + Assert.Equal("https://blobs.test/conversation-1/chart.png?ttl=900", link.Url?.ToString()); + } + + [Fact] + public async Task LoadAsync_AConversationThatWasNeverMade_IsNull() + { + // Arrange + Conversations conversations = new(new InMemoryConversationStore(), blobs: null); + + // Act + var stored = await conversations.LoadAsync("conversation-1", TestContext.Current.CancellationToken); + + // Assert + Assert.Null(stored); } [Fact] @@ -67,11 +102,11 @@ public async Task LinkFilesAsync_LinksFromTheContent_EachOnce_InFirstSeenOrder_W { // Arrange: the store is empty on purpose. The content is the index. CountingBlobStore blobs = new(); - CallRepository calls = new(new InMemoryCallStore(), blobs); + Conversations conversations = new(new InMemoryConversationStore(), blobs); // Act - var links = await calls.LinkFilesAsync( - "call-1", + var links = await conversations.LinkFilesAsync( + "conversation-1", [ new ChatMessage(ChatRole.Assistant, [Kept("chart.png", "image/png"), Refused("lost.pdf")]), ReplyWith(("rows.csv", "text/csv"), ("chart.png", "image/png")), @@ -83,8 +118,8 @@ public async Task LinkFilesAsync_LinksFromTheContent_EachOnce_InFirstSeenOrder_W links, link => { - Assert.Equal(new BlobRef("call-1", "chart.png", "image/png", 3), link.Blob); - Assert.Equal("https://blobs.test/call-1/chart.png?ttl=900", link.Url?.ToString()); + Assert.Equal(new BlobRef("conversation-1", "chart.png", "image/png", 3), link.Blob); + Assert.Equal("https://blobs.test/conversation-1/chart.png?ttl=900", link.Url?.ToString()); }, link => Assert.Equal("rows.csv", link.Blob.Name)); Assert.Equal(0, blobs.Stats); @@ -94,10 +129,10 @@ public async Task LinkFilesAsync_LinksFromTheContent_EachOnce_InFirstSeenOrder_W public async Task LinkFilesAsync_NoBlobStore_LinksNothing() { // Arrange - CallRepository calls = new(new InMemoryCallStore(), blobs: null); + Conversations conversations = new(new InMemoryConversationStore(), blobs: null); // Act - var links = await calls.LinkFilesAsync("call-1", [ReplyWith(("chart.png", "image/png"))], TestContext.Current.CancellationToken); + var links = await conversations.LinkFilesAsync("conversation-1", [ReplyWith(("chart.png", "image/png"))], TestContext.Current.CancellationToken); // Assert Assert.Empty(links); @@ -107,15 +142,15 @@ public async Task LinkFilesAsync_NoBlobStore_LinksNothing() public async Task LinkFilesAsync_SameNameKeptTwice_TheLaterFactsWinInTheFirstPlace() { // Arrange: the model redrew chart.png after rows.csv; the store replaced the first. - CallRepository calls = new(new InMemoryCallStore(), new RecordingBlobStore()); + Conversations conversations = new(new InMemoryConversationStore(), new RecordingBlobStore()); ChatMessage reply = new(ChatRole.Assistant, [Kept("chart.png", "image/png", 10), Kept("rows.csv", "text/csv", 5), Kept("chart.png", "image/png", 20)]); // Act - var links = await calls.LinkFilesAsync("call-1", [reply], TestContext.Current.CancellationToken); + var links = await conversations.LinkFilesAsync("conversation-1", [reply], TestContext.Current.CancellationToken); // Assert Assert.Equal( - [new BlobRef("call-1", "chart.png", "image/png", 20), new BlobRef("call-1", "rows.csv", "text/csv", 5)], + [new BlobRef("conversation-1", "chart.png", "image/png", 20), new BlobRef("conversation-1", "rows.csv", "text/csv", 5)], links.Select(link => link.Blob)); } @@ -126,10 +161,10 @@ public async Task LinkFilesAsync_SameNameKeptTwice_TheLaterFactsWinInTheFirstPla public async Task LinkFilesAsync_UnsafeName_IsNotLinked(string name) { // Arrange - CallRepository calls = new(new InMemoryCallStore(), new RecordingBlobStore()); + Conversations conversations = new(new InMemoryConversationStore(), new RecordingBlobStore()); // Act - var links = await calls.LinkFilesAsync("call-1", [new ChatMessage(ChatRole.Assistant, [Kept(name, "image/png")])], TestContext.Current.CancellationToken); + var links = await conversations.LinkFilesAsync("conversation-1", [new ChatMessage(ChatRole.Assistant, [Kept(name, "image/png")])], TestContext.Current.CancellationToken); // Assert Assert.Empty(links); diff --git a/tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs b/tests/AgentCore.Application.Tests/Conversation/DelegatingConversationStoreTests.cs similarity index 50% rename from tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs rename to tests/AgentCore.Application.Tests/Conversation/DelegatingConversationStoreTests.cs index 5c6db484..06333ee0 100644 --- a/tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/DelegatingConversationStoreTests.cs @@ -1,30 +1,30 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Ports; using AgentCore.Application.Transcript; using AgentCore.TestSupport; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; /// The forwarding base every store fake is built on. -public sealed class DelegatingCallStoreTests +public sealed class DelegatingConversationStoreTests { private static CancellationToken Token => TestContext.Current.CancellationToken; - private sealed class CountingAppends(ICallStore inner) : DelegatingCallStore(inner) + private sealed class CountingAppends(IConversationStore inner) : DelegatingConversationStore(inner) { public int Appends { get; private set; } - public override ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, + public override ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, CancellationToken cancellationToken = default) { Appends++; - return base.AppendAsync(callId, messages, state, cancellationToken); + return base.AppendAsync(conversationId, messages, state, cancellationToken); } } @@ -32,12 +32,12 @@ public override ValueTask> AppendAsync( public async Task AnOverride_CountsItsOwnCalls_AndStillReachesTheInnerStore() { // Arrange - CountingAppends store = new(new InMemoryCallStore()); + CountingAppends store = new(new InMemoryConversationStore()); await store.CreateAsync("c1", Token); // Act await store.AppendAsync( - "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hi"), "m0")], cancellationToken: Token); + "c1", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hi"), "m0")], cancellationToken: Token); // Assert Assert.Equal(1, store.Appends); @@ -48,13 +48,13 @@ await store.AppendAsync( public async Task AMethodNotOverridden_ReachesTheInnerStoreUnchanged() { // Arrange - CountingAppends store = new(new InMemoryCallStore()); + CountingAppends store = new(new InMemoryConversationStore()); // Act - var call = await store.CreateAsync("c1", Token); + var conversation = await store.CreateAsync("c1", Token); // Assert - Assert.Equal("c1", call.CallId); + Assert.Equal("c1", conversation.ConversationId); Assert.Equal(0, store.Appends); } } diff --git a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs b/tests/AgentCore.Application.Tests/Conversation/InMemoryConversationStoreTests.cs similarity index 64% rename from tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs rename to tests/AgentCore.Application.Tests/Conversation/InMemoryConversationStoreTests.cs index 8a2b751d..7a9e0dee 100644 --- a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/InMemoryConversationStoreTests.cs @@ -1,37 +1,37 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Transcript; using AgentCore.Application.Tests.Runtime; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; /// Store 0, kept in this process. -public sealed class InMemoryCallStoreTests +public sealed class InMemoryConversationStoreTests { private static CancellationToken Token => TestContext.Current.CancellationToken; [Fact] - public async Task CreateAsync_TheSameIdTwice_IsOneCall() + public async Task CreateAsync_TheSameIdTwice_IsOneConversation() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); // Act var first = await store.CreateAsync("c1", Token); var second = await store.CreateAsync("c1", Token); // Assert - Assert.Equal(first.CallId, second.CallId); + Assert.Equal(first.ConversationId, second.ConversationId); Assert.Equal(first.CreatedAt, second.CreatedAt); } [Fact] - public async Task GetAsync_ACallThatWasNeverMade_IsNull() + public async Task GetAsync_AConversationThatWasNeverMade_IsNull() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); // Act var found = await store.GetAsync("missing", Token); @@ -41,10 +41,10 @@ public async Task GetAsync_ACallThatWasNeverMade_IsNull() } [Fact] - public async Task RenameAsync_ACall_ChangesOnlyItsTitle() + public async Task RenameAsync_AConversation_ChangesOnlyItsTitle() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); // Act @@ -53,29 +53,29 @@ public async Task RenameAsync_ACall_ChangesOnlyItsTitle() // Assert var found = await store.GetAsync("c1", Token); Assert.Equal("A squeaky belt", found!.Title); - Assert.Equal(CallStatus.Regular, found.Status); + Assert.Equal(ConversationStatus.Regular, found.Status); } [Fact] - public async Task ListAsync_APrincipalWithNoCalls_IsEmptyAndHasNoCursor() + public async Task ListAsync_APrincipalWithNoConversations_IsEmptyAndHasNoCursor() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); // Act var page = await store.ListAsync("nobody", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Empty(page.Calls); + Assert.Empty(page.Conversations); Assert.Null(page.NextCursor); } [Fact] - public async Task ListAsync_AnotherPrincipalsCall_IsNotReturned() + public async Task ListAsync_AnotherPrincipalsConversation_IsNotReturned() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("mine", Token); await store.CreateAsync("theirs", Token); await store.AttachPrincipalAsync("mine", "person-a", "caller", Token); @@ -85,14 +85,14 @@ public async Task ListAsync_AnotherPrincipalsCall_IsNotReturned() var page = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Equal(["mine"], page.Calls.Select(call => call.CallId)); + Assert.Equal(["mine"], page.Conversations.Select(conversation => conversation.ConversationId)); } [Fact] - public async Task ListAsync_TwoKeysOnOneCall_FindsItByEither() + public async Task ListAsync_TwoKeysOnOneConversation_FindsItByEither() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "tenant-a", "tenant", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -102,15 +102,15 @@ public async Task ListAsync_TwoKeysOnOneCall_FindsItByEither() var byPerson = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Single(byTenant.Calls); - Assert.Single(byPerson.Calls); + Assert.Single(byTenant.Conversations); + Assert.Single(byPerson.Conversations); } [Fact] public async Task AttachPrincipalAsync_TheSamePairTwice_IsOneAttachment() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); // Act @@ -119,14 +119,14 @@ public async Task AttachPrincipalAsync_TheSamePairTwice_IsOneAttachment() // Assert var page = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); - Assert.Single(page.Calls); + Assert.Single(page.Conversations); } [Fact] - public async Task DetachPrincipalAsync_TheOnlyKey_LeavesTheCallUnlisted() + public async Task DetachPrincipalAsync_TheOnlyKey_LeavesTheConversationUnlisted() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -134,33 +134,33 @@ public async Task DetachPrincipalAsync_TheOnlyKey_LeavesTheCallUnlisted() await store.DetachPrincipalAsync("c1", "person-a", Token); // Assert - Assert.Empty((await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token)).Calls); + Assert.Empty((await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token)).Conversations); Assert.NotNull(await store.GetAsync("c1", Token)); } [Fact] - public async Task ListAsync_ArchivedCalls_AreOutOfARegularListing() + public async Task ListAsync_ArchivedConversations_AreOutOfARegularListing() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); - await store.SetStatusAsync("c1", CallStatus.Archived, Token); + await store.SetStatusAsync("c1", ConversationStatus.Archived, Token); // Act - var regular = await store.ListAsync("person-a", after: null, limit: 10, CallStatus.Regular, Token); + var regular = await store.ListAsync("person-a", after: null, limit: 10, ConversationStatus.Regular, Token); var everything = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Empty(regular.Calls); - Assert.Single(everything.Calls); + Assert.Empty(regular.Conversations); + Assert.Single(everything.Conversations); } [Fact] - public async Task ListAsync_MoreCallsThanTheLimit_PagesWithNoGapAndNoRepeat() + public async Task ListAsync_MoreConversationsThanTheLimit_PagesWithNoGapAndNoRepeat() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); for (var i = 0; i < 5; i++) { await store.CreateAsync($"c{i}", Token); @@ -173,7 +173,7 @@ public async Task ListAsync_MoreCallsThanTheLimit_PagesWithNoGapAndNoRepeat() do { var page = await store.ListAsync("person-a", cursor, limit: 2, cancellationToken: Token); - seen.AddRange(page.Calls.Select(call => call.CallId)); + seen.AddRange(page.Conversations.Select(conversation => conversation.ConversationId)); cursor = page.NextCursor; } while (cursor is not null); @@ -187,7 +187,7 @@ public async Task ListAsync_MoreCallsThanTheLimit_PagesWithNoGapAndNoRepeat() public async Task SetExternalIdAsync_AConsumersOwnId_IsReadBack() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); // Act @@ -201,7 +201,7 @@ public async Task SetExternalIdAsync_AConsumersOwnId_IsReadBack() public async Task SetExternalIdAsync_Null_ClearsTheId() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.SetExternalIdAsync("c1", "crm-77", Token); @@ -213,10 +213,10 @@ public async Task SetExternalIdAsync_Null_ClearsTheId() } [Fact] - public async Task DeleteAsync_ACall_TakesItsAttachmentsWithIt() + public async Task DeleteAsync_AConversation_TakesItsAttachmentsWithIt() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -225,35 +225,35 @@ public async Task DeleteAsync_ACall_TakesItsAttachmentsWithIt() // Assert Assert.Null(await store.GetAsync("c1", Token)); - Assert.Empty((await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token)).Calls); + Assert.Empty((await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token)).Conversations); } [Fact] - public async Task DeleteAsync_ACall_TakesItsResumeStateWithIt() + public async Task DeleteAsync_AConversation_TakesItsResumeStateWithIt() { // Arrange — the state lives beside the row rather than on it, so it has to be forgotten by - // hand. In PostgreSQL it is a column of the call row and DELETE FROM call takes it, and the + // hand. In PostgreSQL it is a column of the conversation row and DELETE FROM conversation takes it, and the // two backings answering differently is the defect this pins. - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); - await store.AppendAsync("c1", [Word()], new CallSessionState { Stage = "collecting" }, Token); + await store.AppendAsync("c1", [Word()], new ConversationSessionState { Stage = "collecting" }, Token); // Act await store.DeleteAsync("c1", Token); - // Assert — a call made again under the same id is a NEW call, not the dead one resurrected + // Assert — a conversation made again under the same id is a NEW conversation, not the dead one resurrected // with its stage and the caller data the extractor left in its slots. Assert.Null((await store.CreateAsync("c1", Token)).State); } [Fact] - public async Task DeleteAsync_ACall_TakesItsSameIdContinuationWithIt() + public async Task DeleteAsync_AConversation_TakesItsSameIdContinuationWithIt() { - // Arrange — one id plays three roles now: the conversation, the call, and the continuation - // key. Deleting the call must forget the key or the next thread turn resumes the dead call. - InMemoryCallStore store = new(); + // Arrange — one id plays three roles now: the conversation, the conversation, and the continuation + // key. Deleting the conversation must forget the key or the next thread turn resumes the dead conversation. + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); - using var document = System.Text.Json.JsonDocument.Parse("""{ "callId": "c1" }"""); + using var document = System.Text.Json.JsonDocument.Parse("""{ "conversationId": "c1" }"""); await store.SaveContinuationAsync("c1", document.RootElement, Token); // Act @@ -264,14 +264,14 @@ public async Task DeleteAsync_ACall_TakesItsSameIdContinuationWithIt() } [Fact] - public async Task SweepAsync_ACallPastRetention_TakesItsResumeStateWithIt() + public async Task SweepAsync_AConversationPastRetention_TakesItsResumeStateWithIt() { - // Arrange — retention is the promise that a call stops existing, and slots hold what the + // Arrange — retention is the promise that a conversation stops existing, and slots hold what the // extractor took from the caller, so state left behind is data kept past the promise. TestTimeProvider clock = new(); - InMemoryCallStore store = new(clock); + InMemoryConversationStore store = new(clock); await store.CreateAsync("c1", Token); - await store.AppendAsync("c1", [Word()], new CallSessionState { Stage = "collecting" }, Token); + await store.AppendAsync("c1", [Word()], new ConversationSessionState { Stage = "collecting" }, Token); // Act clock.Advance(TimeSpan.FromDays(2)); @@ -282,6 +282,6 @@ public async Task SweepAsync_ACallPastRetention_TakesItsResumeStateWithIt() Assert.Null((await store.CreateAsync("c1", Token)).State); } - private static CallMessageDraft Word() + private static ConversationMessageDraft Word() => new(0, new ChatMessage(ChatRole.User, "hello"), "m0"); } diff --git a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs b/tests/AgentCore.Application.Tests/Conversation/InMemoryConversationStoreTranscriptTests.cs similarity index 56% rename from tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs rename to tests/AgentCore.Application.Tests/Conversation/InMemoryConversationStoreTranscriptTests.cs index 69122ea5..0ff7a2bc 100644 --- a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/InMemoryConversationStoreTranscriptTests.cs @@ -1,12 +1,12 @@ -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Calls; +namespace AgentCore.Application.Tests.Conversation; /// The words half of store 0, now that one store holds both halves. -public sealed class InMemoryCallStoreTranscriptTests +public sealed class InMemoryConversationStoreTranscriptTests { private static CancellationToken Token => TestContext.Current.CancellationToken; @@ -14,15 +14,15 @@ public sealed class InMemoryCallStoreTranscriptTests public async Task ReadAsync_AfterAppend_ReturnsTheRowsOldestFirst() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); // Act await store.AppendAsync( "c1", [ - new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0"), - new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "hi"), "m1"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.Assistant, "hi"), "m1"), ], cancellationToken: Token); // Assert @@ -36,11 +36,11 @@ await store.AppendAsync( public async Task RewriteAsync_AnExistingMessage_ReplacesItsContent() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AppendAsync( "c1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "long reply"), "m0")], + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.Assistant, "long reply"), "m0")], cancellationToken: Token); // Act @@ -52,16 +52,16 @@ await store.AppendAsync( } [Fact] - public async Task EraseAsync_ACallWithWords_RemovesThemAndReportsTheCount() + public async Task EraseAsync_AConversationWithWords_RemovesThemAndReportsTheCount() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.CreateAsync("c2", Token); await store.AppendAsync( - "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "a"), "m0")], cancellationToken: Token); + "c1", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "a"), "m0")], cancellationToken: Token); await store.AppendAsync( - "c2", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "b"), "m0")], cancellationToken: Token); + "c2", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "b"), "m0")], cancellationToken: Token); // Act var erased = await store.EraseAsync("c1", Token); @@ -73,34 +73,34 @@ await store.AppendAsync( } [Fact] - public async Task GetAsync_AfterAppend_ReportsWhenTheCallWasLastSpokenOn() + public async Task GetAsync_AfterAppend_ReportsWhenTheConversationWasLastSpokenOn() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); // Act await store.AppendAsync( - "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], cancellationToken: Token); + "c1", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], cancellationToken: Token); // Assert - var call = await store.GetAsync("c1", Token); - Assert.NotNull(call); - Assert.NotNull(call.LastMessageAt); + var conversation = await store.GetAsync("c1", Token); + Assert.NotNull(conversation); + Assert.NotNull(conversation.LastMessageAt); } [Fact] - public async Task ReadAsync_ACallWithMessages_ReturnsThemOldestFirst() + public async Task ReadAsync_AConversationWithMessages_ReturnsThemOldestFirst() { // Arrange — the store numbers rows in draft order, so this pins the read order against the // ordinal the store assigned rather than against the order the drafts happened to list. - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AppendAsync( "c1", [ - new CallMessageDraft(0, new ChatMessage(ChatRole.User, "first"), "m0"), - new CallMessageDraft(0, new ChatMessage(ChatRole.User, "second"), "m1"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "first"), "m0"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "second"), "m1"), ], cancellationToken: Token); @@ -113,10 +113,10 @@ await store.AppendAsync( } [Fact] - public async Task ReadAsync_ACallThatHoldsNothing_IsEmpty() + public async Task ReadAsync_AConversationThatHoldsNothing_IsEmpty() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); // Act var rows = await store.ReadAsync("missing", Token); @@ -126,16 +126,16 @@ public async Task ReadAsync_ACallThatHoldsNothing_IsEmpty() } [Fact] - public async Task ReadAsync_AnotherCallsMessages_AreNotReturned() + public async Task ReadAsync_AnotherConversationsMessages_AreNotReturned() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.CreateAsync("c2", Token); await store.AppendAsync( - "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "mine"), "m0")], cancellationToken: Token); + "c1", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "mine"), "m0")], cancellationToken: Token); await store.AppendAsync( - "c2", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); + "c2", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); // Act var rows = await store.ReadAsync("c1", Token); @@ -145,16 +145,16 @@ await store.AppendAsync( } [Fact] - public async Task EraseAsync_ACall_TakesEveryRowAndReportsHowMany() + public async Task EraseAsync_AConversation_TakesEveryRowAndReportsHowMany() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.AppendAsync( "c1", [ - new CallMessageDraft(0, new ChatMessage(ChatRole.User, "one"), "m0"), - new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "two"), "m1"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "one"), "m0"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.Assistant, "two"), "m1"), ], cancellationToken: Token); @@ -167,16 +167,16 @@ await store.AppendAsync( } [Fact] - public async Task EraseAsync_ACall_LeavesEveryOtherCallAlone() + public async Task EraseAsync_AConversation_LeavesEveryOtherConversationAlone() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("c1", Token); await store.CreateAsync("c2", Token); await store.AppendAsync( - "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "mine"), "m0")], cancellationToken: Token); + "c1", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "mine"), "m0")], cancellationToken: Token); await store.AppendAsync( - "c2", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); + "c2", [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); // Act await store.EraseAsync("c1", Token); diff --git a/tests/AgentCore.Application.Tests/Calls/Memory/InMemoryCallStoreAppendTests.cs b/tests/AgentCore.Application.Tests/Conversation/Memory/InMemoryConversationStoreAppendTests.cs similarity index 76% rename from tests/AgentCore.Application.Tests/Calls/Memory/InMemoryCallStoreAppendTests.cs rename to tests/AgentCore.Application.Tests/Conversation/Memory/InMemoryConversationStoreAppendTests.cs index c1df5f71..b65c97c6 100644 --- a/tests/AgentCore.Application.Tests/Calls/Memory/InMemoryCallStoreAppendTests.cs +++ b/tests/AgentCore.Application.Tests/Conversation/Memory/InMemoryConversationStoreAppendTests.cs @@ -1,28 +1,28 @@ using System.Text.RegularExpressions; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Ports; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Calls.Memory; +namespace AgentCore.Application.Tests.Conversation.Memory; /// -/// The store numbers every row from the call's own counter, in memory: the seam that lets a host -/// append to a call from outside any turn, whether or not a session for the call is live. +/// The store numbers every row from the conversation's own counter, in memory: the seam that lets a host +/// append to a conversation from outside any turn, whether or not a session for the conversation is live. /// -#pragma warning disable CA1859 // store is typed as ICallStore throughout: AppendAsync(callId, message, ct) +#pragma warning disable CA1859 // store is typed as IConversationStore throughout: AppendAsync(conversationId, message, ct) // is a default interface method, and only resolves through the interface type. -public sealed partial class InMemoryCallStoreAppendTests +public sealed partial class InMemoryConversationStoreAppendTests { private static CancellationToken Token => TestContext.Current.CancellationToken; [Fact] - public async Task AppendAsync_OneMessage_OnAFreshCall_IsOrdinalZeroAndTurnZero() + public async Task AppendAsync_OneMessage_OnAFreshConversation_IsOrdinalZeroAndTurnZero() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); // Act @@ -38,7 +38,7 @@ public async Task AppendAsync_OneMessage_OnAFreshCall_IsOrdinalZeroAndTurnZero() public async Task AppendAsync_OneMessage_WithItsOwnId_KeepsIt() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); ChatMessage message = new(ChatRole.User, "hello") { MessageId = "caller-named" }; @@ -53,7 +53,7 @@ public async Task AppendAsync_OneMessage_WithItsOwnId_KeepsIt() public async Task AppendAsync_TwoOutsideAppends_AreNumberedZeroThenOne() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); // Act @@ -63,19 +63,19 @@ public async Task AppendAsync_TwoOutsideAppends_AreNumberedZeroThenOne() // Assert Assert.Equal(0, first.Ordinal); Assert.Equal(1, second.Ordinal); - var call = await store.GetAsync("c1", Token); - Assert.Equal(2, call?.NextOrdinal); + var conversation = await store.GetAsync("c1", Token); + Assert.Equal(2, conversation?.NextOrdinal); } [Fact] public async Task AppendAsync_ABatchWithAnExplicitTurnIndex_NumbersThreeConsecutiveRowsInDraftOrder() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "outside"), Token); - CallMessageDraft[] drafts = + ConversationMessageDraft[] drafts = [ new(4, new ChatMessage(ChatRole.User, "a"), "m-a"), new(4, new ChatMessage(ChatRole.Assistant, "b"), "m-b"), @@ -95,12 +95,12 @@ public async Task AppendAsync_ABatchWithAnExplicitTurnIndex_NumbersThreeConsecut public async Task AppendAsync_OutsideAppend_AfterABatchThatWroteState_IsStampedWithTheStoredNextTurnIndex() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); await store.AppendAsync( "c1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { NextTurnIndex = 7 }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { NextTurnIndex = 7 }, Token); // Act @@ -111,10 +111,10 @@ await store.AppendAsync( } [Fact] - public async Task AppendAsync_ACallThatDoesNotExist_ThrowsNamingIt() + public async Task AppendAsync_AConversationThatDoesNotExist_ThrowsNamingIt() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); // Act var failure = await Record.ExceptionAsync( @@ -129,7 +129,7 @@ public async Task AppendAsync_ACallThatDoesNotExist_ThrowsNamingIt() public async Task RewriteAsync_OneRow_ChangesOnlyThatRowsContent() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "first") { MessageId = "m0" }, Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "second") { MessageId = "m1" }, Token); @@ -146,7 +146,7 @@ public async Task RewriteAsync_OneRow_ChangesOnlyThatRowsContent() public async Task AppendAsync_AfterATruncate_NeverReusesTheOrdinalsItTook() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "zero"), Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "one"), Token); @@ -164,7 +164,7 @@ public async Task AppendAsync_AfterATruncate_NeverReusesTheOrdinalsItTook() public async Task ReadAsync_ARowWithAdditionalProperties_KeepsThemAcrossTheRoundTrip() { // Arrange - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); await store.CreateAsync("c1", Token); ChatMessage message = new(ChatRole.User, "hello") { diff --git a/tests/AgentCore.Application.Tests/Diagnostics/DiagnosticsFakes.cs b/tests/AgentCore.Application.Tests/Diagnostics/DiagnosticsFakes.cs index 1608946a..726b261c 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/DiagnosticsFakes.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/DiagnosticsFakes.cs @@ -103,7 +103,7 @@ public async ValueTask AppendAsync(AuditEvent auditEvent, CancellationToken canc /// A sink that refuses every event. /// /// -/// Audit is a record of the call and never a part of it, so a sink that fails must be reported and +/// Audit is a record of the conversation and never a part of it, so a sink that fails must be reported and /// the turn must go on. /// internal sealed class ThrowingAuditSink : IAuditSinkPort diff --git a/tests/AgentCore.Application.Tests/Diagnostics/LibraryOpenTelemetryTests.cs b/tests/AgentCore.Application.Tests/Diagnostics/LibraryOpenTelemetryTests.cs index c75ad475..50719b6b 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/LibraryOpenTelemetryTests.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/LibraryOpenTelemetryTests.cs @@ -29,7 +29,7 @@ namespace AgentCore.Application.Tests.Diagnostics; /// the compiled pipeline actually does. /// /// -/// Every agent id and call id here is unique per test run (a fresh ), because an +/// Every agent id and conversation id here is unique per test run (a fresh ), because an /// subscribes to the whole process and another test class may run /// beside this one on the same two library sources. /// @@ -202,13 +202,13 @@ public void EveryCompiledAgent_KeepsSensitiveDataCaptureOffOnBothLayers() // OpenTelemetryAgent.EnableSensitiveData otherwise defaults to // TelemetryHelpers.EnableSensitiveDataDefault, which reads // OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT from the environment. This repo carries - // live customer phone calls, so ConfigurationCompiler forces it false explicitly rather than + // live customer phone conversations, so ConfigurationCompiler forces it false explicitly rather than // trusting that variable to stay unset. Assert.False(otelAgent.EnableSensitiveData); // The chat-level layer WithToolFailureAuditing wires in below AuditingFunctionInvokingChatClient // is a second, independent OpenTelemetryChatClient instance with its own EnableSensitiveData, - // and it is forced off the same way, at the same call site. + // and it is forced off the same way, at the same conversation site. var chatClient = compiled.Agent.GetService(); Assert.NotNull(chatClient); Assert.False(chatClient.EnableSensitiveData); @@ -219,20 +219,20 @@ public void EveryCompiledAgent_KeepsSensitiveDataCaptureOffOnBothLayers() // ------------------------------------------------------------------------------------------- /// - /// The call id reaches a trace once, from AgentCoreTelemetry.StartTurn. + /// The conversation id reaches a trace once, from AgentCoreTelemetry.StartTurn. /// /// - /// Naming the call on ChatOptions.ConversationId would put the attribute on the library's + /// Naming the conversation on ChatOptions.ConversationId would put the attribute on the library's /// children as well, and it is the one thing that must not be done to get it. To /// ChatClientAgent a conversation id means the SERVICE keeps the history, so it answers by /// ignoring the agent's own ChatHistoryProvider for the whole run — store 1, silently /// gone. Keeping it then costs a per-run override of the provider and /// ThrowOnChatHistoryProviderConflict = false on every compiled agent. The attribute is - /// not worth a disabled safety check: a reader that wants the call id of a child span walks up + /// not worth a disabled safety check: a reader that wants the conversation id of a child span walks up /// the trace to agentcore.turn. /// [Fact] - public async Task ASingleAgentTurn_CarriesTheCallIdOnTheTurnSpanAndOnNeitherLibrarySpan() + public async Task ASingleAgentTurn_CarriesTheConversationIdOnTheTurnSpanAndOnNeitherLibrarySpan() { var agentId = "agent-" + Guid.NewGuid().ToString("N"); var yaml = $$""" @@ -250,8 +250,8 @@ public async Task ASingleAgentTurn_CarriesTheCallIdOnTheTurnSpanAndOnNeitherLibr using var turns = ListenTo(spans, AgentCoreTelemetry.ActivitySourceName); using ToolCallingChatClient client = new("hello there."); - var callId = "call-" + Guid.NewGuid().ToString("N"); - var session = Build(yaml, client, tools: null).Create(callId); + var conversationId = "conversation-" + Guid.NewGuid().ToString("N"); + var session = Build(yaml, client, tools: null).Create(conversationId); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -270,7 +270,7 @@ public async Task ASingleAgentTurn_CarriesTheCallIdOnTheTurnSpanAndOnNeitherLibr span => span.DisplayName == AgentCoreTelemetry.TurnActivityName && string.Equals(span.Id, invokeAgent.ParentId, StringComparison.Ordinal)); - Assert.Equal(callId, turn.GetTagItem("gen_ai.conversation.id")); + Assert.Equal(conversationId, turn.GetTagItem("gen_ai.conversation.id")); Assert.Null(invokeAgent.GetTagItem("gen_ai.conversation.id")); Assert.Null(chat.GetTagItem("gen_ai.conversation.id")); } @@ -284,10 +284,10 @@ public async Task ASingleAgentTurn_CarriesTheCallIdOnTheTurnSpanAndOnNeitherLibr /// One turn makes two model calls, and both of them emit a chat span. /// /// - /// CallSessionTests.ATurn_MakesTwoModelCalls_TheReplyAndTheExtractor proves the two calls - /// happen. This proves both are instrumented. Until CallSessionFactory.CreateExtractor + /// ConversationSessionTests.ATurn_MakesTwoModelCalls_TheReplyAndTheExtractor proves the two conversations + /// happen. This proves both are instrumented. Until ConversationSessionFactory.CreateExtractor /// wrapped the client it resolves, only the reply had a span: the extractor's duration, its token - /// usage, and its failures reached no exporter at all, so a two-turn call reported half the model + /// usage, and its failures reached no exporter at all, so a two-turn conversation reported half the model /// calls it made and roughly a third less spend than it cost. /// [Fact] @@ -313,7 +313,7 @@ public async Task ATurnWithAnExtractor_EmitsAChatSpanForTheExtractorCallAndNotOn model: { ref: reply } items: - { id: {{greeterId}}, instructions: "greet the caller" } - - { id: {{closerId}}, instructions: "close the call" } + - { id: {{closerId}}, instructions: "close the conversation" } entries: main: policy: @@ -334,8 +334,8 @@ public async Task ATurnWithAnExtractor_EmitsAChatSpanForTheExtractorCallAndNotOn using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new("""{ "callerSaidGoodbye": null }"""); - var callId = "call-" + Guid.NewGuid().ToString("N"); - var session = BuildWithExtractor(yaml, reply, fill).Create(callId); + var conversationId = "conversation-" + Guid.NewGuid().ToString("N"); + var session = BuildWithExtractor(yaml, reply, fill).Create(conversationId); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -346,11 +346,11 @@ public async Task ATurnWithAnExtractor_EmitsAChatSpanForTheExtractorCallAndNotOn var mine = Snapshot(spans); - // Scoped by this run's own call id, because the listener subscribes to the whole process. + // Scoped by this run's own conversation id, because the listener subscribes to the whole process. var turn = Assert.Single( mine, span => span.DisplayName == AgentCoreTelemetry.TurnActivityName - && string.Equals((string?)span.GetTagItem("gen_ai.conversation.id"), callId, StringComparison.Ordinal)); + && string.Equals((string?)span.GetTagItem("gen_ai.conversation.id"), conversationId, StringComparison.Ordinal)); var invokeAgent = Assert.Single( mine, @@ -363,7 +363,7 @@ public async Task ATurnWithAnExtractor_EmitsAChatSpanForTheExtractorCallAndNotOn span => IsChatRoundSpan(span) && string.Equals(span.ParentId, invokeAgent.Id, StringComparison.Ordinal)); // The extractor's chat span is the one this test exists for. It hangs directly off the turn - // span and not off invoke_agent, because CallSession runs the extractor after the agent's run + // span and not off invoke_agent, because ConversationSession runs the extractor after the agent's run // has finished and its spans have closed, with Activity.Current back at agentcore.turn. var extractorChat = Assert.Single( mine, @@ -427,7 +427,7 @@ private static List Snapshot(List spans) } } - private static CallSessionFactory Build(string yaml, IChatClient client, Func? tools) + private static ConversationSessionFactory Build(string yaml, IChatClient client, Func? tools) { var document = ConfigurationLoader.LoadYaml(yaml); FakeChatClientFactory factory = new(client); @@ -439,29 +439,29 @@ private static CallSessionFactory Build(string yaml, IChatClient client, FuncBuilds a factory for a document that declares an extractor, scripting the two models /// apart on the ref names the document uses. - private static CallSessionFactory BuildWithExtractor(string yaml, IChatClient reply, IChatClient fill) + private static ConversationSessionFactory BuildWithExtractor(string yaml, IChatClient reply, IChatClient fill) { var document = ConfigurationLoader.LoadYaml(yaml); var factory = new RoutingChatClientFactory(reply).Route("fill", fill); var compiled = ConfigurationCompiler.CompileAll(document, new AgentCompilationContext(factory))["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, factory), + ConversationSessionFactory.CreateExtractor(compiled, factory), timeProvider: null, logger: null, - CallObservers.Standard(new InMemoryAuditSink(), logger: null)); + ConversationObservers.Standard(new InMemoryAuditSink(), logger: null)); } } diff --git a/tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs b/tests/AgentCore.Application.Tests/Diagnostics/LoggingConversationObserverTests.cs similarity index 61% rename from tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs rename to tests/AgentCore.Application.Tests/Diagnostics/LoggingConversationObserverTests.cs index 23928eda..570cd54b 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/LoggingConversationObserverTests.cs @@ -10,14 +10,14 @@ namespace AgentCore.Application.Tests.Diagnostics; /// The "log once" rows of section 8.7, written from a fact instead of from the turn loop. /// /// -/// Moving the call sites behind the hook must change neither the text an operator greps for nor how +/// Moving the conversation sites behind the hook must change neither the text an operator greps for nor how /// often it appears, so these tests pin the event id, the level, and the fields of each of the six -/// lines. They also pin the six kinds that write nothing here: a normal call is recorded by the chain +/// lines. They also pin the six kinds that write nothing here: a normal conversation is recorded by the chain /// of D23, and a log is not. /// -public sealed class LoggingCallObserverTests +public sealed class LoggingConversationObserverTests { - private const string CallId = "call-1"; + private const string ConversationId = "conversation-1"; /// The ids the source-generated methods carry. They are unchanged by the hook. private const int ExtractionFailedEventId = 1; @@ -28,19 +28,19 @@ public sealed class LoggingCallObserverTests private const int StateRestorePartialEventId = 13; /// The kinds this observer writes no line for. - public static TheoryData QuietKinds => + public static TheoryData QuietKinds => [ - CallEventKind.CallStarted, - CallEventKind.TurnCompleted, - CallEventKind.ReplyInterrupted, - CallEventKind.CallEnded, + ConversationEventKind.ConversationStarted, + ConversationEventKind.TurnCompleted, + ConversationEventKind.ReplyInterrupted, + ConversationEventKind.ConversationEnded, // Logged, but not here: the line is written where the write was refused, which is the only // place the exception still exists. A line from this observer too would double it. - CallEventKind.TranscriptWriteFailed, + ConversationEventKind.TranscriptWriteFailed, // The quietest of them all: counted, and not logged anywhere. - CallEventKind.ModerationClean, + ConversationEventKind.ModerationClean, ]; [Fact] @@ -50,13 +50,13 @@ public async Task ASpentToolBudget_IsAnErrorNamingTheTurnAndTheFault() await Observe( logger, - Event(CallEventKind.ToolFailed, turnIndex: 2, AuditPayloadKeys.ToolError, "the CRM refused.")); + Event(ConversationEventKind.ToolFailed, turnIndex: 2, AuditPayloadKeys.ToolError, "the CRM refused.")); var line = Assert.Single(logger.Of(ToolBudgetSpentEventId)); Assert.Equal(LogLevel.Error, line.Level); Assert.Equal( - "A tool of call call-1 failed four times in turn 2: the CRM refused. " - + "The turn spoke the fallback and the call continues.", + "A tool of conversation conversation-1 failed four times in turn 2: the CRM refused. " + + "The turn spoke the fallback and the conversation continues.", line.Message); } @@ -65,12 +65,12 @@ public async Task AQuietRun_IsAWarningNamingTheTurn() { RecordingLogger logger = new(); - await Observe(logger, Event(CallEventKind.EmptyReply, turnIndex: 3)); + await Observe(logger, Event(ConversationEventKind.EmptyReply, turnIndex: 3)); var line = Assert.Single(logger.Of(EmptyReplyEventId)); Assert.Equal(LogLevel.Warning, line.Level); Assert.Equal( - "Turn 3 of call call-1 returned an empty reply, so it spoke the fallback. " + "Turn 3 of conversation conversation-1 returned an empty reply, so it spoke the fallback. " + "The run reached 40 tool rounds, or the model answered nothing.", line.Message); } @@ -80,16 +80,16 @@ public async Task AnExtractorThatProducedNothing_IsAWarningAndNeverAnError() { RecordingLogger logger = new(); - // Row two: the slots stay unchanged and the call continues. + // Row two: the slots stay unchanged and the conversation continues. await Observe( logger, - Event(CallEventKind.ExtractionFailed, turnIndex: 0, CallEventPayloadKeys.Reason, "it timed out.")); + Event(ConversationEventKind.ExtractionFailed, turnIndex: 0, ConversationEventPayloadKeys.Reason, "it timed out.")); var line = Assert.Single(logger.Of(ExtractionFailedEventId)); Assert.Equal(LogLevel.Warning, line.Level); Assert.Equal( - "The extractor of call call-1 produced nothing for turn 0: it timed out. " - + "The slots stay unchanged and the call continues.", + "The extractor of conversation conversation-1 produced nothing for turn 0: it timed out. " + + "The slots stay unchanged and the conversation continues.", line.Message); } @@ -101,7 +101,7 @@ public async Task ARefusedPrompt_ReportsTheCategoriesAndNeverTheWords() await Observe( logger, Event( - CallEventKind.PromptFlagged, + ConversationEventKind.PromptFlagged, turnIndex: 1, AuditPayloadKeys.ModerationCategories, "harassment,violence")); @@ -109,7 +109,7 @@ await Observe( var line = Assert.Single(logger.Of(PromptRefusedEventId)); Assert.Equal(LogLevel.Warning, line.Level); Assert.Equal( - "Moderation flagged turn 1 of call call-1 for harassment,violence, " + "Moderation flagged turn 1 of conversation conversation-1 for harassment,violence, " + "so the agent refused it and spoke the refusal line.", line.Message); } @@ -122,46 +122,46 @@ public async Task AModerationEndpointThatDidNotAnswer_IsAWarningBecauseTheVendor await Observe( logger, Event( - CallEventKind.ModerationUnavailable, + ConversationEventKind.ModerationUnavailable, turnIndex: 4, - CallEventPayloadKeys.Reason, + ConversationEventPayloadKeys.Reason, "it did not answer within 500 ms.")); var line = Assert.Single(logger.Of(ModerationUnavailableEventId)); Assert.Equal(LogLevel.Warning, line.Level); Assert.Equal( - "Moderation did not answer for turn 4 of call call-1 (it did not answer within 500 ms.). " + "Moderation did not answer for turn 4 of conversation conversation-1 (it did not answer within 500 ms.). " + "The turn ran unchecked, because moderation fails open.", line.Message); } [Fact] - public async Task APartialStateRestore_IsAWarningNamingTheCallAndWhatItLost() + public async Task APartialStateRestore_IsAWarningNamingTheConversationAndWhatItLost() { RecordingLogger logger = new(); - // No turn index: the call is still opening. It is documented as logged, and until this line - // existed it was not — a document change that cost every resumed call its stage produced no + // No turn index: the conversation is still opening. It is documented as logged, and until this line + // existed it was not — a document change that cost every resumed conversation its stage produced no // line and no metric, and six tests of the restore itself passed straight over the silence. await Observe( logger, Event( - CallEventKind.StateRestorePartial, + ConversationEventKind.StateRestorePartial, turnIndex: null, - CallEventPayloadKeys.Reason, + ConversationEventPayloadKeys.Reason, "the document no longer declares the slot 'model'.")); var line = Assert.Single(logger.Of(StateRestorePartialEventId)); Assert.Equal(LogLevel.Warning, line.Level); Assert.Equal( - "Call call-1 could not restore part of its stored state: the document no longer declares " - + "the slot 'model'. The call resumes without that part.", + "Conversation conversation-1 could not restore part of its stored state: the document no longer declares " + + "the slot 'model'. The conversation resumes without that part.", line.Message); } [Theory] [MemberData(nameof(QuietKinds))] - public async Task AKindTheChainRecords_WritesNoLine(CallEventKind kind) + public async Task AKindTheChainRecords_WritesNoLine(ConversationEventKind kind) { RecordingLogger logger = new(); @@ -174,8 +174,8 @@ public async Task AKindTheChainRecords_WritesNoLine(CallEventKind kind) public async Task NoLogger_IsStillAnObserver() { // The library never throws for want of one. - var pending = new LoggingCallObserver().OnCallEventAsync( - Event(CallEventKind.EmptyReply, turnIndex: 0), + var pending = new LoggingConversationObserver().OnConversationEventAsync( + Event(ConversationEventKind.EmptyReply, turnIndex: 0), TestContext.Current.CancellationToken); await pending; @@ -185,19 +185,19 @@ public async Task NoLogger_IsStillAnObserver() [Fact] public async Task NoEvent_IsRefused() => await Assert.ThrowsAsync(async () => - await new LoggingCallObserver() - .OnCallEventAsync(null!, TestContext.Current.CancellationToken)); + await new LoggingConversationObserver() + .OnConversationEventAsync(null!, TestContext.Current.CancellationToken)); - private static async Task Observe(ILogger logger, CallEvent callEvent) + private static async Task Observe(ILogger logger, ConversationEvent conversationEvent) { - LoggingCallObserver observer = new(logger); + LoggingConversationObserver observer = new(logger); // The observer never waits, so this always completes on this thread. It is awaited anyway, // because the port says nothing about which of the two it does. - await observer.OnCallEventAsync(callEvent, TestContext.Current.CancellationToken); + await observer.OnConversationEventAsync(conversationEvent, TestContext.Current.CancellationToken); } - private static CallEvent Event(CallEventKind kind, int? turnIndex, string? key = null, string? detail = null) + private static ConversationEvent Event(ConversationEventKind kind, int? turnIndex, string? key = null, string? detail = null) { Dictionary payload = new(StringComparer.Ordinal); if (key is not null && detail is not null) @@ -205,9 +205,9 @@ private static CallEvent Event(CallEventKind kind, int? turnIndex, string? key = payload[key] = detail; } - return new CallEvent + return new ConversationEvent { - CallId = CallId, + ConversationId = ConversationId, Kind = kind, OccurredAt = DateTimeOffset.UnixEpoch, TurnIndex = turnIndex, diff --git a/tests/AgentCore.Application.Tests/Diagnostics/TelemetryCallObserverTests.cs b/tests/AgentCore.Application.Tests/Diagnostics/TelemetryConversationObserverTests.cs similarity index 67% rename from tests/AgentCore.Application.Tests/Diagnostics/TelemetryCallObserverTests.cs rename to tests/AgentCore.Application.Tests/Diagnostics/TelemetryConversationObserverTests.cs index a67acd14..0e93fff9 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/TelemetryCallObserverTests.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/TelemetryConversationObserverTests.cs @@ -10,19 +10,19 @@ namespace AgentCore.Application.Tests.Diagnostics; /// /// /// -/// Nothing about the numbers changed when the call sites moved behind the hook, so these tests pin the +/// Nothing about the numbers changed when the conversation sites moved behind the hook, so these tests pin the /// instrument, the attribute key, and the value each kind writes. T61 is why the values are closed and -/// why no call id appears among them: a cumulative series lives forever once it is created, and the +/// why no conversation id appears among them: a cumulative series lives forever once it is created, and the /// Grafana Cloud free tier binds at 10,000. /// /// /// The meter is a process-wide singleton, so another test running beside this one measures on the same /// instruments. Every assertion here is therefore about what the observer DID write, and the negative /// side — which kinds are counted as audit events at all — is pinned on the mapping itself, in -/// CallEventKindsTests, where nothing else can add to the reading. +/// ConversationEventKindsTests, where nothing else can add to the reading. /// /// -public sealed class TelemetryCallObserverTests +public sealed class TelemetryConversationObserverTests { private const string FailureInstrument = "agentcore.turn.failures"; private const string ModerationInstrument = "agentcore.moderation.verdicts"; @@ -33,38 +33,38 @@ public sealed class TelemetryCallObserverTests private const string AuditKey = "agentcore.audit.kind"; /// Each failure kind, beside the value section 8.7 gives its row. - public static TheoryData Failures => + public static TheoryData Failures => new() { - { CallEventKind.ToolFailed, "tool" }, - { CallEventKind.EmptyReply, "empty_reply" }, - { CallEventKind.ExtractionFailed, "extraction" }, + { ConversationEventKind.ToolFailed, "tool" }, + { ConversationEventKind.EmptyReply, "empty_reply" }, + { ConversationEventKind.ExtractionFailed, "extraction" }, }; /// Each moderation verdict, beside the value an operator alerts on. - public static TheoryData Verdicts => + public static TheoryData Verdicts => new() { - { CallEventKind.PromptFlagged, "flagged" }, - { CallEventKind.ModerationClean, "clean" }, - { CallEventKind.ModerationUnavailable, "unavailable" }, + { ConversationEventKind.PromptFlagged, "flagged" }, + { ConversationEventKind.ModerationClean, "clean" }, + { ConversationEventKind.ModerationUnavailable, "unavailable" }, }; /// Each stored kind, beside the wire token the chain of D23 hashes. - public static TheoryData StoredKinds => + public static TheoryData StoredKinds => new() { - { CallEventKind.CallStarted, "call.started" }, - { CallEventKind.PromptFlagged, "prompt.flagged" }, - { CallEventKind.ToolFailed, "tool.failed" }, - { CallEventKind.TurnCompleted, "turn.completed" }, - { CallEventKind.ReplyInterrupted, "reply.interrupted" }, - { CallEventKind.CallEnded, "call.ended" }, + { ConversationEventKind.ConversationStarted, "conversation.started" }, + { ConversationEventKind.PromptFlagged, "prompt.flagged" }, + { ConversationEventKind.ToolFailed, "tool.failed" }, + { ConversationEventKind.TurnCompleted, "turn.completed" }, + { ConversationEventKind.ReplyInterrupted, "reply.interrupted" }, + { ConversationEventKind.ConversationEnded, "conversation.ended" }, }; [Theory] [MemberData(nameof(Failures))] - public async Task AFailureRow_IsCountedUnderItsOwnKind(CallEventKind kind, string expected) + public async Task AFailureRow_IsCountedUnderItsOwnKind(ConversationEventKind kind, string expected) { var measured = await MeasureAsync(kind); @@ -73,7 +73,7 @@ public async Task AFailureRow_IsCountedUnderItsOwnKind(CallEventKind kind, strin [Theory] [MemberData(nameof(Verdicts))] - public async Task AModerationVerdict_IsCountedUnderItsOwnOutcome(CallEventKind kind, string expected) + public async Task AModerationVerdict_IsCountedUnderItsOwnOutcome(ConversationEventKind kind, string expected) { var measured = await MeasureAsync(kind); @@ -82,7 +82,7 @@ public async Task AModerationVerdict_IsCountedUnderItsOwnOutcome(CallEventKind k [Theory] [MemberData(nameof(StoredKinds))] - public async Task AStoredKind_IsCountedUnderTheTokenTheChainWrites(CallEventKind kind, string expected) + public async Task AStoredKind_IsCountedUnderTheTokenTheChainWrites(ConversationEventKind kind, string expected) { var measured = await MeasureAsync(kind); @@ -92,12 +92,12 @@ public async Task AStoredKind_IsCountedUnderTheTokenTheChainWrites(CallEventKind [Fact] public async Task NoEvent_IsRefused() => await Assert.ThrowsAsync(async () => - await new TelemetryCallObserver().OnCallEventAsync(null!, TestContext.Current.CancellationToken)); + await new TelemetryConversationObserver().OnConversationEventAsync(null!, TestContext.Current.CancellationToken)); /// Hands one fact to the observer and reads back what the meter saw. /// What happened. /// Every attribute of every measurement, as instrument, key, and value. - private static async Task> MeasureAsync(CallEventKind kind) + private static async Task> MeasureAsync(ConversationEventKind kind) { List readings = []; using MeterListener listener = new(); @@ -122,10 +122,10 @@ private static async Task> MeasureAsync(CallEventKind kind) listener.Start(); - await new TelemetryCallObserver().OnCallEventAsync( - new CallEvent + await new TelemetryConversationObserver().OnConversationEventAsync( + new ConversationEvent { - CallId = "call-1", + ConversationId = "conversation-1", Kind = kind, OccurredAt = DateTimeOffset.UnixEpoch, EventId = Guid.CreateVersion7(), diff --git a/tests/AgentCore.Application.Tests/Diagnostics/TelemetrySeamTests.cs b/tests/AgentCore.Application.Tests/Diagnostics/TelemetrySeamTests.cs index 4aa6e9a7..7ae7ff68 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/TelemetrySeamTests.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/TelemetrySeamTests.cs @@ -189,7 +189,7 @@ public void AnEmptyListIsNotAnAbsentOne() /// /// The raw string in ExampleDocument strips its common indentation, so inside /// providers: a key sits at two spaces and its own keys at four. Every line is written - /// here rather than by the caller, because YAML indentation written by hand at a call site is + /// here rather than by the caller, because YAML indentation written by hand at a conversation site is /// how the first draft of these tests failed. /// private static string Document(params string[] entries) diff --git a/tests/AgentCore.Application.Tests/Diagnostics/TurnObservabilityTests.cs b/tests/AgentCore.Application.Tests/Diagnostics/TurnObservabilityTests.cs index 01d41027..9580390d 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/TurnObservabilityTests.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/TurnObservabilityTests.cs @@ -21,7 +21,7 @@ namespace AgentCore.Application.Tests.Diagnostics; /// What a turn reports: one span, three metrics, and the three "log once" rows of section 8.7. /// /// -/// Every test here runs offline. There is no collector, no exporter, and no network call. +/// Every test here runs offline. There is no collector, no exporter, and no network conversation. /// public sealed class TurnObservabilityTests { @@ -33,7 +33,7 @@ public sealed class TurnObservabilityTests "agentcore.audit.kind", // Three values: clean, flagged, unavailable. Three series for each replica, against the - // 10,000 ceiling of item 12. No call id rides on it, so T61 holds. + // 10,000 ceiling of item 12. No conversation id rides on it, so T61 holds. "agentcore.moderation.outcome", ]; @@ -52,7 +52,7 @@ public sealed class TurnObservabilityTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller" } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -83,23 +83,23 @@ public sealed class TurnObservabilityTests // T61: the metric attributes, and what may never appear on one. // ------------------------------------------------------------------------------------------- [Fact] - public async Task NoMetricAttribute_EverCarriesTheCallId() + public async Task NoMetricAttribute_EverCarriesTheConversationId() { - // A value nothing else in the process can produce, so a hit is this call and not another. - var callId = "call-" + Guid.NewGuid().ToString("N"); + // A value nothing else in the process can produce, so a hit is this conversation and not another. + var conversationId = "conversation-" + Guid.NewGuid().ToString("N"); - var tags = await MeasureAsync(callId); + var tags = await MeasureAsync(conversationId); - // The .NET default is cumulative temporality, so one call id on a metric attribute is one - // permanent series. A day of calls would then be a day of permanent series, and the free + // The .NET default is cumulative temporality, so one conversation id on a metric attribute is one + // permanent series. A day of conversations would then be a day of permanent series, and the free // tier binds at 10,000. See D26 and T61. - Assert.DoesNotContain(tags, tag => string.Equals(tag.Value as string, callId, StringComparison.Ordinal)); + Assert.DoesNotContain(tags, tag => string.Equals(tag.Value as string, conversationId, StringComparison.Ordinal)); } [Fact] public async Task EveryMetricAttribute_ComesFromAClosedSet() { - var tags = await MeasureAsync("call-" + Guid.NewGuid().ToString("N")); + var tags = await MeasureAsync("conversation-" + Guid.NewGuid().ToString("N")); // The listener really saw the instruments of this library. Assert.NotEmpty(tags); @@ -151,19 +151,19 @@ public async Task ATurn_RecordsItsDurationOnceWithTheOutcome() // The span. A high-cardinality value belongs here and nowhere else. // ------------------------------------------------------------------------------------------- [Fact] - public async Task ATurn_IsOneSpanThatCarriesTheCallIdAsAGenAiAttribute() + public async Task ATurn_IsOneSpanThatCarriesTheConversationIdAsAGenAiAttribute() { - var callId = "call-" + Guid.NewGuid().ToString("N"); - var spans = await RecordSpansAsync(callId); + var conversationId = "conversation-" + Guid.NewGuid().ToString("N"); + var spans = await RecordSpansAsync(conversationId); var span = Assert.Single(spans); Assert.Equal(AgentCoreTelemetry.TurnActivityName, span.OperationName); // Item 7 asks for gen_ai.* attributes on the trace, and gen_ai.conversation.id is the - // convention's own name for the conversation a request belongs to. A call is that + // convention's own name for the conversation a request belongs to. A conversation is that // conversation, and a span attribute costs no series. - Assert.Equal(callId, span.GetTagItem("gen_ai.conversation.id")); + Assert.Equal(conversationId, span.GetTagItem("gen_ai.conversation.id")); Assert.Equal(0, span.GetTagItem("agentcore.turn.index")); Assert.Equal("greeting", span.GetTagItem("agentcore.stage.before")); Assert.Equal("greeting", span.GetTagItem("agentcore.stage.after")); @@ -179,16 +179,16 @@ public async Task AFailedTurn_MarksItsSpanWithTheReasonOfSectionEightSeven() using SequencedChatClient reply = new(" "); using SequencedChatClient fill = new(StayingNull); - var session = Build(PolicyYaml, reply, fill).Create("call-" + Guid.NewGuid().ToString("N")); + var session = Build(PolicyYaml, reply, fill).Create("conversation-" + Guid.NewGuid().ToString("N")); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); var span = Assert.Single(Snapshot(spans), item => string.Equals( - item.GetTagItem("gen_ai.conversation.id") as string, session.CallId, StringComparison.Ordinal)); + item.GetTagItem("gen_ai.conversation.id") as string, session.ConversationId, StringComparison.Ordinal)); Assert.Equal("failed", span.GetTagItem("agentcore.turn.outcome")); Assert.Equal(ActivityStatusCode.Error, span.Status); - Assert.Equal(CallSession.EmptyReplyReason, span.StatusDescription); + Assert.Equal(ConversationSession.EmptyReplyReason, span.StatusDescription); } [Fact] @@ -199,7 +199,7 @@ public async Task AStreamedTurn_IsOneSpanToo() using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); - var session = Build(PolicyYaml, reply, fill).Create("call-" + Guid.NewGuid().ToString("N")); + var session = Build(PolicyYaml, reply, fill).Create("conversation-" + Guid.NewGuid().ToString("N")); await foreach (var update in session.RunTurnStreamingAsync("hi", TestContext.Current.CancellationToken)) { @@ -209,7 +209,7 @@ public async Task AStreamedTurn_IsOneSpanToo() // The span travels on the turn record and not on Activity.Current, because an async iterator // restores the execution context of its caller at every yield. var span = Assert.Single(Snapshot(spans), item => string.Equals( - item.GetTagItem("gen_ai.conversation.id") as string, session.CallId, StringComparison.Ordinal)); + item.GetTagItem("gen_ai.conversation.id") as string, session.ConversationId, StringComparison.Ordinal)); Assert.Equal("completed", span.GetTagItem("agentcore.turn.outcome")); } @@ -218,19 +218,19 @@ public async Task AStreamedTurn_IsOneSpanToo() // Section 8.7: three rows say "log once". // ------------------------------------------------------------------------------------------- [Fact] - public async Task AFailedExtraction_IsLoggedOnceForTheTurnAndTheCallContinues() + public async Task AFailedExtraction_IsLoggedOnceForTheTurnAndTheConversationContinues() { RecordingLogger logger = new(); using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new("I am sorry, I cannot do that."); - var session = Build(PolicyYaml, reply, fill, logger: logger).Create("call-x"); + var session = Build(PolicyYaml, reply, fill, logger: logger).Create("conversation-x"); var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); // Row two of section 8.7: leave the slots unchanged, log once for the turn, and continue. var line = Assert.Single(logger.Of(1)); Assert.Equal(LogLevel.Warning, line.Level); - Assert.Contains("call-x", line.Message, StringComparison.Ordinal); + Assert.Contains("conversation-x", line.Message, StringComparison.Ordinal); Assert.NotNull(turn.ExtractionFailure); Assert.Equal("hello there.", turn.ReplyText); } @@ -241,7 +241,7 @@ public async Task AnEmptyReply_IsLoggedOnce() RecordingLogger logger = new(); using SequencedChatClient reply = new(" "); using SequencedChatClient fill = new(StayingNull); - var session = Build(PolicyYaml, reply, fill, logger: logger).Create("call-x"); + var session = Build(PolicyYaml, reply, fill, logger: logger).Create("conversation-x"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -257,14 +257,14 @@ public async Task TheFourthConsecutiveToolFailure_IsLoggedOnce() { RecordingLogger logger = new(); using LoopingToolCallingChatClient reply = new(); - var session = Build(ToolYaml, reply, null, new ThrowingToolBuilder().Create, logger: logger).Create("call-x"); + var session = Build(ToolYaml, reply, null, new ThrowingToolBuilder().Create, logger: logger).Create("conversation-x"); await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); - // Row six of section 8.7. The turn spoke the fallback, and the call is still alive. + // Row six of section 8.7. The turn spoke the fallback, and the conversation is still alive. // // ONE line, and the turn spent four tool calls to get here. Each of those four is a row in - // the chain of D23, which is where a record of a call belongs; the log gets the turn-level + // the chain of D23, which is where a record of a conversation belongs; the log gets the turn-level // fact alone, so the volume an operator pays Grafana Cloud for did not move. var line = Assert.Single(logger.Of(2)); Assert.Equal(LogLevel.Error, line.Level); @@ -285,7 +285,7 @@ public async Task ASessionWithNoLogger_RunsATurnAndThrowsNothing() // Two of the three "log once" rows fire in this one turn, and neither has anywhere to write. var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); Assert.NotNull(turn.ExtractionFailure); } @@ -320,14 +320,14 @@ public void AGuardThatDoesNotParse_IsLoggedOnceUnderItsName() // ------------------------------------------------------------------------------------------- // Helpers. // ------------------------------------------------------------------------------------------- - /// Runs three turns of one call and collects every metric attribute the library wrote. - /// The id of the call. + /// Runs three turns of one conversation and collects every metric attribute the library wrote. + /// The id of the conversation. /// Every attribute of every measurement, flattened. /// /// The three turns cover the three outcomes: one answers, one meets a section 8.7 row, and one - /// ends the call. That reaches every instrument the library owns. + /// ends the conversation. That reaches every instrument the library owns. /// - private static async Task>> MeasureAsync(string callId) + private static async Task>> MeasureAsync(string conversationId) { List> tags = []; using MeterListener listener = new(); @@ -347,7 +347,7 @@ public void AGuardThatDoesNotParse_IsLoggedOnceUnderItsName() using SequencedChatClient reply = new("hello there.", " ", "goodbye."); using SequencedChatClient fill = new(StayingNull, StayingNull, """{ "callerSaidGoodbye": true }"""); var session = Build(PolicyYaml, reply, fill, auditSink: new Application.Audit.Memory.InMemoryAuditSink()) - .Create(callId); + .Create(conversationId); var token = TestContext.Current.CancellationToken; await session.RunTurnAsync("hi", token); @@ -371,19 +371,19 @@ private static void Collect( } /// Runs one turn and collects the spans of this library. - private static async Task> RecordSpansAsync(string callId) + private static async Task> RecordSpansAsync(string conversationId) { List spans = []; using var listener = ListenTo(spans); using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); - var session = Build(PolicyYaml, reply, fill).Create(callId); + var session = Build(PolicyYaml, reply, fill).Create(conversationId); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); return [.. Snapshot(spans).Where(span => string.Equals( - span.GetTagItem("gen_ai.conversation.id") as string, callId, StringComparison.Ordinal))]; + span.GetTagItem("gen_ai.conversation.id") as string, conversationId, StringComparison.Ordinal))]; } /// Copies what the listener has collected so far. @@ -424,7 +424,7 @@ private static ActivityListener ListenTo(List spans) return listener; } - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IChatClient? fill, @@ -433,7 +433,7 @@ private static CallSessionFactory Build( IAuditSinkPort? auditSink = null, ILogger? logger = null) { - // There is always a sink now: CallObservers.Standard takes a required one, because the + // There is always a sink now: ConversationObservers.Standard takes a required one, because the // composition root resolves providers.audit for every host and falls back to the in-process // memory kind. An optional parameter has to be a compile-time constant, so the default is // spelled here instead — a fact that does not care where its events land gets a fresh @@ -454,12 +454,12 @@ private static CallSessionFactory Build( Tools = TestToolRegistry.From(document, tools, TestContext.Current.CancellationToken), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), + ConversationSessionFactory.CreateExtractor(compiled, chatClients), timeProvider, logger, - CallObservers.Standard(sink, logger)); + ConversationObservers.Standard(sink, logger)); } } diff --git a/tests/AgentCore.Application.Tests/Embeddings/CompositeEmbeddingGeneratorFactoryTests.cs b/tests/AgentCore.Application.Tests/Embeddings/CompositeEmbeddingGeneratorFactoryTests.cs index 1adec23e..f7e7049d 100644 --- a/tests/AgentCore.Application.Tests/Embeddings/CompositeEmbeddingGeneratorFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Embeddings/CompositeEmbeddingGeneratorFactoryTests.cs @@ -35,7 +35,7 @@ public sealed class CompositeEmbeddingGeneratorFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -52,7 +52,7 @@ public sealed class CompositeEmbeddingGeneratorFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -99,7 +99,7 @@ public async Task TheAdapter_ReceivesTheEntryAndTheResolverChainTheHostBound() } // --------------------------------------------------------------------------------------------- - // What it refuses, at startup and never on the first call. + // What it refuses, at startup and never on the first conversation. // --------------------------------------------------------------------------------------------- [Fact] public async Task AKindNoAdapterServes_FailsAndNamesTheRegisteredKinds() diff --git a/tests/AgentCore.Application.Tests/Evaluation/Fakes/RecordingEvaluator.cs b/tests/AgentCore.Application.Tests/Evaluation/Fakes/RecordingEvaluator.cs index c606076c..ecfc5a97 100644 --- a/tests/AgentCore.Application.Tests/Evaluation/Fakes/RecordingEvaluator.cs +++ b/tests/AgentCore.Application.Tests/Evaluation/Fakes/RecordingEvaluator.cs @@ -4,7 +4,7 @@ namespace AgentCore.Application.Tests.Evaluation.Fakes; /// -/// An evaluator that answers with one fixed metric and counts its calls. +/// An evaluator that answers with one fixed metric and counts its conversations. /// /// /// The registry and the publisher hold evaluators and scores. Neither reads a real metric, so the diff --git a/tests/AgentCore.Application.Tests/Evaluation/PromptModeratorTests.cs b/tests/AgentCore.Application.Tests/Evaluation/PromptModeratorTests.cs index e6c49660..2cc04cab 100644 --- a/tests/AgentCore.Application.Tests/Evaluation/PromptModeratorTests.cs +++ b/tests/AgentCore.Application.Tests/Evaluation/PromptModeratorTests.cs @@ -46,7 +46,7 @@ public async Task TheModeratedText_IsWhatTheCallerSaid() public async Task AnEndpointThatDidNotAnswer_ReadsAsNothingFlagged() { // Fail open. A vendor outage must not refuse every caller, so an evaluation carrying no - // verdict reads the same as a clean one here. CallSession tells the two apart on a metric. + // verdict reads the same as a clean one here. ConversationSession tells the two apart on a metric. PromptModerator moderator = new(ScriptedModerationEvaluator.Unanswered()); var categories = await moderator.FlaggedCategoriesAsync("...", TestContext.Current.CancellationToken); @@ -57,7 +57,7 @@ public async Task AnEndpointThatDidNotAnswer_ReadsAsNothingFlagged() [Fact] public async Task AnEndpointThatThrows_Propagates() { - // The moderator does not swallow. CallSession owns the catch, because it owns the log line + // The moderator does not swallow. ConversationSession owns the catch, because it owns the log line // and the metric that report a turn went unchecked. PromptModerator moderator = new(ScriptedModerationEvaluator.Throwing(new InvalidOperationException("boom"))); diff --git a/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs b/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs deleted file mode 100644 index 79dfb4b9..00000000 --- a/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs +++ /dev/null @@ -1,107 +0,0 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; -using AgentCore.TestSupport; -using AgentCore.Application.Runtime; -using AgentCore.Application.Transcript; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Tests.Fakes; - -/// A store kept in this process, with the calls made against its words recorded. -internal sealed class RecordingCallStore() : DelegatingCallStore(new InMemoryCallStore()) -{ - private readonly Lock _lock = new(); - - /// The words as the store holds them now. It backs , not . - private readonly Dictionary<(string CallId, int Ordinal), CallMessage> _rows = []; - - /// Gets every row the provider appended, in the order it appended them. - public List Rows { get; } = []; - - /// Gets every rewrite the provider asked for, in order. - public List Rewrites { get; } = []; - - /// Gets how many times a whole call was read back. - public int Reads { get; private set; } - - /// Reads one call as the store holds it now, oldest message first. - /// The call to read. - public IReadOnlyList Live(string callId) - { - lock (_lock) - { - return [.. _rows.Values.Where(row => row.CallId == callId).OrderBy(row => row.Ordinal)]; - } - } - - /// - public override async ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - { - var rows = await base.AppendAsync(callId, messages, state, cancellationToken).ConfigureAwait(false); - - lock (_lock) - { - Rows.AddRange(rows); - foreach (var row in rows) - { - _rows[(row.CallId, row.Ordinal)] = row; - } - } - - return rows; - } - - /// - public override async ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) - { - await base.RewriteAsync(callId, messageId, content, cancellationToken).ConfigureAwait(false); - - lock (_lock) - { - foreach (var pair in _rows) - { - if (pair.Key.CallId != callId || pair.Value.MessageId != messageId) - { - continue; - } - - var rewritten = pair.Value with { Content = content }; - _rows[pair.Key] = rewritten; - Rewrites.Add(rewritten); - break; - } - } - } - - /// - public override ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) - { - lock (_lock) - { - Reads++; - } - - return ValueTask.FromResult(Live(callId)); - } - - /// - public override ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) - { - lock (_lock) - { - var going = _rows.Keys.Where(key => key.CallId == callId).ToList(); - foreach (var key in going) - { - _rows.Remove(key); - } - - return ValueTask.FromResult(going.Count); - } - } -} diff --git a/tests/AgentCore.Application.Tests/Fakes/RecordingChatClientAdapter.cs b/tests/AgentCore.Application.Tests/Fakes/RecordingChatClientAdapter.cs index d95749cc..eb31e210 100644 --- a/tests/AgentCore.Application.Tests/Fakes/RecordingChatClientAdapter.cs +++ b/tests/AgentCore.Application.Tests/Fakes/RecordingChatClientAdapter.cs @@ -26,7 +26,7 @@ internal sealed class RecordingChatClientAdapter : IChatClientAdapter /// Gets the client built for one as name. public IChatClient ClientOf(string asName) => _clients[asName]; - /// Gets the same client, typed so a test reads what a call carried. + /// Gets the same client, typed so a test reads what a conversation carried. public RecordingChatClient RecorderOf(string asName) => _clients[asName]; public ValueTask CreateClientAsync( @@ -46,11 +46,11 @@ public ValueTask CreateClientAsync( } /// -/// A chat client that keeps the options of its last call, so a test reads what the seam set. +/// A chat client that keeps the options of its last conversation, so a test reads what the seam set. /// internal sealed class RecordingChatClient : IChatClient { - /// Gets the options of the last call, or before one. + /// Gets the options of the last conversation, or before one. public ChatOptions? LastOptions { get; private set; } /// Gets how many times ran, so a test can catch a double dispose. diff --git a/tests/AgentCore.Application.Tests/Fakes/RecordingConversationStore.cs b/tests/AgentCore.Application.Tests/Fakes/RecordingConversationStore.cs new file mode 100644 index 00000000..4146190b --- /dev/null +++ b/tests/AgentCore.Application.Tests/Fakes/RecordingConversationStore.cs @@ -0,0 +1,107 @@ +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; +using AgentCore.TestSupport; +using AgentCore.Application.Runtime; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Tests.Fakes; + +/// A store kept in this process, with the conversations made against its words recorded. +internal sealed class RecordingConversationStore() : DelegatingConversationStore(new InMemoryConversationStore()) +{ + private readonly Lock _lock = new(); + + /// The words as the store holds them now. It backs , not . + private readonly Dictionary<(string ConversationId, int Ordinal), ConversationMessage> _rows = []; + + /// Gets every row the provider appended, in the order it appended them. + public List Rows { get; } = []; + + /// Gets every rewrite the provider asked for, in order. + public List Rewrites { get; } = []; + + /// Gets how many times a whole conversation was read back. + public int Reads { get; private set; } + + /// Reads one conversation as the store holds it now, oldest message first. + /// The conversation to read. + public IReadOnlyList Live(string conversationId) + { + lock (_lock) + { + return [.. _rows.Values.Where(row => row.ConversationId == conversationId).OrderBy(row => row.Ordinal)]; + } + } + + /// + public override async ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, + CancellationToken cancellationToken = default) + { + var rows = await base.AppendAsync(conversationId, messages, state, cancellationToken).ConfigureAwait(false); + + lock (_lock) + { + Rows.AddRange(rows); + foreach (var row in rows) + { + _rows[(row.ConversationId, row.Ordinal)] = row; + } + } + + return rows; + } + + /// + public override async ValueTask RewriteAsync( + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + { + await base.RewriteAsync(conversationId, messageId, content, cancellationToken).ConfigureAwait(false); + + lock (_lock) + { + foreach (var pair in _rows) + { + if (pair.Key.ConversationId != conversationId || pair.Value.MessageId != messageId) + { + continue; + } + + var rewritten = pair.Value with { Content = content }; + _rows[pair.Key] = rewritten; + Rewrites.Add(rewritten); + break; + } + } + } + + /// + public override ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) + { + lock (_lock) + { + Reads++; + } + + return ValueTask.FromResult(Live(conversationId)); + } + + /// + public override ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default) + { + lock (_lock) + { + var going = _rows.Keys.Where(key => key.ConversationId == conversationId).ToList(); + foreach (var key in going) + { + _rows.Remove(key); + } + + return ValueTask.FromResult(going.Count); + } + } +} diff --git a/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs b/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs index d68d3ecd..986498d2 100644 --- a/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs +++ b/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs @@ -52,7 +52,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - "call_" + Guid.NewGuid().ToString("N"), + "conversation_" + Guid.NewGuid().ToString("N"), _toolName, new Dictionary(StringComparer.Ordinal) { ["command"] = _commands.Dequeue() })]) { diff --git a/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs b/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs deleted file mode 100644 index 81c825f7..00000000 --- a/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs +++ /dev/null @@ -1,29 +0,0 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; -using AgentCore.Application.Transcript; -using AgentCore.TestSupport; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Tests.Fakes; - -/// Refuses every write of words, the way a backing that is down does. -internal sealed class ThrowingCallStore() : DelegatingCallStore(new InMemoryCallStore()) -{ - public override ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - => throw new InvalidOperationException("the call store is down."); - - public override ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) - => throw new InvalidOperationException("the call store is down."); - - public override ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) - => throw new InvalidOperationException("the call store is down."); - - public override ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) - => throw new InvalidOperationException("the call store is down."); -} diff --git a/tests/AgentCore.Application.Tests/Fakes/ThrowingConversationStore.cs b/tests/AgentCore.Application.Tests/Fakes/ThrowingConversationStore.cs new file mode 100644 index 00000000..e18a2abb --- /dev/null +++ b/tests/AgentCore.Application.Tests/Fakes/ThrowingConversationStore.cs @@ -0,0 +1,29 @@ +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; +using AgentCore.Application.Transcript; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Tests.Fakes; + +/// Refuses every write of words, the way a backing that is down does. +internal sealed class ThrowingConversationStore() : DelegatingConversationStore(new InMemoryConversationStore()) +{ + public override ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, + CancellationToken cancellationToken = default) + => throw new InvalidOperationException("the conversation store is down."); + + public override ValueTask RewriteAsync( + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => throw new InvalidOperationException("the conversation store is down."); + + public override ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) + => throw new InvalidOperationException("the conversation store is down."); + + public override ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default) + => throw new InvalidOperationException("the conversation store is down."); +} diff --git a/tests/AgentCore.Application.Tests/Fakes/ToolCallingChatClient.cs b/tests/AgentCore.Application.Tests/Fakes/ToolCallingChatClient.cs index 6926ad32..8071c3c0 100644 --- a/tests/AgentCore.Application.Tests/Fakes/ToolCallingChatClient.cs +++ b/tests/AgentCore.Application.Tests/Fakes/ToolCallingChatClient.cs @@ -21,7 +21,7 @@ namespace AgentCore.Application.Tests.Fakes; /// internal sealed class ToolCallingChatClient : IChatClient { - private const string CallId = "call_1"; + private const string ConversationId = "conversation_1"; private readonly string _reply; private readonly Dictionary _arguments; @@ -96,7 +96,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, - [new FunctionCallContent(CallId, tool.Name, _arguments)]) + [new FunctionCallContent(ConversationId, tool.Name, _arguments)]) { ResponseId = responseId, MessageId = responseId, diff --git a/tests/AgentCore.Application.Tests/Knowledge/CompositeKnowledgeStoreFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/CompositeKnowledgeStoreFactoryTests.cs index 7875b68a..cf3d044e 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/CompositeKnowledgeStoreFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/CompositeKnowledgeStoreFactoryTests.cs @@ -36,7 +36,7 @@ public sealed class CompositeKnowledgeStoreFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -57,7 +57,7 @@ public sealed class CompositeKnowledgeStoreFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -143,7 +143,7 @@ public async Task TheAdapter_ReceivesRequireScopeSeparatelyFromScopeDeclared() } // --------------------------------------------------------------------------------------------- - // What it refuses, at startup and never on the first call. + // What it refuses, at startup and never on the first conversation. // --------------------------------------------------------------------------------------------- [Fact] public async Task AKindNoAdapterServes_FailsAndNamesTheRegisteredKinds() @@ -207,7 +207,7 @@ public async Task CitationsWithBothCitationFieldsDisabled_FailsTheLoadPointingAt instructions: "I answer everything" knowledge: { citations: true } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -240,7 +240,7 @@ public async Task CitationsWithOnlyTheLocatorMapped_StillLoads() instructions: "I answer everything" knowledge: { citations: true } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs index 76e20086..a90de5f8 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs @@ -280,7 +280,7 @@ private static async Task CallAsync( })), [TurnInvocation.ArgumentsKey] = new TurnInvocation { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Knowledge = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) }, diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs index b296b765..141478d1 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs @@ -81,7 +81,7 @@ public void For_CarriesEveryFieldTheOutageIsDiagnosedFrom() [Fact] public void For_NoTurnIdIsReachable_LeavesTheFieldEmptyRatherThanInventingOne() { - // Ruling 19, then Ruling 21. The provider that writes this record can reach no call id and no + // Ruling 19, then Ruling 21. The provider that writes this record can reach no conversation id and no // turn index, so it passes null. A synthesised id would read as real to whoever greps for it. var record = KnowledgeAuditRecord.For(turnId: null, "analyst", KnowledgeMode.Tool, "e33", scope: null, [], latencyMs: 106, failure: null); diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeCitationFormatterFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeCitationFormatterFactoryTests.cs index 737830f4..a46e7ecd 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeCitationFormatterFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeCitationFormatterFactoryTests.cs @@ -19,7 +19,7 @@ public sealed class KnowledgeCitationFormatterFactoryTests """ apiVersion: agentcore/v1 providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs index efd3b3f2..8e558a18 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs @@ -24,11 +24,11 @@ namespace AgentCore.Application.Tests.Knowledge; /// /// /// Every test drives the search tool KnowledgeProviderFactory offers, the same way -/// KnowledgeProviderFactoryTests does, rather than through CallSession: the probe reads +/// KnowledgeProviderFactoryTests does, rather than through ConversationSession: the probe reads /// only the turn (, the knowledge scope, the history flag) and the /// resolved knowledge: block, so filing exactly those by hand proves the same mechanism a -/// real call would exercise, at a fraction of the setup. The genuinely two-turn and -/// delegation-shaped cases live in CallSessionProbeTests. +/// real conversation would exercise, at a fraction of the setup. The genuinely two-turn and +/// delegation-shaped cases live in ConversationSessionProbeTests. /// public sealed class KnowledgeProbeTests { @@ -394,12 +394,12 @@ public async Task K23_AProbeSpread_PublishesNoSources() TurnSources sources = new(); var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications(), sources: sources); - using (sources.BeginOuterCall("call-1")) + using (sources.BeginOuterCall("conversation-1")) { await InvokeSearchAsync(provider, "e33", turn); } - Assert.Empty(sources.TakeFor("call-1")); + Assert.Empty(sources.TakeFor("conversation-1")); } // K32: the probe's own try, its own budget, its own log events. @@ -465,7 +465,7 @@ public async Task Probe_SecondSearchTimesOut_IsTreatedAsAFailure_NeverAsUnreacha // K43: at most once per turn -- the latch, the replay, and cancellation. [Fact] - public async Task K43_ThreeSearchCallsInOneTurn_RunOneProbe_AndIncrementOnce() + public async Task K43_ThreeSearchConversationsInOneTurn_RunOneProbe_AndIncrementOnce() { var port = new ProbeFakePort((facets, _) => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); @@ -482,13 +482,13 @@ public async Task K43_ThreeSearchCallsInOneTurn_RunOneProbe_AndIncrementOnce() Assert.Same(first[0], third[0]); // Every call's own main search runs (three), and only the winner's search reached the - // narrowed scope (one): four port calls, one probe. + // narrowed scope (one): four port conversations, one probe. Assert.Equal(4, port.Calls); Assert.Equal(1, clarificationsObject.Read("applies_to").ProbeAsks); } [Fact] - public async Task K43_TwoCalls_TheFirstEmittedHoldsNothing_TheSecondReplaysTheSameBytes() + public async Task K43_TwoConversations_TheFirstEmittedHoldsNothing_TheSecondReplaysTheSameBytes() { var port = new ProbeFakePort((_, _) => Task.FromResult>([])); var provider = Provider(port, Resolved(["applies_to"])); @@ -503,7 +503,7 @@ public async Task K43_TwoCalls_TheFirstEmittedHoldsNothing_TheSecondReplaysTheSa } [Fact] - public async Task K43_TwoCalls_TheFirstProbeThrows_TheSecondReplaysHoldsNothing() + public async Task K43_TwoConversations_TheFirstProbeThrows_TheSecondReplaysHoldsNothing() { var thrown = 0; var port = new ProbeFakePort((facets, _) => @@ -574,11 +574,11 @@ public async Task K43_ACancelledProbe_WakesAGenuinelyWaitingLoser_RatherThanLett // elapsed time tells correct from broken. // // The loser's own token is never cancelled -- deliberately unrelated to the winner's - // caller.Token, unlike a same-turn call that would share it. A shared token was tried first + // caller.Token, unlike a same-turn conversation that would share it. A shared token was tried first // and measured to make this row untestable: Task.WaitAsync(timeout, token) reacts to a // cancelled TOKEN exactly as fast as it reacts to the awaited TASK being cancelled, so with // one shared token the loser wakes just as quickly whether or not Probe.Fail() ever - // runs -- removing the call and re-running this same test with a shared token still passed, + // runs -- removing the conversation and re-running this same test with a shared token still passed, // in under 150 ms. An unrelated token closes that hole: the loser's own wait then has exactly // one way to end early -- the shared payload being failed -- and otherwise runs out its own // two-second clock (ProbeDeadlineSeconds + ProbeWaitMarginSeconds), which is what the timing @@ -642,7 +642,7 @@ public async Task K43_ACancelledProbe_WakesAGenuinelyWaitingLoser_RatherThanLett public async Task K43_ProbeThatThrowsEveryTurn_StillAdvancesProbeAsks() { // Acceptance: "a probe that throws every turn still advances probeAsks." Two turns, - // simulated with the same BeginTurn a real CallSession calls: the latch and the per-turn mark + // simulated with the same BeginTurn a real ConversationSession conversations: the latch and the per-turn mark // reset, the counter does not. var attempts = 0; var port = new ProbeFakePort((facets, _) => @@ -857,7 +857,7 @@ public async Task AThrowBetweenTheProbeSearchAndThePublish_StillResolvesTheLatch Assert.Contains("unreachable", results[0].Text, StringComparison.Ordinal); // The latch stays claimed, so the turn cannot probe again -- but it is resolved, so a second - // call replays at once rather than running out its own clock. + // conversation replays at once rather than running out its own clock. var loser = clarificationsObject.ClaimProbe(); Assert.False(loser.Won); await Assert.ThrowsAnyAsync( @@ -1011,7 +1011,7 @@ private static TurnInvocation TurnOf( bool carriesHistory = false, TurnSources? sources = null) => new() { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Knowledge = scope, @@ -1112,7 +1112,7 @@ private static KnowledgeCard CardWithFacetList(string id, string facetKey, IRead /// SIMULATED CALLER's own token (K43's cancellation row), never the test host's — see /// , its /// only caller. Named apart from - /// so a deliberately non-TestContext token at this one call site does not read as a mistake. + /// so a deliberately non-TestContext token at this one conversation site does not read as a mistake. /// private static async Task> InvokeSearchWithCallerTokenAsync( AIContextProvider provider, string query, TurnInvocation turn, CancellationToken callerToken) diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs index 5d12b530..0dbd61bc 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs @@ -214,7 +214,7 @@ public async Task Create_UnscopedAgentWithNoAmbientScope_StillSearches() public async Task Create_UnscopedAgentUnderAScopedHostAmbient_StillSearchesTheWholeCorpus() { // Ruling 20, and the defect it resolves. example.yaml ships a mixed deployment: the resolver - // requires a scope, so the host sets ct900 for the whole call, and the analyst -- which the + // requires a scope, so the host sets ct900 for the whole conversation, and the analyst -- which the // same document says "searches every product on purpose" -- was silently filtered to ct900 // with it. The store folds whatever scope it is handed into the filter, so the turn's scope // has to stop here for an unscoped agent. @@ -264,7 +264,7 @@ public async Task Create_ScopedAgent_ReachesTheStoreUnderTheHostsOwnScope() [Fact] public async Task Create_UnscopedAgent_PutsTheHostsScopeBackAfterTheSearch() { - // The empty scope covers one port call and nothing else. Leaking it would silently unscope the + // The empty scope covers one port conversation and nothing else. Leaking it would silently unscope the // scoped agent that runs next -- the very leak this whole design fails closed against, // arriving from the inside. var port = new StubKnowledgePort([Card("a")]); @@ -309,7 +309,7 @@ public async Task Create_ASearchThatThrew_WritesTheCauseTheModelNeverSees() { // In tool mode the framework replaces the message with "Error: Function failed.", and in // prefetch mode this delegate answers a notice rather than throwing. Neither channel carries - // the cause, so an outage during a live call turns on this one line existing. + // the cause, so an outage during a live conversation turns on this one line existing. RecordingLoggerFactory loggers = new(); InvalidOperationException down = new("qdrant is down"); @@ -487,13 +487,13 @@ public async Task Create_CitationsOn_PublishesASourceForEachCardShown() StubSession session = new(); TurnRegistry.Set(session, PrefetchTurn(sources: sources)); - using (sources.BeginOuterCall("call-1")) + using (sources.BeginOuterCall("conversation-1")) { await provider.InvokingAsync( Invoking("the screen says e33", session), TestContext.Current.CancellationToken); } - var cited = sources.TakeFor("call-1"); + var cited = sources.TakeFor("conversation-1"); Assert.Equal(2, cited.Count); Assert.Equal( ["a", "b"], cited.Select(content => content.Source.SourceId).OrderBy(id => id)); @@ -514,13 +514,13 @@ public async Task Create_CitationsOff_PublishesNothing() StubSession session = new(); TurnRegistry.Set(session, PrefetchTurn(sources: sources)); - using (sources.BeginOuterCall("call-1")) + using (sources.BeginOuterCall("conversation-1")) { await provider.InvokingAsync( Invoking("the screen says e33", session), TestContext.Current.CancellationToken); } - Assert.Empty(sources.TakeFor("call-1")); + Assert.Empty(sources.TakeFor("conversation-1")); } [Fact] @@ -536,13 +536,13 @@ public async Task Create_MoreCardsThanTheLimit_CitesOnlyTheCardsTheModelIsShown( StubSession session = new(); TurnRegistry.Set(session, PrefetchTurn(sources: sources)); - using (sources.BeginOuterCall("call-1")) + using (sources.BeginOuterCall("conversation-1")) { await provider.InvokingAsync( Invoking("the screen says e33", session), TestContext.Current.CancellationToken); } - var cited = sources.TakeFor("call-1"); + var cited = sources.TakeFor("conversation-1"); Assert.Equal(2, cited.Count); Assert.Equal( ["a", "b"], cited.Select(content => content.Source.SourceId).OrderBy(id => id)); @@ -677,7 +677,7 @@ public async Task Search_ToolModeThatThrows_StillSaysUnreachable() /// The provider. private static TurnInvocation PrefetchTurn(KnowledgeScope? scope = null, TurnSources? sources = null) => new() { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Knowledge = scope, @@ -687,7 +687,7 @@ public async Task Search_ToolModeThatThrows_StillSaysUnreachable() private static TurnInvocation ToolTurn( KnowledgeScope? scope = null, Clarifications? clarifications = null, TurnSources? sources = null) => new() { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Knowledge = scope, diff --git a/tests/AgentCore.Application.Tests/Llm/CompositeChatClientFactoryTests.cs b/tests/AgentCore.Application.Tests/Llm/CompositeChatClientFactoryTests.cs index 52f0c0b6..3a236e54 100644 --- a/tests/AgentCore.Application.Tests/Llm/CompositeChatClientFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Llm/CompositeChatClientFactoryTests.cs @@ -28,7 +28,7 @@ public sealed class CompositeChatClientFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -47,7 +47,7 @@ public sealed class CompositeChatClientFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -66,7 +66,7 @@ public sealed class CompositeChatClientFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -84,7 +84,7 @@ public sealed class CompositeChatClientFactoryTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -142,7 +142,7 @@ public async Task EveryClient_IsBuiltWhileTheFactoryBuildsAndNeverAgain() factory.GetChatClient(new ModelReference { Ref = "reply" }); factory.GetChatClient(new ModelReference { Ref = "fill" }); - // One build for each 'as' name, at startup. A call costs no build. + // One build for each 'as' name, at startup. A conversation costs no build. Assert.Equal(["reply", "fill"], openai.BuiltNames); } @@ -197,7 +197,7 @@ public async Task ADocumentWithNoModel_FailsAReferenceThatNamesNone() // The temperature wrapper: the document keeps its setting, the vendor client stays one. // --------------------------------------------------------------------------------------------- [Fact] - public async Task ATemperature_ReachesTheCallWithoutASecondVendorClient() + public async Task ATemperature_ReachesTheConversationWithoutASecondVendorClient() { RecordingChatClientAdapter openai = new("openai"); @@ -239,7 +239,7 @@ [new ChatMessage(ChatRole.User, "hi")], } [Fact] - public async Task ACallWithNoOptions_StillGetsTheDocumentTemperature() + public async Task AConversationWithNoOptions_StillGetsTheDocumentTemperature() { RecordingChatClientAdapter openai = new("openai"); @@ -255,7 +255,7 @@ [new ChatMessage(ChatRole.User, "hi")], } [Fact] - public async Task ATemperature_ReachesAStreamingCallToo() + public async Task ATemperature_ReachesAStreamingConversationToo() { RecordingChatClientAdapter openai = new("openai"); diff --git a/tests/AgentCore.Application.Tests/Policy/CallPolicyGoldenSet.cs b/tests/AgentCore.Application.Tests/Policy/ConversationPolicyGoldenSet.cs similarity index 79% rename from tests/AgentCore.Application.Tests/Policy/CallPolicyGoldenSet.cs rename to tests/AgentCore.Application.Tests/Policy/ConversationPolicyGoldenSet.cs index f46d82fa..9b733d59 100644 --- a/tests/AgentCore.Application.Tests/Policy/CallPolicyGoldenSet.cs +++ b/tests/AgentCore.Application.Tests/Policy/ConversationPolicyGoldenSet.cs @@ -3,7 +3,7 @@ namespace AgentCore.Application.Tests.Policy; /// The stage of a service call. The stage set of spike/callpolicy. -internal enum CallStage +internal enum ConversationStage { Greeting, Identify, @@ -14,7 +14,7 @@ internal enum CallStage } /// -/// Everything the turn loop learned about the call so far. The externalized, typed state. +/// Everything the turn loop learned about the conversation so far. The externalized, typed state. /// internal sealed record CallFacts { @@ -54,7 +54,7 @@ internal sealed record CallFacts ["failedResolveTurns"] = JsonValue.Create(FailedResolveTurns), ["stage"] = JsonValue.Create(stage), ["turnIndex"] = JsonValue.Create(turnIndex), - ["callDurationSeconds"] = JsonValue.Create(0d), + ["conversationDurationSeconds"] = JsonValue.Create(0d), }; } @@ -62,7 +62,7 @@ internal sealed record CallFacts /// The hand-written transition table of spike/callpolicy, copied unchanged. /// /// -/// Rule 15 of section 11: the six golden calls replay against a configuration-declared policy and +/// Rule 15 of section 11: the six golden conversations replay against a configuration-declared policy and /// reproduce this machine exactly. Nothing else in the test holds a transition rule, so the /// comparison stays about the runtime and not about the rules. /// @@ -70,40 +70,40 @@ internal static class Transitions { public const int EscalateAfterTurns = 3; - public static CallStage Next(CallStage current, CallFacts f) => current switch + public static ConversationStage Next(ConversationStage current, CallFacts f) => current switch { - CallStage.Greeting => CallStage.Identify, + ConversationStage.Greeting => ConversationStage.Identify, - CallStage.Identify when f.CallerSaidGoodbye => CallStage.Close, - CallStage.Identify when f.CallerAskedForHuman => CallStage.Escalate, - CallStage.Identify when f.MachineIdentified => CallStage.Classify, - CallStage.Identify => CallStage.Identify, + ConversationStage.Identify when f.CallerSaidGoodbye => ConversationStage.Close, + ConversationStage.Identify when f.CallerAskedForHuman => ConversationStage.Escalate, + ConversationStage.Identify when f.MachineIdentified => ConversationStage.Classify, + ConversationStage.Identify => ConversationStage.Identify, - CallStage.Classify when f.CallerSaidGoodbye => CallStage.Close, - CallStage.Classify when f.CallerAskedForHuman => CallStage.Escalate, - CallStage.Classify when f.ProblemKnown => CallStage.Resolve, - CallStage.Classify => CallStage.Classify, + ConversationStage.Classify when f.CallerSaidGoodbye => ConversationStage.Close, + ConversationStage.Classify when f.CallerAskedForHuman => ConversationStage.Escalate, + ConversationStage.Classify when f.ProblemKnown => ConversationStage.Resolve, + ConversationStage.Classify => ConversationStage.Classify, - CallStage.Resolve when f.CallerSaidGoodbye => CallStage.Close, - CallStage.Resolve when f.CallerAskedForHuman => CallStage.Escalate, - CallStage.Resolve when f.Resolved => CallStage.Close, - CallStage.Resolve when f.FailedResolveTurns >= EscalateAfterTurns => CallStage.Escalate, - CallStage.Resolve => CallStage.Resolve, + ConversationStage.Resolve when f.CallerSaidGoodbye => ConversationStage.Close, + ConversationStage.Resolve when f.CallerAskedForHuman => ConversationStage.Escalate, + ConversationStage.Resolve when f.Resolved => ConversationStage.Close, + ConversationStage.Resolve when f.FailedResolveTurns >= EscalateAfterTurns => ConversationStage.Escalate, + ConversationStage.Resolve => ConversationStage.Resolve, - CallStage.Escalate => CallStage.Close, - CallStage.Close => CallStage.Close, + ConversationStage.Escalate => ConversationStage.Close, + ConversationStage.Close => ConversationStage.Close, _ => throw new ArgumentOutOfRangeException(nameof(current), current, null), }; /// Maps one stage to the id the configuration declares. - public static string ToStageId(CallStage stage) => stage switch + public static string ToStageId(ConversationStage stage) => stage switch { - CallStage.Greeting => "greeting", - CallStage.Identify => "identify", - CallStage.Classify => "classify", - CallStage.Resolve => "resolve", - CallStage.Escalate => "escalate", + ConversationStage.Greeting => "greeting", + ConversationStage.Identify => "identify", + ConversationStage.Classify => "classify", + ConversationStage.Resolve => "resolve", + ConversationStage.Escalate => "escalate", _ => "close", }; } @@ -111,15 +111,15 @@ internal static class Transitions /// One caller turn: the facts the turn loop observed after it ended. internal sealed record GoldenTurn(string Label, CallFacts Facts); -/// One whole call, replayed against a policy. -internal sealed record GoldenCall(string Name, IReadOnlyList Turns); +/// One whole conversation, replayed against a policy. +internal sealed record GoldenConversation(string Name, IReadOnlyList Turns); /// -/// The six deterministic call scenarios of spike/callpolicy. No model runs. +/// The six deterministic conversation scenarios of spike/callpolicy. No model runs. /// internal static class GoldenSet { - public static IReadOnlyList Calls { get; } = + public static IReadOnlyList Conversations { get; } = [ new("happy-path-fault-code", [ @@ -176,12 +176,12 @@ internal static class GoldenSet ]), ]; - /// Replays one call against the hand-written table. - public static IReadOnlyList ReplayHandWritten(GoldenCall call) + /// Replays one conversation against the hand-written table. + public static IReadOnlyList ReplayHandWritten(GoldenConversation conversation) { - var stage = CallStage.Greeting; - List stages = new(call.Turns.Count); - foreach (var turn in call.Turns) + var stage = ConversationStage.Greeting; + List stages = new(conversation.Turns.Count); + foreach (var turn in conversation.Turns) { stage = Transitions.Next(stage, turn.Facts); stages.Add(stage); @@ -309,7 +309,7 @@ public static IReadOnlyList ReplayHandWritten(GoldenCall call) terminal: true providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Application.Tests/Policy/GoldenCallReplayTests.cs b/tests/AgentCore.Application.Tests/Policy/GoldenConversationReplayTests.cs similarity index 52% rename from tests/AgentCore.Application.Tests/Policy/GoldenCallReplayTests.cs rename to tests/AgentCore.Application.Tests/Policy/GoldenConversationReplayTests.cs index 88eb801f..2578e738 100644 --- a/tests/AgentCore.Application.Tests/Policy/GoldenCallReplayTests.cs +++ b/tests/AgentCore.Application.Tests/Policy/GoldenConversationReplayTests.cs @@ -7,57 +7,57 @@ namespace AgentCore.Application.Tests.Policy; /// -/// Rule 15 of section 11. The six golden calls of spike/callpolicy replay against a +/// Rule 15 of section 11. The six golden conversations of spike/callpolicy replay against a /// configuration-declared policy and reproduce the hand-written machine exactly. /// -public sealed class GoldenCallReplayTests +public sealed class GoldenConversationReplayTests { private static readonly AgentCoreConfiguration Document = ConfigurationLoader.LoadYaml(GoldenSet.Yaml); - public static TheoryData CallNames() + public static TheoryData ConversationNames() { TheoryData names = []; - foreach (var call in GoldenSet.Calls) + foreach (var conversation in GoldenSet.Conversations) { - names.Add(call.Name); + names.Add(conversation.Name); } return names; } [Fact] - public void GoldenSet_HoldsSixCalls() => Assert.Equal(6, GoldenSet.Calls.Count); + public void GoldenSet_HoldsSixConversations() => Assert.Equal(6, GoldenSet.Conversations.Count); [Theory] - [MemberData(nameof(CallNames))] - public void GoldenCall_ReplaysThroughTheDeclaredPolicyExactly(string name) + [MemberData(nameof(ConversationNames))] + public void GoldenConversation_ReplaysThroughTheDeclaredPolicyExactly(string name) { - var call = GoldenSet.Calls.Single(candidate => string.Equals(candidate.Name, name, StringComparison.Ordinal)); + var conversation = GoldenSet.Conversations.Single(candidate => string.Equals(candidate.Name, name, StringComparison.Ordinal)); - var expected = GoldenSet.ReplayHandWritten(call).Select(Transitions.ToStageId).ToList(); - var actual = ReplayDeclared(call); + var expected = GoldenSet.ReplayHandWritten(conversation).Select(Transitions.ToStageId).ToList(); + var actual = ReplayDeclared(conversation); Assert.Equal(expected, actual); } [Fact] - public void EveryGoldenCall_ReplaysThroughTheDeclaredPolicyExactly() + public void EveryGoldenConversation_ReplaysThroughTheDeclaredPolicyExactly() { - foreach (var call in GoldenSet.Calls) + foreach (var conversation in GoldenSet.Conversations) { - var expected = GoldenSet.ReplayHandWritten(call).Select(Transitions.ToStageId).ToList(); - Assert.Equal(expected, ReplayDeclared(call)); + var expected = GoldenSet.ReplayHandWritten(conversation).Select(Transitions.ToStageId).ToList(); + Assert.Equal(expected, ReplayDeclared(conversation)); } } [Fact] public void HumanRequest_BeatsAResolvedFix() { - var call = GoldenSet.Calls.Single(candidate => + var conversation = GoldenSet.Conversations.Single(candidate => string.Equals(candidate.Name, "human-request-beats-a-resolved-fix", StringComparison.Ordinal)); // Both resolved and callerAskedForHuman are true on the last turn, and the answer is escalate. - Assert.Equal("escalate", ReplayDeclared(call)[^1]); + Assert.Equal("escalate", ReplayDeclared(conversation)[^1]); } [Fact] @@ -73,14 +73,14 @@ public void DeclaredPolicy_RendersEachGuardNameNextToItsEdge() Assert.DoesNotContain("callerSaidGoodbye", mermaid, StringComparison.Ordinal); } - private static List ReplayDeclared(GoldenCall call) + private static List ReplayDeclared(GoldenConversation conversation) { StagePolicy policy = new(Document.Entries["main"].Policy!, new TestGuardEvaluator(Document)); - List stages = new(call.Turns.Count); - for (var index = 0; index < call.Turns.Count; index++) + List stages = new(conversation.Turns.Count); + for (var index = 0; index < conversation.Turns.Count; index++) { - var snapshot = call.Turns[index].Facts.ToSnapshot(policy.Stage, index); + var snapshot = conversation.Turns[index].Facts.ToSnapshot(policy.Stage, index); stages.Add(policy.Advance(snapshot)); } diff --git a/tests/AgentCore.Application.Tests/Policy/StagePolicyTests.cs b/tests/AgentCore.Application.Tests/Policy/StagePolicyTests.cs index cb8bf59f..5afc2703 100644 --- a/tests/AgentCore.Application.Tests/Policy/StagePolicyTests.cs +++ b/tests/AgentCore.Application.Tests/Policy/StagePolicyTests.cs @@ -141,7 +141,7 @@ public void TwoSiblingGuardsTrue_Throws() } [Fact] - public void AGuardThatThrows_IsFalseAndTheCallContinues() + public void AGuardThatThrows_IsFalseAndTheConversationContinues() { var (policy, guards) = Build( """ diff --git a/tests/AgentCore.Application.Tests/Ports/VendorAdapterTests.cs b/tests/AgentCore.Application.Tests/Ports/VendorAdapterTests.cs index caf64271..97895a58 100644 --- a/tests/AgentCore.Application.Tests/Ports/VendorAdapterTests.cs +++ b/tests/AgentCore.Application.Tests/Ports/VendorAdapterTests.cs @@ -12,7 +12,7 @@ public sealed class VendorAdapterTests [InlineData(typeof(IModerationAdapter))] [InlineData(typeof(ITelemetryAdapter))] [InlineData(typeof(ISpeechAdapter))] - [InlineData(typeof(ICallAdapter))] + [InlineData(typeof(IConversationAdapter))] public void EveryVendorSeamDerivesFromTheOneBase(Type seam) { Assert.True( diff --git a/tests/AgentCore.Application.Tests/Providers/VendorAdapterSelectorTests.cs b/tests/AgentCore.Application.Tests/Providers/VendorAdapterSelectorTests.cs index 6ef2c940..ebc61348 100644 --- a/tests/AgentCore.Application.Tests/Providers/VendorAdapterSelectorTests.cs +++ b/tests/AgentCore.Application.Tests/Providers/VendorAdapterSelectorTests.cs @@ -59,7 +59,7 @@ public void AKindNoAdapterServesFailsTheStart() } [Fact] - public void AHostThatRegisteredNothingIsToldWhichCallToMake() + public void AHostThatRegisteredNothingIsToldWhichConversationToMake() { var failure = Assert.Throws( // The type argument is written out because an empty list infers no adapter type. diff --git a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs index 7a7150ce..f4be8079 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs @@ -1,5 +1,5 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; using AgentCore.Application.Transcript; @@ -14,52 +14,52 @@ namespace AgentCore.Application.Tests.Runtime; /// /// The shim's session envelope: what /// SerializeSessionAsync/DeserializeSessionAsync carry across a checkpoint, and what a -/// resumed call keeps of store 0's own record. +/// resumed conversation keeps of store 0's own record. /// public sealed class AgentCoreAgentSessionTests { [Fact] - public async Task SerializeSessionAsync_WritesTheStateTheCallHolds() + public async Task SerializeSessionAsync_WritesTheStateTheConversationHolds() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); - var call = session.GetService(); - Assert.NotNull(call); - Assert.True(call.State.TryWrite("escalate", JsonValue.Create(true))); + var conversation = session.GetService(); + Assert.NotNull(conversation); + Assert.True(conversation.State.TryWrite("escalate", JsonValue.Create(true))); var serialized = await agent.SerializeSessionAsync( session, cancellationToken: TestContext.Current.CancellationToken); - var read = serialized.GetProperty("state").Deserialize(CallStateJson.Options); + var read = serialized.GetProperty("state").Deserialize(ConversationStateJson.Options); Assert.NotNull(read); - Assert.Equal(CallSessionState.CurrentVersion, read.Version); - Assert.Equal(call.Stage, read.Stage); + Assert.Equal(ConversationSessionState.CurrentVersion, read.Version); + Assert.Equal(conversation.Stage, read.Stage); Assert.True(read.Slots["escalate"]!.GetValue()); } [Fact] - public async Task SerializeSessionAsync_NamesTheCallTheStateBelongsTo() + public async Task SerializeSessionAsync_NamesTheConversationTheStateBelongsTo() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _); - var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); + var session = await agent.CreateSessionAsync("conversation-42", TestContext.Current.CancellationToken); var serialized = await agent.SerializeSessionAsync( session, cancellationToken: TestContext.Current.CancellationToken); - // Store 1 is keyed by call id. State that travelled without one would come back on a call + // Store 1 is keyed by conversation id. State that travelled without one would come back on a conversation // that has no words behind it, which is the one failure this envelope exists to prevent. - Assert.Equal("call-42", serialized.GetProperty("callId").GetString()); + Assert.Equal("conversation-42", serialized.GetProperty("conversationId").GetString()); } [Fact] - public async Task SerializeSessionAsync_NoSession_IsRefusedRatherThanAnsweredWithAFreshCall() + public async Task SerializeSessionAsync_NoSession_IsRefusedRatherThanAnsweredWithAFreshConversation() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _); - // A run answers a null session by making one — the framework's one-shot shape, a call nothing + // A run answers a null session by making one — the framework's one-shot shape, a conversation nothing // continues. There is no one-shot serialize: the envelope would name a fresh random id beside // an empty state, and a host would keep that as its checkpoint and never learn it points at // nothing. @@ -68,10 +68,10 @@ await Assert.ThrowsAsync(async () => } [Fact] - public async Task ARoundTrip_ComesBackOnTheSameCall() + public async Task ARoundTrip_ComesBackOnTheSameConversation() { var agent = BuildAgent(new SequencedChatClient("a reply", "another reply"), out _); - var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); + var session = await agent.CreateSessionAsync("conversation-42", TestContext.Current.CancellationToken); _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); var serialized = await agent.SerializeSessionAsync( @@ -79,15 +79,15 @@ public async Task ARoundTrip_ComesBackOnTheSameCall() var revived = await agent.DeserializeSessionAsync( serialized, cancellationToken: TestContext.Current.CancellationToken); - Assert.Equal("call-42", revived.GetService()?.CallId); + Assert.Equal("conversation-42", revived.GetService()?.ConversationId); } [Fact] - public async Task DeserializeSessionAsync_BringsBackACallThatCarriesThatState() + public async Task DeserializeSessionAsync_BringsBackAConversationThatCarriesThatState() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); - CallSessionState stored = new() + ConversationSessionState stored = new() { Stage = string.Empty, Slots = new Dictionary(StringComparer.Ordinal) @@ -97,17 +97,17 @@ public async Task DeserializeSessionAsync_BringsBackACallThatCarriesThatState() }; var revived = await agent.DeserializeSessionAsync( - Envelope("call-42", stored), cancellationToken: TestContext.Current.CancellationToken); + Envelope("conversation-42", stored), cancellationToken: TestContext.Current.CancellationToken); - // The turn is what opens the session, and the session is the one place a call resumes from, + // The turn is what opens the session, and the session is the one place a conversation resumes from, // whichever of the two sources it resumes out of. _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - var call = revived.GetService(); + var conversation = revived.GetService(); - Assert.NotNull(call); - Assert.False(call.IsComplete); - Assert.True(call.State.Read("escalate")!.GetValue()); + Assert.NotNull(conversation); + Assert.False(conversation.IsComplete); + Assert.True(conversation.State.Read("escalate")!.GetValue()); } [Fact] @@ -115,7 +115,7 @@ public async Task ARoundTripBeforeTheFirstTurn_LosesNothing() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); - CallSessionState checkpoint = new() + ConversationSessionState checkpoint = new() { Slots = new Dictionary(StringComparer.Ordinal) { @@ -125,7 +125,7 @@ public async Task ARoundTripBeforeTheFirstTurn_LosesNothing() }; var revived = await agent.DeserializeSessionAsync( - Envelope("call-42", checkpoint), cancellationToken: TestContext.Current.CancellationToken); + Envelope("conversation-42", checkpoint), cancellationToken: TestContext.Current.CancellationToken); // No turn in between. The restore has not run yet, so a snapshot taken off the state // document would answer nothing at all — and this host would then write that nothing over @@ -133,28 +133,28 @@ public async Task ARoundTripBeforeTheFirstTurn_LosesNothing() var serialized = await agent.SerializeSessionAsync( revived, cancellationToken: TestContext.Current.CancellationToken); - Assert.Equal("call-42", serialized.GetProperty("callId").GetString()); + Assert.Equal("conversation-42", serialized.GetProperty("conversationId").GetString()); - var read = serialized.GetProperty("state").Deserialize(CallStateJson.Options); + var read = serialized.GetProperty("state").Deserialize(ConversationStateJson.Options); Assert.NotNull(read); Assert.True(read.Slots["escalate"]!.GetValue()); Assert.Equal("carried", read.Slots["note"]!.GetValue()); - // And the ordinary path is untouched. Once the turn opens the call, the document is what - // the call would resume from and the checkpoint is spent — so a value written after that + // And the ordinary path is untouched. Once the turn opens the conversation, the document is what + // the conversation would resume from and the checkpoint is spent — so a value written after that // turn is what comes back, not the one the checkpoint still holds. Store 1's writer reads // this same method, so a snapshot that kept answering the checkpoint would freeze store 0 - // at the moment the call was revived and never record another thing the call learned. + // at the moment the conversation was revived and never record another thing the conversation learned. _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - var call = revived.GetService(); - Assert.NotNull(call); - Assert.True(call.State.TryWrite("note", JsonValue.Create("learned after the turn"))); + var conversation = revived.GetService(); + Assert.NotNull(conversation); + Assert.True(conversation.State.TryWrite("note", JsonValue.Create("learned after the turn"))); var again = await agent.SerializeSessionAsync( revived, cancellationToken: TestContext.Current.CancellationToken); - var after = again.GetProperty("state").Deserialize(CallStateJson.Options); + var after = again.GetProperty("state").Deserialize(ConversationStateJson.Options); Assert.NotNull(after); Assert.True(after.Slots["escalate"]!.GetValue()); @@ -168,8 +168,8 @@ public async Task DeserializeSessionAsync_WithStateTheDocumentRefuses_StillRunsT // Nothing here is anything Snapshot would write. DeserializeSessionAsync is host-facing, so // the blob is arbitrary JSON: Restore is best effort and drops each of these with its own - // diagnostic rather than refusing the call. - CallSessionState stored = new() + // diagnostic rather than refusing the conversation. + ConversationSessionState stored = new() { Stage = "a stage this document never declared", IsComplete = true, @@ -181,16 +181,16 @@ public async Task DeserializeSessionAsync_WithStateTheDocumentRefuses_StillRunsT }; var revived = await agent.DeserializeSessionAsync( - Envelope("call-42", stored), cancellationToken: TestContext.Current.CancellationToken); + Envelope("conversation-42", stored), cancellationToken: TestContext.Current.CancellationToken); var reply = await agent.RunAsync( "hello", revived, cancellationToken: TestContext.Current.CancellationToken); Assert.Equal("a reply", reply.Text); - // The refused stage took IsComplete with it: a call brought back complete would turn every + // The refused stage took IsComplete with it: a conversation brought back complete would turn every // turn away, which is the outcome the best-effort restore exists to avoid. - Assert.False(revived.GetService()?.IsComplete); + Assert.False(revived.GetService()?.IsComplete); } [Fact] @@ -201,9 +201,9 @@ public async Task SerializeSessionAsync_CarriesNoWords() _ = await agent.RunAsync( "remember this sentence", session, cancellationToken: TestContext.Current.CancellationToken); - var call = session.GetService(); - Assert.NotNull(call); - Assert.True(call.State.TryWrite("escalate", JsonValue.Create(true))); + var conversation = session.GetService(); + Assert.NotNull(conversation); + Assert.True(conversation.State.TryWrite("escalate", JsonValue.Create(true))); var serialized = await agent.SerializeSessionAsync( session, cancellationToken: TestContext.Current.CancellationToken); @@ -220,16 +220,16 @@ public async Task SerializeSessionAsync_CarriesNoWords() } [Fact] - public async Task DeserializeSessionAsync_WhenStore0KnowsTheCall_Store0Wins() + public async Task DeserializeSessionAsync_WhenStore0KnowsTheConversation_Store0Wins() { - InMemoryCallStore store = new(); - await store.CreateAsync("call-42", TestContext.Current.CancellationToken); + InMemoryConversationStore store = new(); + await store.CreateAsync("conversation-42", TestContext.Current.CancellationToken); - // Store 0's own copy of this call: one word, and the state written in the same batch. + // Store 0's own copy of this conversation: one word, and the state written in the same batch. await store.AppendAsync( - "call-42", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "an earlier turn"), "m0")], - new CallSessionState + "conversation-42", + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "an earlier turn"), "m0")], + new ConversationSessionState { Slots = new Dictionary(StringComparer.Ordinal) { @@ -242,7 +242,7 @@ await store.AppendAsync( // It disagrees with store 0 on one slot and carries a second store 0 knows nothing about. // The second is what a merge would leak: store 0 has no value to write over it. - CallSessionState checkpoint = new() + ConversationSessionState checkpoint = new() { Slots = new Dictionary(StringComparer.Ordinal) { @@ -252,21 +252,21 @@ await store.AppendAsync( }; var revived = await agent.DeserializeSessionAsync( - Envelope("call-42", checkpoint), cancellationToken: TestContext.Current.CancellationToken); + Envelope("conversation-42", checkpoint), cancellationToken: TestContext.Current.CancellationToken); _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - var call = revived.GetService(); - Assert.NotNull(call); + var conversation = revived.GetService(); + Assert.NotNull(conversation); // False, which is store 0's value and not the checkpoint's. Store 0's blob rides the same // batch as the words above, so its state and store 1's words are of one moment; a // checkpoint's state beside those same words can be of two. One precedence, stated. - Assert.False(call.State.Read("escalate")!.GetValue()); + Assert.False(conversation.State.Read("escalate")!.GetValue()); // And store 0 wins outright rather than per slot. Where store 0 holds state, the checkpoint // contributes nothing at all — not even the slot store 0 never heard of. - Assert.True(call.State.IsUnfilled("note")); + Assert.True(conversation.State.IsUnfilled("note")); } [Fact] @@ -274,90 +274,90 @@ public async Task DeserializeSessionAsync_WithNeitherMember_Throws() { var agent = BuildAgent(new SequencedChatClient("unused"), out _, SlottedAgentYaml); - // The bare CallSessionState: the literal value store 0 keeps in call.state, and the other - // of the two shapes in this system. Read as an envelope it names no call, and a new random - // id would take the call's whole transcript with it. + // The bare ConversationSessionState: the literal value store 0 keeps in conversation.state, and the other + // of the two shapes in this system. Read as an envelope it names no conversation, and a new random + // id would take the conversation's whole transcript with it. var bare = JsonSerializer.SerializeToElement( - new CallSessionState { Stage = string.Empty }, CallStateJson.Options); + new ConversationSessionState { Stage = string.Empty }, ConversationStateJson.Options); var failure = await Assert.ThrowsAsync( async () => await agent.DeserializeSessionAsync( bare, cancellationToken: TestContext.Current.CancellationToken)); - Assert.Contains("{ callId, state }", failure.Message, StringComparison.Ordinal); + Assert.Contains("{ conversationId, state }", failure.Message, StringComparison.Ordinal); } [Fact] - public async Task DeserializeSessionAsync_WithStateButNoCallId_StartsANewCall() + public async Task DeserializeSessionAsync_WithStateButNoConversationId_StartsANewConversation() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); // Lenient on purpose, and the remark promises it: state without an id is still state, and a - // call that names none gets one made up, exactly as CreateSessionAsync does. + // conversation that names none gets one made up, exactly as CreateSessionAsync does. var named = JsonSerializer.SerializeToElement( new Dictionary(StringComparer.Ordinal) { ["state"] = JsonSerializer.SerializeToNode( - new CallSessionState + new ConversationSessionState { Slots = new Dictionary(StringComparer.Ordinal) { ["escalate"] = JsonValue.Create(true), }, }, - CallStateJson.Options), + ConversationStateJson.Options), }, - CallStateJson.Options); + ConversationStateJson.Options); var revived = await agent.DeserializeSessionAsync( named, cancellationToken: TestContext.Current.CancellationToken); - var call = revived.GetService(); + var conversation = revived.GetService(); - Assert.NotNull(call); - Assert.NotEmpty(call.CallId); + Assert.NotNull(conversation); + Assert.NotEmpty(conversation.ConversationId); _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - Assert.True(call.State.Read("escalate")!.GetValue()); + Assert.True(conversation.State.Read("escalate")!.GetValue()); } [Fact] - public async Task ARoundTripOfATerminalCall_ComesBackTerminalAndRefusesItsTurn() + public async Task ARoundTripOfATerminalConversation_ComesBackTerminalAndRefusesItsTurn() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _, TerminalAgentYaml); - var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); + var session = await agent.CreateSessionAsync("conversation-42", TestContext.Current.CancellationToken); _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); - Assert.True(session.GetService()!.IsComplete); + Assert.True(session.GetService()!.IsComplete); var serialized = await agent.SerializeSessionAsync( session, cancellationToken: TestContext.Current.CancellationToken); var revived = await agent.DeserializeSessionAsync( serialized, cancellationToken: TestContext.Current.CancellationToken); - // A behaviour change worth pinning rather than inferring: before the call state blob, a - // reloaded page met a call that had forgotten it ended and answered one more turn. + // A behaviour change worth pinning rather than inferring: before the conversation state blob, a + // reloaded page met a conversation that had forgotten it ended and answered one more turn. var failure = await Assert.ThrowsAsync( () => agent.RunAsync("again", revived, cancellationToken: TestContext.Current.CancellationToken)); Assert.Contains("runs no further turn", failure.Message, StringComparison.Ordinal); - Assert.True(revived.GetService()!.IsComplete); + Assert.True(revived.GetService()!.IsComplete); } [Fact] - public async Task Resume_AfterTheCallHasOpened_ThrowsRatherThanDoingNothing() + public async Task Resume_AfterTheConversationHasOpened_ThrowsRatherThanDoingNothing() { var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); - var call = session.GetService(); - Assert.NotNull(call); + var conversation = session.GetService(); + Assert.NotNull(conversation); // The state is read as the session opens and never again, so a late hand-off would be a // silent no-op. Saying so is the whole reason the guard is here. - var failure = Assert.Throws(() => call.Resume(new CallSessionState())); + var failure = Assert.Throws(() => conversation.Resume(new ConversationSessionState())); Assert.Contains("already run a turn", failure.Message, StringComparison.Ordinal); } diff --git a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTestSupport.cs b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTestSupport.cs index db9d993d..0bfbb8c1 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTestSupport.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTestSupport.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -45,7 +45,7 @@ internal static class AgentCoreAgentTestSupport agent: solo """; - // A policy that ends itself after one turn, so a call can be driven terminal and then round + // A policy that ends itself after one turn, so a conversation can be driven terminal and then round // tripped. The guard reads the reserved turnIndex slot, so no extractor and no tool is needed. internal const string TerminalAgentYaml = """ @@ -70,26 +70,26 @@ internal static AgentCoreAgent BuildAgent( IChatClient reply, out CompiledAgent compiled, string yaml = SingleAgentYaml, - ICallStore? store = null, + IConversationStore? store = null, string entryName = "main") { var document = ConfigurationLoader.LoadYaml(yaml); compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(new RoutingChatClientFactory(reply)) { CallStore = store })[entryName]; + new AgentCompilationContext(new RoutingChatClientFactory(reply)) { ConversationStore = store })[entryName]; - CallSessionFactory sessions = new(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + ConversationSessionFactory sessions = new(compiled, new GuardEvaluator(compiled.Configuration.Guards)); return new AgentCoreAgent(sessions, entryName); } - /// Writes what a host hands to DeserializeSessionAsync: a call id, its state, and its entry. - internal static JsonElement Envelope(string callId, CallSessionState state, string entryName = "main") + /// Writes what a host hands to DeserializeSessionAsync: a conversation id, its state, and its entry. + internal static JsonElement Envelope(string conversationId, ConversationSessionState state, string entryName = "main") => JsonSerializer.SerializeToElement( new Dictionary(StringComparer.Ordinal) { - ["callId"] = JsonValue.Create(callId), - ["state"] = JsonSerializer.SerializeToNode(state, CallStateJson.Options), + ["conversationId"] = JsonValue.Create(conversationId), + ["state"] = JsonSerializer.SerializeToNode(state, ConversationStateJson.Options), ["entry"] = JsonValue.Create(entryName), }, - CallStateJson.Options); + ConversationStateJson.Options); } diff --git a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs index c3c576c0..1b9e40d9 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs @@ -8,12 +8,12 @@ namespace AgentCore.Application.Tests.Runtime; /// /// The shim: the whole turn loop behind the framework's own -/// seam. One session is one call, one run is one turn. +/// seam. One session is one conversation, one run is one turn. /// public sealed class AgentCoreAgentTests { [Fact] - public async Task RunAsync_WithOneSession_RunsTurnsOfOneCall() + public async Task RunAsync_WithOneSession_RunsTurnsOfOneConversation() { var reply = new SequencedChatClient("first reply", "second reply"); var agent = BuildAgent(reply, out _); @@ -26,7 +26,7 @@ public async Task RunAsync_WithOneSession_RunsTurnsOfOneCall() Assert.Equal("first reply", first.Text); Assert.Equal("second reply", second.Text); - // The second run carried the whole call: turn one's exchange sits in front of turn two. + // The second run carried the whole conversation: turn one's exchange sits in front of turn two. var request = reply.Requests[1]; Assert.Contains(request, message => message.Role == ChatRole.User && message.Text == "hello"); Assert.Contains(request, message => message.Role == ChatRole.Assistant && message.Text == "first reply"); @@ -50,10 +50,10 @@ public async Task RunStreamingAsync_StreamsTheFilteredReply() Assert.NotEmpty(updates); Assert.Equal("streamed reply", string.Concat(updates.Select(update => update.Text))); - // The turn committed: the session's call holds the finished turn. - var call = session.GetService(); - Assert.NotNull(call); - Assert.Equal("streamed reply", call.LastTurn?.ReplyText); + // The turn committed: the session's conversation holds the finished turn. + var conversation = session.GetService(); + Assert.NotNull(conversation); + Assert.Equal("streamed reply", conversation.LastTurn?.ReplyText); } [Fact] @@ -92,7 +92,7 @@ [new ChatMessage(ChatRole.Assistant, "not a prompt")], } [Fact] - public async Task RunAsync_WithNoSession_RunsOneShotCalls() + public async Task RunAsync_WithNoSession_RunsOneShotConversations() { var reply = new SequencedChatClient("one", "two"); var agent = BuildAgent(reply, out _); @@ -100,7 +100,7 @@ public async Task RunAsync_WithNoSession_RunsOneShotCalls() _ = await agent.RunAsync("first", cancellationToken: TestContext.Current.CancellationToken); _ = await agent.RunAsync("second", cancellationToken: TestContext.Current.CancellationToken); - // No session, no continuity: the second run is a new call and saw nothing of the first. + // No session, no continuity: the second run is a new conversation and saw nothing of the first. Assert.DoesNotContain(reply.Requests[1], message => message.Text == "first"); Assert.DoesNotContain(reply.Requests[1], message => message.Text == "one"); } @@ -121,25 +121,25 @@ public async Task RunAsync_WithAForeignSession_Throws() } [Fact] - public async Task CreateSessionAsync_WithACallId_NamesTheCall() + public async Task CreateSessionAsync_WithAConversationId_NamesTheConversation() { var agent = BuildAgent(new SequencedChatClient("unused"), out _); - var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); + var session = await agent.CreateSessionAsync("conversation-42", TestContext.Current.CancellationToken); - Assert.Equal("call-42", session.GetService()?.CallId); + Assert.Equal("conversation-42", session.GetService()?.ConversationId); } [Fact] - public async Task GetService_OnTheSession_AnswersTheCallSession() + public async Task GetService_OnTheSession_AnswersTheConversationSession() { var agent = BuildAgent(new SequencedChatClient("unused"), out _); var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - var call = session.GetService(); + var conversation = session.GetService(); - Assert.NotNull(call); - Assert.Same(call, session.GetService()); + Assert.NotNull(conversation); + Assert.Same(conversation, session.GetService()); } [Fact] diff --git a/tests/AgentCore.Application.Tests/Runtime/AgentSessionAcrossAgentsTests.cs b/tests/AgentCore.Application.Tests/Runtime/AgentSessionAcrossAgentsTests.cs index 62e1a327..be52db44 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AgentSessionAcrossAgentsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AgentSessionAcrossAgentsTests.cs @@ -5,12 +5,12 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// Pins the library fact the transcript paragraph of -/// stands on: one carries a call that changes agent. +/// Pins the library fact the transcript paragraph of +/// stands on: one carries a conversation that changes agent. /// /// /// -/// The paragraph used to claim the opposite — "a conversation bound to one agent cannot carry a call +/// The paragraph used to claim the opposite — "a conversation bound to one agent cannot carry a conversation /// that changes agent" — and this test is the disproof, kept so a library upgrade that breaks the /// corrected claim fails here instead of silently re-validating the old design reason. Each agent /// holds its own ; sharing the @@ -28,7 +28,7 @@ public sealed class AgentSessionAcrossAgentsTests private const string SharedKey = "agentcore.test.transcript"; [Fact] - public async Task OneSession_CarriesACall_AcrossTwoAgents() + public async Task OneSession_CarriesAConversation_AcrossTwoAgents() { var clientA = new EchoingChatClient("A"); var clientB = new EchoingChatClient("B"); @@ -67,7 +67,7 @@ public async Task OneSession_CarriesACall_AcrossTwoAgents() ], clientA.Requests[1]); - // The session's own record holds the one whole call, in order. + // The session's own record holds the one whole conversation, in order. Assert.True(session.TryGetInMemoryChatHistory(out var history, SharedKey)); Assert.Equal( [ diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs index 61914577..2b74c041 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs @@ -19,7 +19,7 @@ namespace AgentCore.Application.Tests.Runtime; /// /// /// Every test drives directly against a fake inner -/// , with no YAML document and no CallSession, so a failure here +/// , with no YAML document and no ConversationSession, so a failure here /// isolates the seam itself rather than the turn loop built on top of it. /// public sealed class AuditingFunctionInvokingChatClientErrorPolicyTests @@ -58,7 +58,7 @@ public async Task AFaultTheModelCanAnswer_BecomesTheErrorResultTheModelReads() public async Task AFaultTheModelCanAnswer_IsNeverReported() { List reported = []; - var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; + var turn = new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; var tool = new ThrowingDeclaredTool(LookupOrder, new InvalidOperationException("the order is already closed.")); await RunSingleRoundAsync(tool, TestContext.Current.CancellationToken, turn: turn); @@ -109,7 +109,7 @@ public async Task AFaultTheModelCannotAnswer_KeepsItsOriginalStack() public async Task AFaultTheModelCannotAnswer_IsReportedOnceForEveryPropagatingRound() { List reported = []; - var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; + var turn = new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; var failure = new TimeoutException("the endpoint did not answer."); var tool = new ThrowingDeclaredTool(LookupOrder, failure); @@ -128,7 +128,7 @@ public async Task AFaultTheModelCannotAnswer_IsReportedOnceForEveryPropagatingRo public async Task ACallerThatHungUp_PassesTheCancellationThroughUnreported() { List reported = []; - var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; + var turn = new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; using CancellationTokenSource source = new(); // The tool cancels the very token the call was made with and then throws, exactly as a @@ -204,7 +204,7 @@ public async Task ARealBindingTool_GetsTheSameErrorResultThroughTheRealMiddlewar /// Runs one request/response round and returns the JSON the tool result carried. /// The tool the fake model calls. - /// Cancels the call. + /// Cancels the conversation. /// /// The arguments the fake model fills, or for none — enough for a tool /// that validates its own arguments before it ever reaches its adapter. diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs index 7cf93913..6155f51f 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs @@ -19,7 +19,7 @@ namespace AgentCore.Application.Tests.Runtime; /// /// The first two facts drive directly, the same way /// does, with the turn filed -/// on the call's own options. The third drives a real turn, +/// on the conversation's own options. The third drives a real turn, /// because that is the only place that proves the session actually threads its /// own Clarifications instance through — a fact the first two cannot see, since they file the /// turn by hand. @@ -131,14 +131,14 @@ await outerClient.GetResponseAsync( private static TurnInvocation TurnOf(Clarifications clarifications) => new() { - CallId = "call", + ConversationId = "conversation", TurnIndex = 0, Stage = "", Clarifications = clarifications, }; // ------------------------------------------------------------------------------------------- - // The wiring fact: a real CallSession turn opens its own Clarifications and files it on the + // The wiring fact: a real ConversationSession turn opens its own Clarifications and files it on the // run, so the probe — not the store — sees it. The increment below proves both halves: no // holder, or no filing, and the probe's search never runs. // ------------------------------------------------------------------------------------------- @@ -162,7 +162,7 @@ public async Task RunTurnAsync_AToolModeKnowledgeSearch_SeesTheHolder() model: { ref: fill } when: after_reply providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -198,8 +198,8 @@ public async Task RunTurnAsync_AToolModeKnowledgeSearch_SeesTheHolder() Knowledge = port, })["main"]; - var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); - var session = factory.Create("call-strip-1"); + var factory = new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + var session = factory.Create("conversation-strip-1"); await session.RunTurnAsync("what is it", TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs deleted file mode 100644 index 83336987..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -using AgentCore.Application.Runtime; -using AgentCore.Domain.Audit; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -/// -/// What one call event kind is to the audit vocabulary, and what it is called in a log line. -/// -public sealed class CallEventKindsTests -{ - /// Every kind the chain stores, beside the row it writes and the token it hashes. - public static TheoryData StoredKinds => - new() - { - { CallEventKind.CallStarted, AuditEventKind.CallStarted, "call.started" }, - { CallEventKind.PromptFlagged, AuditEventKind.PromptFlagged, "prompt.flagged" }, - { CallEventKind.ToolFailed, AuditEventKind.ToolFailed, "tool.failed" }, - { CallEventKind.TurnCompleted, AuditEventKind.TurnCompleted, "turn.completed" }, - { CallEventKind.ReplyInterrupted, AuditEventKind.ReplyInterrupted, "reply.interrupted" }, - { CallEventKind.CallEnded, AuditEventKind.CallEnded, "call.ended" }, - { CallEventKind.TurnSuperseded, AuditEventKind.TurnSuperseded, "turn.superseded" }, - }; - - /// Every diagnostic kind, beside the name a log line gives it. - public static TheoryData DiagnosticKinds => - new() - { - { CallEventKind.ModerationUnavailable, "moderation.unavailable" }, - { CallEventKind.ModerationClean, "moderation.clean" }, - { CallEventKind.EmptyReply, "reply.empty" }, - { CallEventKind.ExtractionFailed, "extraction.failed" }, - { CallEventKind.TranscriptWriteFailed, "transcript.write.failed" }, - { CallEventKind.StateRestorePartial, "state.restore.partial" }, - { CallEventKind.TranscriptResyncFailed, "transcript.resync.failed" }, - }; - - [Theory] - [MemberData(nameof(StoredKinds))] - public void AStoredKind_NamesItsRowAndItsToken(CallEventKind kind, AuditEventKind expected, string token) - { - Assert.True(CallEventKinds.TryGetAuditKind(kind, out AuditEventKind mapped)); - Assert.Equal(expected, mapped); - - // The token is the chain's, and it is a permanent promise. Nothing here invents one. - Assert.Equal(token, CallEventKinds.ToToken(kind)); - Assert.Equal(AuditEventKinds.ToToken(expected), CallEventKinds.ToToken(kind)); - } - - [Theory] - [MemberData(nameof(DiagnosticKinds))] - public void ADiagnosticKind_MapsToNoRowAndIsStillNamed(CallEventKind kind, string token) - { - Assert.False(CallEventKinds.TryGetAuditKind(kind, out _)); - - // It reaches no chain, so AuditEventKinds knows no token for it. A report still has to name it. - Assert.Equal(token, CallEventKinds.ToToken(kind)); - } - - [Fact] - public void EveryKind_IsEitherStoredOrDiagnostic_AndEveryOneIsCovered() - { - var stored = Enum.GetValues() - .Count(kind => CallEventKinds.TryGetAuditKind(kind, out _)); - - Assert.Equal(14, Enum.GetValues().Length); - Assert.Equal(7, stored); - } - - [Fact] - public void AValueOutsideTheClosedSet_IsNamedRatherThanThrownOver() - { - // A kind the enum does not hold must not cost a report the fault it is carrying. - const CallEventKind Unknown = (CallEventKind)999; - - Assert.False(CallEventKinds.TryGetAuditKind(Unknown, out _)); - Assert.Equal("999", CallEventKinds.ToToken(Unknown)); - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs b/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs index 84b93379..a22b86f3 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs @@ -47,15 +47,15 @@ public void Create_NoToolCalls_IsEmpty() } [Fact] - public void Create_TwoResultsShareOneCallId_RendersTheLastOneWithoutThrowing() + public void Create_TwoResultsShareOneConversationId_RendersTheLastOneWithoutThrowing() { var group = Group( CompactionGroupKind.ToolCall, [ new ChatMessage(ChatRole.Assistant, - [new FunctionCallContent("call-1", "lookup", new Dictionary())]), - new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", "first")]), - new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", "last")]), + [new FunctionCallContent("conversation-1", "lookup", new Dictionary())]), + new ChatMessage(ChatRole.Tool, [new FunctionResultContent("conversation-1", "first")]), + new ChatMessage(ChatRole.Tool, [new FunctionResultContent("conversation-1", "last")]), ]); var written = CappedToolCallFormatter.Create(50)(group); @@ -75,8 +75,8 @@ private static CompactionMessageGroup Group(string tool, string result) => Group CompactionGroupKind.ToolCall, [ new ChatMessage(ChatRole.Assistant, - [new FunctionCallContent("call-1", tool, new Dictionary())]), - new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", result)]), + [new FunctionCallContent("conversation-1", tool, new Dictionary())]), + new ChatMessage(ChatRole.Tool, [new FunctionResultContent("conversation-1", result)]), ]); } #pragma warning restore MAAI001 diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs index c05c814e..4632407c 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs @@ -5,14 +5,14 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// : the per-call holder K36 describes, K41's per-turn mark, and K43's +/// : the per-conversation holder K36 describes, K41's per-turn mark, and K43's /// probe latch and replay payload. /// public sealed class ClarificationsTests { // ----------------------------------------------------------------------------------------- // K43: the probe latch is a compare-and-set. Several search-tool calls in one turn, or several - // graph participants sharing this call, must cost exactly one probe. + // graph participants sharing this conversation, must cost exactly one probe. // ----------------------------------------------------------------------------------------- [Fact] public void ClaimProbe_ManyConcurrentCallers_ExactlyOneClaimsEachTrial() @@ -124,7 +124,7 @@ public async Task Publish_LetsEveryWaiterReplayTheSameCards() // ----------------------------------------------------------------------------------------- // K43: BeginTurn opens a fresh turn. It clears the probe latch and its payload together, and - // never the counter — that is per-call, not per-turn. + // never the counter — that is per-conversation, not per-turn. // ----------------------------------------------------------------------------------------- [Fact] public void BeginTurn_ClearsTheLatch_AndLeavesTheCounter() @@ -185,8 +185,8 @@ await Assert.ThrowsAsync( } // ----------------------------------------------------------------------------------------- - // Reconnect: the ask budget is per call, not per session, so what one session spent must reach - // the next one through the call's stored state. + // Reconnect: the ask budget is per conversation, not per session, so what one session spent must reach + // the next one through the conversation's stored state. // ----------------------------------------------------------------------------------------- [Fact] public void SpentAndRestoreSpent_CarryTheBudget_AndNotWhatWasNamed() diff --git a/tests/AgentCore.Application.Tests/Runtime/CompactionStrategyFactoryTests.cs b/tests/AgentCore.Application.Tests/Runtime/CompactionStrategyFactoryTests.cs index a0b85ac4..fc6217f7 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CompactionStrategyFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CompactionStrategyFactoryTests.cs @@ -58,8 +58,8 @@ public async Task Create_ToolResult_ShrinksTheText() [Fact] public async Task Create_SameWordsTwiceFromEmptyState_Agrees() { - // The claim the resume design rests on: a resumed call builds a new session, so the provider - // starts empty and re-derives. If two passes disagreed, a resumed call would not match the + // The claim the resume design rests on: a resumed conversation builds a new session, so the provider + // starts empty and re-derives. If two passes disagreed, a resumed conversation would not match the // call it resumed, and compaction state would have to be persisted. var history = HistoryWithToolResults(6, resultChars: 4000); var settings = Resolved(CompactionStrategyKind.ToolResult, messages: 8); @@ -101,9 +101,9 @@ private static List HistoryWithToolResults(int turns, int resultCha { messages.Add(new ChatMessage(ChatRole.User, $"question {index}")); messages.Add(new ChatMessage(ChatRole.Assistant, - [new FunctionCallContent($"call-{index}", "lookup", new Dictionary())])); + [new FunctionCallContent($"conversation-{index}", "lookup", new Dictionary())])); messages.Add(new ChatMessage(ChatRole.Tool, - [new FunctionResultContent($"call-{index}", new string('x', resultChars))])); + [new FunctionResultContent($"conversation-{index}", new string('x', resultChars))])); messages.Add(new ChatMessage(ChatRole.Assistant, $"answer {index}")); } diff --git a/tests/AgentCore.Application.Tests/Runtime/ConversationEventKindsTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationEventKindsTests.cs new file mode 100644 index 00000000..6364a4a6 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationEventKindsTests.cs @@ -0,0 +1,79 @@ +using AgentCore.Application.Runtime; +using AgentCore.Domain.Audit; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// What one conversation event kind is to the audit vocabulary, and what it is called in a log line. +/// +public sealed class ConversationEventKindsTests +{ + /// Every kind the chain stores, beside the row it writes and the token it hashes. + public static TheoryData StoredKinds => + new() + { + { ConversationEventKind.ConversationStarted, AuditEventKind.ConversationStarted, "conversation.started" }, + { ConversationEventKind.PromptFlagged, AuditEventKind.PromptFlagged, "prompt.flagged" }, + { ConversationEventKind.ToolFailed, AuditEventKind.ToolFailed, "tool.failed" }, + { ConversationEventKind.TurnCompleted, AuditEventKind.TurnCompleted, "turn.completed" }, + { ConversationEventKind.ReplyInterrupted, AuditEventKind.ReplyInterrupted, "reply.interrupted" }, + { ConversationEventKind.ConversationEnded, AuditEventKind.ConversationEnded, "conversation.ended" }, + { ConversationEventKind.TurnSuperseded, AuditEventKind.TurnSuperseded, "turn.superseded" }, + }; + + /// Every diagnostic kind, beside the name a log line gives it. + public static TheoryData DiagnosticKinds => + new() + { + { ConversationEventKind.ModerationUnavailable, "moderation.unavailable" }, + { ConversationEventKind.ModerationClean, "moderation.clean" }, + { ConversationEventKind.EmptyReply, "reply.empty" }, + { ConversationEventKind.ExtractionFailed, "extraction.failed" }, + { ConversationEventKind.TranscriptWriteFailed, "transcript.write.failed" }, + { ConversationEventKind.StateRestorePartial, "state.restore.partial" }, + { ConversationEventKind.TranscriptResyncFailed, "transcript.resync.failed" }, + }; + + [Theory] + [MemberData(nameof(StoredKinds))] + public void AStoredKind_NamesItsRowAndItsToken(ConversationEventKind kind, AuditEventKind expected, string token) + { + Assert.True(ConversationEventKinds.TryGetAuditKind(kind, out AuditEventKind mapped)); + Assert.Equal(expected, mapped); + + // The token is the chain's, and it is a permanent promise. Nothing here invents one. + Assert.Equal(token, ConversationEventKinds.ToToken(kind)); + Assert.Equal(AuditEventKinds.ToToken(expected), ConversationEventKinds.ToToken(kind)); + } + + [Theory] + [MemberData(nameof(DiagnosticKinds))] + public void ADiagnosticKind_MapsToNoRowAndIsStillNamed(ConversationEventKind kind, string token) + { + Assert.False(ConversationEventKinds.TryGetAuditKind(kind, out _)); + + // It reaches no chain, so AuditEventKinds knows no token for it. A report still has to name it. + Assert.Equal(token, ConversationEventKinds.ToToken(kind)); + } + + [Fact] + public void EveryKind_IsEitherStoredOrDiagnostic_AndEveryOneIsCovered() + { + var stored = Enum.GetValues() + .Count(kind => ConversationEventKinds.TryGetAuditKind(kind, out _)); + + Assert.Equal(14, Enum.GetValues().Length); + Assert.Equal(7, stored); + } + + [Fact] + public void AValueOutsideTheClosedSet_IsNamedRatherThanThrownOver() + { + // A kind the enum does not hold must not cost a report the fault it is carrying. + const ConversationEventKind Unknown = (ConversationEventKind)999; + + Assert.False(ConversationEventKinds.TryGetAuditKind(Unknown, out _)); + Assert.Equal("999", ConversationEventKinds.ToToken(Unknown)); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallObserverDispatcherTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationObserverDispatcherTests.cs similarity index 61% rename from tests/AgentCore.Application.Tests/Runtime/CallObserverDispatcherTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationObserverDispatcherTests.cs index b7ad998f..05f7a22f 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallObserverDispatcherTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationObserverDispatcherTests.cs @@ -12,14 +12,14 @@ namespace AgentCore.Application.Tests.Runtime; /// /// Section 7 measures a durable insert at 13 ms p50 against 91 nanoseconds to enqueue, so the rule /// these tests fix is that no observer ever sits on the turn: a fast one costs the caller nothing but -/// the call itself, a slow one is watched off-turn, and one that throws is reported and forgotten. +/// the conversation itself, a slow one is watched off-turn, and one that throws is reported and forgotten. /// The fourth rule is the one the old fire-and-forget code did not have. The chain of D23 is a record -/// of a call, so the facts of one call must reach an observer in the order the call produced them, +/// of a conversation, so the facts of one conversation must reach an observer in the order the conversation produced them, /// however long any one of them takes. /// -public sealed class CallObserverDispatcherTests +public sealed class ConversationObserverDispatcherTests { - private const string CallId = "call-1"; + private const string ConversationId = "conversation-1"; /// The id Log.AuditAppendFailed carries. It is unchanged by the hook. private const int AuditAppendFailedEventId = 5; @@ -28,27 +28,27 @@ public sealed class CallObserverDispatcherTests public void AnObserverThatAnswersAtOnce_HasTheEventBeforeDispatchReturns() { var observer = new RecordingObserver(); - var dispatcher = new CallObserverDispatcher([observer]); + var dispatcher = new ConversationObserverDispatcher([observer]); - dispatcher.Dispatch(Event(CallEventKind.CallStarted)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationStarted)); // No await anywhere: a synchronous observer runs on the caller's thread, which is what makes // the fast path cost the turn the enqueue and nothing else. - Assert.Equal([CallEventKind.CallStarted], observer.Seen); + Assert.Equal([ConversationEventKind.ConversationStarted], observer.Seen); } [Fact] public void ManyEventsThroughTheFastPath_ArriveInOrder() { var observer = new RecordingObserver(); - var dispatcher = new CallObserverDispatcher([observer]); + var dispatcher = new ConversationObserverDispatcher([observer]); - dispatcher.Dispatch(Event(CallEventKind.CallStarted)); - dispatcher.Dispatch(Event(CallEventKind.TurnCompleted)); - dispatcher.Dispatch(Event(CallEventKind.CallEnded)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationStarted)); + dispatcher.Dispatch(Event(ConversationEventKind.TurnCompleted)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationEnded)); Assert.Equal( - [CallEventKind.CallStarted, CallEventKind.TurnCompleted, CallEventKind.CallEnded], + [ConversationEventKind.ConversationStarted, ConversationEventKind.TurnCompleted, ConversationEventKind.ConversationEnded], observer.Seen); } @@ -60,21 +60,21 @@ public void EveryObserver_ReadsTheSameEvent_InTheOrderTheyWereGiven() var order = new List(); first.OnEvent = _ => order.Add("first"); second.OnEvent = _ => order.Add("second"); - var dispatcher = new CallObserverDispatcher([first, second]); + var dispatcher = new ConversationObserverDispatcher([first, second]); - dispatcher.Dispatch(Event(CallEventKind.ToolFailed)); + dispatcher.Dispatch(Event(ConversationEventKind.ToolFailed)); - Assert.Equal([CallEventKind.ToolFailed], first.Seen); - Assert.Equal([CallEventKind.ToolFailed], second.Seen); + Assert.Equal([ConversationEventKind.ToolFailed], first.Seen); + Assert.Equal([ConversationEventKind.ToolFailed], second.Seen); Assert.Equal(["first", "second"], order); } [Fact] public void NoObserversAtAll_IsANoOp() { - var dispatcher = new CallObserverDispatcher([]); + var dispatcher = new ConversationObserverDispatcher([]); - dispatcher.Dispatch(Event(CallEventKind.CallStarted)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationStarted)); Assert.Equal(0, dispatcher.Count); } @@ -83,11 +83,11 @@ public void NoObserversAtAll_IsANoOp() public async Task AnObserverThatBlocks_DoesNotBlockTheCaller() { var observer = new GatedObserver(); - var dispatcher = new CallObserverDispatcher([observer]); + var dispatcher = new ConversationObserverDispatcher([observer]); - // The observer is inside OnCallEventAsync and will stay there until the test releases it. + // The observer is inside OnConversationEventAsync and will stay there until the test releases it. // Dispatch still returns, which is the whole contract of the port. - dispatcher.Dispatch(Event(CallEventKind.TurnCompleted)); + dispatcher.Dispatch(Event(ConversationEventKind.TurnCompleted)); await observer.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); Assert.Empty(observer.Seen); @@ -97,18 +97,18 @@ public async Task AnObserverThatBlocks_DoesNotBlockTheCaller() } [Fact] - public async Task TwoSlowEvents_ReachTheObserverInTheOrderTheCallRaisedThem() + public async Task TwoSlowEvents_ReachTheObserverInTheOrderTheConversationRaisedThem() { // The old code was `_ = ObserveAppendAsync(...)`, so the second event overtook the first // whenever the first was slower. The second gate is released FIRST here, which is exactly // the race that used to shuffle the chain. var observer = new GatedObserver(); - var dispatcher = new CallObserverDispatcher([observer]); + var dispatcher = new ConversationObserverDispatcher([observer]); - dispatcher.Dispatch(Event(CallEventKind.TurnCompleted)); + dispatcher.Dispatch(Event(ConversationEventKind.TurnCompleted)); await observer.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); - dispatcher.Dispatch(Event(CallEventKind.CallEnded)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationEnded)); // The second event is queued behind the first, so the observer has not even been asked about // it yet. There is nothing to release. @@ -117,7 +117,7 @@ public async Task TwoSlowEvents_ReachTheObserverInTheOrderTheCallRaisedThem() observer.Release(); await WaitFor(() => observer.Seen.Count == 2); - Assert.Equal([CallEventKind.TurnCompleted, CallEventKind.CallEnded], observer.Seen); + Assert.Equal([ConversationEventKind.TurnCompleted, ConversationEventKind.ConversationEnded], observer.Seen); } [Fact] @@ -128,17 +128,17 @@ public async Task ASlowObserver_DoesNotDelayALaterEventForAFastOne() // row, which is the cost section 8.6 and section 8.7 are not allowed to pay. var slow = new GatedObserver(); var fast = new RecordingObserver(); - var dispatcher = new CallObserverDispatcher([slow, fast]); + var dispatcher = new ConversationObserverDispatcher([slow, fast]); - dispatcher.Dispatch(Event(CallEventKind.TurnCompleted)); + dispatcher.Dispatch(Event(ConversationEventKind.TurnCompleted)); await slow.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); - // The slow observer is inside OnCallEventAsync for the first event and stays there. - dispatcher.Dispatch(Event(CallEventKind.CallEnded)); + // The slow observer is inside OnConversationEventAsync for the first event and stays there. + dispatcher.Dispatch(Event(ConversationEventKind.ConversationEnded)); // No await anywhere between the dispatch and this assertion: the second fact reached the fast // observer on the caller's thread while the first one was still open at the slow one. - Assert.Equal([CallEventKind.TurnCompleted, CallEventKind.CallEnded], fast.Seen); + Assert.Equal([ConversationEventKind.TurnCompleted, ConversationEventKind.ConversationEnded], fast.Seen); // And the slow observer was never asked about the second fact, because its own first one is // still open. Its order is kept while it costs nobody else anything. @@ -147,23 +147,23 @@ public async Task ASlowObserver_DoesNotDelayALaterEventForAFastOne() slow.Release(); await WaitFor(() => slow.Seen.Count == 2); - Assert.Equal([CallEventKind.TurnCompleted, CallEventKind.CallEnded], slow.Seen); + Assert.Equal([ConversationEventKind.TurnCompleted, ConversationEventKind.ConversationEnded], slow.Seen); } [Fact] public async Task AQueuedEvent_StillArrivesWhenTheEventBeforeItFailed() { - var observer = new GatedObserver { ThrowsOn = CallEventKind.TurnCompleted }; - var dispatcher = new CallObserverDispatcher([observer]); + var observer = new GatedObserver { ThrowsOn = ConversationEventKind.TurnCompleted }; + var dispatcher = new ConversationObserverDispatcher([observer]); - dispatcher.Dispatch(Event(CallEventKind.TurnCompleted)); + dispatcher.Dispatch(Event(ConversationEventKind.TurnCompleted)); await observer.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); - dispatcher.Dispatch(Event(CallEventKind.CallEnded)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationEnded)); observer.Release(); await WaitFor(() => observer.Seen.Count == 1); - Assert.Equal([CallEventKind.CallEnded], observer.Seen); + Assert.Equal([ConversationEventKind.ConversationEnded], observer.Seen); } [Fact] @@ -172,17 +172,17 @@ public void AnObserverThatThrowsAtOnce_NeitherPropagatesNorCostsTheOthersTheEven var logger = new RecordingLogger(); var throwing = new ThrowingObserver(); var recording = new RecordingObserver(); - var dispatcher = new CallObserverDispatcher([throwing, recording], logger); + var dispatcher = new ConversationObserverDispatcher([throwing, recording], logger); - // Audit is a record of the call and never a part of it, so nothing here reaches the turn. - dispatcher.Dispatch(Event(CallEventKind.CallStarted)); + // Audit is a record of the conversation and never a part of it, so nothing here reaches the turn. + dispatcher.Dispatch(Event(ConversationEventKind.ConversationStarted)); - Assert.Equal([CallEventKind.CallStarted], recording.Seen); + Assert.Equal([ConversationEventKind.ConversationStarted], recording.Seen); var line = Assert.Single(logger.Of(AuditAppendFailedEventId)); Assert.Equal(LogLevel.Error, line.Level); - Assert.Contains("call.started", line.Message, StringComparison.Ordinal); - Assert.Contains(CallId, line.Message, StringComparison.Ordinal); + Assert.Contains("conversation.started", line.Message, StringComparison.Ordinal); + Assert.Contains(ConversationId, line.Message, StringComparison.Ordinal); Assert.IsType(line.Exception); } @@ -190,17 +190,17 @@ public void AnObserverThatThrowsAtOnce_NeitherPropagatesNorCostsTheOthersTheEven public async Task AnObserverThatThrowsLongAfterTheTurn_IsReportedAndNothingElseHappens() { var logger = new RecordingLogger(); - var observer = new GatedObserver { ThrowsOn = CallEventKind.CallEnded }; - var dispatcher = new CallObserverDispatcher([observer], logger); + var observer = new GatedObserver { ThrowsOn = ConversationEventKind.ConversationEnded }; + var dispatcher = new ConversationObserverDispatcher([observer], logger); - dispatcher.Dispatch(Event(CallEventKind.CallEnded)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationEnded)); await observer.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); observer.Release(); await WaitFor(() => logger.Of(AuditAppendFailedEventId).Count == 1); var line = Assert.Single(logger.Of(AuditAppendFailedEventId)); - Assert.Contains("call.ended", line.Message, StringComparison.Ordinal); + Assert.Contains("conversation.ended", line.Message, StringComparison.Ordinal); Assert.IsType(line.Exception); } @@ -208,11 +208,11 @@ public async Task AnObserverThatThrowsLongAfterTheTurn_IsReportedAndNothingElseH public void ADiagnosticKind_IsReportedUnderItsOwnToken() { var logger = new RecordingLogger(); - var dispatcher = new CallObserverDispatcher([new ThrowingObserver()], logger); + var dispatcher = new ConversationObserverDispatcher([new ThrowingObserver()], logger); // The four diagnostic kinds reach no chain, so AuditEventKinds knows no token for them. The // report still has to name what failed. - dispatcher.Dispatch(Event(CallEventKind.ExtractionFailed)); + dispatcher.Dispatch(Event(ConversationEventKind.ExtractionFailed)); var line = Assert.Single(logger.Of(AuditAppendFailedEventId)); Assert.Contains("extraction.failed", line.Message, StringComparison.Ordinal); @@ -223,22 +223,22 @@ public void AFailingObserver_DoesNotStopTheNextEvent() { var throwing = new ThrowingObserver(); var recording = new RecordingObserver(); - var dispatcher = new CallObserverDispatcher([throwing, recording]); + var dispatcher = new ConversationObserverDispatcher([throwing, recording]); - dispatcher.Dispatch(Event(CallEventKind.CallStarted)); - dispatcher.Dispatch(Event(CallEventKind.CallEnded)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationStarted)); + dispatcher.Dispatch(Event(ConversationEventKind.ConversationEnded)); - Assert.Equal([CallEventKind.CallStarted, CallEventKind.CallEnded], recording.Seen); + Assert.Equal([ConversationEventKind.ConversationStarted, ConversationEventKind.ConversationEnded], recording.Seen); } [Fact] public void NoEvent_IsRefused() => Assert.Throws( - () => new CallObserverDispatcher([new RecordingObserver()]).Dispatch(null!)); + () => new ConversationObserverDispatcher([new RecordingObserver()]).Dispatch(null!)); - private static CallEvent Event(CallEventKind kind) => new() + private static ConversationEvent Event(ConversationEventKind kind) => new() { - CallId = CallId, + ConversationId = ConversationId, Kind = kind, OccurredAt = DateTimeOffset.UnixEpoch, }; @@ -256,13 +256,13 @@ private static async Task WaitFor(Func condition) /// /// An observer that answers at once and remembers what it read. /// - private sealed class RecordingObserver : ICallObserver + private sealed class RecordingObserver : IConversationObserver { private readonly Lock _gate = new(); - private readonly List _seen = []; + private readonly List _seen = []; /// Gets what the observer read, oldest first. - public IReadOnlyList Seen + public IReadOnlyList Seen { get { @@ -274,18 +274,18 @@ public IReadOnlyList Seen } /// Runs beside the recording, so a test can watch the order across observers. - public Action? OnEvent { get; set; } + public Action? OnEvent { get; set; } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { Assert.False(cancellationToken.CanBeCanceled, "The dispatcher passes CancellationToken.None."); lock (_gate) { - _seen.Add(callEvent.Kind); + _seen.Add(conversationEvent.Kind); } - OnEvent?.Invoke(callEvent); + OnEvent?.Invoke(conversationEvent); return ValueTask.CompletedTask; } } @@ -298,15 +298,15 @@ public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancell /// answers what it was asked about. The difference is what an ordering test /// reads. /// - private sealed class GatedObserver : ICallObserver + private sealed class GatedObserver : IConversationObserver { private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly Lock _lock = new(); - private readonly List _seen = []; + private readonly List _seen = []; private int _entries; /// Gets the events the observer accepted, oldest first. - public IReadOnlyList Seen + public IReadOnlyList Seen { get { @@ -324,26 +324,26 @@ public IReadOnlyList Seen public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); /// The one kind the observer refuses, or when it refuses none. - public CallEventKind? ThrowsOn { get; init; } + public ConversationEventKind? ThrowsOn { get; init; } - /// Lets every open call complete. + /// Lets every open conversation complete. public void Release() => _gate.TrySetResult(); - public async ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public async ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { Interlocked.Increment(ref _entries); Entered.TrySetResult(); await _gate.Task.ConfigureAwait(false); - if (ThrowsOn == callEvent.Kind) + if (ThrowsOn == conversationEvent.Kind) { throw new InvalidOperationException(ThrowingObserver.Message); } lock (_lock) { - _seen.Add(callEvent.Kind); + _seen.Add(conversationEvent.Kind); } } } @@ -351,12 +351,12 @@ public async ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken c /// /// An observer that refuses every event before it has awaited anything. /// - private sealed class ThrowingObserver : ICallObserver + private sealed class ThrowingObserver : IConversationObserver { /// The message every refusal carries. public const string Message = "the observer is broken."; - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) => throw new InvalidOperationException(Message); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallObserversTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationObserversTests.cs similarity index 56% rename from tests/AgentCore.Application.Tests/Runtime/CallObserversTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationObserversTests.cs index 24c737c7..9cb9f6c1 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallObserversTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationObserversTests.cs @@ -8,21 +8,21 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// assembles the readings of one call, in the order the cost +/// assembles the readings of one conversation, in the order the cost /// story of section 7 asks for. /// /// /// The order is the contract: the counters of section 8.6 and the rows of section 8.7 are taken /// above the enqueue, and code this library did not write goes after all three. The list is what -/// is handed, so this is where the rule is tested rather than +/// is handed, so this is where the rule is tested rather than /// inside the factory that no longer knows it. /// -public sealed class CallObserversTests +public sealed class ConversationObserversTests { /// A host reading that records nothing and only has to be found in the list. - private sealed class HostObserver : ICallObserver + private sealed class HostObserver : IConversationObserver { - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) => ValueTask.CompletedTask; } @@ -38,34 +38,34 @@ public void EveryLibraryReadingIsTaken() { // The audit reading is no longer conditional on a host having bound something. The // composition root resolves providers.audit for every host and falls back to the in-process - // memory kind, so all three readings of a call are always built and the chain of D23 is + // memory kind, so all three readings of a conversation are always built and the chain of D23 is // written whatever the document names. - var observers = CallObservers.Standard(new AcceptingSink(), logger: null); + var observers = ConversationObservers.Standard(new AcceptingSink(), logger: null); Assert.Equal(3, observers.Count); - Assert.IsType(observers[2]); + Assert.IsType(observers[2]); } [Fact] public void NoSinkIsNotAShapeTheListCanHave() { // There is no "bound nothing" list to build, so asking for one is a caller's mistake rather - // than a two-observer reading of the call. + // than a two-observer reading of the conversation. Assert.Throws( "auditSink", - () => CallObservers.Standard(auditSink: null!, logger: null)); + () => ConversationObservers.Standard(auditSink: null!, logger: null)); } [Fact] public void BoundSinkPutsTheAuditReadingLast() { - var observers = CallObservers.Standard(new AcceptingSink(), logger: null); + var observers = ConversationObservers.Standard(new AcceptingSink(), logger: null); Assert.Collection( observers, - observer => Assert.IsType(observer), - observer => Assert.IsType(observer), - observer => Assert.IsType(observer)); + observer => Assert.IsType(observer), + observer => Assert.IsType(observer), + observer => Assert.IsType(observer)); } [Fact] @@ -73,13 +73,13 @@ public void HostReadingsComeAfterEveryLibraryReading() { HostObserver host = new(); - var observers = CallObservers.Standard(new AcceptingSink(), logger: null, [host]); + var observers = ConversationObservers.Standard(new AcceptingSink(), logger: null, [host]); Assert.Collection( observers, - observer => Assert.IsType(observer), - observer => Assert.IsType(observer), - observer => Assert.IsType(observer), + observer => Assert.IsType(observer), + observer => Assert.IsType(observer), + observer => Assert.IsType(observer), observer => Assert.Same(host, observer)); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionApprovalTests.cs similarity index 94% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionApprovalTests.cs index 150b48a0..c1606d75 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionApprovalTests.cs @@ -12,12 +12,12 @@ namespace AgentCore.Application.Tests.Runtime; /// /// The approval round trip through the turn loop: a gated tool suspends the turn with a request -/// instead of failing it, and the caller's answer on the same call runs the tool. +/// instead of failing it, and the caller's answer on the same conversation runs the tool. /// /// -/// Every test here runs offline. There is no network call and no API key anywhere in this file. +/// Every test here runs offline. There is no network conversation and no API key anywhere in this file. /// -public sealed class CallSessionApprovalTests +public sealed class ConversationSessionApprovalTests { private const string GatedYaml = """ @@ -143,7 +143,7 @@ public async Task AGatedToolCall_KeepsTheQueueInTheSnapshot() Assert.True(session.Snapshot().Providers.ContainsKey("_pendingApprovalRequests")); } - private static CallSession Session(string yaml, Action onSend, CancellationToken token) + private static ConversationSession Session(string yaml, Action onSend, CancellationToken token) { ToolCallingChatClient client = new( "done.", @@ -159,7 +159,7 @@ private static CallSession Session(string yaml, Action onSend, CancellationToken token), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new TestGuardEvaluator(document), extractor: null, diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionEditTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionEditTests.cs similarity index 73% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionEditTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionEditTests.cs index bbe8635e..25d25918 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionEditTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionEditTests.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -13,9 +13,9 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// A caller sends an earlier message again, and the call takes back what it said after it. +/// A caller sends an earlier message again, and the conversation takes back what it said after it. /// -public sealed class CallSessionEditTests +public sealed class ConversationSessionEditTests { private const string OneAgentYaml = """ apiVersion: agentcore/v1 @@ -49,18 +49,18 @@ public async Task AnEdit_TakesTheReplacedWordsOutOfWhatTheModelReads() await session.RunTurnAtOriginAsync( "first question", - new CallTurnOrigin("caller-1", null) { NamesParent = true }, + new ConversationTurnOrigin("caller-1", null) { NamesParent = true }, TestContext.Current.CancellationToken); var firstReply = session.LastReplyMessageId; await session.RunTurnAtOriginAsync( "second question", - new CallTurnOrigin("caller-2", firstReply) { NamesParent = true }, + new ConversationTurnOrigin("caller-2", firstReply) { NamesParent = true }, TestContext.Current.CancellationToken); await session.RunTurnAtOriginAsync( "second question, rewritten", - new CallTurnOrigin("caller-3", firstReply) { NamesParent = true }, + new ConversationTurnOrigin("caller-3", firstReply) { NamesParent = true }, TestContext.Current.CancellationToken); // What the model was actually handed, not what the reply says: a stub controls the reply @@ -80,7 +80,7 @@ public async Task AnEdit_NamesTheTurnsItWithdrew() await session.RunTurnAtOriginAsync( "q1", - new CallTurnOrigin("caller-1", null) { NamesParent = true }, + new ConversationTurnOrigin("caller-1", null) { NamesParent = true }, TestContext.Current.CancellationToken); var firstReply = session.LastReplyMessageId; @@ -89,26 +89,26 @@ await session.RunTurnAtOriginAsync( await session.RunTurnAtOriginAsync( "q2, rewritten", - new CallTurnOrigin("caller-4", firstReply) { NamesParent = true }, + new ConversationTurnOrigin("caller-4", firstReply) { NamesParent = true }, TestContext.Current.CancellationToken); // The rows of turns 1 and 2 are deleted by now, so the trail can only say what it was told. var superseded = Assert.Single( - observer.Events, raised => raised.Kind == CallEventKind.TurnSuperseded); + observer.Events, raised => raised.Kind == ConversationEventKind.TurnSuperseded); Assert.Equal("1", superseded.Payload[AuditPayloadKeys.WithdrewFromTurnIndex]); Assert.Equal("2", superseded.Payload[AuditPayloadKeys.WithdrewThroughTurnIndex]); Assert.Equal(3, superseded.TurnIndex); } [Fact] - public async Task AnEditOnATerminalCall_IsRefusedAndTakesNothing() + public async Task AnEditOnATerminalConversation_IsRefusedAndTakesNothing() { using ScriptedChatClient reply = new("an answer."); var session = CreateSession(TerminalYaml, reply); await session.RunTurnAtOriginAsync( "q1", - new CallTurnOrigin("caller-1", null) { NamesParent = true }, + new ConversationTurnOrigin("caller-1", null) { NamesParent = true }, TestContext.Current.CancellationToken); var firstReply = session.LastReplyMessageId; Assert.True(session.IsComplete); @@ -116,10 +116,10 @@ await session.RunTurnAtOriginAsync( await Assert.ThrowsAsync( () => session.RunTurnAtOriginAsync( "q1, rewritten", - new CallTurnOrigin("caller-2", null) { NamesParent = true }, + new ConversationTurnOrigin("caller-2", null) { NamesParent = true }, TestContext.Current.CancellationToken)); - // The withdrawal deletes. A turn the guards refuse must not have taken the tail of the call + // The withdrawal deletes. A turn the guards refuse must not have taken the tail of the conversation // with it on the way out, or the caller is left with neither the old words nor the new. Assert.Equal(2, session.Transcript.Count); Assert.NotNull(firstReply); @@ -134,19 +134,19 @@ public async Task AnOriginThatNamesNoParent_WithdrawsNothing() await session.RunTurnAsync("q1", TestContext.Current.CancellationToken); - // A null parent means the start of the call and would take every word of it. A caller that + // A null parent means the start of the conversation and would take every word of it. A caller that // named its own message and said nothing about a parent has asked for no such thing. await session.RunTurnAtOriginAsync( "q2", - new CallTurnOrigin("caller-2", null) { NamesParent = false }, + new ConversationTurnOrigin("caller-2", null) { NamesParent = false }, TestContext.Current.CancellationToken); Assert.Equal(4, session.Transcript.Count); - Assert.DoesNotContain(observer.Events, raised => raised.Kind == CallEventKind.TurnSuperseded); + Assert.DoesNotContain(observer.Events, raised => raised.Kind == ConversationEventKind.TurnSuperseded); } - private static CallSession CreateSession( - string yaml, IChatClient reply, ICallObserver? observer = null) + private static ConversationSession CreateSession( + string yaml, IChatClient reply, IConversationObserver? observer = null) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new FakeChatClientFactory(reply); @@ -154,26 +154,26 @@ private static CallSession CreateSession( document, new AgentCompilationContext(chatClients) { - CallStore = new InMemoryCallStore(), + ConversationStore = new InMemoryConversationStore(), Tools = TestToolRegistry.From(document, null, TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null, observers: observer is null ? null : [observer]); - return factory.Create("call-1"); + return factory.Create("conversation-1"); } - /// Keeps every fact of the call, in the order the turn loop raised them. - private sealed class RecordingObserver : ICallObserver + /// Keeps every fact of the conversation, in the order the turn loop raised them. + private sealed class RecordingObserver : IConversationObserver { private readonly Lock _gate = new(); - private readonly List _events = []; + private readonly List _events = []; - public IReadOnlyList Events + public IReadOnlyList Events { get { @@ -184,11 +184,11 @@ public IReadOnlyList Events } } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { lock (_gate) { - _events.Add(callEvent); + _events.Add(conversationEvent); } return ValueTask.CompletedTask; diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionFactoryModelFacingTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionFactoryModelFacingTests.cs similarity index 88% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionFactoryModelFacingTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionFactoryModelFacingTests.cs index 384315c7..772670e6 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionFactoryModelFacingTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionFactoryModelFacingTests.cs @@ -12,13 +12,13 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// CallSessionFactory.CreateExtractor is the third site that must strip a -/// before a model reads it — CallSession.ExtractAsync hands the +/// ConversationSessionFactory.CreateExtractor is the third site that must strip a +/// before a model reads it — ConversationSession.ExtractAsync hands the /// extractor [turn.Spoken, .. response.Messages], and response.Messages is exactly the -/// list a drawing tool attaches to. This proves the extractor builds, +/// list a drawing tool attaches to. This proves the extractor builds, /// not a hand-constructed ModelFacingChatClient. /// -public sealed class CallSessionFactoryModelFacingTests +public sealed class ConversationSessionFactoryModelFacingTests { private const string Yaml = """ @@ -46,7 +46,7 @@ public async Task TheExtractorTheFactoryBuilds_NeverForwardsARenderContentTheTur RequestCapturingChatClient recorder = new( new ScriptedChatClient("""{ "callerSaidGoodbye": null }""")); - var extractor = CallSessionFactory.CreateExtractor( + var extractor = ConversationSessionFactory.CreateExtractor( compiled, new RoutingChatClientFactory(new ScriptedChatClient("ok")).Route("fill", recorder)); Assert.NotNull(extractor); diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionGraphReplyTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionGraphReplyTests.cs similarity index 87% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionGraphReplyTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionGraphReplyTests.cs index 0add7e9a..3555a2c9 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionGraphReplyTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionGraphReplyTests.cs @@ -24,10 +24,10 @@ namespace AgentCore.Application.Tests.Runtime; /// deliberation as the spoken words. The turn loop takes the last message instead. /// /// -/// Every test here runs offline. There is no network call and no API key in this file. +/// Every test here runs offline. There is no network conversation and no API key in this file. /// /// -public sealed class CallSessionGraphReplyTests +public sealed class ConversationSessionGraphReplyTests { /// What the first node of the graph says while it works. The caller must not hear it. private const string Thinking = "Let me check the order system."; @@ -73,7 +73,7 @@ public async Task CompleteTurn_GraphRow_SpeaksFinalNodeReplyOnly() using ScriptedChatClient researcher = new(Thinking); using ScriptedChatClient responder = new(Spoken); InMemoryAuditSink sink = new(); - var session = Build(GraphYaml, researcher, responder, sink).Create("call-graph"); + var session = Build(GraphYaml, researcher, responder, sink).Create("conversation-graph"); // Act. var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); @@ -83,7 +83,7 @@ public async Task CompleteTurn_GraphRow_SpeaksFinalNodeReplyOnly() Assert.DoesNotContain(Thinking, turn.ReplyText, StringComparison.Ordinal); var completed = Assert.Single( - sink.EventsOf("call-graph"), + sink.EventsOf("conversation-graph"), entry => entry.Kind == AuditEventKind.TurnCompleted); Assert.Equal(AuditHash.OfText(Spoken).Value, completed.Payload[AuditPayloadKeys.ReplyTextSha256]); } @@ -95,7 +95,7 @@ public async Task CompleteTurn_ToolCallingTurn_SpeaksFinalAssistantMessage() using ToolCallingChatClient reply = new(Spoken); InMemoryAuditSink sink = new(); var session = Build(ToolYaml, reply, null, sink, new StubToolBuilder("""{ "status": "shipped" }""").Create) - .Create("call-tool"); + .Create("conversation-tool"); // Act. var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); @@ -105,7 +105,7 @@ public async Task CompleteTurn_ToolCallingTurn_SpeaksFinalAssistantMessage() Assert.Equal(Spoken, turn.ReplyText); var completed = Assert.Single( - sink.EventsOf("call-tool"), + sink.EventsOf("conversation-tool"), entry => entry.Kind == AuditEventKind.TurnCompleted); Assert.Equal(AuditHash.OfText(Spoken).Value, completed.Payload[AuditPayloadKeys.ReplyTextSha256]); } @@ -117,22 +117,22 @@ public async Task CompleteTurn_GraphRowWhoseFinalNodeGoesQuiet_SpeaksTheFallback using ScriptedChatClient researcher = new(Thinking); using ScriptedChatClient responder = new(" "); InMemoryAuditSink sink = new(); - var session = Build(GraphYaml, researcher, responder, sink).Create("call-quiet"); + var session = Build(GraphYaml, researcher, responder, sink).Create("conversation-quiet"); // Act. var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); - // Assert. A quiet answer is silence on a voice call, so the turn speaks the fallback. It must + // Assert. A quiet answer is silence on a voice conversation, so the turn speaks the fallback. It must // never fall back to the node before it, which is the graph thinking out loud. - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); - Assert.Equal(CallSession.EmptyReplyReason, turn.Failure); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.EmptyReplyReason, turn.Failure); Assert.DoesNotContain(Thinking, turn.ReplyText, StringComparison.Ordinal); var completed = Assert.Single( - sink.EventsOf("call-quiet"), + sink.EventsOf("conversation-quiet"), entry => entry.Kind == AuditEventKind.TurnCompleted); Assert.Equal( - AuditHash.OfText(CallSession.FallbackReply).Value, + AuditHash.OfText(ConversationSession.FallbackReply).Value, completed.Payload[AuditPayloadKeys.ReplyTextSha256]); } @@ -142,7 +142,7 @@ public async Task Streaming_GraphRowWhoseFinalNodeGoesQuiet_SpeaksTheFallback() // Arrange. The same graph, on the run shape that hands each piece over as it arrives. using ScriptedChatClient researcher = new(Thinking); using ScriptedChatClient responder = new(" "); - var session = Build(GraphYaml, researcher, responder, new InMemoryAuditSink()).Create("call-quiet"); + var session = Build(GraphYaml, researcher, responder, new InMemoryAuditSink()).Create("conversation-quiet"); // Act. List spoken = []; @@ -155,10 +155,10 @@ public async Task Streaming_GraphRowWhoseFinalNodeGoesQuiet_SpeaksTheFallback() // Assert. The host hears one fallback and none of the deliberation. The quiet node's own // whitespace still passes the seam — a space between two words is speech, so the filter // cannot drop one — and it is inaudible. - Assert.Equal(CallSession.FallbackReply, string.Concat(spoken).Trim()); + Assert.Equal(ConversationSession.FallbackReply, string.Concat(spoken).Trim()); Assert.DoesNotContain(Thinking, string.Concat(spoken), StringComparison.Ordinal); Assert.NotNull(session.LastTurn); - Assert.Equal(CallSession.EmptyReplyReason, session.LastTurn.Failure); + Assert.Equal(ConversationSession.EmptyReplyReason, session.LastTurn.Failure); } [Fact] @@ -167,7 +167,7 @@ public async Task Streaming_GraphRow_StreamsEveryFragmentOfTheFinalNodeAndNoneOf // Arrange. The node that answers speaks in pieces, the way a real model streams. using ScriptedChatClient researcher = new(Thinking); using ScriptedChatClient responder = new("Order 41 ", "ships Friday."); - var session = Build(GraphYaml, researcher, responder, new InMemoryAuditSink()).Create("call-stream"); + var session = Build(GraphYaml, researcher, responder, new InMemoryAuditSink()).Create("conversation-stream"); // Act. List spoken = []; @@ -190,7 +190,7 @@ public async Task Streaming_GraphRow_StreamsEveryFragmentOfTheFinalNodeAndNoneOf /// Where the turn's events land. /// The tool factory, if the configuration declares a tool. /// The factory. - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IChatClient? responder, @@ -211,9 +211,9 @@ private static CallSessionFactory Build( Tools = TestToolRegistry.From(document, tools, TestContext.Current.CancellationToken), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - observers: CallObservers.Standard(sink, logger: null)); + observers: ConversationObservers.Standard(sink, logger: null)); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionInterruptionTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionInterruptionTests.cs similarity index 92% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionInterruptionTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionInterruptionTests.cs index d8480da6..e1bb7e7f 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionInterruptionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionInterruptionTests.cs @@ -21,9 +21,9 @@ namespace AgentCore.Application.Tests.Runtime; /// 11: the record holds the text the caller heard, and a side effect that already ran is not dropped. /// /// -/// Every test here runs offline. There is no network call and no API key anywhere in this file. +/// Every test here runs offline. There is no network conversation and no API key anywhere in this file. /// -public sealed class CallSessionInterruptionTests +public sealed class ConversationSessionInterruptionTests { private const string NoToolYaml = """ @@ -127,10 +127,10 @@ public async Task AToolCallThatFinishedBeforeTheBargeIn_StaysInTheTranscript() } [Fact] - public async Task AParallelToolRound_KeepsTheCallThatFinishedAndDropsTheOneThatDidNot() + public async Task AParallelToolRound_KeepsTheConversationThatFinishedAndDropsTheOneThatDidNot() { // A parallel round can pair one call and leave a sibling call, in the same message, mid- - // flight. The rule is per call id, so only the unfinished call is dropped. + // flight. The rule is per conversation id, so only the unfinished conversation is dropped. using ParallelToolCallChatClient reply = new(); PartiallyAnsweredToolFactory tools = new(); var session = CreateSession(ParallelToolYaml, reply, tools.Create); @@ -154,7 +154,7 @@ public async Task AParallelToolRound_KeepsTheCallThatFinishedAndDropsTheOneThatD CancellationToken.None); // The first call already answered by the time the second call is blocked in flight. - await tools.SecondCallStarted.Task.WaitAsync(linked.Token); + await tools.SecondConversationStarted.Task.WaitAsync(linked.Token); Assert.True(session.Interrupt("the first one is", TimeSpan.FromMilliseconds(1820))); await pump; @@ -207,7 +207,7 @@ public async Task ProseBesideAFinishedToolCall_LeavesTheTranscriptOnTheHeardText // ------------------------------------------------------------------------------------------- // A barge-in that arrives after the turn task already ended. Telnyx paces the audio, so the // model finishes streaming long before the vendor finishes speaking, and this is the common - // shape on a real call rather than an edge case. + // shape on a real conversation rather than an edge case. // ------------------------------------------------------------------------------------------- [Fact(Timeout = 30_000)] @@ -238,7 +238,7 @@ public async Task AnInterruptAfterTheTurnEnded_AmendsTheFinishedTurn() Assert.Equal("Hello there", assistant.Text); // T23: the chain is append-only, so the correction is a second event that names the first. - var events = sink.EventsOf(session.CallId); + var events = sink.EventsOf(session.ConversationId); var completed = Assert.Single(events, item => item.Kind == AuditEventKind.TurnCompleted); var amendment = Assert.Single(events, item => item.Kind == AuditEventKind.ReplyInterrupted); Assert.Equal(completed.EventId, amendment.AmendsEventId); @@ -250,7 +250,7 @@ public async Task AnInterruptAfterTheTurnEnded_AmendsTheFinishedTurn() // One barge-in cuts one reply once. A repeat frame amends nothing a second time. Assert.False(session.Interrupt("Hello there caller", TimeSpan.FromMilliseconds(2400))); - Assert.Single(sink.EventsOf(session.CallId), item => item.Kind == AuditEventKind.ReplyInterrupted); + Assert.Single(sink.EventsOf(session.ConversationId), item => item.Kind == AuditEventKind.ReplyInterrupted); } [Fact(Timeout = 30_000)] @@ -265,7 +265,7 @@ public void AnInterruptBeforeAnyTurnEverRan_ChangesNothingAndThrowsNothing() Assert.Null(session.LastTurn); Assert.Empty(session.Transcript); Assert.DoesNotContain( - sink.EventsOf(session.CallId), + sink.EventsOf(session.ConversationId), item => item.Kind == AuditEventKind.ReplyInterrupted); } @@ -285,7 +285,7 @@ public async Task AnInterruptWhileAnUnheardSecondTurnRuns_AmendsTheFirstTurnAndL await foreach (var _ in session.RunTurnStreamingAsync("one", bounded.Token).ConfigureAwait(false)) { - // Turn one runs to its end, exactly as it does on a real call. + // Turn one runs to its end, exactly as it does on a real conversation. } var first = session.LastTurn; @@ -336,7 +336,7 @@ public async Task AnInterruptWhileAnUnheardSecondTurnRuns_AmendsTheFirstTurnAndL Assert.Null(session.LastTurn!.InterruptedAfter); var amendment = Assert.Single( - sink.EventsOf(session.CallId), + sink.EventsOf(session.ConversationId), item => item.Kind == AuditEventKind.ReplyInterrupted); Assert.Equal(first!.TurnIndex, amendment.TurnIndex); Assert.Equal( @@ -357,7 +357,7 @@ public async Task AnInterruptWhileTheExtractorRuns_IsRecordedAndNotOnlyReported( // later still, in the finally of whichever method opened the turn, so a frame that lands // inside that await finds a live run and — on a streaming turn, audible since its first // yielded fragment — takes the in-flight path, sets the record, and answers true. And true, - // on Interrupt's own contract, means "this call recorded the barge-in". The commit lock + // on Interrupt's own contract, means "this conversation recorded the barge-in". The commit lock // reads the field a second time for exactly this frame. Without that read the turn commits // as an ordinary completed turn: InterruptedAfter stays null, the transcript keeps the whole // reply the model produced rather than the words the caller heard, and the chain carries no @@ -370,11 +370,11 @@ public async Task AnInterruptWhileTheExtractorRuns_IsRecordedAndNotOnlyReported( var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(ExtractorYaml), new AgentCompilationContext(chatClients))["main"]; InMemoryAuditSink sink = new(); - var session = new CallSessionFactory( + var session = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), - observers: CallObservers.Standard(sink, logger: null)).Create(); + ConversationSessionFactory.CreateExtractor(compiled, chatClients), + observers: ConversationObservers.Standard(sink, logger: null)).Create(); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10)); using var bounded = CancellationTokenSource.CreateLinkedTokenSource( @@ -426,7 +426,7 @@ public async Task AnInterruptWhileTheExtractorRuns_IsRecordedAndNotOnlyReported( Assert.Equal("Hello there", assistant.Text); // T23: the correction is a second event that names the first, and never an edit of it. - var events = sink.EventsOf(session.CallId); + var events = sink.EventsOf(session.ConversationId); var completed = Assert.Single(events, item => item.Kind == AuditEventKind.TurnCompleted); var amendment = Assert.Single(events, item => item.Kind == AuditEventKind.ReplyInterrupted); Assert.Equal(completed.EventId, amendment.AmendsEventId); @@ -438,7 +438,7 @@ public async Task AnInterruptWhileTheExtractorRuns_IsRecordedAndNotOnlyReported( // One barge-in cuts one reply once. The turn is no longer amendable, so a repeat says so. Assert.False(session.Interrupt("Hello there caller", TimeSpan.FromMilliseconds(2400))); - Assert.Single(sink.EventsOf(session.CallId), item => item.Kind == AuditEventKind.ReplyInterrupted); + Assert.Single(sink.EventsOf(session.ConversationId), item => item.Kind == AuditEventKind.ReplyInterrupted); } // ------------------------------------------------------------------------------------------- @@ -446,30 +446,30 @@ public async Task AnInterruptWhileTheExtractorRuns_IsRecordedAndNotOnlyReported( // ------------------------------------------------------------------------------------------- [Fact] - public async Task AnExtractorThatNeverReturns_DoesNotHoldTheCallOpenForever() + public async Task AnExtractorThatNeverReturns_DoesNotHoldTheConversationOpenForever() { // The extractor runs on the host token on purpose, so a barge-in never cancels it. Nothing - // else bounds it, and a hung extractor would hold the call. livekit carries a five-second + // else bounds it, and a hung extractor would hold the conversation. livekit carries a five-second // watchdog for the same reason. await using var fixture = InterruptionFixture.StartWithHangingExtractor(reply: "hello"); var turn = await fixture.RunTurnAsync("hi").WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); Assert.NotNull(turn); - Assert.Equal(CallSession.ExtractionTimedOutReason, fixture.LastExtractionFailure); + Assert.Equal(ConversationSession.ExtractionTimedOutReason, fixture.LastExtractionFailure); } // ------------------------------------------------------------------------------------------- // Helpers. // ------------------------------------------------------------------------------------------- - private static CallSession CreateSession( + private static ConversationSession CreateSession( string yaml, IChatClient reply, Func? tools = null, IAuditSinkPort? auditSink = null) { - // There is always a sink now: CallObservers.Standard takes a required one, because the + // There is always a sink now: ConversationObservers.Standard takes a required one, because the // composition root resolves providers.audit for every host and falls back to the in-process // memory kind. An optional parameter has to be a compile-time constant, so the default is // spelled here instead — a fact that does not care where its events land gets a fresh @@ -485,11 +485,11 @@ private static CallSession CreateSession( Tools = TestToolRegistry.From(document, tools, TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), - observers: CallObservers.Standard(sink, logger: null)); + ConversationSessionFactory.CreateExtractor(compiled, chatClients), + observers: ConversationObservers.Standard(sink, logger: null)); return factory.Create(); } @@ -511,7 +511,7 @@ private sealed class InterruptionFixture : IAsyncDisposable private readonly TaskCompletionSource _firstUpdate = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly Task _run; - private InterruptionFixture(CallSession session, IChatClient reply, Action openGate, CancellationToken hostToken) + private InterruptionFixture(ConversationSession session, IChatClient reply, Action openGate, CancellationToken hostToken) { Session = session; _disposables = [reply]; @@ -524,20 +524,20 @@ private InterruptionFixture(CallSession session, IChatClient reply, Action openG } /// Builds a fixture over a turn that runs directly, with no streaming pump behind it. - private InterruptionFixture(CallSession session, IReadOnlyList disposables, CancellationToken hostToken) + private InterruptionFixture(ConversationSession session, IReadOnlyList disposables, CancellationToken hostToken) { Session = session; _disposables = disposables; _openGate = static () => { }; _cancellation = CancellationTokenSource.CreateLinkedTokenSource(hostToken); _cancellation.CancelAfter(TimeSpan.FromSeconds(30)); - // RunTurnAsync drives the turn itself, on the caller's own call. There is no round to + // RunTurnAsync drives the turn itself, on the caller's own conversation. There is no round to // stream and gate, so there is nothing here for a background pump to do. _run = Task.CompletedTask; } /// Gets the session the turn runs on. - public CallSession Session { get; } + public ConversationSession Session { get; } /// Starts a turn over a plain text reply, gated after its first fragment. public static InterruptionFixture Start(string reply) @@ -568,7 +568,7 @@ public static InterruptionFixture StartWithProseBesideTool(string reply) /// The extractor runs on fill, the route gives a /// test to script apart from the reply model. answers that /// route, and it awaits a nobody ever sets, so nothing but - /// ends the call. + /// ends the conversation. /// public static InterruptionFixture StartWithHangingExtractor(string reply) { @@ -578,10 +578,10 @@ public static InterruptionFixture StartWithHangingExtractor(string reply) var document = ConfigurationLoader.LoadYaml(ExtractorYaml); var compiled = ConfigurationCompiler.CompileAll(document, new AgentCompilationContext(chatClients))["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients)); + ConversationSessionFactory.CreateExtractor(compiled, chatClients)); return new InterruptionFixture( factory.Create(), @@ -653,11 +653,11 @@ private async Task PumpAsync() /// /// covers the tool round, and /// covers a gated round, but the finished-tool fact of this file needs both in one run: a tool - /// call whose result already arrived before the barge-in reaches the reply that follows it. + /// conversation whose result already arrived before the barge-in reaches the reply that follows it. /// private sealed class GatedToolThenReplyChatClient : IChatClient { - private const string ToolCallId = "call_1"; + private const string ToolCallId = "conversation_1"; private readonly string[] _fragments; private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -741,8 +741,8 @@ public void Dispose() /// /// /// yields a tool round that carries nothing but the - /// call. A real model routinely writes a line first — "Let me check that for you" — and puts the - /// call beside it on the same message. No other fake in this project can produce that shape, and + /// conversation. A real model routinely writes a line first — "Let me check that for you" — and puts the + /// conversation beside it on the same message. No other fake in this project can produce that shape, and /// it is the shape the transcript rule of item 6a has to survive. /// private sealed class ProseBesideToolChatClient : IChatClient @@ -750,7 +750,7 @@ private sealed class ProseBesideToolChatClient : IChatClient /// The line the model speaks before it calls the tool. public const string Prose = "Let me check that for you"; - private const string ToolCallId = "call_1"; + private const string ToolCallId = "conversation_1"; private readonly string[] _fragments; private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -773,7 +773,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( if (!answered && options?.Tools?.OfType().FirstOrDefault() is { } tool) { - // The prose and the call ride one message, which is what a real model produces. + // The prose and the conversation ride one message, which is what a real model produces. yield return new ChatResponseUpdate( ChatRole.Assistant, [ @@ -925,16 +925,16 @@ public void Dispose() /// The runtime commits a round's tool results as one batch, so a round that never finishes /// invoking surfaces no message at all, finished or not. Round one is a single call and finishes /// on its own, so its result is already on the transcript when round two's message asks for two - /// calls at once. That is the only way to reach the shape the multi-call fact needs: a message + /// conversations at once. That is the only way to reach the shape the multi-conversation fact needs: a message /// with two calls where the finished-tool filter must trim rather than drop or keep it whole. /// private sealed class ParallelToolCallChatClient : IChatClient { - /// The id of the call whose result arrives before the barge-in. - public const string FirstCallId = "call_a"; + /// The id of the conversation whose result arrives before the barge-in. + public const string FirstCallId = "conversation_a"; - /// The id of the call still in flight when the barge-in arrives. - public const string SecondCallId = "call_b"; + /// The id of the conversation still in flight when the barge-in arrives. + public const string SecondCallId = "conversation_b"; public async IAsyncEnumerable GetStreamingResponseAsync( IEnumerable messages, @@ -970,7 +970,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield break; } - // Round two. The already-answered call rides again beside the new one, on one message. + // Round two. The already-answered conversation rides again beside the new one, on one message. yield return new ChatResponseUpdate( ChatRole.Assistant, [ @@ -1018,14 +1018,14 @@ public void Dispose() /// /// /// The barge-in cancels the run's token, and nothing else ever completes the second call, so its - /// result never joins . tells - /// a test the first call already finished and the second is now the one in flight, which is the - /// instant a test must interrupt to pin the per-call-id rule. + /// result never joins . tells + /// a test the first conversation already finished and the second is now the one in flight, which is the + /// instant a test must interrupt to pin the per-conversation-id rule. /// private sealed class PartiallyAnsweredToolFactory { /// Signals once the second call is in flight and blocked. - public TaskCompletionSource SecondCallStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource SecondConversationStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public AIFunction? Create(ToolConfiguration tool) { @@ -1040,7 +1040,7 @@ private async Task AnswerAsync(int index, CancellationToken cancellation return "50"; } - SecondCallStarted.TrySetResult(); + SecondConversationStarted.TrySetResult(); await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); // Unreachable: the delay above only ever ends in cancellation. @@ -1054,7 +1054,7 @@ private async Task AnswerAsync(int index, CancellationToken cancellation /// /// never answers at all, which is what §8.7's deadline needs. /// This one has to answer, because the fact it serves is about what the turn commits *after* the - /// extractor returns: the window a late barge-in lands in is exactly the width of this call, and + /// extractor returns: the window a late barge-in lands in is exactly the width of this conversation, and /// nothing else in the turn loop opens one that a test can stand inside of. The gate is not read /// through on purpose — the extractor runs on the host token so /// a barge-in never cancels it, and a defect that did cancel it would end this wait quietly and @@ -1106,7 +1106,7 @@ public void Dispose() /// Answers nothing, ever. It stands in for the extractor model hanging past its deadline. /// - /// §8.7's deadline is what ends this call, not the model, so awaits + /// §8.7's deadline is what ends this conversation, not the model, so awaits /// a nobody ever sets. It returns only when its own /// cancels. /// diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionProbeTests.cs similarity index 93% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionProbeTests.cs index d6db658e..36bd2688 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionProbeTests.cs @@ -12,12 +12,12 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// §8's probe, driven through real turns rather than by seeding the +/// §8's probe, driven through real turns rather than by seeding the /// ambient: the genuinely two-turn row (K43's latch reset against K22's persistent counter) needs /// the real turn loop's own BeginTurn, which KnowledgeProbeTests's ambient-level /// tests cannot exercise. /// -public sealed class CallSessionProbeTests +public sealed class ConversationSessionProbeTests { /// One tool-mode, scoped agent over two droppable facets, so K33 never blocks the drop. private const string ProbeYaml = @@ -38,7 +38,7 @@ public sealed class CallSessionProbeTests model: { ref: fill } when: after_reply providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -69,7 +69,7 @@ public async Task TwoTurns_TheProbeAlwaysThrows_TheSecondTurnStillRunsAFreshProb // turn that attempts a genuinely new probe search -- rather than replaying turn one's stored // failure -- is what proves BeginTurn actually ran, wired through the real turn loop rather // than asserted directly against Clarifications (KnowledgeProbeTests already covers that unit - // in isolation, without needing a live CallSession). + // in isolation, without needing a live ConversationSession). var narrowedCalls = 0; var port = new ThrowingOnNarrowedScopePort(() => Interlocked.Increment(ref narrowedCalls)); @@ -87,11 +87,11 @@ public async Task TwoTurns_TheProbeAlwaysThrows_TheSecondTurnStillRunsAFreshProb var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(ProbeYaml), new AgentCompilationContext(chatClients) { Knowledge = port })["main"]; - var stateExtractor = CallSessionFactory.CreateExtractor(compiled, chatClients); + var stateExtractor = ConversationSessionFactory.CreateExtractor(compiled, chatClients); - var session = new CallSessionFactory( + var session = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), stateExtractor) - .Create("call-probe-two-turn"); + .Create("conversation-probe-two-turn"); await session.RunTurnAsync("what model is it", TestContext.Current.CancellationToken); await session.RunTurnAsync("still not sure", TestContext.Current.CancellationToken); @@ -155,7 +155,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - $"call_{index}", + $"conversation_{index}", toolName, new Dictionary(StringComparer.Ordinal) { ["userQuestion"] = "what model is it" })]) { diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionTests.cs similarity index 92% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionTests.cs index f087964d..0c7fd07c 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionTests.cs @@ -13,12 +13,12 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// The turn loop. One session runs one call, and one turn walks the writers in one fixed order. +/// The turn loop. One session runs one conversation, and one turn walks the writers in one fixed order. /// /// -/// Every test here runs offline. There is no network call and no API key anywhere in this file. +/// Every test here runs offline. There is no network conversation and no API key anywhere in this file. /// -public sealed class CallSessionTests +public sealed class ConversationSessionTests { private const string PolicyYaml = """ @@ -45,7 +45,7 @@ public sealed class CallSessionTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller" } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -78,7 +78,7 @@ public sealed class CallSessionTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller" } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -133,7 +133,7 @@ public sealed class CallSessionTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller", tools: [ lookup_order ] } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -165,11 +165,11 @@ public async Task ATurn_RunsTheAgentOfTheCurrentStageAndReportsWhatItDid() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); - var session = Build(PolicyYaml, reply, fill).Create("call-1"); + var session = Build(PolicyYaml, reply, fill).Create("conversation-1"); var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - Assert.Equal("call-1", turn.CallId); + Assert.Equal("conversation-1", turn.ConversationId); Assert.Equal(0, turn.TurnIndex); Assert.Equal("greeting", turn.StageBefore); Assert.Equal("greeting", turn.StageAfter); @@ -188,7 +188,7 @@ public async Task ATurn_MakesTwoModelCalls_TheReplyAndTheExtractor() await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // The extractor has no retry: one reply call, and one extractor call. + // The extractor has no retry: one reply conversation, and one extractor call. Assert.Equal(1, reply.Calls); Assert.Equal(1, fill.Calls); } @@ -309,7 +309,7 @@ public async Task TheReminder_NeverAsksTheCallerForAnInferredFlag() // The session owns the transcript, and the stage switches the agent. // ------------------------------------------------------------------------------------------- [Fact] - public async Task TheStage_SwitchesTheAgentAndTheTranscriptCarriesTheWholeCall() + public async Task TheStage_SwitchesTheAgentAndTheTranscriptCarriesTheWholeConversation() { using SequencedChatClient reply = new("first reply.", "second reply."); var session = Build(TwoStagesYaml, reply, null).Create(); @@ -458,7 +458,7 @@ public async Task AFailedExtraction_DoesNotDropTheTurn() var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // Section 8.7: the extractor never drops a call. The turn ends, and it carries the reason. + // Section 8.7: the extractor never drops a conversation. The turn ends, and it carries the reason. Assert.NotNull(turn.ExtractionFailure); Assert.Equal("hello there.", turn.ReplyText); Assert.Equal("greeting", turn.StageAfter); @@ -489,21 +489,21 @@ public async Task TheReservedSlots_CountTheFinishedTurnsAndReadTheInjectedClock( var session = Build(PolicyYaml, reply, fill, timeProvider: clock).Create(); Assert.Equal(0, session.State.TurnIndex); - Assert.Equal(0, session.State.CallDurationSeconds); + Assert.Equal(0, session.State.ConversationDurationSeconds); clock.Advance(TimeSpan.FromSeconds(12.5)); var first = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); Assert.Equal(0, first.TurnIndex); Assert.Equal(1, session.State.TurnIndex); - Assert.Equal(12.5, session.State.CallDurationSeconds); + Assert.Equal(12.5, session.State.ConversationDurationSeconds); clock.Advance(TimeSpan.FromSeconds(7.5)); var second = await session.RunTurnAsync("still there?", TestContext.Current.CancellationToken); Assert.Equal(1, second.TurnIndex); Assert.Equal(2, session.State.TurnIndex); - Assert.Equal(20, session.State.CallDurationSeconds); + Assert.Equal(20, session.State.ConversationDurationSeconds); } [Fact] @@ -520,10 +520,10 @@ public async Task TheStage_ReachesTheStateDocumentSoAGuardReadsIt() } // ------------------------------------------------------------------------------------------- - // A finished call. + // A finished conversation. // ------------------------------------------------------------------------------------------- [Fact] - public async Task ACompleteCall_RejectsAFurtherTurn() + public async Task ACompleteConversation_RejectsAFurtherTurn() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(SaidGoodbye); @@ -653,17 +653,17 @@ public async Task AnEmptyReply_SpeaksTheFallbackAndReportsWhyTheTurnFailed() var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // Request 41 goes out with no tools and the run returns with no exception. On a voice call + // Request 41 goes out with no tools and the run returns with no exception. On a voice conversation // that is silence, so the turn loop reads the reply rather than trusting the absence of a // failure. - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); - Assert.Equal(CallSession.EmptyReplyReason, turn.Failure); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.EmptyReplyReason, turn.Failure); Assert.Null(turn.InterruptedAfter); // The writers still ran, and the transcript holds what the caller heard. Assert.Equal(1, session.State.TurnIndex); Assert.Equal(1, session.State.Read("greetingTurns")!.GetValue()); - Assert.Equal(CallSession.FallbackReply, session.Transcript[^1].Text); + Assert.Equal(ConversationSession.FallbackReply, session.Transcript[^1].Text); } [Fact] @@ -676,7 +676,7 @@ public async Task AnEmptyReply_LeavesTheSessionReadyForTheNextTurn() var first = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); var second = await session.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - Assert.Equal(CallSession.FallbackReply, first.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, first.ReplyText); Assert.Equal("I am back.", second.ReplyText); Assert.Null(second.Failure); Assert.Equal(1, second.TurnIndex); @@ -696,10 +696,10 @@ public async Task Streaming_SpeaksTheFallbackWhenTheRunProducesNoText() // The host hears the fallback rather than nothing at all: R2 makes a quiet run an ordinary // successful one, and the spoken line leaves the seam the same way any reply does. - Assert.Equal([CallSession.FallbackReply], updates.Select(update => update.Text)); + Assert.Equal([ConversationSession.FallbackReply], updates.Select(update => update.Text)); Assert.NotNull(session.LastTurn); - Assert.Equal(CallSession.FallbackReply, session.LastTurn.ReplyText); - Assert.Equal(CallSession.EmptyReplyReason, session.LastTurn.Failure); + Assert.Equal(ConversationSession.FallbackReply, session.LastTurn.ReplyText); + Assert.Equal(ConversationSession.EmptyReplyReason, session.LastTurn.Failure); Assert.Equal("close", session.Stage); } @@ -707,7 +707,7 @@ public async Task Streaming_SpeaksTheFallbackWhenTheRunProducesNoText() // Section 8.7, sixth row: the 4th consecutive tool failure. // ------------------------------------------------------------------------------------------- [Fact] - public async Task TheFourthConsecutiveToolFailure_EndsTheTurnAndNeverKillsTheCall() + public async Task TheFourthConsecutiveToolFailure_EndsTheTurnAndNeverKillsTheConversation() { using LoopingToolCallingChatClient reply = new(); using SequencedChatClient fill = new(StayingNull); @@ -718,9 +718,9 @@ public async Task TheFourthConsecutiveToolFailure_EndsTheTurnAndNeverKillsTheCal // MaximumConsecutiveErrorsPerRequest is 3, so the 4th failure throws out of the run. Assert.Equal(4, tools.Calls); - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); Assert.NotNull(turn.Failure); - Assert.StartsWith(CallSession.ToolFailureReason, turn.Failure, StringComparison.Ordinal); + Assert.StartsWith(ConversationSession.ToolFailureReason, turn.Failure, StringComparison.Ordinal); Assert.Contains(ThrowingToolBuilder.Message, turn.Failure, StringComparison.Ordinal); // The writers ran in their fixed order, and the machine picked the stage of the next turn. @@ -729,13 +729,13 @@ public async Task TheFourthConsecutiveToolFailure_EndsTheTurnAndNeverKillsTheCal Assert.False(session.IsComplete); // The transcript holds the spoken line alone. A half-finished tool round would otherwise - // leave a call with no result behind, and the next turn would send it. + // leave a conversation with no result behind, and the next turn would send it. Assert.Equal(2, session.Transcript.Count); - Assert.Equal(CallSession.FallbackReply, session.Transcript[^1].Text); + Assert.Equal(ConversationSession.FallbackReply, session.Transcript[^1].Text); } [Fact] - public async Task ARealDeclaredToolThatCannotReachItsEndpoint_EndsTheTurnPerRowSixAndKeepsTheCall() + public async Task ARealDeclaredToolThatCannotReachItsEndpoint_EndsTheTurnPerRowSixAndKeepsTheConversation() { // The same row, reached the way a shipped tool actually reaches it. ThrowingToolBuilder // throws straight at the framework; this goes through DeclaredTool, so the classification @@ -750,13 +750,13 @@ public async Task ARealDeclaredToolThatCannotReachItsEndpoint_EndsTheTurnPerRowS // MaximumConsecutiveErrorsPerRequest is 3, so the 4th failure throws out of the run. Assert.Equal(4, tools.Calls); - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); Assert.NotNull(turn.Failure); - Assert.StartsWith(CallSession.ToolFailureReason, turn.Failure, StringComparison.Ordinal); + Assert.StartsWith(ConversationSession.ToolFailureReason, turn.Failure, StringComparison.Ordinal); Assert.Contains(UnreachableEndpointToolBuilder.Message, turn.Failure, StringComparison.Ordinal); // The writers ran in their fixed order, the machine picked the stage of the next turn, and - // the call is still alive. + // the conversation is still alive. Assert.Equal(1, session.State.TurnIndex); Assert.Equal("greeting", turn.StageAfter); Assert.False(session.IsComplete); @@ -793,7 +793,7 @@ public async Task TheFourthConsecutiveToolFailure_LeavesTheSessionUnlocked() var second = await session.RunTurnAsync("try again", TestContext.Current.CancellationToken); Assert.Equal(1, second.TurnIndex); - Assert.Equal(CallSession.FallbackReply, second.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, second.ReplyText); } [Fact] @@ -814,8 +814,8 @@ public async Task Streaming_EndsTheTurnWhenTheFourthConsecutiveToolFailureThrows // The enumeration ends rather than throwing, so the host never sees the fault. Assert.Equal(4, tools.Calls); Assert.NotNull(session.LastTurn); - Assert.Equal(CallSession.FallbackReply, session.LastTurn.ReplyText); - Assert.StartsWith(CallSession.ToolFailureReason, session.LastTurn.Failure!, StringComparison.Ordinal); + Assert.Equal(ConversationSession.FallbackReply, session.LastTurn.ReplyText); + Assert.StartsWith(ConversationSession.ToolFailureReason, session.LastTurn.Failure!, StringComparison.Ordinal); Assert.Equal(1, session.State.TurnIndex); } @@ -934,7 +934,7 @@ public void AnInterruptionWithNoRunningTurn_ReportsFalseAndChangesNothing() using SequencedChatClient fill = new(StayingNull); var session = Build(PolicyYaml, reply, fill).Create(); - // A frame that arrives after the turn ended must not drop the call, so it answers false. + // A frame that arrives after the turn ended must not drop the conversation, so it answers false. Assert.False(session.Interrupt("nothing played", TimeSpan.FromMilliseconds(5))); Assert.Null(session.LastTurn); @@ -993,19 +993,19 @@ public async Task TheSession_SatisfiesTheInboundPort() { using SequencedChatClient reply = new("hello there.", "still here."); using SequencedChatClient fill = new(StayingNull); - var port = Assert.IsType(Build(PolicyYaml, reply, fill).Create("call-9"), exactMatch: false); + var port = Assert.IsType(Build(PolicyYaml, reply, fill).Create("conversation-9"), exactMatch: false); var turn = await port.RunTurnAsync("hi", TestContext.Current.CancellationToken); // The relay shim and the SSE endpoint both drive this contract and reach past it for nothing. - Assert.Equal("call-9", port.CallId); + Assert.Equal("conversation-9", port.ConversationId); Assert.Equal("greeting", port.Stage); Assert.False(port.IsComplete); Assert.Same(turn, port.LastTurn); // A frame that lands after the turn ended is recorded, not ignored. The vendor paces the // audio, so the caller was still hearing this reply long after the model stopped producing - // it, and the port amends the finished turn. See the remarks on CallSession.Interrupt. + // it, and the port amends the finished turn. See the remarks on ConversationSession.Interrupt. Assert.True(port.Interrupt("nothing played", TimeSpan.Zero)); List updates = []; @@ -1021,7 +1021,7 @@ public async Task TheSession_SatisfiesTheInboundPort() // The factory. // ------------------------------------------------------------------------------------------- [Fact] - public void TheFactory_MakesACallIdWhenTheHostGivesNone() + public void TheFactory_MakesAConversationIdWhenTheHostGivesNone() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(StayingNull); @@ -1030,30 +1030,30 @@ public void TheFactory_MakesACallIdWhenTheHostGivesNone() var first = factory.Create(); var second = factory.Create(); - Assert.NotEmpty(first.CallId); - Assert.NotEqual(first.CallId, second.CallId); + Assert.NotEmpty(first.ConversationId); + Assert.NotEqual(first.ConversationId, second.ConversationId); } [Fact] - public async Task TheFactory_GivesEachCallItsOwnStateAndItsOwnMachine() + public async Task TheFactory_GivesEachConversationItsOwnStateAndItsOwnMachine() { using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new(SaidGoodbye, StayingNull); var factory = Build(PolicyYaml, reply, fill); - var first = factory.Create("call-1"); - var second = factory.Create("call-2"); + var first = factory.Create("conversation-1"); + var second = factory.Create("conversation-2"); await first.RunTurnAsync("goodbye", TestContext.Current.CancellationToken); - // One machine belongs to one call. The first call ended, and the second one has not started. + // One machine belongs to one conversation. The first conversation ended, and the second one has not started. Assert.True(first.IsComplete); Assert.False(second.IsComplete); Assert.Equal("greeting", second.Stage); Assert.Empty(second.Transcript); Assert.NotSame(first.State, second.State); - // Both calls share the one compiled agent. T44 and rule 16. + // Both conversations share the one compiled agent. T44 and rule 16. Assert.Same(first.Compiled, second.Compiled); } @@ -1063,7 +1063,7 @@ public void TheFactory_BuildsNoExtractorWhenTheDocumentDeclaresNone() using SequencedChatClient reply = new("hello there."); var compiled = Compile(TwoStagesYaml, reply, null, null); - Assert.Null(CallSessionFactory.CreateExtractor(compiled, new FakeChatClientFactory(reply))); + Assert.Null(ConversationSessionFactory.CreateExtractor(compiled, new FakeChatClientFactory(reply))); } [Fact] @@ -1073,7 +1073,7 @@ public void TheFactory_BuildsTheExtractorTheDocumentDeclares() using SequencedChatClient fill = new(StayingNull); var compiled = Compile(PolicyYaml, reply, fill, null); - var extractor = CallSessionFactory.CreateExtractor( + var extractor = ConversationSessionFactory.CreateExtractor( compiled, new RoutingChatClientFactory(reply).Route("fill", fill)); @@ -1087,7 +1087,7 @@ public void TheFactory_BuildsTheExtractorTheDocumentDeclares() private static bool Contains(ChatMessage message, string text) => message.Text.Contains(text, StringComparison.Ordinal); - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IChatClient? fill, @@ -1101,10 +1101,10 @@ private static CallSessionFactory Build( chatClients.Route("fill", fill); } - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), + ConversationSessionFactory.CreateExtractor(compiled, chatClients), timeProvider); } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionWorkspaceTests.cs similarity index 79% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationSessionWorkspaceTests.cs index 7163409d..5cb1516a 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationSessionWorkspaceTests.cs @@ -14,13 +14,13 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// The call workspace as a host sees it: bound (or not) through , -/// deleted when the call ends, and visible to a bound tool through . +/// The conversation workspace as a host sees it: bound (or not) through , +/// deleted when the conversation ends, and visible to a bound tool through . /// /// -/// Every test here runs offline. There is no network call and no API key anywhere in this file. +/// Every test here runs offline. There is no network conversation and no API key anywhere in this file. /// -public sealed class CallSessionWorkspaceTests : IDisposable +public sealed class ConversationSessionWorkspaceTests : IDisposable { private const string SimpleYaml = """ @@ -52,7 +52,7 @@ public sealed class CallSessionWorkspaceTests : IDisposable model: { ref: reply } items: - { id: greeter, instructions: "greet the caller" } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -70,7 +70,7 @@ public sealed class CallSessionWorkspaceTests : IDisposable """ apiVersion: agentcore/v1 tools: - - { id: request_human, kind: binding, binds: RequestHuman, description: "Ask a human to take the call." } + - { id: request_human, kind: binding, binds: RequestHuman, description: "Ask a human to take the conversation." } agents: items: - { id: only, instructions: "help the caller", tools: [ request_human ] } @@ -90,14 +90,14 @@ public void Dispose() } [Fact] - public void ARootBound_CreatesTheCallsFolder() + public void ARootBound_CreatesTheConversationsFolder() { using SequencedChatClient reply = new("hi there."); var factory = Build(SimpleYaml, reply, fill: null, _root); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); - Assert.Equal(Path.Combine(_root, "call-1"), session.Workspace); + Assert.Equal(Path.Combine(_root, "conversation-1"), session.Workspace); Assert.True(Directory.Exists(session.Workspace)); } @@ -107,24 +107,24 @@ public void NoRootBound_LeavesWorkspaceNull_AndCreatesNothing() using SequencedChatClient reply = new("hi there."); var factory = Build(SimpleYaml, reply, fill: null, workspaceRoot: null); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); Assert.Null(session.Workspace); Assert.False(Directory.Exists(_root)); } [Fact] - public void EndCall_DeletesTheFolder_AndIsSafeToCallTwice() + public void EndConversation_DeletesTheFolder_AndIsSafeToCallTwice() { using SequencedChatClient reply = new("hi there."); var factory = Build(SimpleYaml, reply, fill: null, _root); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); var path = session.Workspace!; - session.EndCall(CallEndReason.CallerHungUp); + session.EndConversation(ConversationEndReason.CallerHungUp); Assert.False(Directory.Exists(path)); - Assert.False(session.EndCall(CallEndReason.CallerHungUp)); + Assert.False(session.EndConversation(ConversationEndReason.CallerHungUp)); } [Fact] @@ -133,7 +133,7 @@ public async Task ATurnThatReachesATerminalStage_AlsoDeletesTheFolder() using SequencedChatClient reply = new("hello there."); using SequencedChatClient fill = new("""{ "callerSaidGoodbye": true }"""); var factory = Build(TerminalYaml, reply, fill, _root); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); var path = session.Workspace!; var turn = await session.RunTurnAsync("goodbye", TestContext.Current.CancellationToken); @@ -144,7 +144,7 @@ public async Task ATurnThatReachesATerminalStage_AlsoDeletesTheFolder() } [Fact] - public async Task ABoundTool_SeesTheRunningCallsWorkspace() + public async Task ABoundTool_SeesTheRunningConversationsWorkspace() { List captured = []; ToolBindingRegistry bindings = new(); @@ -165,11 +165,11 @@ [new BindingToolSource(bindings)], TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("I need a person", TestContext.Current.CancellationToken); @@ -178,7 +178,7 @@ [new BindingToolSource(bindings)], Assert.NotNull(scope.Workspace); } - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IChatClient? fill, @@ -198,10 +198,10 @@ private static CallSessionFactory Build( Tools = TestToolRegistry.From(document, builder: null, TestContext.Current.CancellationToken), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), + ConversationSessionFactory.CreateExtractor(compiled, chatClients), workspaceRoot: workspaceRoot); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs b/tests/AgentCore.Application.Tests/Runtime/ConversationWorkspaceTests.cs similarity index 61% rename from tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs rename to tests/AgentCore.Application.Tests/Runtime/ConversationWorkspaceTests.cs index 44fe3ad8..fa451a33 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ConversationWorkspaceTests.cs @@ -4,9 +4,9 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// in isolation: the folder it creates and the folder it deletes. +/// in isolation: the folder it creates and the folder it deletes. /// -public sealed class CallWorkspaceTests : IDisposable +public sealed class ConversationWorkspaceTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-ws-" + Guid.NewGuid().ToString("N")); @@ -21,16 +21,16 @@ public void Dispose() [Fact] public void Create_MakesTheFolder() { - var workspace = CallWorkspace.Create(_root, "call-1"); + var workspace = ConversationWorkspace.Create(_root, "conversation-1"); - Assert.Equal(Path.Combine(_root, "call-1"), workspace.Path); + Assert.Equal(Path.Combine(_root, "conversation-1"), workspace.Path); Assert.True(Directory.Exists(workspace.Path)); } [Fact] public void Delete_RemovesTheFolder_AndIsSafeToCallTwice() { - var workspace = CallWorkspace.Create(_root, "call-1"); + var workspace = ConversationWorkspace.Create(_root, "conversation-1"); workspace.Delete(logger: null); Assert.False(Directory.Exists(workspace.Path)); @@ -47,45 +47,45 @@ public void Delete_RemovesTheFolder_AndIsSafeToCallTwice() [InlineData(".")] [InlineData("")] [InlineData(" ")] - public void Create_RefusesACallIdThatCouldEscapeTheRoot(string callId) + public void Create_RefusesAConversationIdThatCouldEscapeTheRoot(string conversationId) { - Assert.Throws(() => CallWorkspace.Create(_root, callId)); + Assert.Throws(() => ConversationWorkspace.Create(_root, conversationId)); Assert.False(Directory.Exists(_root)); } /// /// GetFullPath normalises a trailing space or period out of the last segment on Windows, - /// so a naive containment check would let " ." alias the root and "call-1." alias a sibling + /// so a naive containment check would let " ." alias the root and "conversation-1." alias a sibling /// folder. On Windows this must throw. On Linux the segment is a legal folder name and is not an /// alias of anything, so it is fine for Create to make it — as long as the folder it makes /// is strictly under root and named exactly what the caller asked for. /// [Theory] [InlineData(" .")] - [InlineData("call-1.")] - public void Create_RefusesOrExactlyHonoursACallIdWithATrailingSpaceOrPeriod(string callId) + [InlineData("conversation-1.")] + public void Create_RefusesOrExactlyHonoursAConversationIdWithATrailingSpaceOrPeriod(string conversationId) { if (OperatingSystem.IsWindows()) { - Assert.ThrowsAny(() => CallWorkspace.Create(_root, callId)); + Assert.ThrowsAny(() => ConversationWorkspace.Create(_root, conversationId)); Assert.False(Directory.Exists(_root)); return; } - var workspace = CallWorkspace.Create(_root, callId); + var workspace = ConversationWorkspace.Create(_root, conversationId); Assert.StartsWith(_root + Path.DirectorySeparatorChar, workspace.Path, StringComparison.Ordinal); - Assert.Equal(callId, Path.GetFileName(workspace.Path)); + Assert.Equal(conversationId, Path.GetFileName(workspace.Path)); } [Fact] - public void Create_TwiceWithTheSameCallId_ReusesTheFolderAndKeepsWhatWasWrittenIntoIt() + public void Create_TwiceWithTheSameConversationId_ReusesTheFolderAndKeepsWhatWasWrittenIntoIt() { - var first = CallWorkspace.Create(_root, "call-1"); + var first = ConversationWorkspace.Create(_root, "conversation-1"); var marker = Path.Combine(first.Path, "marker.txt"); File.WriteAllText(marker, "kept"); - var second = CallWorkspace.Create(_root, "call-1"); + var second = ConversationWorkspace.Create(_root, "conversation-1"); Assert.Equal(first.Path, second.Path); Assert.Equal("kept", File.ReadAllText(marker)); diff --git a/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs b/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs index 4e73d777..c2005a42 100644 --- a/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs @@ -10,18 +10,18 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// Tools that belong to one call, offered to the runs that call delegates and to nothing else. +/// Tools that belong to one conversation, offered to the runs that call delegates and to nothing else. /// /// /// -/// The compiled agent is a process singleton, so a tool that belongs to one call cannot be compiled +/// The compiled agent is a process singleton, so a tool that belongs to one conversation cannot be compiled /// onto it. It travels on the turn instead, and the gate is the id of the delegating tool the run /// sits under. A gate on the agent NAME would be wrong: CompiledAgentRegistry makes compiled /// agents singletons, so two kind: agent declarations can name one agent and both would be /// handed the tool. /// /// -/// Every test here runs offline: no network call and no API key. +/// Every test here runs offline: no network conversation and no API key. /// /// public sealed class DelegatedToolsTests @@ -51,7 +51,7 @@ public sealed class DelegatedToolsTests [Fact] public async Task AToolSetForADelegation_ReachesTheRunThatDelegationMakes() { - var (session, greeter, specialist) = NewCall(); + var (session, greeter, specialist) = NewConversation(); session.SetDelegatedTools("ask_specialist", [DrawTool]); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -66,7 +66,7 @@ public async Task AToolSetForADelegation_ReachesAStreamingTurnToo() // The framework streams the tool-call update BEFORE it invokes the function, so the first // yield restores the caller's execution context while the delegation is still pending. Only // the per-round re-entry in RunTurnStreamingAsync keeps the turn's tools alive across it. - var (session, _, specialist) = NewCall(); + var (session, _, specialist) = NewConversation(); session.SetDelegatedTools("ask_specialist", [DrawTool]); await foreach (var _ in session.RunTurnStreamingAsync("hi", TestContext.Current.CancellationToken)) @@ -79,7 +79,7 @@ public async Task AToolSetForADelegation_ReachesAStreamingTurnToo() [Fact] public async Task AToolSetForAnotherDelegation_ReachesNobody() { - var (session, greeter, specialist) = NewCall(); + var (session, greeter, specialist) = NewConversation(); session.SetDelegatedTools("some_other_tool", [DrawTool]); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -89,9 +89,9 @@ public async Task AToolSetForAnotherDelegation_ReachesNobody() } [Fact] - public async Task ACallThatSetsNoTools_OffersTheSameToolsItAlwaysDid() + public async Task AConversationThatSetsNoTools_OffersTheSameToolsItAlwaysDid() { - var (session, _, specialist) = NewCall(); + var (session, _, specialist) = NewConversation(); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -103,7 +103,7 @@ public async Task ACallThatSetsNoTools_OffersTheSameToolsItAlwaysDid() public async Task TheSecondCallOfSetDelegatedTools_ReplacesTheFirst() { var replacement = AIFunctionFactory.Create(() => "drawn.", "draw_later", "The one that wins."); - var (session, _, specialist) = NewCall(); + var (session, _, specialist) = NewConversation(); session.SetDelegatedTools("ask_specialist", [DrawTool]); session.SetDelegatedTools("ask_specialist", [replacement]); @@ -117,14 +117,14 @@ public async Task TheSecondCallOfSetDelegatedTools_ReplacesTheFirst() [Fact] public void SetDelegatedTools_RefusesNulls() { - var (session, _, _) = NewCall(); + var (session, _, _) = NewConversation(); Assert.Throws(() => session.SetDelegatedTools(null!, [DrawTool])); Assert.Throws(() => session.SetDelegatedTools("ask_specialist", null!)); } - /// Opens a call whose greeter delegates once, over two scripted models. - private static (CallSession Session, ToolCallingChatClient Greeter, ToolCallingChatClient Specialist) NewCall() + /// Opens a conversation whose greeter delegates once, over two scripted models. + private static (ConversationSession Session, ToolCallingChatClient Greeter, ToolCallingChatClient Specialist) NewConversation() { ToolCallingChatClient greeter = new( "hello there.", @@ -138,7 +138,7 @@ private static (CallSession Session, ToolCallingChatClient Greeter, ToolCallingC var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(DelegationYaml), new AgentCompilationContext(chatClients))["main"]; - var session = new CallSessionFactory( + var session = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null).Create(); diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs index 657ea6bd..19fa07d2 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/BackgroundChildAgentTests.cs @@ -10,7 +10,7 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// -/// A child session created inside the parent's run carries the parent's call id; one created +/// A child session created inside the parent's run carries the parent's conversation id; one created /// outside any run carries nothing. /// /// @@ -21,14 +21,14 @@ namespace AgentCore.Application.Tests.Runtime.Harness; public sealed class BackgroundChildAgentTests { [Fact] - public async Task CreateSessionAsync_InsideTheParentsRun_StampsTheParentsCallId() + public async Task CreateSessionAsync_InsideTheParentsRun_StampsTheParentsConversationId() { // Arrange var token = TestContext.Current.CancellationToken; BackgroundChildAgent child = new(new ChatClientAgent(new ScriptedChatClient("child"))); SessionCreatingProvider creating = new(child); ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); - var turn = new TurnInvocation { CallId = "call-9", TurnIndex = 0, Stage = "s" }; + var turn = new TurnInvocation { ConversationId = "conversation-9", TurnIndex = 0, Stage = "s" }; // Act await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); @@ -36,7 +36,7 @@ public async Task CreateSessionAsync_InsideTheParentsRun_StampsTheParentsCallId( // Assert Assert.NotNull(creating.Created); Assert.True(creating.Created.StateBag.TryGetValue(BlobOwnerKey.Value, out var stamped)); - Assert.Equal("call-9", stamped); + Assert.Equal("conversation-9", stamped); } [Fact] @@ -48,7 +48,7 @@ public async Task CreateSessionAsync_InsideAParentRunWithAZone_StampsTheZoneOnTh SessionCreatingProvider creating = new(child); ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); var zone = TimeZoneInfo.CreateCustomTimeZone("Asia/Taipei", TimeSpan.FromHours(8), "Taipei", "Taipei"); - var turn = new TurnInvocation { CallId = "call-9", TurnIndex = 0, Stage = "s", TimeZone = zone }; + var turn = new TurnInvocation { ConversationId = "conversation-9", TurnIndex = 0, Stage = "s", TimeZone = zone }; // Act await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); @@ -70,10 +70,10 @@ public async Task CreateSessionAsync_InsideTheParentsRun_FilesTheParentsWorkspac var renders = new TurnRenders(); var turn = new TurnInvocation { - CallId = "call-9", + ConversationId = "conversation-9", TurnIndex = 0, Stage = "s", - Workspace = "/work/call-9", + Workspace = "/work/conversation-9", Renders = renders, }; @@ -84,8 +84,8 @@ public async Task CreateSessionAsync_InsideTheParentsRun_FilesTheParentsWorkspac Assert.NotNull(creating.Created); var filed = TurnRegistry.For(creating.Created); Assert.NotNull(filed); - Assert.Equal("/work/call-9", filed.Workspace); - Assert.Equal("call-9", filed.CallId); + Assert.Equal("/work/conversation-9", filed.Workspace); + Assert.Equal("conversation-9", filed.ConversationId); Assert.True(filed.Nested); Assert.Null(filed.Renders); } diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationFilesProviderTests.cs similarity index 85% rename from tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ConversationFilesProviderTests.cs index 041b7510..b523c5aa 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationFilesProviderTests.cs @@ -12,26 +12,26 @@ namespace AgentCore.Application.Tests.Runtime.Harness; #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. /// -/// as a unit: it serves the framework's file tools rooted at the +/// as a unit: it serves the framework's file tools rooted at the /// workspace of the turn filed for the invoking session, and refuses to serve any when no turn /// is filed. /// -public sealed class CallFilesProviderTests : IDisposable +public sealed class ConversationFilesProviderTests : IDisposable { - private readonly string _root = Path.Combine(Path.GetTempPath(), $"call-files-{Guid.NewGuid():N}"); + private readonly string _root = Path.Combine(Path.GetTempPath(), $"conversation-files-{Guid.NewGuid():N}"); - public CallFilesProviderTests() => Directory.CreateDirectory(_root); + public ConversationFilesProviderTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); [Fact] public async Task InvokingAsync_WithASessionFiledTurn_ServesFileTools() { - using CallFilesProvider provider = new(_root, Options()); + using ConversationFilesProvider provider = new(_root, Options()); StubSession session = new(); TurnRegistry.Set( session, - new TurnInvocation { CallId = "call-1", TurnIndex = 0, Stage = "", Workspace = _root }); + new TurnInvocation { ConversationId = "conversation-1", TurnIndex = 0, Stage = "", Workspace = _root }); var context = await provider.InvokingAsync( Invoking(session), TestContext.Current.CancellationToken); @@ -43,7 +43,7 @@ public async Task InvokingAsync_WithASessionFiledTurn_ServesFileTools() [Fact] public async Task InvokingAsync_WithoutATurn_ThrowsInvalidOperationException() { - using CallFilesProvider provider = new(_root, Options()); + using ConversationFilesProvider provider = new(_root, Options()); var exception = await Assert.ThrowsAsync( () => provider.InvokingAsync( diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionBackgroundTests.cs similarity index 87% rename from tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionBackgroundTests.cs index 32b705f0..fdfe9959 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionBackgroundTests.cs @@ -12,11 +12,11 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// -/// The call-end release of background sessions: a child still running when the call closes or a -/// turn reaches a terminal stage is cancelled instead of leaking past the call. +/// The conversation-end release of background sessions: a child still running when the conversation closes or a +/// turn reaches a terminal stage is cancelled instead of leaking past the conversation. /// #pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. -public sealed class CallSessionBackgroundTests +public sealed class ConversationSessionBackgroundTests { private const string LingeringChildYaml = """ @@ -67,17 +67,17 @@ public async Task CloseAsync_WithAChildStillRunning_CancelsIt() ["description"] = "d", }); var child = new BlockingChatClient(); - InMemoryCallSessions sessions = new(BuildFactory(LingeringChildYaml, parent, child), TimeSpan.FromMinutes(30), TimeProvider.System); + InMemoryConversationSessions sessions = new(BuildFactory(LingeringChildYaml, parent, child), TimeSpan.FromMinutes(30), TimeProvider.System); - var session = await sessions.OpenAsync("call-1", token); + var session = await sessions.OpenAsync("conversation-1", token); await session.RunTurnAsync("go", token); - // The turn is over and the call is not, and the child is still in its model call: the + // The turn is over and the conversation is not, and the child is still in its model call: the // leak this step closes. Nothing has cancelled it yet. await child.Started.WaitAsync(TimeSpan.FromSeconds(10), token); Assert.False(child.Cancelled.IsCompleted); - await sessions.CloseAsync("call-1", token); + await sessions.CloseAsync("conversation-1", token); await child.Cancelled.WaitAsync(TimeSpan.FromSeconds(10), token); } @@ -97,7 +97,7 @@ public async Task ATurnThatReachesATerminalStage_CancelsAChildStillRunningWithou var child = new BlockingChatClient(); var factory = BuildFactory(TerminalChildYaml, parent, child); - await using var session = factory.Create("call-1"); + await using var session = factory.Create("conversation-1"); var turn = await session.RunTurnAsync("go", token); Assert.True(turn.IsTerminal); @@ -105,7 +105,7 @@ public async Task ATurnThatReachesATerminalStage_CancelsAChildStillRunningWithou await child.Cancelled.WaitAsync(TimeSpan.FromSeconds(10), token); } - private static CallSessionFactory BuildFactory(string yaml, IChatClient parent, IChatClient child) + private static ConversationSessionFactory BuildFactory(string yaml, IChatClient parent, IChatClient child) { var chatClients = new RoutingChatClientFactory(parent); chatClients.Route("parent", parent); @@ -114,7 +114,7 @@ private static CallSessionFactory BuildFactory(string yaml, IChatClient parent, var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(yaml), new AgentCompilationContext(chatClients))["main"]; - return new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + return new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); } /// A model that stays inside its first request until the run is cancelled. diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionGraphStateTests.cs similarity index 79% rename from tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionGraphStateTests.cs index ac9f7841..d071a22c 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionGraphStateTests.cs @@ -1,6 +1,6 @@ using System.Text.Json; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -16,10 +16,10 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// /// Harness step: a graph row whose document declares a harness switch keeps one workflow -/// session for the whole call, so todos: (and mode:) survive turns and resume. +/// session for the whole conversation, so todos: (and mode:) survive turns and resume. /// A graph row without one still runs every turn fresh, exactly as before. /// -public sealed class CallSessionGraphStateTests +public sealed class ConversationSessionGraphStateTests { private const string TodosYaml = """ @@ -52,22 +52,22 @@ public sealed class CallSessionGraphStateTests [Fact] public async Task SecondTurn_AdderRequestCarriesTheRestoredTodo_AndNoRenderedHistory() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); var adder = new ScriptedToolCallingChatClient(("todos_add", """{"todos":[{"title":"buy milk"}]}""")) { FinalText = "added" }; var adderRequests = new RequestCapturingChatClient(adder); var echo = new ScriptedToolCallingChatClient() { FinalText = "echo1" }; var factory = Build(TodosYaml, store, adderRequests, echo); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("track this", TestContext.Current.CancellationToken); - var turn1Calls = adderRequests.Requests.Count; + var turn1Conversations = adderRequests.Requests.Count; adder.FinalText = "second"; echo.FinalText = "echo2"; await session.RunTurnAsync("anything new?", TestContext.Current.CancellationToken); // The restored session injects the todo list into the run-2 instructions… - var run2 = adderRequests.Requests[turn1Calls]; + var run2 = adderRequests.Requests[turn1Conversations]; Assert.Contains(run2, message => message.Text.Contains("buy milk", StringComparison.Ordinal)); // …and the resumed conversation already carries what came before, so the turn @@ -78,16 +78,16 @@ public async Task SecondTurn_AdderRequestCarriesTheRestoredTodo_AndNoRenderedHis [Fact] public async Task ResumeFromTheSameStore_AdderRequestCarriesTheRestoredTodo() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); var adder = new ScriptedToolCallingChatClient(("todos_add", """{"todos":[{"title":"buy milk"}]}""")) { FinalText = "added" }; var adderRequests = new RequestCapturingChatClient(adder); var echo = new ScriptedToolCallingChatClient() { FinalText = "echo1" }; var factory = Build(TodosYaml, store, adderRequests, echo); - var first = factory.Create("call-1"); + var first = factory.Create("conversation-1"); await first.RunTurnAsync("track this", TestContext.Current.CancellationToken); - var second = factory.Create("call-1"); + var second = factory.Create("conversation-1"); await second.RunTurnAsync("anything new?", TestContext.Current.CancellationToken); var resumed = adderRequests.Requests[^1]; @@ -97,18 +97,18 @@ public async Task ResumeFromTheSameStore_AdderRequestCarriesTheRestoredTodo() [Fact] public async Task NoHarnessSwitch_AfterATurn_Store0HoldsNeitherBlobNorProviders() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); var factory = Build( PlainYaml, store, new ScriptedToolCallingChatClient() { FinalText = "one" }, new ScriptedToolCallingChatClient() { FinalText = "two" }); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); var turn = await session.RunTurnAsync("go", TestContext.Current.CancellationToken); Assert.Equal("two", turn.ReplyText); - var record = await store.GetAsync("call-1", TestContext.Current.CancellationToken); + var record = await store.GetAsync("conversation-1", TestContext.Current.CancellationToken); Assert.NotNull(record?.State); Assert.Null(record.State.WorkflowState); Assert.Empty(record.State.Providers); @@ -117,14 +117,14 @@ public async Task NoHarnessSwitch_AfterATurn_Store0HoldsNeitherBlobNorProviders( [Fact] public async Task TodosSwitch_AfterATurn_Store0HoldsTheBlobAndNoPickedKeys() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); var adder = new ScriptedToolCallingChatClient(("todos_add", """{"todos":[{"title":"buy milk"}]}""")) { FinalText = "added" }; var factory = Build(TodosYaml, store, adder, new ScriptedToolCallingChatClient() { FinalText = "echo1" }); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("track this", TestContext.Current.CancellationToken); - var record = await store.GetAsync("call-1", TestContext.Current.CancellationToken); + var record = await store.GetAsync("conversation-1", TestContext.Current.CancellationToken); Assert.NotNull(record?.State); Assert.NotNull(record.State.WorkflowState); Assert.Empty(record.State.Providers); @@ -133,12 +133,12 @@ public async Task TodosSwitch_AfterATurn_Store0HoldsTheBlobAndNoPickedKeys() [Fact] public async Task PickedProvidersWithoutABlob_AreIgnored_AdderStartsFresh() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); var adder = new ScriptedToolCallingChatClient() { FinalText = "added" }; var adderRequests = new RequestCapturingChatClient(adder); var factory = Build(TodosYaml, store, adderRequests, new ScriptedToolCallingChatClient() { FinalText = "echo1" }); - CallSessionState fabricated = new() + ConversationSessionState fabricated = new() { Providers = new Dictionary(StringComparer.Ordinal) { @@ -147,7 +147,7 @@ [new TodoProvider().StateKeys[0]] = JsonDocument.Parse( }, }; - var session = factory.Create("call-1", fabricated); + var session = factory.Create("conversation-1", fabricated); await session.RunTurnAsync("anything new?", TestContext.Current.CancellationToken); Assert.DoesNotContain( @@ -155,7 +155,7 @@ [new TodoProvider().StateKeys[0]] = JsonDocument.Parse( message => message.Text.Contains("buy milk", StringComparison.Ordinal)); } - private static CallSessionFactory Build(string yaml, ICallStore store, IChatClient first, IChatClient second) + private static ConversationSessionFactory Build(string yaml, IConversationStore store, IChatClient first, IChatClient second) { var document = ConfigurationLoader.LoadYaml(yaml); RoutingChatClientFactory chatClients = new(first); @@ -163,8 +163,8 @@ private static CallSessionFactory Build(string yaml, ICallStore store, IChatClie chatClients.Route("second", second); var compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(chatClients) { CallStore = store })["main"]; + new AgentCompilationContext(chatClients) { ConversationStore = store })["main"]; - return new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + return new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionProviderStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionProviderStateTests.cs similarity index 79% rename from tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionProviderStateTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionProviderStateTests.cs index 9b037075..e3fb43b1 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionProviderStateTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionProviderStateTests.cs @@ -1,8 +1,8 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Text.Json; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -18,10 +18,10 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// /// The end-to-end path of harness step 4: a todos: item written during a turn lands in store -/// 0's Providers, and a call that resumes — from the same store, or from a host checkpoint — +/// 0's Providers, and a conversation that resumes — from the same store, or from a host checkpoint — /// gets it re-injected by the framework's own . /// -public sealed class CallSessionProviderStateTests +public sealed class ConversationSessionProviderStateTests { private const string TodosYaml = """ @@ -48,14 +48,14 @@ public sealed class CallSessionProviderStateTests [Fact] public async Task AfterATurn_Store0HoldsOnlyTheTodoProviderKey_WithTheTodoInIt() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); var compiled = Compile(TodosYaml, new TodoAddThenTextChatClient(), store); - var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); - var session = factory.Create("call-1"); + var factory = new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("please track this", TestContext.Current.CancellationToken); - var record = await store.GetAsync("call-1", TestContext.Current.CancellationToken); + var record = await store.GetAsync("conversation-1", TestContext.Current.CancellationToken); Assert.NotNull(record); Assert.NotNull(record.State); @@ -70,15 +70,15 @@ public async Task AfterATurn_Store0HoldsOnlyTheTodoProviderKey_WithTheTodoInIt() [Fact] public async Task ASecondSessionFromTheSameFactoryAndStore_ReInjectsTheTodo() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); TodoAddThenTextChatClient chatClient = new(); var compiled = Compile(TodosYaml, chatClient, store); - var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + var factory = new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); - var first = factory.Create("call-1"); + var first = factory.Create("conversation-1"); await first.RunTurnAsync("please track this", TestContext.Current.CancellationToken); - var second = factory.Create("call-1"); + var second = factory.Create("conversation-1"); await second.RunTurnAsync("what's on my list", TestContext.Current.CancellationToken); Assert.Contains( @@ -89,14 +89,14 @@ public async Task ASecondSessionFromTheSameFactoryAndStore_ReInjectsTheTodo() [Fact] public async Task AResumeFromAHostCheckpoint_ThroughAgentCoreAgent_ReInjectsTheTodo() { - InMemoryCallStore firstStore = new(); + InMemoryConversationStore firstStore = new(); TodoAddThenTextChatClient firstChatClient = new(); var firstCompiled = Compile(TodosYaml, firstChatClient, firstStore); AgentCoreAgent firstAgent = new( - new CallSessionFactory(firstCompiled, new GuardEvaluator(firstCompiled.Configuration.Guards)), "main"); + new ConversationSessionFactory(firstCompiled, new GuardEvaluator(firstCompiled.Configuration.Guards)), "main"); var firstSession = await firstAgent.CreateSessionAsync( - "call-1", TestContext.Current.CancellationToken); + "conversation-1", TestContext.Current.CancellationToken); await firstAgent.RunAsync( "please track this", firstSession, cancellationToken: TestContext.Current.CancellationToken); @@ -104,12 +104,12 @@ await firstAgent.RunAsync( firstSession, cancellationToken: TestContext.Current.CancellationToken); // A fresh store: this proves the checkpoint carries the provider state on its own, not - // because store 0 still remembers the call. - InMemoryCallStore secondStore = new(); + // because store 0 still remembers the conversation. + InMemoryConversationStore secondStore = new(); SequencedChatClient secondChatClient = new("hello there."); var secondCompiled = Compile(TodosYaml, secondChatClient, secondStore); AgentCoreAgent secondAgent = new( - new CallSessionFactory(secondCompiled, new GuardEvaluator(secondCompiled.Configuration.Guards)), "main"); + new ConversationSessionFactory(secondCompiled, new GuardEvaluator(secondCompiled.Configuration.Guards)), "main"); var revived = await secondAgent.DeserializeSessionAsync( serialized, cancellationToken: TestContext.Current.CancellationToken); @@ -124,12 +124,12 @@ await secondAgent.RunAsync( [Fact] public async Task AVersion99StoredState_DropsTheProviders_TheTodoNeverReachesTheRequest() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); SequencedChatClient chatClient = new("hello there."); var compiled = Compile(TodosYaml, chatClient, store); - var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + var factory = new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); - CallSessionState fabricated = new() + ConversationSessionState fabricated = new() { Version = 99, Providers = new Dictionary(StringComparer.Ordinal) @@ -139,7 +139,7 @@ [new TodoProvider().StateKeys[0]] = JsonDocument.Parse( }, }; - var session = factory.Create("call-1", fabricated); + var session = factory.Create("conversation-1", fabricated); await session.RunTurnAsync("what's on my list", TestContext.Current.CancellationToken); @@ -151,31 +151,31 @@ [new TodoProvider().StateKeys[0]] = JsonDocument.Parse( [Fact] public async Task NoTodosBlock_AfterATurn_Store0HoldsNoProviders() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); SequencedChatClient chatClient = new("hello there."); var compiled = Compile(NoTodosYaml, chatClient, store); - var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); - var session = factory.Create("call-1"); + var factory = new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + var session = factory.Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - var record = await store.GetAsync("call-1", TestContext.Current.CancellationToken); + var record = await store.GetAsync("conversation-1", TestContext.Current.CancellationToken); Assert.NotNull(record); Assert.NotNull(record.State); Assert.Empty(record.State.Providers); } - private static CompiledAgent Compile(string yaml, IChatClient chatClient, ICallStore store) + private static CompiledAgent Compile(string yaml, IChatClient chatClient, IConversationStore store) => ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(yaml), - new AgentCompilationContext(new FakeChatClientFactory(chatClient)) { CallStore = store })["main"]; + new AgentCompilationContext(new FakeChatClientFactory(chatClient)) { ConversationStore = store })["main"]; /// /// Calls todos_add {"todos":[{"title":"buy milk"}]} on the very first request this /// instance ever answers, then answers text on every request after — regardless of whether the /// transcript already carries a tool result, so the same instance can drive two sessions of one - /// call: the one that adds the todo, and the one that resumes it. + /// conversation: the one that adds the todo, and the one that resumes it. /// private sealed class TodoAddThenTextChatClient : IChatClient { @@ -207,7 +207,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionShellTests.cs similarity index 80% rename from tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionShellTests.cs index 6cfd1d77..2333f9c1 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationSessionShellTests.cs @@ -15,9 +15,9 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// /// The end-to-end path of a shell: block: the tool the model is handed, the workspace it /// runs in, the policy that refuses a command, and the process it starts being cleaned up when the -/// call closes or a turn reaches a terminal stage. +/// conversation closes or a turn reaches a terminal stage. /// -public sealed class CallSessionShellTests : IDisposable +public sealed class ConversationSessionShellTests : IDisposable { private const string ShellYaml = """ @@ -77,7 +77,7 @@ public async Task FirstRequest_ListsATool_NamedRunShell() var client = new ShellScriptedClient(RunShellToolName, "pwd", "rm -rf x", "echo $$"); var factory = BuildFactory(ShellYaml, client); - await using var session = factory.Create("call-1"); + await using var session = factory.Create("conversation-1"); await session.RunTurnAsync("go", TestContext.Current.CancellationToken); @@ -86,14 +86,14 @@ public async Task FirstRequest_ListsATool_NamedRunShell() } [Fact] - public async Task PwdResult_ContainsTheCallsWorkspace() + public async Task PwdResult_ContainsTheConversationsWorkspace() { // ShellYaml's policy declares deny: only, no allow:. If AgentHarnessProviders.BuildPolicy // ever stopped translating the empty allow: list to null, ShellPolicy would treat it as // deny-all and this undenied pwd would come back rejected instead of succeeding. var client = new ShellScriptedClient(RunShellToolName, "pwd", "rm -rf x", "echo $$"); var factory = BuildFactory(ShellYaml, client); - await using var session = factory.Create("call-1"); + await using var session = factory.Create("conversation-1"); await session.RunTurnAsync("go", TestContext.Current.CancellationToken); @@ -105,7 +105,7 @@ public async Task RmResult_ComesBackAsRejectedText_NotAFailedTurn() { var client = new ShellScriptedClient(RunShellToolName, "pwd", "rm -rf x", "echo $$"); var factory = BuildFactory(ShellYaml, client); - await using var session = factory.Create("call-1"); + await using var session = factory.Create("conversation-1"); var turn = await session.RunTurnAsync("go", TestContext.Current.CancellationToken); @@ -114,19 +114,19 @@ public async Task RmResult_ComesBackAsRejectedText_NotAFailedTurn() } [Fact] - public async Task AfterTheCallIsClosed_TheEchoPidIsGoneFromProc() + public async Task AfterTheConversationIsClosed_TheEchoPidIsGoneFromProc() { var client = new ShellScriptedClient(RunShellToolName, "pwd", "rm -rf x", "echo $$"); var factory = BuildFactory(ShellYaml, client); - InMemoryCallSessions sessions = new(factory, TimeSpan.FromMinutes(30), TimeProvider.System); + InMemoryConversationSessions sessions = new(factory, TimeSpan.FromMinutes(30), TimeProvider.System); - var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + var session = await sessions.OpenAsync("conversation-1", TestContext.Current.CancellationToken); await session.RunTurnAsync("go", TestContext.Current.CancellationToken); var pid = ParsePid(client.ToolResults[2]); - Assert.True(Directory.Exists($"/proc/{pid}"), "the bash should be alive before the call closes"); + Assert.True(Directory.Exists($"/proc/{pid}"), "the bash should be alive before the conversation closes"); - await sessions.CloseAsync("call-1", TestContext.Current.CancellationToken); + await sessions.CloseAsync("conversation-1", TestContext.Current.CancellationToken); await ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); } @@ -136,41 +136,41 @@ public async Task CloseAsync_WhenTheStoreThrowsOnFlush_StillDisposesTheShell() { // AgentCoreChatHistoryProvider.WriteAfterAsync catches every exception a store write // raises and reports it through TranscriptWriteDropped, whose own contract is that it - // never throws back out — "the call outlives a store that refuses" — so FlushTranscriptAsync + // never throws back out — "the conversation outlives a store that refuses" — so FlushTranscriptAsync // itself surfaces nothing here, which is today's behaviour: CloseAsync completes rather than // throw. What this proves is the part that used to be at risk: even though the flush ate the - // fault silently, the shell this call started is still disposed once CloseAsync returns. - var store = new ThrowingCallStore(); + // fault silently, the shell this conversation started is still disposed once CloseAsync returns. + var store = new ThrowingConversationStore(); var client = new ShellScriptedClient(RunShellToolName, "echo $$"); var document = ConfigurationLoader.LoadYaml(ShellYaml); var chatClients = new RoutingChatClientFactory(client); var compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(chatClients) { WorkspaceRoot = _root, CallStore = store })["main"]; - var factory = new CallSessionFactory( + new AgentCompilationContext(chatClients) { WorkspaceRoot = _root, ConversationStore = store })["main"]; + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); - InMemoryCallSessions sessions = new(factory, TimeSpan.FromMinutes(30), TimeProvider.System); + InMemoryConversationSessions sessions = new(factory, TimeSpan.FromMinutes(30), TimeProvider.System); - var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + var session = await sessions.OpenAsync("conversation-1", TestContext.Current.CancellationToken); await session.RunTurnAsync("go", TestContext.Current.CancellationToken); var pid = ParsePid(client.ToolResults[0]); - await sessions.CloseAsync("call-1", TestContext.Current.CancellationToken); + await sessions.CloseAsync("conversation-1", TestContext.Current.CancellationToken); await ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); } [Fact] - public async Task ASecondCallFromTheSameFactory_GetsADifferentPid() + public async Task ASecondConversationFromTheSameFactory_GetsADifferentPid() { var client = new ToolCallingChatClient( "done", new Dictionary(StringComparer.Ordinal) { ["command"] = "echo $$" }); var factory = BuildFactory(ShellYaml, client); - await using var sessionA = factory.Create("call-a"); + await using var sessionA = factory.Create("conversation-a"); await sessionA.RunTurnAsync("go", TestContext.Current.CancellationToken); - await using var sessionB = factory.Create("call-b"); + await using var sessionB = factory.Create("conversation-b"); await sessionB.RunTurnAsync("go", TestContext.Current.CancellationToken); var pidA = ParsePid(client.ToolResults[0]); @@ -184,7 +184,7 @@ public async Task NoShellBlock_NoRunShellToolInTheRequest() { using SequencedChatClient reply = new("hello there."); var factory = BuildFactory(NoShellYaml, reply); - await using var session = factory.Create("call-1"); + await using var session = factory.Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -199,7 +199,7 @@ public async Task ATurnThatReachesATerminalStage_DisposesTheShellWithoutCloseAsy { var client = new ShellScriptedClient(RunShellToolName, "echo $$"); var factory = BuildFactory(TerminalShellYaml, client); - var session = factory.Create("call-1"); + var session = factory.Create("conversation-1"); var turn = await session.RunTurnAsync("go", TestContext.Current.CancellationToken); Assert.True(turn.IsTerminal); @@ -210,11 +210,11 @@ public async Task ATurnThatReachesATerminalStage_DisposesTheShellWithoutCloseAsy } [Fact] - public async Task FirstRequest_CarriesShellEnvironmentInstructions_NamingTheCallsWorkspace() + public async Task FirstRequest_CarriesShellEnvironmentInstructions_NamingTheConversationsWorkspace() { var client = new ShellScriptedClient(RunShellToolName, "pwd"); var factory = BuildFactory(ShellYaml, client); - await using var session = factory.Create("call-1"); + await using var session = factory.Create("conversation-1"); await session.RunTurnAsync("go", TestContext.Current.CancellationToken); @@ -224,15 +224,15 @@ public async Task FirstRequest_CarriesShellEnvironmentInstructions_NamingTheCall } [Fact] - public async Task ASecondCall_GetsItsOwnWorkspaceInItsInstructions() + public async Task ASecondConversation_GetsItsOwnWorkspaceInItsInstructions() { var client = new ShellScriptedClient(RunShellToolName); var factory = BuildFactory(ShellYaml, client); - await using var sessionA = factory.Create("call-a"); + await using var sessionA = factory.Create("conversation-a"); await sessionA.RunTurnAsync("go", TestContext.Current.CancellationToken); - await using var sessionB = factory.Create("call-b"); + await using var sessionB = factory.Create("conversation-b"); await sessionB.RunTurnAsync("go", TestContext.Current.CancellationToken); var instructionsA = client.Requests[0].Options?.Instructions; @@ -267,7 +267,7 @@ private static string ToolName() } } - private CallSessionFactory BuildFactory(string yaml, IChatClient client) + private ConversationSessionFactory BuildFactory(string yaml, IChatClient client) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new RoutingChatClientFactory(client); @@ -276,7 +276,7 @@ private CallSessionFactory BuildFactory(string yaml, IChatClient client) document, new AgentCompilationContext(chatClients) { WorkspaceRoot = _root })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationShellsTests.cs similarity index 71% rename from tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ConversationShellsTests.cs index 89907a68..26fdf0b8 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ConversationShellsTests.cs @@ -7,13 +7,13 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// -/// : one executor per instance, created on +/// : one executor per instance, created on /// first ask, torn down together. /// -public sealed class CallShellsTests : IDisposable +public sealed class ConversationShellsTests : IDisposable { private readonly string _workspace = - Directory.CreateTempSubdirectory("call-shells-tests-").FullName; + Directory.CreateTempSubdirectory("conversation-shells-tests-").FullName; public void Dispose() { @@ -27,10 +27,10 @@ public void Dispose() } [Fact] - public async Task Get_Local_RunsInTheCallsWorkspace() + public async Task Get_Local_RunsInTheConversationsWorkspace() { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); var result = await shells.Get(options).RunAsync("pwd", TestContext.Current.CancellationToken); @@ -41,8 +41,8 @@ public async Task Get_Local_RunsInTheCallsWorkspace() [Fact] public async Task Get_Local_TimeoutSignalsWithoutThrowing_AndReturnsUnder3Seconds() { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: TimeSpan.FromSeconds(1)); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Local, Policy: null, Timeout: TimeSpan.FromSeconds(1)); var stopwatch = System.Diagnostics.Stopwatch.StartNew(); var result = await shells.Get(options).RunAsync("sleep 3", TestContext.Current.CancellationToken); @@ -57,8 +57,8 @@ public async Task Get_Local_TimeoutSignalsWithoutThrowing_AndReturnsUnder3Second [Fact] public async Task Get_Local_DenyPolicyRejectsTheCommand_AndTheFileSurvives() { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new( + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new( ShellKind.Local, new ShellPolicy(denyList: ["^rm "]), Timeout: null); var file = Path.Combine(_workspace, "keepme.txt"); @@ -73,15 +73,15 @@ await Assert.ThrowsAsync( [Fact] public async Task Get_NullAllowListPlusOneDeny_AllowsWhatItDoesNotDeny() { - // This proves ShellPolicy's own semantics directly, at the CallShells layer: a null + // This proves ShellPolicy's own semantics directly, at the ConversationShells layer: a null // allowList disables the allow check entirely, so only the deny list refuses a command. // ShellPolicy also treats a supplied-but-empty allow list as deny-all (per its own remarks), // which is why AgentHarnessProviders.BuildPolicy must translate an agent's empty allow: into // null rather than pass it through — that compile-time translation, and the end-to-end // consequence of getting it wrong (an undenied command like pwd being refused), is proven in - // CallSessionShellTests (a shell: policy with deny: and no allow: still lets pwd run). - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new( + // ConversationSessionShellTests (a shell: policy with deny: and no allow: still lets pwd run). + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new( ShellKind.Local, new ShellPolicy(denyList: ["^rm "], allowList: null), Timeout: null); var ok = await shells.Get(options).RunAsync("echo hi", TestContext.Current.CancellationToken); @@ -94,8 +94,8 @@ await Assert.ThrowsAsync( [Fact] public async Task Get_SameOptionsTwice_ReturnsTheSameExecutorInstance() { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); var first = shells.Get(options); var second = shells.Get(options); @@ -106,9 +106,9 @@ public async Task Get_SameOptionsTwice_ReturnsTheSameExecutorInstance() [Fact] public async Task Get_TwoDifferentOptions_ReturnsTwoDifferentExecutors() { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions a = new(ShellKind.Local, Policy: null, Timeout: null); - CallShellOptions b = new(ShellKind.Local, Policy: null, Timeout: null); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions a = new(ShellKind.Local, Policy: null, Timeout: null); + ConversationShellOptions b = new(ShellKind.Local, Policy: null, Timeout: null); Assert.NotSame(shells.Get(a), shells.Get(b)); } @@ -116,8 +116,8 @@ public async Task Get_TwoDifferentOptions_ReturnsTwoDifferentExecutors() [Fact] public async Task DisposeAsync_TwiceIsFine_AndKillsTheLocalBash() { - CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); + ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); var pidResult = await shells.Get(options).RunAsync("echo $$", TestContext.Current.CancellationToken); var pid = int.Parse(pidResult.Stdout.Trim()); @@ -132,11 +132,11 @@ public async Task DisposeAsync_TwiceIsFine_AndKillsTheLocalBash() [Fact] public async Task Get_AfterDispose_ThrowsObjectDisposedException() { - CallShells shells = new(_workspace, logger: null); + ConversationShells shells = new(_workspace, logger: null); await shells.DisposeAsync(); Assert.Throws( - () => shells.Get(new CallShellOptions(ShellKind.Local, Policy: null, Timeout: null))); + () => shells.Get(new ConversationShellOptions(ShellKind.Local, Policy: null, Timeout: null))); } [Fact] @@ -145,8 +145,8 @@ public async Task Get_Local_CleanEnvironment_DropsTheHostsCanaryButKeepsPathAndA Environment.SetEnvironmentVariable("AGENTCORE_TEST_CANARY", "leaked"); try { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new( + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new( ShellKind.Local, Policy: null, Timeout: null, @@ -174,8 +174,8 @@ public async Task Get_Docker_ReturnsADockerShellExecutor_WithNoDockerNeeded() { // DockerShellExecutor construction is lazy: it never talks to docker until RunAsync, so this // needs no docker binary on the test host. - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Docker, Policy: null, Timeout: null); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Docker, Policy: null, Timeout: null); var executor = shells.Get(options); @@ -183,10 +183,10 @@ public async Task Get_Docker_ReturnsADockerShellExecutor_WithNoDockerNeeded() } [Fact] - public async Task GetEnvironmentAsync_ProbesThroughThisCallsExecutor_AndCachesTheSnapshot() + public async Task GetEnvironmentAsync_ProbesThroughThisConversationsExecutor_AndCachesTheSnapshot() { - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); var first = await shells.GetEnvironmentAsync(options, TestContext.Current.CancellationToken); var second = await shells.GetEnvironmentAsync(options, TestContext.Current.CancellationToken); @@ -201,8 +201,8 @@ public async Task GetEnvironmentAsync_WithADenyAllPolicy_StillReturnsARenderable { // Every probe a deny-all policy refuses comes back a null field rather than a throw // (MAF's own swallowing), so the instructions still render their header. - await using CallShells shells = new(_workspace, logger: null); - CallShellOptions options = new(ShellKind.Local, new ShellPolicy(denyList: ["^."]), Timeout: null); + await using ConversationShells shells = new(_workspace, logger: null); + ConversationShellOptions options = new(ShellKind.Local, new ShellPolicy(denyList: ["^."]), Timeout: null); var snapshot = await shells.GetEnvironmentAsync(options, TestContext.Current.CancellationToken); var text = ShellEnvironmentProvider.DefaultInstructionsFormatter(snapshot); @@ -213,11 +213,11 @@ public async Task GetEnvironmentAsync_WithADenyAllPolicy_StillReturnsARenderable [Fact] public async Task GetEnvironmentAsync_AfterDispose_ThrowsObjectDisposedException() { - CallShells shells = new(_workspace, logger: null); + ConversationShells shells = new(_workspace, logger: null); await shells.DisposeAsync(); await Assert.ThrowsAsync(() => shells.GetEnvironmentAsync( - new CallShellOptions(ShellKind.Local, Policy: null, Timeout: null), + new ConversationShellOptions(ShellKind.Local, Policy: null, Timeout: null), TestContext.Current.CancellationToken)); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs index 07eec1c2..91527598 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs @@ -8,7 +8,7 @@ namespace AgentCore.Application.Tests.Runtime.Harness; /// /// and — the two -/// halves of moving MAF's per-provider state bag beside CallSessionState. +/// halves of moving MAF's per-provider state bag beside ConversationSessionState. /// public sealed class HarnessSessionStateTests { diff --git a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughConversationSessionTests.cs similarity index 86% rename from tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs rename to tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughConversationSessionTests.cs index 8ee72c4d..4049d7a3 100644 --- a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughConversationSessionTests.cs @@ -1,5 +1,5 @@ using System.Text.Json.Nodes; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -29,7 +29,7 @@ namespace AgentCore.Application.Tests.Runtime; /// as a store nobody searched as well as a scope nobody could read. /// /// -public sealed class KnowledgeScopeThroughCallSessionTests +public sealed class KnowledgeScopeThroughConversationSessionTests { private const string Yaml = """ @@ -63,7 +63,7 @@ public sealed class KnowledgeScopeThroughCallSessionTests extractor: model: { ref: fill } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -97,7 +97,7 @@ public async Task RunTurnAsync_UnderAHostScope_TheStoreStillSeesThatScope() { using SequencedChatClient reply = new("hello there."); var port = new StubKnowledgePort([Card("a")]); - var session = Build(reply, port).Create("call-1"); + var session = Build(reply, port).Create("conversation-1"); var scope = Scope(); session.Scope = scope; @@ -114,7 +114,7 @@ public async Task RunTurnStreamingAsync_UnderAHostScope_TheStoreStillSeesThatSco // fact rather than an argument from the non-streaming one. using SequencedChatClient reply = new("hello there."); var port = new StubKnowledgePort([Card("a")]); - var session = Build(reply, port).Create("call-2"); + var session = Build(reply, port).Create("conversation-2"); var scope = Scope(); session.Scope = scope; @@ -135,7 +135,7 @@ public async Task RunTurnAsync_WithNoHostScope_LeavesTheAmbientAbsent() // still reaches the provider's gate, and the agent is told it cannot look anything up. using SequencedChatClient reply = new("hello there."); var port = new StubKnowledgePort([Card("a")]); - var session = Build(reply, port).Create("call-3"); + var session = Build(reply, port).Create("conversation-3"); await session.RunTurnAsync("the screen says e33", TestContext.Current.CancellationToken); @@ -146,10 +146,10 @@ public async Task RunTurnAsync_WithNoHostScope_LeavesTheAmbientAbsent() public async Task RunTurnAsync_AfterTheTurn_PutsBackWhatTheHostHadOpen() { // The turn loop opens ambients of its own over the host's. Closing them must restore the - // host's scope rather than clearing it, or a second turn of the same call runs unscoped. + // host's scope rather than clearing it, or a second turn of the same conversation runs unscoped. using SequencedChatClient reply = new("hello there."); var port = new StubKnowledgePort([Card("a")]); - var session = Build(reply, port).Create("call-4"); + var session = Build(reply, port).Create("conversation-4"); var scope = Scope(); session.Scope = scope; @@ -159,7 +159,7 @@ public async Task RunTurnAsync_AfterTheTurn_PutsBackWhatTheHostHadOpen() } [Fact] - public async Task Scope_ResumedCall_IsBuiltFromTheRestoredSlots() + public async Task Scope_ResumedConversation_IsBuiltFromTheRestoredSlots() { // The host cannot do this itself: Restore runs inside OpenSessionAsync, which is the first // statement of the run method, so session.State is empty until the turn has begun. @@ -177,7 +177,7 @@ public async Task Scope_ResumedCall_IsBuiltFromTheRestoredSlots() } [Fact] - public async Task Scope_ResumedCall_WithAnOffEnumSlot_LeavesThatSlotWildcard() + public async Task Scope_ResumedConversation_WithAnOffEnumSlot_LeavesThatSlotWildcard() { // "F63 Treadmill" is outside applies_to's enum: [f63, other], so Restore's TryWrite refuses // it and the slot stays unfilled. Compose then reads it as the wildcard, same as a slot @@ -225,30 +225,30 @@ public async Task Scope_StreamingTurn_ComposesTheSameScope() } - private static CallSessionFactory Build(IChatClient reply, StubKnowledgePort port, string yaml = Yaml) + private static ConversationSessionFactory Build(IChatClient reply, StubKnowledgePort port, string yaml = Yaml) { var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(yaml), new AgentCompilationContext(new FakeChatClientFactory(reply)) { Knowledge = port })["main"]; - return new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + return new ConversationSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); } - private CallSession FreshSession(IChatClient reply) + private ConversationSession FreshSession(IChatClient reply) { _port = new StubKnowledgePort([Card("a")]); - return Build(reply, _port, ScopedYaml).Create("call-fresh"); + return Build(reply, _port, ScopedYaml).Create("conversation-fresh"); } - private CallSession ResumedSession(IChatClient reply, IReadOnlyDictionary stored) + private ConversationSession ResumedSession(IChatClient reply, IReadOnlyDictionary stored) { _port = new StubKnowledgePort([Card("a")]); - // The real restore path: a CallSessionState of the shape store 0 hands back, fed through - // CallSessionFactory.Create so Resume/Restore write the slots, rather than the test poking + // The real restore path: a ConversationSessionState of the shape store 0 hands back, fed through + // ConversationSessionFactory.Create so Resume/Restore write the slots, rather than the test poking // session.State directly and skipping the coercion and enum checks Restore applies. - CallSessionState state = new() + ConversationSessionState state = new() { Stage = "greeting", Slots = stored.ToDictionary( @@ -257,7 +257,7 @@ private CallSession ResumedSession(IChatClient reply, IReadOnlyDictionary -/// A clock a test owns. The turn loop reads callDurationSeconds from a +/// A clock a test owns. The turn loop reads conversationDurationSeconds from a /// , so no test needs a stopwatch. /// internal sealed class TestTimeProvider : TimeProvider @@ -199,7 +199,7 @@ public void Dispose() /// A model that calls the first tool it is offered on every request, and never answers with text. /// /// -/// calls one tool once, which keeps a healthy run finite. Section +/// conversations one tool once, which keeps a healthy run finite. Section /// 8.7 needs the other case: a tool that keeps failing. This client never stops calling, so the run /// spends the error budget of MaximumConsecutiveErrorsPerRequest and the 4th failure throws. /// @@ -234,7 +234,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, - [new FunctionCallContent($"call_{index}", tool.Name, new Dictionary(StringComparer.Ordinal))]) + [new FunctionCallContent($"conversation_{index}", tool.Name, new Dictionary(StringComparer.Ordinal))]) { ResponseId = responseId, MessageId = responseId, @@ -402,7 +402,7 @@ internal sealed class NamedToolCallingChatClient : IChatClient /// What it says once the tool round is over. /// /// How many calls to that one name it emits in a single assistant message. Two reproduces the - /// parallel-call case, where the name alone no longer identifies the call. + /// parallel-conversation case, where the name alone no longer identifies the conversation. /// public NamedToolCallingChatClient(string toolName, string reply, int callsPerTurn = 1) { @@ -438,21 +438,21 @@ public async IAsyncEnumerable GetStreamingResponseAsync( } var round = Interlocked.Increment(ref _calls); - List calls = []; + List conversations = []; for (var index = 0; index < _callsPerTurn; index++) { // Every call of one message carries its own id, exactly as a vendor emits them. This is // the only thing that tells two calls to the same tool apart. - var callId = $"call_{round}_{index}"; + var conversationId = $"conversation_{round}_{index}"; lock (CallIds) { - CallIds.Add(callId); + CallIds.Add(conversationId); } - calls.Add(new FunctionCallContent(callId, _toolName, new Dictionary(StringComparer.Ordinal))); + conversations.Add(new FunctionCallContent(conversationId, _toolName, new Dictionary(StringComparer.Ordinal))); } - yield return new ChatResponseUpdate(ChatRole.Assistant, calls) + yield return new ChatResponseUpdate(ChatRole.Assistant, conversations) { ResponseId = responseId, MessageId = responseId, @@ -655,7 +655,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( var responseId = Guid.NewGuid().ToString("N"); // Past the end of the script, or offered no tool at all on the cap's last request, it - // answers in words. Answering with a call it cannot make would hang the loop. + // answers in words. Answering with a conversation it cannot make would hang the loop. if (index >= _script.Length || options?.Tools is not { Count: > 0 }) { yield return new ChatResponseUpdate(ChatRole.Assistant, FinalText ?? string.Empty) @@ -678,7 +678,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, - [new FunctionCallContent($"call_{index}", tool, callArguments)]) + [new FunctionCallContent($"conversation_{index}", tool, callArguments)]) { ResponseId = responseId, MessageId = responseId, diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs index 4acee378..9cce460f 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs @@ -20,12 +20,12 @@ namespace AgentCore.Application.Tests.Runtime.Turn; /// /// /// The compiled agent is a process singleton, so the provider bound to it is one too and may hold -/// nothing per call. It finds the turn in the session-keyed registry instead, and it applies what +/// nothing per conversation. It finds the turn in the session-keyed registry instead, and it applies what /// it finds only to a run on the session that turn filed. That rule is what keeps a delegated /// run — which is call and return on a session of its own — out of the turn's context. /// /// -/// Every test here runs offline: no network call and no API key. +/// Every test here runs offline: no network conversation and no API key. /// /// public sealed class TurnContextProviderTests @@ -88,10 +88,10 @@ public sealed class TurnContextProviderTests """; [Fact] - public async Task TheProvider_HandsTheTurnsInstructionsToARunOnTheCallsSession() + public async Task TheProvider_HandsTheTurnsInstructionsToARunOnTheConversationsSession() { StubSession session = new(); - TurnRegistry.Set(session, new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Instructions = "ask for the model" }); + TurnRegistry.Set(session, new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", Instructions = "ask for the model" }); var context = await InvokeAsync(session); @@ -107,9 +107,9 @@ public async Task TheProvider_HandsTheTurnsInstructionsToARunOnTheCallsSession() [Fact] public async Task TheProvider_HandsNothingToARunOnAnotherSession() { - StubSession call = new(); + StubSession conversation = new(); StubSession delegated = new(); - TurnRegistry.Set(call, new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Instructions = "ask for the model" }); + TurnRegistry.Set(conversation, new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", Instructions = "ask for the model" }); var context = await InvokeAsync(delegated); @@ -208,8 +208,8 @@ private static ChatClientAgent ChatClientAgentOf(AIAgent agent) return inner; } - /// Compiles over two named models and opens a call on it. - private static CallSession CreateSession(IChatClient reply, IChatClient specialist) + /// Compiles over two named models and opens a conversation on it. + private static ConversationSession CreateSession(IChatClient reply, IChatClient specialist) { RoutingChatClientFactory chatClients = new(reply); chatClients.Route("reply", reply); @@ -218,7 +218,7 @@ private static CallSession CreateSession(IChatClient reply, IChatClient speciali var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(ReminderYaml), new AgentCompilationContext(chatClients))["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null).Create(); diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs index 6aabbbc3..ded47faf 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs @@ -98,7 +98,7 @@ public void AnUnstructuredResult_IsNotRecorded(object? result) public async Task AnOutermostToolCall_IsRecordedUnderTheToolsName() { TurnResults results = new(); - var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Results = results }; + var turn = new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", Results = results }; var tool = AIFunctionFactory.Create(() => Orders, "lookup_orders"); await Run(tool, turn); @@ -112,7 +112,7 @@ public async Task AToolCallNestedInsideAnother_IsNotRecorded() { // The outer model never saw a nested result, so it cannot ask to draw it. TurnResults results = new(); - var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Results = results }; + var turn = new TurnInvocation { ConversationId = "conversation", TurnIndex = 0, Stage = "", Results = results }; var inner = AIFunctionFactory.Create(() => Orders, "inner_lookup"); var outer = AIFunctionFactory.Create( async () => diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnPipelineTests.cs b/tests/AgentCore.Application.Tests/Runtime/TurnPipelineTests.cs index ce404a22..04fb3020 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnPipelineTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/TurnPipelineTests.cs @@ -27,7 +27,7 @@ namespace AgentCore.Application.Tests.Runtime; /// FallbackChatClient answers a run that threw or produced no text. Both report what they did /// on a TurnDisposition, and the turn loop reads it to raise the rows it always raised. /// -/// Every test here runs offline. There is no network call and no API key in this file. +/// Every test here runs offline. There is no network conversation and no API key in this file. /// public sealed class TurnPipelineTests { @@ -72,7 +72,7 @@ public async Task Run_FlaggedInput_CompletesWithRefusalReply() // Arrange. using SequencedChatClient model = new("never spoken"); var session = Build(PlainYaml, model, moderation: ScriptedModerationEvaluator.Flagging("hate")) - .Create("call-1"); + .Create("conversation-1"); // Act. var turn = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -89,7 +89,7 @@ public async Task RunStreaming_FlaggedInput_CompletesWithRefusalReply() // Arrange. using SequencedChatClient model = new("never spoken"); var session = Build(PlainYaml, model, moderation: ScriptedModerationEvaluator.Flagging("hate")) - .Create("call-1"); + .Create("conversation-1"); // Act. The refusal arrives on the ordinary stream path, not on a branch of its own. List spoken = []; @@ -110,7 +110,7 @@ public async Task Run_FlaggedInput_InvokesNoTools() using ToolCallingChatClient model = new("never spoken"); StubToolBuilder tools = new("""{ "status": "shipped" }"""); var session = Build(ToolYaml, model, tools: tools.Create, moderation: ScriptedModerationEvaluator.Flagging("hate")) - .Create("call-1"); + .Create("conversation-1"); // Act. await session.RunTurnAsync("...", TestContext.Current.CancellationToken); @@ -127,13 +127,13 @@ public async Task Run_ModelThrows_CompletesWithFallbackReply() { // Arrange. using ThrowingChatClient model = new(new InvalidOperationException("the vendor is down")); - var session = Build(PlainYaml, model).Create("call-1"); + var session = Build(PlainYaml, model).Create("conversation-1"); // Act. Nothing escapes: the layer below the agent caught it. var turn = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); // Assert. - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); Assert.NotNull(turn.Failure); Assert.Contains("the vendor is down", turn.Failure, StringComparison.Ordinal); Assert.False(session.IsComplete); @@ -144,14 +144,14 @@ public async Task Run_EmptyModelReply_CompletesWithFallbackReply() { // Arrange. Request 41 goes out with no tools and returns quietly. using SequencedChatClient model = new(" "); - var session = Build(PlainYaml, model).Create("call-1"); + var session = Build(PlainYaml, model).Create("conversation-1"); // Act. var turn = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); // Assert. - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); - Assert.Equal(CallSession.EmptyReplyReason, turn.Failure); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.EmptyReplyReason, turn.Failure); } [Fact] @@ -165,7 +165,7 @@ public async Task Run_ModerationEndpointDown_RunsTurnAndReportsUnavailable() model, sink: sink, moderation: ScriptedModerationEvaluator.Throwing(new InvalidOperationException("boom"))) - .Create("call-1"); + .Create("conversation-1"); // Act. var turn = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); @@ -173,7 +173,7 @@ public async Task Run_ModerationEndpointDown_RunsTurnAndReportsUnavailable() // Assert. The turn ran unchecked rather than being refused. Assert.Equal("the ordinary reply", turn.ReplyText); Assert.Equal(1, model.Calls); - Assert.DoesNotContain(sink.EventsOf("call-1"), entry => entry.Kind == AuditEventKind.PromptFlagged); + Assert.DoesNotContain(sink.EventsOf("conversation-1"), entry => entry.Kind == AuditEventKind.PromptFlagged); } // ------------------------------------------------------------------------------------------- @@ -185,16 +185,16 @@ public async Task Run_FlaggedOutcome_RaisesSameAuditRowsAsBefore() // Arrange. InMemoryAuditSink sink = new(); var session = Build(PlainYaml, new SequencedChatClient("never spoken"), sink: sink, - moderation: ScriptedModerationEvaluator.Flagging("violence", "harassment")).Create("call-1"); + moderation: ScriptedModerationEvaluator.Flagging("violence", "harassment")).Create("conversation-1"); // Act. await session.RunTurnAsync("...", TestContext.Current.CancellationToken); - // Assert. call.started, prompt.flagged, turn.completed — the flag still precedes the turn + // Assert. conversation.started, prompt.flagged, turn.completed — the flag still precedes the turn // event, because the verdict is known before the model runs. - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.PromptFlagged, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.PromptFlagged, AuditEventKind.TurnCompleted], events.Select(entry => entry.Kind)); Assert.Equal("violence,harassment", events[1].Payload[AuditPayloadKeys.ModerationCategories]); } @@ -205,16 +205,16 @@ public async Task Run_ThrownOutcome_RaisesSameAuditRowsAsBefore() // Arrange. InMemoryAuditSink sink = new(); using ThrowingChatClient model = new(new InvalidOperationException("the vendor is down")); - var session = Build(PlainYaml, model, sink: sink).Create("call-1"); + var session = Build(PlainYaml, model, sink: sink).Create("conversation-1"); // Act. await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); // Assert. The turn-altitude tool.failed row still names the fault, and still precedes the // turn.completed of the same turn. - var events = sink.EventsOf("call-1"); + var events = sink.EventsOf("conversation-1"); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.ToolFailed, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.ToolFailed, AuditEventKind.TurnCompleted], events.Select(entry => entry.Kind)); Assert.Contains("the vendor is down", events[1].Payload[AuditPayloadKeys.ToolError], StringComparison.Ordinal); } @@ -273,7 +273,7 @@ public async Task Run_GraphRow_ModeratesTheCallerOnceAndNotOncePerNode() using SequencedChatClient researcher = new("Let me check the order system."); using SequencedChatClient responder = new("Order 41 ships Friday."); var endpoint = ScriptedModerationEvaluator.Clean(); - var session = BuildGraph(researcher, responder, endpoint).Create("call-1"); + var session = BuildGraph(researcher, responder, endpoint).Create("conversation-1"); // Act. await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); @@ -290,15 +290,15 @@ public async Task Run_GraphRowWhereNoNodeSpeaks_SpeaksTheFallbackOnceForTheTurn( // Arrange. Every node runs and none of them produces a word. using SequencedChatClient researcher = new(" "); using SequencedChatClient responder = new(" "); - var session = BuildGraph(researcher, responder, moderation: null).Create("call-1"); + var session = BuildGraph(researcher, responder, moderation: null).Create("conversation-1"); // Act. var turn = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); // Assert. R2 is a rule about a turn: one fallback is spoken to the caller, and none of it is // fed back into the graph as a node reply. - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); - Assert.Equal(CallSession.EmptyReplyReason, turn.Failure); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.EmptyReplyReason, turn.Failure); Assert.Equal(1, researcher.Calls); Assert.Equal(1, responder.Calls); } @@ -320,7 +320,7 @@ public async Task Run_GraphRowWhereNoNodeSpeaks_SpeaksTheFallbackOnceForTheTurn( agents: [ researcher, responder ] """; - private static CallSessionFactory BuildGraph( + private static ConversationSessionFactory BuildGraph( IChatClient researcher, IChatClient responder, ScriptedModerationEvaluator? moderation) @@ -335,10 +335,10 @@ private static CallSessionFactory BuildGraph( Moderation = moderation is null ? null : new PromptModerator(moderation), })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - observers: CallObservers.Standard(new InMemoryAuditSink(), logger: null)); + observers: ConversationObservers.Standard(new InMemoryAuditSink(), logger: null)); } private static CompiledAgent Compile( @@ -360,7 +360,7 @@ private static CompiledAgent Compile( })["main"]; } - private static CallSessionFactory Build( + private static ConversationSessionFactory Build( string yaml, IChatClient reply, IAuditSinkPort? sink = null, @@ -369,9 +369,9 @@ private static CallSessionFactory Build( { var compiled = Compile(yaml, reply, out _, tools, moderation); - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - observers: CallObservers.Standard(sink ?? new InMemoryAuditSink(), logger: null)); + observers: ConversationObservers.Standard(sink ?? new InMemoryAuditSink(), logger: null)); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs b/tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs index dc2a0aaf..4e88b6c0 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs @@ -38,7 +38,7 @@ public sealed class TurnScreenTests [Fact] public async Task ATurnThatDoesNotStream_ShowsItsToolsTheScreen() { - var (session, probe) = NewCall(); + var (session, probe) = NewConversation(); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -56,7 +56,7 @@ public async Task ATurnThatStreams_ShowsItsToolsTheScreenToo() // yield, and the framework streams the tool-call update BEFORE it invokes the function, so a // scope opened once reaches no round at all. Only the per-round re-entry in // RunTurnStreamingAsync keeps the screen alive across it. - var (session, probe) = NewCall(); + var (session, probe) = NewConversation(); await foreach (var _ in session.RunTurnStreamingAsync("hi", TestContext.Current.CancellationToken)) { @@ -67,11 +67,11 @@ public async Task ATurnThatStreams_ShowsItsToolsTheScreenToo() } [Fact] - public async Task ACallThatWasGivenNoScreen_ShowsItsToolsNone() + public async Task AConversationThatWasGivenNoScreen_ShowsItsToolsNone() { // The voice path. The tool reads the null and tells the model it cannot show anything, // rather than claiming a picture a telephone caller will never see. - var (session, probe) = NewCall(withScreen: false); + var (session, probe) = NewConversation(withScreen: false); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); @@ -85,7 +85,7 @@ public async Task AScreenTakenBackBeforeATurn_LeavesTheToolWithNone() // A host sets this per request, and the whole-reply branch of the chat endpoint sets none. // Taking it back has to reach the tool, or a session that streamed once keeps a screen the // next answer has nowhere to write. - var (session, probe) = NewCall(); + var (session, probe) = NewConversation(); session.SetHasScreen(false); @@ -95,8 +95,8 @@ public async Task AScreenTakenBackBeforeATurn_LeavesTheToolWithNone() Assert.Null(probe.Seen); } - /// Opens a call whose specialist is handed one tool that reports the screen it found. - private static (CallSession Session, ScreenProbe Probe) NewCall(bool withScreen = true) + /// Opens a conversation whose specialist is handed one tool that reports the screen it found. + private static (ConversationSession Session, ScreenProbe Probe) NewConversation(bool withScreen = true) { ToolCallingChatClient greeter = new( "hello there.", @@ -110,7 +110,7 @@ private static (CallSession Session, ScreenProbe Probe) NewCall(bool withScreen var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(DelegationYaml), new AgentCompilationContext(chatClients))["main"]; - var session = new CallSessionFactory( + var session = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null).Create(); diff --git a/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs b/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs index d7665beb..7878e5c5 100644 --- a/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs +++ b/tests/AgentCore.Application.Tests/Secrets/ResolvedSecretsTests.cs @@ -102,7 +102,7 @@ public async Task OneName_ReadsTheResolverOnce_HoweverManyToolsReferenceIt() resolver, TestContext.Current.CancellationToken); - // Three references, one name, one read. Startup pays for the read, and no call does. + // Three references, one name, one read. Startup pays for the read, and no conversation does. Assert.Equal([ApiKeyName], resolver.Asked); Assert.Equal(1, secrets.Count); } @@ -139,7 +139,7 @@ public async Task ADocumentWithNoReference_ReadsNothing() } // --------------------------------------------------------------------------------------------- - // Failing at startup, and never in the middle of a call. + // Failing at startup, and never in the middle of a conversation. // --------------------------------------------------------------------------------------------- [Fact] public async Task AnUnresolvableName_FailsAtStartupAndNamesThePointer() diff --git a/tests/AgentCore.Application.Tests/Secrets/SecretResolverExtensionsTests.cs b/tests/AgentCore.Application.Tests/Secrets/SecretResolverExtensionsTests.cs index e8332dee..303449c1 100644 --- a/tests/AgentCore.Application.Tests/Secrets/SecretResolverExtensionsTests.cs +++ b/tests/AgentCore.Application.Tests/Secrets/SecretResolverExtensionsTests.cs @@ -120,7 +120,7 @@ public async Task NoChainAtAll_ReadsTheVariableAlone() try { // A host that binds no resolver is an ordinary case, so the null is answered here rather - // than at every call site. + // than at every conversation site. var value = await SecretResolverExtensions.RequireAsync( null, secret, diff --git a/tests/AgentCore.Application.Tests/Sessions/CallSessionsTests.cs b/tests/AgentCore.Application.Tests/Sessions/ConversationSessionsTests.cs similarity index 62% rename from tests/AgentCore.Application.Tests/Sessions/CallSessionsTests.cs rename to tests/AgentCore.Application.Tests/Sessions/ConversationSessionsTests.cs index 4c34e287..9fb0ff8e 100644 --- a/tests/AgentCore.Application.Tests/Sessions/CallSessionsTests.cs +++ b/tests/AgentCore.Application.Tests/Sessions/ConversationSessionsTests.cs @@ -12,35 +12,35 @@ namespace AgentCore.Application.Tests.Sessions; /// -/// The lifecycle of one call's session: opened, found again, and closed. +/// The lifecycle of one conversation's session: opened, found again, and closed. /// -public sealed class CallSessionsTests +public sealed class ConversationSessionsTests { private static CancellationToken Token => TestContext.Current.CancellationToken; [Fact] - public async Task ASessionThatWasOpenedIsFoundAgainUnderItsCallId() + public async Task ASessionThatWasOpenedIsFoundAgainUnderItsConversationId() { - InMemoryCallSessions sessions = new(Factory(), TimeSpan.FromMinutes(30), Clock()); + InMemoryConversationSessions sessions = new(Factory(), TimeSpan.FromMinutes(30), Clock()); - var opened = await sessions.OpenAsync("call-1", Token); + var opened = await sessions.OpenAsync("conversation-1", Token); - Assert.Same(opened, await sessions.TryGetAsync("call-1", Token)); + Assert.Same(opened, await sessions.TryGetAsync("conversation-1", Token)); } [Fact] - public async Task ClosingACallWaitsForTheWordsItStillOwes() + public async Task ClosingAConversationWaitsForTheWordsItStillOwes() { // A real store answers over a network, so a write outlives the turn that queued it. This // session is the only thing that can wait for it, and closing is the last moment anything can. - ParkingCallStore transcript = new(); - InMemoryCallSessions sessions = new(Factory(transcript), TimeSpan.FromMinutes(30), Clock()); - var session = await sessions.OpenAsync("call-1", Token); + ParkingConversationStore transcript = new(); + InMemoryConversationSessions sessions = new(Factory(transcript), TimeSpan.FromMinutes(30), Clock()); + var session = await sessions.OpenAsync("conversation-1", Token); var turn = session.RunTurnAsync("hello", Token); await transcript.Parked; - var closing = sessions.CloseAsync("call-1", Token).AsTask(); + var closing = sessions.CloseAsync("conversation-1", Token).AsTask(); var returnedEarly = await Task.WhenAny(closing, Task.Delay(200, Token)) == closing; Assert.False(returnedEarly); @@ -48,7 +48,7 @@ public async Task ClosingACallWaitsForTheWordsItStillOwes() await closing; Assert.True(transcript.Landed); - Assert.Null(await sessions.TryGetAsync("call-1", Token)); + Assert.Null(await sessions.TryGetAsync("conversation-1", Token)); await turn; } @@ -56,15 +56,15 @@ public async Task ClosingACallWaitsForTheWordsItStillOwes() public async Task ASessionNobodyTouchedPastTheIdleTimeoutIsClosed() { var clock = Clock(); - InMemoryCallSessions sessions = new(Factory(), TimeSpan.FromMinutes(30), clock); - await sessions.OpenAsync("call-1", Token); + InMemoryConversationSessions sessions = new(Factory(), TimeSpan.FromMinutes(30), clock); + await sessions.OpenAsync("conversation-1", Token); clock.Advance(TimeSpan.FromMinutes(31)); await sessions.SweepAsync(Token); - // A caller that abandons a text call never reaches a terminal stage, so nothing else would + // A caller that abandons a text conversation never reaches a terminal stage, so nothing else would // ever drop this session and the process would hold it for its whole life. - Assert.Null(await sessions.TryGetAsync("call-1", Token)); + Assert.Null(await sessions.TryGetAsync("conversation-1", Token)); Assert.Equal(0, sessions.Count); } @@ -72,18 +72,18 @@ public async Task ASessionNobodyTouchedPastTheIdleTimeoutIsClosed() public async Task ReadingASessionPutsItsIdleClockBackToZero() { var clock = Clock(); - InMemoryCallSessions sessions = new(Factory(), TimeSpan.FromMinutes(30), clock); - await sessions.OpenAsync("call-1", Token); + InMemoryConversationSessions sessions = new(Factory(), TimeSpan.FromMinutes(30), clock); + await sessions.OpenAsync("conversation-1", Token); clock.Advance(TimeSpan.FromMinutes(20)); - Assert.NotNull(await sessions.TryGetAsync("call-1", Token)); + Assert.NotNull(await sessions.TryGetAsync("conversation-1", Token)); - // Forty minutes since it was opened, twenty since it was last read. A call still being had + // Forty minutes since it was opened, twenty since it was last read. A conversation still being had // must not be dropped out from under the caller. clock.Advance(TimeSpan.FromMinutes(20)); await sessions.SweepAsync(Token); - Assert.NotNull(await sessions.TryGetAsync("call-1", Token)); + Assert.NotNull(await sessions.TryGetAsync("conversation-1", Token)); } [Fact] @@ -91,10 +91,10 @@ public async Task AnExpiringSessionStillHandsOverTheWordsItOwed() { // The reason expiry goes through CloseAsync. An evictor that dropped the entry on its own // would return with the write still in flight, and nothing left able to wait for it. - ParkingCallStore transcript = new(); + ParkingConversationStore transcript = new(); var clock = Clock(); - InMemoryCallSessions sessions = new(Factory(transcript), TimeSpan.FromMinutes(30), clock); - var session = await sessions.OpenAsync("call-1", Token); + InMemoryConversationSessions sessions = new(Factory(transcript), TimeSpan.FromMinutes(30), clock); + var session = await sessions.OpenAsync("conversation-1", Token); var turn = session.RunTurnAsync("hello", Token); await transcript.Parked; @@ -115,19 +115,19 @@ public async Task AnExpiringSessionStillHandsOverTheWordsItOwed() [Fact] public async Task AnExpiringSessionWritesTheLastEventOfItsChain() { - // §11 item 6 makes call.ended the last event of every call. A caller who simply stops + // §11 item 6 makes conversation.ended the last event of every conversation. A caller who simply stops // replying closes no socket and reaches no terminal stage, so expiry is the only thing left // that can write it, and a chain with no end is a permanent gap in the record of D23. - RecordingCallObserver observer = new(); + RecordingConversationObserver observer = new(); var clock = Clock(); - InMemoryCallSessions sessions = new( + InMemoryConversationSessions sessions = new( Factory(observer: observer), TimeSpan.FromMinutes(30), clock); - await sessions.OpenAsync("call-1", Token); + await sessions.OpenAsync("conversation-1", Token); clock.Advance(TimeSpan.FromMinutes(31)); await sessions.SweepAsync(Token); - Assert.Contains(observer.Kinds, kind => kind == CallEventKind.CallEnded); + Assert.Contains(observer.Kinds, kind => kind == ConversationEventKind.ConversationEnded); } @@ -144,22 +144,22 @@ private static FakeTimeProvider Clock() agent: only """; - private static CallSessionFactory Factory( - ICallStore? transcript = null, + private static ConversationSessionFactory Factory( + IConversationStore? transcript = null, string? yaml = null, IChatClient? reply = null, - ICallObserver? observer = null) + IConversationObserver? observer = null) { var document = ConfigurationLoader.LoadYaml(yaml ?? Document); RoutingChatClientFactory chatClients = new(reply ?? new StubChatClient()); var compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(chatClients) { CallStore = transcript })["main"]; + new AgentCompilationContext(chatClients) { ConversationStore = transcript })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients), + ConversationSessionFactory.CreateExtractor(compiled, chatClients), observers: observer is null ? null : [observer]); } @@ -180,12 +180,12 @@ public void Dispose() } } - /// Records the kind of every event one call raised. - private sealed class RecordingCallObserver : ICallObserver + /// Records the kind of every event one conversation raised. + private sealed class RecordingConversationObserver : IConversationObserver { - private readonly List _kinds = []; + private readonly List _kinds = []; - public IReadOnlyList Kinds + public IReadOnlyList Kinds { get { @@ -196,16 +196,16 @@ public IReadOnlyList Kinds } } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken = default) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken = default) { lock (_kinds) { - _kinds.Add(callEvent.Kind); + _kinds.Add(conversationEvent.Kind); } return ValueTask.CompletedTask; } } - /// The default store, counting the reads that keep a call out of the idle sweep. + /// The default store, counting the reads that keep a conversation out of the idle sweep. } diff --git a/tests/AgentCore.Application.Tests/Skills/SkillsProviderFactoryTests.cs b/tests/AgentCore.Application.Tests/Skills/SkillsProviderFactoryTests.cs index 8b6169dc..4ae2dcfd 100644 --- a/tests/AgentCore.Application.Tests/Skills/SkillsProviderFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Skills/SkillsProviderFactoryTests.cs @@ -9,7 +9,7 @@ namespace AgentCore.Application.Tests.Skills; /// /// One agent must see its own skills and no others, must never be asked to approve a tool call -/// mid-call, and must never be told a script tool exists. +/// mid-conversation, and must never be told a script tool exists. /// public sealed class SkillsProviderFactoryTests { diff --git a/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs b/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs index 66855fb4..65ba5e67 100644 --- a/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs +++ b/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs @@ -7,7 +7,7 @@ namespace AgentCore.Application.Tests.State; /// -/// : the durable-blob view of a call's declared state. +/// : the durable-blob view of a conversation's declared state. /// public sealed class StateDocumentTests { @@ -93,7 +93,7 @@ public void TryWrite_ValueInsideTheEnum_IsAccepted() } [Fact] - public void WrittenSlots_HandsOutAFreshCopyEveryCall() + public void WrittenSlots_HandsOutAFreshCopyEveryConversation() { StateDocument state = new(Document); var result = JsonNode.Parse("""{ "model": "F63" }"""); @@ -105,8 +105,8 @@ public void WrittenSlots_HandsOutAFreshCopyEveryCall() // The declared state schema only ever writes scalars (section 8.3's four writers coerce // to boolean/integer/number/string), so a scalar JsonValue is the only value shape this // slot can hold today, and a scalar exposes no public mutator. The clone's contract is - // still checked the way a caller could actually break it without one: two calls must not - // hand back the same node instance, because a caller free to reparent or wrap one call's + // still checked the way a caller could actually break it without one: two conversations must not + // hand back the same node instance, because a caller free to reparent or wrap one conversation's // node (e.g. into a JsonObject of its own) would otherwise reach into the live document, // or into the copy a different caller was given. Assert.NotSame(first["model"], second["model"]); @@ -134,8 +134,8 @@ public void WrittenSlots_OmitsASlotNoWriterHasFilled() public async Task WrittenSlots_ReadWhileTheTurnLoopIsStillWriting_AnswersInsteadOfThrowing() { // The turn loop is this document's only WRITER, but it is not its only toucher. - // CallSession.Snapshot reads it off the turn, and AgentCoreAgent.SerializeSessionCoreAsync is - // a framework seam any host thread may call while a turn is running — an exposure this branch + // ConversationSession.Snapshot reads it off the turn, and AgentCoreAgent.SerializeSessionCoreAsync is + // a framework seam any host thread may conversation while a turn is running — an exposure this branch // created, because that seam used to throw NotSupportedException instead of answering. // Enumerating a plain Dictionary mid-write is an InvalidOperationException, and it would // surface out of the framework's own serialization API. diff --git a/tests/AgentCore.Application.Tests/State/StateExtractorTests.cs b/tests/AgentCore.Application.Tests/State/StateExtractorTests.cs index 5bbfc922..146dbf9c 100644 --- a/tests/AgentCore.Application.Tests/State/StateExtractorTests.cs +++ b/tests/AgentCore.Application.Tests/State/StateExtractorTests.cs @@ -137,7 +137,7 @@ public void AReplyThatDoesNotDeserialize_LeavesTheSlotsUnchanged() var result = extractor.Write(state, "I am sorry, I cannot do that."); - // Section 8.7: the extractor has no retry, and a failed extraction never drops a call. + // Section 8.7: the extractor has no retry, and a failed extraction never drops a conversation. Assert.False(result.Deserialized); Assert.NotNull(result.Failure); Assert.Equal(0, result.Filled); @@ -178,7 +178,7 @@ public async Task TheExtractor_MakesExactlyOneModelCall() [new ChatMessage(ChatRole.User, "goodbye")], TestContext.Current.CancellationToken); - // The extractor has no retry: one call, and one only. + // The extractor has no retry: one conversation, and one only. Assert.Equal(1, client.Calls); Assert.True(result.Deserialized); Assert.True(state.Read("callerSaidGoodbye")!.GetValue()); diff --git a/tests/AgentCore.Application.Tests/State/StateWriterTests.cs b/tests/AgentCore.Application.Tests/State/StateWriterTests.cs index b3727635..ffd13979 100644 --- a/tests/AgentCore.Application.Tests/State/StateWriterTests.cs +++ b/tests/AgentCore.Application.Tests/State/StateWriterTests.cs @@ -141,13 +141,13 @@ public void CounterWriter_HoldsStillOnceTheSlotItWatchesIsTrue() [Fact] public void TheThreeReservedSlots_AreAlwaysPresentAndReadOnly() { - StateDocument state = new(Document) { Stage = "resolve", TurnIndex = 7, CallDurationSeconds = 42.5 }; + StateDocument state = new(Document) { Stage = "resolve", TurnIndex = 7, ConversationDurationSeconds = 42.5 }; var snapshot = state.Snapshot(); Assert.Equal("resolve", snapshot[ReservedStateSlots.Stage]!.GetValue()); Assert.Equal(7, snapshot[ReservedStateSlots.TurnIndex]!.GetValue()); - Assert.Equal(42.5, snapshot[ReservedStateSlots.CallDurationSeconds]!.GetValue()); + Assert.Equal(42.5, snapshot[ReservedStateSlots.ConversationDurationSeconds]!.GetValue()); foreach (var reserved in ReservedStateSlots.All) { diff --git a/tests/AgentCore.Application.Tests/State/ToolResultPathTests.cs b/tests/AgentCore.Application.Tests/State/ToolResultPathTests.cs index 758d3c54..ca8d4dfe 100644 --- a/tests/AgentCore.Application.Tests/State/ToolResultPathTests.cs +++ b/tests/AgentCore.Application.Tests/State/ToolResultPathTests.cs @@ -163,7 +163,7 @@ public void PointerPath_AMalformedEscapeSequence_ResolvesToNull() { // Owner ruling, fix round 1: ACCEPTED as a deliberate tightening. "~2" is not a valid RFC // 6901 escape (only ~0 and ~1 are defined). The pre-swap hand-rolled resolver's Replace - // calls simply didn't match "~2", so the segment survived as the literal text "a~2b" and + // conversations simply didn't match "~2", so the segment survived as the literal text "a~2b" and // resolved whatever property happened to have that exact (unusual) name. Json.Pointer. // JsonPointer validates every escape up front and rejects the whole pointer as malformed, so // this now resolves to nothing even though the document does hold a property named "a~2b". diff --git a/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs index c791f5d4..f7becd11 100644 --- a/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs @@ -155,7 +155,7 @@ public async Task TheDeclaredSchema_ReachesTheModelUnchanged() // classification that makes that true off DeclaredTool and into // AuditingFunctionInvokingChatClient, so calling the bare tool directly now sees the exception // the host delegate threw. See AuditingFunctionInvokingChatClientErrorPolicyTests and - // CallSessionTests for the end-to-end guarantee. + // ConversationSessionTests for the end-to-end guarantee. // --------------------------------------------------------------------------------------------- [Fact] public async Task AHostDelegateThatThrows_PropagatesForTheMiddlewareToClassify() diff --git a/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs b/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs index 9fcdf149..923958bd 100644 --- a/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs @@ -17,7 +17,7 @@ namespace AgentCore.Application.Tests.Tools; /// /// The shipped example holds two built-ins: web.search, a marker that builds one /// HostedWebSearchTool and runs no code of its own — see HostedWebSearchDropTests for -/// what reaches a compiled agent — and file.publish, a plain function whose call path is +/// what reaches a compiled agent — and file.publish, a plain function whose conversation path is /// covered in FilePublishToolDefinitionTests. /// public sealed class BuiltinToolTests diff --git a/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs b/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs index 5119b05d..6e8d8105 100644 --- a/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs @@ -76,7 +76,7 @@ public async Task ACallerThatHungUp_StillPassesTheCancellationThrough() using CancellationTokenSource source = new(); await source.CancelAsync(); - // Nobody reads this result, and swallowing it would keep a dead call running. + // Nobody reads this result, and swallowing it would keep a dead conversation running. await Assert.ThrowsAnyAsync( async () => await new ThrowingTool(new OperationCanceledException()).InvokeAsync( [], diff --git a/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs b/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs index 0a9d1813..b2b8673a 100644 --- a/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/FilePublishBackgroundChildTests.cs @@ -11,8 +11,8 @@ namespace AgentCore.Application.Tests.Tools; /// -/// A background child runs with no turn, so file.publish finds the owning call on the stamp -/// its session carries and stores the file under the parent call. +/// A background child runs with no turn, so file.publish finds the owning conversation on the stamp +/// its session carries and stores the file under the parent conversation. /// /// /// The child session is created inside the parent's run, the way BackgroundAgentsProvider @@ -23,16 +23,16 @@ public sealed class FilePublishBackgroundChildTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-publish-child-" + Guid.NewGuid().ToString("N")); - public FilePublishBackgroundChildTests() => Directory.CreateDirectory(Path.Combine(_root, "call-9")); + public FilePublishBackgroundChildTests() => Directory.CreateDirectory(Path.Combine(_root, "conversation-9")); public void Dispose() => Directory.Delete(_root, recursive: true); [Fact] - public async Task AChildThatPublishes_StoresTheFileUnderTheParentCall() + public async Task AChildThatPublishes_StoresTheFileUnderTheParentConversation() { // Arrange var token = TestContext.Current.CancellationToken; - File.WriteAllText(Path.Combine(_root, "call-9", "rows.csv"), "a,b"); + File.WriteAllText(Path.Combine(_root, "conversation-9", "rows.csv"), "a,b"); RecordingBlobStore blobs = new(); var publish = new FilePublishToolDefinition().Build( @@ -46,7 +46,7 @@ public async Task AChildThatPublishes_StoresTheFileUnderTheParentCall() BackgroundChildAgent child = new(new ChatClientAgent(childModel, new ChatClientAgentOptions { ChatOptions = new ChatOptions { Tools = [publish] } })); SessionCreatingProvider creating = new(child); ChatClientAgent parent = new(new ScriptedChatClient("parent"), new ChatClientAgentOptions { AIContextProviders = [creating] }); - var turn = new TurnInvocation { CallId = "call-9", TurnIndex = 0, Stage = "s", Workspace = Path.Combine(_root, "call-9") }; + var turn = new TurnInvocation { ConversationId = "conversation-9", TurnIndex = 0, Stage = "s", Workspace = Path.Combine(_root, "conversation-9") }; await parent.RunAsync("go", await parent.CreateSessionAsync(token), turn.RunOptions(), token); @@ -56,9 +56,9 @@ public async Task AChildThatPublishes_StoresTheFileUnderTheParentCall() // Assert Assert.Equal(["publish"], childModel.Called); var result = Assert.Single(childModel.ToolResults); - Assert.Contains("https://blobs.test/call-9/rows.csv", result, StringComparison.Ordinal); + Assert.Contains("https://blobs.test/conversation-9/rows.csv", result, StringComparison.Ordinal); Assert.DoesNotContain(ToolErrorResult.ErrorProperty + "\":true", result, StringComparison.Ordinal); - Assert.Single(blobs.Blobs.Keys, key => key == ("call-9", "rows.csv")); + Assert.Single(blobs.Blobs.Keys, key => key == ("conversation-9", "rows.csv")); } private sealed class SessionCreatingProvider(AIAgent child) : AIContextProvider diff --git a/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs b/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs index 6f25b173..ffea2d7c 100644 --- a/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs @@ -27,7 +27,7 @@ public sealed class FilePublishToolDefinitionTests : IDisposable private readonly RecordingBlobStore _blobs = new(); - public FilePublishToolDefinitionTests() => Directory.CreateDirectory(Path.Combine(_root, "call-1")); + public FilePublishToolDefinitionTests() => Directory.CreateDirectory(Path.Combine(_root, "conversation-1")); public void Dispose() => Directory.Delete(_root, recursive: true); @@ -100,7 +100,7 @@ public async Task Publish_AFileThatIsNotThere_IsRefusedWithAToolError() [Fact] public async Task Publish_AnExtensionThePolicyRefuses_IsRefusedWithTheReason() { - File.WriteAllText(Path.Combine(_root, "call-1", "notes.exe"), "x"); + File.WriteAllText(Path.Combine(_root, "conversation-1", "notes.exe"), "x"); var result = await PublishAsync("notes.exe"); @@ -112,7 +112,7 @@ public async Task Publish_AnExtensionThePolicyRefuses_IsRefusedWithTheReason() [Fact] public async Task Publish_AFileOverTheCap_IsRefusedWithTheReason() { - File.WriteAllBytes(Path.Combine(_root, "call-1", "big.csv"), new byte[64]); + File.WriteAllBytes(Path.Combine(_root, "conversation-1", "big.csv"), new byte[64]); var result = await PublishAsync("big.csv", policy: new BlobPolicy(32, ["csv"])); @@ -121,9 +121,9 @@ public async Task Publish_AFileOverTheCap_IsRefusedWithTheReason() } [Fact] - public async Task Publish_AGoodFile_StoresItUnderTheCallLinksItAndFilesTheCardOnTheTurn() + public async Task Publish_AGoodFile_StoresItUnderTheConversationLinksItAndFilesTheCardOnTheTurn() { - File.WriteAllText(Path.Combine(_root, "call-1", "rows.csv"), "a,b\n1,2\n"); + File.WriteAllText(Path.Combine(_root, "conversation-1", "rows.csv"), "a,b\n1,2\n"); TurnFiles files = new(); using var outer = files.BeginOuterCall("tc_1"); @@ -133,9 +133,9 @@ public async Task Publish_AGoodFile_StoresItUnderTheCallLinksItAndFilesTheCardOn Assert.Equal("rows.csv", result["name"]!.GetValue()); Assert.Equal("text/csv", result["mediaType"]!.GetValue()); Assert.Equal(8, result["length"]!.GetValue()); - Assert.Equal("https://blobs.test/call-1/rows.csv?ttl=900", result["url"]!.GetValue()); + Assert.Equal("https://blobs.test/conversation-1/rows.csv?ttl=900", result["url"]!.GetValue()); - var (mediaType, bytes) = _blobs.Blobs[("call-1", "rows.csv")]; + var (mediaType, bytes) = _blobs.Blobs[("conversation-1", "rows.csv")]; Assert.Equal("text/csv", mediaType); Assert.Equal("a,b\n1,2\n", System.Text.Encoding.UTF8.GetString(bytes)); @@ -151,25 +151,25 @@ public async Task Publish_AGoodFile_StoresItUnderTheCallLinksItAndFilesTheCardOn [Fact] public async Task Publish_AFileInASubfolder_IsStoredUnderItsOwnName() { - Directory.CreateDirectory(Path.Combine(_root, "call-1", "out")); - File.WriteAllBytes(Path.Combine(_root, "call-1", "out", "chart.png"), [1, 2, 3]); + Directory.CreateDirectory(Path.Combine(_root, "conversation-1", "out")); + File.WriteAllBytes(Path.Combine(_root, "conversation-1", "out", "chart.png"), [1, 2, 3]); var result = await PublishAsync("out/chart.png"); Assert.Equal("chart.png", result["name"]!.GetValue()); Assert.Equal("image/png", result["mediaType"]!.GetValue()); - Assert.True(_blobs.Blobs.ContainsKey(("call-1", "chart.png"))); + Assert.True(_blobs.Blobs.ContainsKey(("conversation-1", "chart.png"))); } [Fact] public async Task Publish_OutsideAnyTurn_IsRefusedWithAToolError() { - File.WriteAllText(Path.Combine(_root, "call-1", "rows.csv"), "a"); + File.WriteAllText(Path.Combine(_root, "conversation-1", "rows.csv"), "a"); var result = await PublishAsync("rows.csv", turn: false); Assert.True(ToolErrorResult.IsError(result)); - Assert.Contains("no call is running", result["message"]!.GetValue(), StringComparison.Ordinal); + Assert.Contains("no conversation is running", result["message"]!.GetValue(), StringComparison.Ordinal); } private AITool Build(BlobPolicy? policy = null) @@ -187,10 +187,10 @@ private async Task PublishAsync( { arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { - CallId = "call-1", + ConversationId = "conversation-1", TurnIndex = 0, Stage = string.Empty, - Workspace = Path.Combine(_root, "call-1"), + Workspace = Path.Combine(_root, "conversation-1"), Files = files, }; } diff --git a/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs index 76b11afe..a1af802d 100644 --- a/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs @@ -12,7 +12,7 @@ namespace AgentCore.Application.Tests.Tools; /// The deadline any tool kind can carry. /// /// -/// A tool the model calls on a live telephone call can otherwise take as long as the far side feels +/// A tool the model calls on a live telephone conversation can otherwise take as long as the far side feels /// like taking. The deadline wraps a tool rather than living inside one, so one implementation and /// one message cover every kind rather than each kind growing its own. /// diff --git a/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs b/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs index 1682e815..8a401251 100644 --- a/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs @@ -13,7 +13,7 @@ namespace AgentCore.Application.Tests.Tools; /// -/// Drives a real turn end to end through , with a bound tool that declares +/// Drives a real turn end to end through , with a bound tool that declares /// a parameter, and reads what the runtime actually filled it with. /// public sealed class ToolCallScopeTests @@ -21,7 +21,7 @@ public sealed class ToolCallScopeTests private const string Yaml = """ apiVersion: agentcore/v1 tools: - - { id: request_human, kind: binding, binds: RequestHuman, description: "Ask a human to take the call." } + - { id: request_human, kind: binding, binds: RequestHuman, description: "Ask a human to take the conversation." } agents: items: - { id: only, instructions: "help the caller", tools: [ request_human ] } @@ -35,7 +35,7 @@ public sealed class ToolCallScopeTests """; [Fact] - public async Task ABoundTool_ReceivesTheRunningCallsScope() + public async Task ABoundTool_ReceivesTheRunningConversationsScope() { List captured = []; ToolBindingRegistry bindings = new(); @@ -53,14 +53,14 @@ [new BindingToolSource(bindings)], TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards)); - var session = factory.Create("call-scope-1"); + var session = factory.Create("conversation-scope-1"); await session.RunTurnAsync("I need a person", TestContext.Current.CancellationToken); var first = Assert.Single(captured); - Assert.Equal(session.CallId, first.CallId); + Assert.Equal(session.ConversationId, first.ConversationId); Assert.Equal(0, first.TurnIndex); Assert.Equal("handling", first.Stage); @@ -68,12 +68,12 @@ [new BindingToolSource(bindings)], await session.RunTurnAsync("still need a person", TestContext.Current.CancellationToken); var second = Assert.Single(captured); - Assert.Equal(session.CallId, second.CallId); + Assert.Equal(session.ConversationId, second.ConversationId); Assert.Equal(1, second.TurnIndex); } /// - /// Calls the one offered tool once per turn, rather than once per call: it looks only at what + /// Calls the one offered tool once per turn, rather than once per conversation: it looks only at what /// came after the caller's latest message, so a tool call answered in an earlier turn does not /// stop this one from calling the tool again. /// @@ -106,7 +106,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( ChatRole.Assistant, [ new FunctionCallContent( - $"call_{_nextCallId++}", + $"conversation_{_nextCallId++}", tool.Name, new Dictionary(StringComparer.Ordinal) { diff --git a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs index c025158c..718276d8 100644 --- a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs @@ -18,7 +18,7 @@ namespace AgentCore.Application.Tests.Tools; /// /// /// The document writes binds: CreateCase and no parameters:. Everything the model -/// needs to fill the call comes off the method, so the two can never drift apart. +/// needs to fill the conversation comes off the method, so the two can never drift apart. /// public sealed class TypedBindingToolTests { @@ -107,7 +107,7 @@ public async Task TheNameAndDescription_StillComeFromTheDocument() Assert.Equal("Open a service case for a human agent.", tool.Description); } - /// The model never sees the scope parameter: it names the running call, not an argument the model fills. + /// The model never sees the scope parameter: it names the running conversation, not an argument the model fills. [Fact] public async Task AToolCallScopeParameter_IsLeftOutOfTheSchema() { @@ -116,7 +116,7 @@ public async Task AToolCallScopeParameter_IsLeftOutOfTheSchema() var properties = tool.JsonSchema.GetProperty("properties"); Assert.True(properties.TryGetProperty("reason", out _)); Assert.False(properties.TryGetProperty("scope", out _)); - Assert.DoesNotContain("CallId", tool.JsonSchema.GetRawText(), StringComparison.Ordinal); + Assert.DoesNotContain("ConversationId", tool.JsonSchema.GetRawText(), StringComparison.Ordinal); } // --------------------------------------------------------------------------------------------- @@ -189,7 +189,7 @@ await Assert.ThrowsAnyAsync(async () => } /// - /// A binding declares a parameter to read the call it runs in, but a + /// A binding declares a parameter to read the conversation it runs in, but a /// call to the tool with no turn open on this flow has no call to report. /// [Fact] @@ -223,7 +223,7 @@ public async Task AToolCallScopeParameterWithTheTurnFiled_BindsWithoutAFlow() ["reason"] = "the caller wants a person", [TurnInvocation.ArgumentsKey] = new TurnInvocation { - CallId = "call-9", + ConversationId = "conversation-9", TurnIndex = 4, Stage = "handling", Workspace = "ws", @@ -232,7 +232,7 @@ public async Task AToolCallScopeParameterWithTheTurnFiled_BindsWithoutAFlow() TestContext.Current.CancellationToken); Assert.Equal("the caller wants a person", $"{result}"); - Assert.Equal("call-9", captured!.CallId); + Assert.Equal("conversation-9", captured!.ConversationId); Assert.Equal(4, captured.TurnIndex); Assert.Equal("handling", captured.Stage); Assert.Equal("ws", captured.Workspace); diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs index 3eac06d5..a24807a9 100644 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs @@ -1,6 +1,6 @@ using System.Text.Json; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Transcript; using AgentCore.TestSupport; @@ -10,11 +10,11 @@ namespace AgentCore.Application.Tests.Transcript; -/// What both halves of the provider's test suite share: the call id, the session state -/// key, and the plumbing to open a call and read its history back. +/// What both halves of the provider's test suite share: the conversation id, the session state +/// key, and the plumbing to open a conversation and read its history back. internal static class AgentCoreChatHistoryProviderTestSupport { - internal const string CallId = "call-1"; + internal const string ConversationId = "conversation-1"; /// /// The provider's MAF-default state key: its own type name. The transcript no longer files @@ -24,21 +24,21 @@ internal static class AgentCoreChatHistoryProviderTestSupport internal const string StateKey = "AgentCoreChatHistoryProvider"; /// - /// Opens one call on a fresh session, the way CallSession does at call start: the row is - /// made before any turn can append against it, exactly as CallSession.OpenSessionAsync + /// Opens one conversation on a fresh session, the way ConversationSession does at conversation start: the row is + /// made before any turn can append against it, exactly as ConversationSession.OpenSessionAsync /// makes it before it ever reaches this provider. /// - internal static async Task<(AgentCoreChatHistoryProvider Provider, RecordingCallStore Store, StubSession Session)> NewCall() + internal static async Task<(AgentCoreChatHistoryProvider Provider, RecordingConversationStore Store, StubSession Session)> NewConversation() { - var store = new RecordingCallStore(); - await store.CreateAsync(CallId, TestContext.Current.CancellationToken); + var store = new RecordingConversationStore(); + await store.CreateAsync(ConversationId, TestContext.Current.CancellationToken); var provider = new AgentCoreChatHistoryProvider(store); var session = new StubSession(); - provider.BeginCall(session, CallId, []); + provider.BeginConversation(session, ConversationId, []); return (provider, store, session); } - /// Writes one turn the way CallSession does: name the turn, then append it. + /// Writes one turn the way ConversationSession does: name the turn, then append it. internal static void AppendTurn( AgentCoreChatHistoryProvider provider, AgentSession session, @@ -68,7 +68,7 @@ internal static async Task> ProvideAsync( /// Holds one append open, so a barge-in can arrive while a turn is still writing. It keeps the /// real store's ordering rule: a rewrite of a row that is not there yet changes nothing. /// -internal sealed class BlockingCallStore() : DelegatingCallStore(new InMemoryCallStore()) +internal sealed class BlockingConversationStore() : DelegatingConversationStore(new InMemoryConversationStore()) { private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -80,10 +80,10 @@ internal sealed class BlockingCallStore() : DelegatingCallStore(new InMemoryCall public void Release() => _release.TrySetResult(); - public override async ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, + public override async ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, CancellationToken cancellationToken = default) { if (_block) @@ -93,12 +93,12 @@ public override async ValueTask> AppendAsync( await _release.Task.WaitAsync(cancellationToken); } - return await Inner.AppendAsync(callId, messages, state, cancellationToken); + return await Inner.AppendAsync(conversationId, messages, state, cancellationToken); } public override ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) - => Inner.RewriteAsync(callId, messageId, content, cancellationToken); + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => Inner.RewriteAsync(conversationId, messageId, content, cancellationToken); } internal sealed class StubSession : AgentSession; diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs index 4c823c4d..0050db59 100644 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs @@ -8,7 +8,7 @@ namespace AgentCore.Application.Tests.Transcript; /// -/// Pins what the provider adds to : the lock, the write chain, and the +/// Pins what the provider adds to : the lock, the write chain, and the /// rule that a store failure never reaches the turn. /// public sealed class AgentCoreChatHistoryProviderTests @@ -17,7 +17,7 @@ public sealed class AgentCoreChatHistoryProviderTests public async Task ProvideChatHistory_AfterAppend_ReturnsMessagesInOrder() { // Arrange - var (provider, _, session) = await NewCall(); + var (provider, _, session) = await NewConversation(); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday"); @@ -34,7 +34,7 @@ public async Task ProvideChatHistory_AfterAppend_ReturnsMessagesInOrder() public async Task AppendTurn_MultipleTurns_OrdinalsAreDenseAndUnique() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); // Act @@ -44,14 +44,14 @@ public async Task AppendTurn_MultipleTurns_OrdinalsAreDenseAndUnique() await provider.DrainAsync(session); Assert.Equal([0, 1, 2, 3], store.Rows.Select(row => row.Ordinal)); Assert.Equal([0, 0, 1, 1], store.Rows.Select(row => row.TurnIndex)); - Assert.All(store.Rows, row => Assert.Equal(CallId, row.CallId)); + Assert.All(store.Rows, row => Assert.Equal(ConversationId, row.ConversationId)); } [Fact] public async Task AppendTurn_RefusedTurn_IsStored() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); // Act AppendTurn(provider, session, turnIndex: 0, "something flagged", "I can't help with that."); @@ -67,7 +67,7 @@ public async Task AppendTurn_RefusedTurn_IsStored() public async Task AppendTurn_FailedTurn_IsStored() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); // Act AppendTurn(provider, session, turnIndex: 0, "check my order", "Sorry, I had trouble with that."); @@ -82,14 +82,14 @@ public async Task AppendTurn_FailedTurn_IsStored() /// /// The framework offers to store a finished run, and this provider declines. Measured on /// Microsoft.Agents.AI 1.17.0, that hook stores the request verbatim — reminder and all — and is - /// never called at all for a run the caller cut short, which is every barge-in. CallSession + /// never called at all for a run the caller cut short, which is every barge-in. ConversationSession /// writes the turn it shaped instead. /// [Fact] public async Task StoreChatHistory_FinishedRun_StoresNothing() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); provider.BeginTurn(session, turnIndex: 0); // Act @@ -113,7 +113,7 @@ [new ChatMessage(ChatRole.Assistant, "it ships Friday")]), public async Task AppendTurn_ConcurrentAppends_LosesNoMessage() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); provider.BeginTurn(session, turnIndex: 0); var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var turns = Enumerable.Range(0, 20) @@ -145,11 +145,11 @@ public async Task AppendTurn_ConcurrentAppends_LosesNoMessage() public async Task ProvideChatHistory_TwoConcurrentSessions_DoNotMix() { // Arrange - var provider = new AgentCoreChatHistoryProvider(new RecordingCallStore()); + var provider = new AgentCoreChatHistoryProvider(new RecordingConversationStore()); var first = new StubSession(); var second = new StubSession(); - provider.BeginCall(first, "call-a", []); - provider.BeginCall(second, "call-b", []); + provider.BeginConversation(first, "conversation-a", []); + provider.BeginConversation(second, "conversation-b", []); AppendTurn(provider, first, turnIndex: 0, "a said", "a heard"); // Act @@ -180,7 +180,7 @@ public void StateKeys_IsTheSingleProviderTypeNameKey() public async Task AppendTurn_LeavesTheSessionStateBagEmpty() { // Arrange - var (provider, _, session) = await NewCall(); + var (provider, _, session) = await NewConversation(); // Act AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday"); @@ -191,18 +191,18 @@ public async Task AppendTurn_LeavesTheSessionStateBagEmpty() } /// - /// The provider is one object shared by every call, so two sessions must still reach two + /// The provider is one object shared by every conversation, so two sessions must still reach two /// transcripts. State held against the provider rather than the session would merge them. /// [Fact] public void AppendTurn_TwoSessions_EachHoldsItsOwnTranscript() { // Arrange - var provider = new AgentCoreChatHistoryProvider(new RecordingCallStore()); + var provider = new AgentCoreChatHistoryProvider(new RecordingConversationStore()); var first = new StubSession(); var second = new StubSession(); - provider.BeginCall(first, "call-a", []); - provider.BeginCall(second, "call-b", []); + provider.BeginConversation(first, "conversation-a", []); + provider.BeginConversation(second, "conversation-b", []); // Act AppendTurn(provider, first, turnIndex: 0, "a said", "a heard"); @@ -217,9 +217,9 @@ public void AppendTurn_TwoSessions_EachHoldsItsOwnTranscript() public async Task AppendTurn_BackingStoreThrows_DoesNotFailTheTurn() { // Arrange - var provider = new AgentCoreChatHistoryProvider(new ThrowingCallStore()); + var provider = new AgentCoreChatHistoryProvider(new ThrowingConversationStore()); var session = new StubSession(); - provider.BeginCall(session, CallId, []); + provider.BeginConversation(session, ConversationId, []); // Act AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); @@ -230,13 +230,13 @@ public async Task AppendTurn_BackingStoreThrows_DoesNotFailTheTurn() } [Fact] - public async Task BeginCall_BackingStoreThrows_TellsTheReporterWhichTurnWasLost() + public async Task BeginConversation_BackingStoreThrows_TellsTheReporterWhichTurnWasLost() { // Arrange - var provider = new AgentCoreChatHistoryProvider(new ThrowingCallStore()); + var provider = new AgentCoreChatHistoryProvider(new ThrowingConversationStore()); var session = new StubSession(); List dropped = []; - provider.BeginCall(session, CallId, [], (turnIndex, _) => dropped.Add(turnIndex)); + provider.BeginConversation(session, ConversationId, [], (turnIndex, _) => dropped.Add(turnIndex)); // Act AppendTurn(provider, session, turnIndex: 3, "hello", "hi there"); diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs index 99d84c78..7ba177ef 100644 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; @@ -16,7 +16,7 @@ public sealed class AgentCoreChatHistoryProviderTruncateTests public async Task TruncateLastReply_LastAssistantMessage_RewritesOnlyThatMessage() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday from the depot"); @@ -37,7 +37,7 @@ public async Task TruncateLastReply_LastAssistantMessage_RewritesOnlyThatMessage public async Task ProvideChatHistory_AfterTruncate_ReturnsHeardTextNotProducedText() { // Arrange - var (provider, _, session) = await NewCall(); + var (provider, _, session) = await NewConversation(); AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday from the depot"); // Act @@ -57,11 +57,11 @@ public async Task ProvideChatHistory_AfterTruncate_ReturnsHeardTextNotProducedTe public async Task TruncateLastReply_WhileTheAppendIsStillWriting_ReachesTheStoreAfterIt() { // Arrange - var store = new BlockingCallStore(); - await store.CreateAsync(CallId, TestContext.Current.CancellationToken); + var store = new BlockingConversationStore(); + await store.CreateAsync(ConversationId, TestContext.Current.CancellationToken); var provider = new AgentCoreChatHistoryProvider(store); var session = new StubSession(); - provider.BeginCall(session, CallId, []); + provider.BeginConversation(session, ConversationId, []); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); await provider.DrainAsync(session); store.BlockNextAppend(); @@ -77,19 +77,19 @@ public async Task TruncateLastReply_WhileTheAppendIsStillWriting_ReachesTheStore Assert.True(cut); Assert.Equal( ["hello", "hi there", "order 41?", "it ships"], - (await store.ReadAsync(CallId, TestContext.Current.CancellationToken)).Select(row => row.Content.Text)); + (await store.ReadAsync(ConversationId, TestContext.Current.CancellationToken)).Select(row => row.Content.Text)); } /// /// The held prompt of item 6a: the vendor is still speaking turn 0 when turn 1 begins, so the - /// reply the caller was hearing belongs to the turn before the one now open. CallSession decides + /// reply the caller was hearing belongs to the turn before the one now open. ConversationSession decides /// that a barge-in reaches it; the provider must not refuse because the turn moved on. /// [Fact] public async Task TruncateLastReply_AfterTheNextTurnOpened_CutsTheReplyTheCallerWasHearing() { // Arrange - var (provider, _, session) = await NewCall(); + var (provider, _, session) = await NewConversation(); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there caller"); provider.BeginTurn(session, turnIndex: 1); @@ -112,17 +112,17 @@ public async Task TruncateLastReply_AfterTheNextTurnOpened_CutsTheReplyTheCaller public async Task TruncateLastReply_TurnWithProseBesideAToolCall_DropsEveryWordButTheHeardOnes() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); provider.BeginTurn(session, turnIndex: 0); ChatMessage announced = new( ChatRole.Assistant, - [new TextContent("Let me check that for you"), new FunctionCallContent("call-1", "lookup")]); + [new TextContent("Let me check that for you"), new FunctionCallContent("conversation-1", "lookup")]); provider.AppendTurn( session, [ new ChatMessage(ChatRole.User, "how much?"), announced, - new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", "50")]), + new ChatMessage(ChatRole.Tool, [new FunctionResultContent("conversation-1", "50")]), new ChatMessage(ChatRole.Assistant, "the price is fifty"), ]); @@ -146,7 +146,7 @@ public async Task TruncateLastReply_TurnWithProseBesideAToolCall_DropsEveryWordB public async Task TruncateLastReply_BeforeAnyReplyExists_NoOps() { // Arrange - var (provider, store, session) = await NewCall(); + var (provider, store, session) = await NewConversation(); provider.BeginTurn(session, turnIndex: 0); // Act @@ -162,11 +162,11 @@ public async Task TruncateLastReply_BeforeAnyReplyExists_NoOps() public async Task InMemoryStore_AfterTurnAndBargeIn_HoldsTheHeardTextInOrder() { // Arrange - var store = new InMemoryCallStore(); - await store.CreateAsync(CallId, TestContext.Current.CancellationToken); + var store = new InMemoryConversationStore(); + await store.CreateAsync(ConversationId, TestContext.Current.CancellationToken); var provider = new AgentCoreChatHistoryProvider(store); var session = new StubSession(); - provider.BeginCall(session, CallId, []); + provider.BeginConversation(session, ConversationId, []); AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday from the depot"); // Act @@ -176,6 +176,6 @@ public async Task InMemoryStore_AfterTurnAndBargeIn_HoldsTheHeardTextInOrder() await provider.DrainAsync(session); Assert.Equal( ["order 41?", "it ships"], - (await store.ReadAsync(CallId, TestContext.Current.CancellationToken)).Select(row => row.Content.Text)); + (await store.ReadAsync(ConversationId, TestContext.Current.CancellationToken)).Select(row => row.Content.Text)); } } diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs deleted file mode 100644 index 82d07a77..00000000 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -using AgentCore.Application.Calls.Memory; -using AgentCore.Application.Ports; -using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Transcript; -using AgentCore.TestSupport; -using Microsoft.Extensions.AI; -using Xunit; -using static AgentCore.Application.Tests.Transcript.CallSessionResumeTestSupport; - -namespace AgentCore.Application.Tests.Transcript; - -/// -/// A call outlives the session that started it. -/// -public sealed class CallSessionResumeTests -{ - [Fact] - public async Task ASecondSessionOfOneCall_SendsTheFirstTurnToTheModel() - { - InMemoryCallStore store = new(); - var callId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); - - using ScriptedChatClient reply = new("Dana"); - using RequestCapturingChatClient capture = new(reply); - var resumed = CreateSession(OneAgentYaml, capture, store, callId); - - await resumed.RunTurnAsync("what is my name?", TestContext.Current.CancellationToken); - - Assert.NotEmpty(capture.Requests); - Assert.Contains( - capture.Requests[^1], - message => message.Text.Contains("my name is Dana", StringComparison.Ordinal)); - } - - [Fact] - public async Task ASecondSessionOfOneCall_KeepsEveryWordTheFirstOneWrote() - { - InMemoryCallStore store = new(); - var callId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); - - await SecondTurnAsync(store, callId, "what is my name?", "Dana"); - - var rows = await store.ReadAsync(callId, TestContext.Current.CancellationToken); - - // Two turns, each writing what the caller said and what it heard. A resumed session that - // restarted its ordinals would overwrite the first pair rather than follow them. - Assert.Equal(4, rows.Count); - Assert.Equal([0, 1, 2, 3], rows.Select(row => row.Ordinal)); - } - - [Fact] - public async Task ASecondSessionOfOneCall_CountsItsTurnAsTheNextOne() - { - InMemoryCallStore store = new(); - var callId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); - - await SecondTurnAsync(store, callId, "what is my name?", "Dana"); - - var rows = await store.ReadAsync(callId, TestContext.Current.CancellationToken); - - // The turn index is the join to the audit chain, so a second turn numbered 0 would claim the - // first turn's events as its own. - Assert.Equal([0, 0, 1, 1], rows.Select(row => row.TurnIndex)); - } - - [Fact] - public async Task ASessionOfACallWithNoWords_StartsAtTheBeginning() - { - InMemoryCallStore store = new(); - await store.CreateAsync("empty-call", TestContext.Current.CancellationToken); - - await SecondTurnAsync(store, "empty-call", "hello", "hi there"); - - var rows = await store.ReadAsync("empty-call", TestContext.Current.CancellationToken); - - Assert.Equal([0, 1], rows.Select(row => row.Ordinal)); - Assert.Equal([0, 0], rows.Select(row => row.TurnIndex)); - } - - [Fact] - public async Task ASecondSessionOfOneCall_WhoseWordsCannotBeRead_RefusesTheTurn() - { - InMemoryCallStore backing = new(); - UnreadableCallStore store = new(backing); - var callId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); - - using ScriptedChatClient reply = new("Dana"); - var resumed = CreateSession(OneAgentYaml, reply, store, callId); - - // A read that answered empty would run the turn with no memory of the caller. Meeting a - // stranger is worse than meeting an error, so the turn does not run at all. - await Assert.ThrowsAsync( - () => resumed.RunTurnAsync("what is my name?", TestContext.Current.CancellationToken)); - } - - /// A store 1 that takes words and will not give them back. - private sealed class UnreadableCallStore(ICallStore inner) : DelegatingCallStore(inner) - { - public override ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) - => throw new InvalidOperationException("store 1 will not answer a read."); - } -} diff --git a/tests/AgentCore.Application.Tests/Transcript/CompiledHistoryProviderTests.cs b/tests/AgentCore.Application.Tests/Transcript/CompiledHistoryProviderTests.cs index d7f3739c..eb0cdb25 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CompiledHistoryProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CompiledHistoryProviderTests.cs @@ -22,12 +22,12 @@ namespace AgentCore.Application.Tests.Transcript; /// which is what lets ThrowOnChatHistoryProviderConflict stay at the framework default. /// /// -/// Rows 3 and 4 must stay unbound. A node is handed the call in the request messages the turn loop -/// renders, and it runs on a session the workflow made rather than the call's, so store 1 on a node +/// Rows 3 and 4 must stay unbound. A node is handed the conversation in the request messages the turn loop +/// renders, and it runs on a session the workflow made rather than the conversation's, so store 1 on a node /// is a second history source keyed on a session it does not know. /// /// -/// Every test here runs offline: no network call and no API key. +/// Every test here runs offline: no network conversation and no API key. /// /// public sealed class CompiledHistoryProviderTests @@ -152,7 +152,7 @@ public async Task AModelThatKeepsTheHistoryItself_ConflictsWithStoreOne() { // A response that carries a conversation id is how a service says it keeps the history itself. // That and store 1 are two answers to one question, and the framework refuses both at once. - // Switching this check off to buy something else — a telemetry attribute, say — leaves a call + // Switching this check off to buy something else — a telemetry attribute, say — leaves a conversation // whose model silently sees one message and no history. ServerSideHistoryChatClient client = new("hello"); var compiled = Compile(SingleAgentYaml, client); @@ -171,7 +171,7 @@ public async Task AModelThatKeepsTheHistoryItself_ConflictsWithStoreOne() [Theory] [InlineData(PatternGraphYaml)] [InlineData(ExplicitGraphYaml)] - public async Task AGraphRow_ReplaysTheCallToItsNodesExactlyOnce(string yaml) + public async Task AGraphRow_ReplaysTheConversationToItsNodesExactlyOnce(string yaml) { RecordingChatClient researcher = new("looking into it"); RecordingChatClient responder = new("it ships Friday"); @@ -180,7 +180,7 @@ public async Task AGraphRow_ReplaysTheCallToItsNodesExactlyOnce(string yaml) _ = await session.RunTurnAsync(FirstUtterance, TestContext.Current.CancellationToken); _ = await session.RunTurnAsync(SecondUtterance, TestContext.Current.CancellationToken); - // One system message carries the whole call to a graph row, and it is the only way the call + // One system message carries the whole call to a graph row, and it is the only way the conversation // reaches a node. Two copies of the caller's words in one request is what a second history // source on that node would look like. Assert.Equal(1, Mentions(researcher.Requests[1], FirstUtterance)); @@ -230,8 +230,8 @@ private static CompiledAgent Compile(string yaml, IChatClient client) ConfigurationLoader.LoadYaml(yaml), new AgentCompilationContext(new FakeChatClientFactory(client)))["main"]; - /// Compiles one document over two named models and opens a call on it. - private static CallSession CreateSession(string yaml, IChatClient first, IChatClient second) + /// Compiles one document over two named models and opens a conversation on it. + private static ConversationSession CreateSession(string yaml, IChatClient first, IChatClient second) { RoutingChatClientFactory chatClients = new(first); chatClients.Route("researcher", first); @@ -242,7 +242,7 @@ private static CallSession CreateSession(string yaml, IChatClient first, IChatCl var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(yaml), new AgentCompilationContext(chatClients))["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null).Create(); @@ -349,7 +349,7 @@ private void Record(IEnumerable messages) /// private sealed class DelegatingChatClient : IChatClient { - private const string CallId = "call_1"; + private const string ConversationId = "conversation_1"; /// The one argument AsAIFunction() generates for an agent that declares no schema. private static readonly Dictionary Arguments = @@ -377,7 +377,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( { yield return new ChatResponseUpdate( ChatRole.Assistant, - [new FunctionCallContent(CallId, tool.Name, Arguments)]) + [new FunctionCallContent(ConversationId, tool.Name, Arguments)]) { ResponseId = responseId, MessageId = responseId, diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionCallRowTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionConversationRowTests.cs similarity index 65% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionCallRowTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionConversationRowTests.cs index decd525c..e5ca914e 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionCallRowTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionConversationRowTests.cs @@ -1,5 +1,5 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -13,8 +13,8 @@ namespace AgentCore.Application.Tests.Transcript; -/// A call's row exists before its first word does. -public sealed class CallSessionCallRowTests +/// A conversation's row exists before its first word does. +public sealed class ConversationSessionConversationRowTests { private const string OneAgentYaml = """ apiVersion: agentcore/v1 @@ -27,18 +27,18 @@ public sealed class CallSessionCallRowTests """; /// A store 0 that is down: it takes no row, so no word may follow. - private sealed class RefusingCreate(ICallStore inner) : DelegatingCallStore(inner) + private sealed class RefusingCreate(IConversationStore inner) : DelegatingConversationStore(inner) { - public override ValueTask CreateAsync( - string callId, CancellationToken cancellationToken = default) + public override ValueTask CreateAsync( + string conversationId, CancellationToken cancellationToken = default) => throw new InvalidOperationException("store 0 is down."); } [Fact] - public async Task ATurn_CreatesTheCallRow_BeforeItWritesAnyWord() + public async Task ATurn_CreatesTheConversationRow_BeforeItWritesAnyWord() { // Arrange - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); using ScriptedChatClient reply = new("hello"); var session = CreateSession(OneAgentYaml, reply, store); @@ -47,15 +47,15 @@ public async Task ATurn_CreatesTheCallRow_BeforeItWritesAnyWord() // Assert await session.FlushTranscriptAsync(); - Assert.NotNull(await store.GetAsync(session.CallId, TestContext.Current.CancellationToken)); - Assert.NotEmpty(await store.ReadAsync(session.CallId, TestContext.Current.CancellationToken)); + Assert.NotNull(await store.GetAsync(session.ConversationId, TestContext.Current.CancellationToken)); + Assert.NotEmpty(await store.ReadAsync(session.ConversationId, TestContext.Current.CancellationToken)); } [Fact] public async Task ATurn_WhenStoreZeroRefusesTheRow_FailsAndWritesNoWords() { // Arrange - InMemoryCallStore inner = new(); + InMemoryConversationStore inner = new(); RefusingCreate store = new(inner); using ScriptedChatClient reply = new("hello"); var session = CreateSession(OneAgentYaml, reply, store); @@ -66,10 +66,10 @@ public async Task ATurn_WhenStoreZeroRefusesTheRow_FailsAndWritesNoWords() // Assert Assert.Equal("store 0 is down.", fault.Message); - Assert.Empty(await inner.ReadAsync(session.CallId, TestContext.Current.CancellationToken)); + Assert.Empty(await inner.ReadAsync(session.ConversationId, TestContext.Current.CancellationToken)); } - private static CallSession CreateSession(string yaml, IChatClient reply, ICallStore store) + private static ConversationSession CreateSession(string yaml, IChatClient reply, IConversationStore store) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new FakeChatClientFactory(reply); @@ -77,11 +77,11 @@ private static CallSession CreateSession(string yaml, IChatClient reply, ICallSt document, new AgentCompilationContext(chatClients) { - CallStore = store, + ConversationStore = store, Tools = TestToolRegistry.From(document, null, TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null); diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionGraphTranscriptTests.cs similarity index 89% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionGraphTranscriptTests.cs index fa2aed0c..b6f82e5b 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionGraphTranscriptTests.cs @@ -17,9 +17,9 @@ namespace AgentCore.Application.Tests.Transcript; /// /// /// A workflow takes no chat history provider and no session of ours, so the turn loop carries the -/// call itself. Every test here runs offline, with no network call and no API key. +/// conversation itself. Every test here runs offline, with no network conversation and no API key. /// -public sealed class CallSessionGraphTranscriptTests +public sealed class ConversationSessionGraphTranscriptTests { /// What the first node says while it works. The caller never hears it. private const string Thinking = "Let me check the order system."; @@ -49,7 +49,7 @@ public sealed class CallSessionGraphTranscriptTests public async Task Run_GraphRow_StoresOnlyCallerFacingMessages() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); RecordingNodeClient researcher = new(Thinking); RecordingNodeClient responder = new(Spoken); var session = CreateSession(researcher, responder, store); @@ -61,7 +61,7 @@ public async Task Run_GraphRow_StoresOnlyCallerFacingMessages() await session.FlushTranscriptAsync(); Assert.Equal( ["where is my order", Spoken], - store.Live(session.CallId).Select(row => row.Content.Text)); + store.Live(session.ConversationId).Select(row => row.Content.Text)); } /// @@ -74,13 +74,13 @@ public async Task Run_GraphRow_SecondTurn_ModelSeesNoIntermediateNodeReply() // Arrange RecordingNodeClient researcher = new(Thinking); RecordingNodeClient responder = new(Spoken); - var session = CreateSession(researcher, responder, new RecordingCallStore()); + var session = CreateSession(researcher, responder, new RecordingConversationStore()); _ = await session.RunTurnAsync("where is my order", TestContext.Current.CancellationToken); // Act _ = await session.RunTurnAsync("and the second one?", TestContext.Current.CancellationToken); - // Assert. The demotion of an assistant message to user is why the call rides one system + // Assert. The demotion of an assistant message to user is why the conversation rides one system // message: the node reads who said what off the line, not off the role. var second = researcher.Requests[1]; Assert.Contains( @@ -102,7 +102,7 @@ public async Task Run_GraphRow_SecondTurn_ModelSeesNoIntermediateNodeReply() public async Task Run_GraphRow_ReplyIsFinalNodeOnly() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); RecordingNodeClient researcher = new(Thinking); RecordingNodeClient responder = new(Spoken); var session = CreateSession(researcher, responder, store); @@ -123,7 +123,7 @@ public async Task Run_GraphRow_ReplyIsFinalNodeOnly() public async Task Interrupt_MidGraphReply_StoresTheHeardWordsOnly() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); RecordingNodeClient researcher = new(Thinking); using ScriptedChatClient responder = new("Order 41 ", "ships Friday.") { GateAfterFirstFragment = true }; var session = CreateSession(researcher, responder, store); @@ -140,7 +140,7 @@ public async Task Interrupt_MidGraphReply_StoresTheHeardWordsOnly() await session.FlushTranscriptAsync(); Assert.Equal( ["where is my order", "Order 41"], - store.Live(session.CallId).Select(row => row.Content.Text)); + store.Live(session.ConversationId).Select(row => row.Content.Text)); } /// @@ -151,7 +151,7 @@ public async Task Interrupt_MidGraphReply_StoresTheHeardWordsOnly() public async Task Interrupt_BeforeAnyGraphWordLanded_StoresTheCallerUtteranceAlone() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); RecordingNodeClient researcher = new(Thinking); using ScriptedChatClient responder = new("Order 41 ", "ships Friday.") { GateAfterFirstFragment = true }; var session = CreateSession(researcher, responder, store); @@ -166,11 +166,11 @@ public async Task Interrupt_BeforeAnyGraphWordLanded_StoresTheCallerUtteranceAlo responder.OpenGate(); await turn; await session.FlushTranscriptAsync(); - Assert.Equal(["where is my order"], store.Live(session.CallId).Select(row => row.Content.Text)); + Assert.Equal(["where is my order"], store.Live(session.ConversationId).Select(row => row.Content.Text)); } /// Starts a streaming turn on a background task and says when the caller can hear it. - /// The call to run the turn on. + /// The conversation to run the turn on. /// What the caller said. /// The running turn, and a task that completes at its first spoken update. /// @@ -178,7 +178,7 @@ public async Task Interrupt_BeforeAnyGraphWordLanded_StoresTheCallerUtteranceAlo /// before the first update takes the amendment path instead and records nothing against this /// turn. Waiting for that update is what makes the cut land in the reply. /// - private static (Task Turn, Task Spoke) StartGatedTurn(CallSession session, string userInput) + private static (Task Turn, Task Spoke) StartGatedTurn(ConversationSession session, string userInput) { TaskCompletionSource spoke = new(TaskCreationOptions.RunContinuationsAsynchronously); var turn = Task.Run( @@ -196,8 +196,8 @@ private static (Task Turn, Task Spoke) StartGatedTurn(CallSession session, strin return (turn, spoke.Task.WaitAsync(TimeSpan.FromSeconds(10))); } - private static CallSession CreateSession( - IChatClient researcher, IChatClient responder, ICallStore store) + private static ConversationSession CreateSession( + IChatClient researcher, IChatClient responder, IConversationStore store) { var document = ConfigurationLoader.LoadYaml(GraphYaml); RoutingChatClientFactory chatClients = new(researcher); @@ -205,9 +205,9 @@ private static CallSession CreateSession( var compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(chatClients) { CallStore = store })["main"]; + new AgentCompilationContext(chatClients) { ConversationStore = store })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null); diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionOutsideAppendTests.cs similarity index 79% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionOutsideAppendTests.cs index 6968cd27..17cfc847 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionOutsideAppendTests.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Fakes; @@ -6,7 +6,7 @@ using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; -using static AgentCore.Application.Tests.Transcript.CallSessionResumeTestSupport; +using static AgentCore.Application.Tests.Transcript.ConversationSessionResumeTestSupport; namespace AgentCore.Application.Tests.Transcript; @@ -14,14 +14,14 @@ namespace AgentCore.Application.Tests.Transcript; /// A turn sees a row a host appended from outside any turn — after a human handoff ends, say, /// possibly from another machine — and its own new rows still continue from store 0's counter. /// -#pragma warning disable CA1859 // store is typed as ICallStore throughout: AppendMessageAsync(callId, message, ct) +#pragma warning disable CA1859 // store is typed as IConversationStore throughout: AppendMessageAsync(conversationId, message, ct) // is a default interface method, and only resolves through the interface type. -public sealed class CallSessionOutsideAppendTests +public sealed class ConversationSessionOutsideAppendTests { [Fact] public async Task SecondTurn_SeesTheOutsideMessagesBetweenTheTurns_AndKeepsTheirProperties() { - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); var (_, client) = await RunTwoTurnsWithAnOutsideHandoffAsync(store); var secondRequest = client.Requests[1]; @@ -39,10 +39,10 @@ public async Task SecondTurn_SeesTheOutsideMessagesBetweenTheTurns_AndKeepsTheir [Fact] public async Task AfterTheSecondTurn_TheStoresOrdinalsAreDenseAndUnique() { - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); var (session, _) = await RunTwoTurnsWithAnOutsideHandoffAsync(store); - var rows = await store.ReadAsync(session.CallId, TestContext.Current.CancellationToken); + var rows = await store.ReadAsync(session.ConversationId, TestContext.Current.CancellationToken); var ordinals = rows.Select(row => row.Ordinal).ToArray(); for (var index = 1; index < ordinals.Length; index++) @@ -51,16 +51,16 @@ public async Task AfterTheSecondTurn_TheStoresOrdinalsAreDenseAndUnique() } // No truncate ran in this scenario, so the counter and the row count agree exactly. - var record = await store.GetAsync(session.CallId, TestContext.Current.CancellationToken); + var record = await store.GetAsync(session.ConversationId, TestContext.Current.CancellationToken); Assert.Equal(rows.Count, record?.NextOrdinal); } [Fact] public async Task ASecondSessionOverTheSameStore_SeesTheOutsideMessageAndContinuesTheCounter() { - // Two CallSession instances of one call, standing in for two machines: nothing but the store + // Two ConversationSession instances of one conversation, standing in for two machines: nothing but the store // passes between them. - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); SequencedChatClient clientA = new("hi Dana"); var sessionA = CreateSession(OneAgentYaml, clientA, store); @@ -68,7 +68,7 @@ public async Task ASecondSessionOverTheSameStore_SeesTheOutsideMessageAndContinu await sessionA.FlushTranscriptAsync(); await store.AppendMessageAsync( - sessionA.CallId, + sessionA.ConversationId, new ChatMessage(ChatRole.Assistant, "Dana joined") { AdditionalProperties = new() { ["speaker"] = "human-agent" }, @@ -76,7 +76,7 @@ await store.AppendMessageAsync( TestContext.Current.CancellationToken); SequencedChatClient clientB = new("welcome back"); - var sessionB = CreateSession(OneAgentYaml, clientB, store, sessionA.CallId); + var sessionB = CreateSession(OneAgentYaml, clientB, store, sessionA.ConversationId); await sessionB.RunTurnAsync("still there?", TestContext.Current.CancellationToken); await sessionB.FlushTranscriptAsync(); @@ -85,28 +85,28 @@ await store.AppendMessageAsync( ["my name is Dana", "hi Dana", "Dana joined", "still there?"], clientB.Requests[0].Select(message => message.Text)); - var rows = await store.ReadAsync(sessionA.CallId, TestContext.Current.CancellationToken); + var rows = await store.ReadAsync(sessionA.ConversationId, TestContext.Current.CancellationToken); Assert.Equal([0, 1, 2, 3, 4], rows.Select(row => row.Ordinal)); - var record = await store.GetAsync(sessionA.CallId, TestContext.Current.CancellationToken); + var record = await store.GetAsync(sessionA.ConversationId, TestContext.Current.CancellationToken); Assert.Equal(rows.Count, record?.NextOrdinal); } [Fact] public async Task AnEditAfterAnOutsideAppend_CutsTheOutsideRowWithTheReplyItReplaces() { - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); SequencedChatClient client = new("first reply", "second reply"); var session = CreateSession(OneAgentYaml, client, store); await session.RunTurnAtOriginAsync( "first question", - new CallTurnOrigin("m1", null) { NamesParent = true }, + new ConversationTurnOrigin("m1", null) { NamesParent = true }, TestContext.Current.CancellationToken); await session.FlushTranscriptAsync(); await store.AppendMessageAsync( - session.CallId, + session.ConversationId, new ChatMessage(ChatRole.Assistant, "Dana joined") { AdditionalProperties = new() { ["speaker"] = "human-agent" }, @@ -117,11 +117,11 @@ await store.AppendMessageAsync( // order to cut it along with the reply it replaces. await session.RunTurnAtOriginAsync( "first question, rewritten", - new CallTurnOrigin("m2", "m1") { NamesParent = true }, + new ConversationTurnOrigin("m2", "m1") { NamesParent = true }, TestContext.Current.CancellationToken); await session.FlushTranscriptAsync(); - var rows = await store.ReadAsync(session.CallId, TestContext.Current.CancellationToken); + var rows = await store.ReadAsync(session.ConversationId, TestContext.Current.CancellationToken); Assert.Equal(3, rows.Count); Assert.Equal("m1", rows[0].MessageId); @@ -134,14 +134,14 @@ await session.RunTurnAtOriginAsync( [Fact] public async Task AfterOneTurn_TheStoredBlobCarriesTheTurnIndexAndTheCounterLivesOnTheRecord() { - ICallStore store = new InMemoryCallStore(); + IConversationStore store = new InMemoryConversationStore(); SequencedChatClient client = new("hi there"); var session = CreateSession(OneAgentYaml, client, store); await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); await session.FlushTranscriptAsync(); - var record = await store.GetAsync(session.CallId, TestContext.Current.CancellationToken); + var record = await store.GetAsync(session.ConversationId, TestContext.Current.CancellationToken); // One turn writes two rows (what the caller said, what it heard) and leaves the next turn at // index 1 — the mark the blob carries now that the ordinal has its own column on the record. @@ -152,7 +152,7 @@ public async Task AfterOneTurn_TheStoredBlobCarriesTheTurnIndexAndTheCounterLive [Fact] public async Task SecondTurn_WithNoOutsideAppend_DoesNotReadTheWordsBack() { - RecordingCallStore store = new(); + RecordingConversationStore store = new(); SequencedChatClient client = new("hi Dana", "welcome back"); var session = CreateSession(OneAgentYaml, client, store); @@ -172,14 +172,14 @@ public async Task SecondTurn_WithNoOutsideAppend_DoesNotReadTheWordsBack() [Fact] public async Task SecondTurn_AfterAnOutsideAppend_ReadsTheWordsBackOnce() { - RecordingCallStore store = new(); + RecordingConversationStore store = new(); await RunTwoTurnsWithAnOutsideHandoffAsync(store); Assert.Equal(1, store.Reads); } - private static async Task<(CallSession Session, SequencedChatClient Client)> RunTwoTurnsWithAnOutsideHandoffAsync( - ICallStore store) + private static async Task<(ConversationSession Session, SequencedChatClient Client)> RunTwoTurnsWithAnOutsideHandoffAsync( + IConversationStore store) { SequencedChatClient client = new("hi Dana", "welcome back"); var session = CreateSession(OneAgentYaml, client, store); @@ -188,14 +188,14 @@ public async Task SecondTurn_AfterAnOutsideAppend_ReadsTheWordsBackOnce() await session.FlushTranscriptAsync(); await store.AppendMessageAsync( - session.CallId, + session.ConversationId, new ChatMessage(ChatRole.Assistant, "Dana joined") { AdditionalProperties = new() { ["speaker"] = "human-agent" }, }, TestContext.Current.CancellationToken); await store.AppendMessageAsync( - session.CallId, + session.ConversationId, new ChatMessage(ChatRole.User, "human phase"), TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTestSupport.cs similarity index 77% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTestSupport.cs index 1489bd5e..7a0aadd4 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTestSupport.cs @@ -11,8 +11,8 @@ namespace AgentCore.Application.Tests.Transcript; -/// The documents and session-building helpers a call's resume tests share. -internal static class CallSessionResumeTestSupport +/// The documents and session-building helpers a conversation's resume tests share. +internal static class ConversationSessionResumeTestSupport { internal const string OneAgentYaml = """ apiVersion: agentcore/v1 @@ -75,7 +75,7 @@ internal static class CallSessionResumeTestSupport """; internal static async Task FirstTurnAsync( - ICallStore store, string said, string heard) + IConversationStore store, string said, string heard) { using ScriptedChatClient reply = new(heard); var session = CreateSession(OneAgentYaml, reply, store); @@ -83,25 +83,25 @@ internal static async Task FirstTurnAsync( await session.RunTurnAsync(said, TestContext.Current.CancellationToken); await session.FlushTranscriptAsync(); - return session.CallId; + return session.ConversationId; } internal static async Task SecondTurnAsync( - ICallStore store, string callId, string said, string heard) + IConversationStore store, string conversationId, string said, string heard) { using ScriptedChatClient reply = new(heard); - var session = CreateSession(OneAgentYaml, reply, store, callId); + var session = CreateSession(OneAgentYaml, reply, store, conversationId); await session.RunTurnAsync(said, TestContext.Current.CancellationToken); await session.FlushTranscriptAsync(); } - internal static CallSession CreateSession( + internal static ConversationSession CreateSession( string yaml, IChatClient reply, - ICallStore store, - string? callId = null, - ICallObserver? observer = null) + IConversationStore store, + string? conversationId = null, + IConversationObserver? observer = null) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new FakeChatClientFactory(reply); @@ -109,28 +109,28 @@ internal static CallSession CreateSession( document, new AgentCompilationContext(chatClients) { - CallStore = store, + ConversationStore = store, Tools = TestToolRegistry.From(document, null, TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null, observers: observer is null ? null : [observer]); - return factory.Create(callId); + return factory.Create(conversationId); } } - /// Keeps every fact of the call, in the order the turn loop raised them. - internal sealed class RecordingObserver : ICallObserver + /// Keeps every fact of the conversation, in the order the turn loop raised them. + internal sealed class RecordingObserver : IConversationObserver { private readonly Lock _gate = new(); - private readonly List _events = []; + private readonly List _events = []; - /// Gets what the call raised, oldest first. - public IReadOnlyList Events + /// Gets what the conversation raised, oldest first. + public IReadOnlyList Events { get { @@ -141,11 +141,11 @@ public IReadOnlyList Events } } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { lock (_gate) { - _events.Add(callEvent); + _events.Add(conversationEvent); } return ValueTask.CompletedTask; diff --git a/tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTests.cs new file mode 100644 index 00000000..5638daab --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionResumeTests.cs @@ -0,0 +1,103 @@ +using AgentCore.Application.Conversation.Memory; +using AgentCore.Application.Ports; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Transcript; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Xunit; +using static AgentCore.Application.Tests.Transcript.ConversationSessionResumeTestSupport; + +namespace AgentCore.Application.Tests.Transcript; + +/// +/// A conversation outlives the session that started it. +/// +public sealed class ConversationSessionResumeTests +{ + [Fact] + public async Task ASecondSessionOfOneConversation_SendsTheFirstTurnToTheModel() + { + InMemoryConversationStore store = new(); + var conversationId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); + + using ScriptedChatClient reply = new("Dana"); + using RequestCapturingChatClient capture = new(reply); + var resumed = CreateSession(OneAgentYaml, capture, store, conversationId); + + await resumed.RunTurnAsync("what is my name?", TestContext.Current.CancellationToken); + + Assert.NotEmpty(capture.Requests); + Assert.Contains( + capture.Requests[^1], + message => message.Text.Contains("my name is Dana", StringComparison.Ordinal)); + } + + [Fact] + public async Task ASecondSessionOfOneConversation_KeepsEveryWordTheFirstOneWrote() + { + InMemoryConversationStore store = new(); + var conversationId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); + + await SecondTurnAsync(store, conversationId, "what is my name?", "Dana"); + + var rows = await store.ReadAsync(conversationId, TestContext.Current.CancellationToken); + + // Two turns, each writing what the caller said and what it heard. A resumed session that + // restarted its ordinals would overwrite the first pair rather than follow them. + Assert.Equal(4, rows.Count); + Assert.Equal([0, 1, 2, 3], rows.Select(row => row.Ordinal)); + } + + [Fact] + public async Task ASecondSessionOfOneConversation_CountsItsTurnAsTheNextOne() + { + InMemoryConversationStore store = new(); + var conversationId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); + + await SecondTurnAsync(store, conversationId, "what is my name?", "Dana"); + + var rows = await store.ReadAsync(conversationId, TestContext.Current.CancellationToken); + + // The turn index is the join to the audit chain, so a second turn numbered 0 would claim the + // first turn's events as its own. + Assert.Equal([0, 0, 1, 1], rows.Select(row => row.TurnIndex)); + } + + [Fact] + public async Task ASessionOfAConversationWithNoWords_StartsAtTheBeginning() + { + InMemoryConversationStore store = new(); + await store.CreateAsync("empty-conversation", TestContext.Current.CancellationToken); + + await SecondTurnAsync(store, "empty-conversation", "hello", "hi there"); + + var rows = await store.ReadAsync("empty-conversation", TestContext.Current.CancellationToken); + + Assert.Equal([0, 1], rows.Select(row => row.Ordinal)); + Assert.Equal([0, 0], rows.Select(row => row.TurnIndex)); + } + + [Fact] + public async Task ASecondSessionOfOneConversation_WhoseWordsCannotBeRead_RefusesTheTurn() + { + InMemoryConversationStore backing = new(); + UnreadableConversationStore store = new(backing); + var conversationId = await FirstTurnAsync(store, "my name is Dana", "Hello Dana"); + + using ScriptedChatClient reply = new("Dana"); + var resumed = CreateSession(OneAgentYaml, reply, store, conversationId); + + // A read that answered empty would run the turn with no memory of the caller. Meeting a + // stranger is worse than meeting an error, so the turn does not run at all. + await Assert.ThrowsAsync( + () => resumed.RunTurnAsync("what is my name?", TestContext.Current.CancellationToken)); + } + + /// A store 1 that takes words and will not give them back. + private sealed class UnreadableConversationStore(IConversationStore inner) : DelegatingConversationStore(inner) + { + public override ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) + => throw new InvalidOperationException("store 1 will not answer a read."); + } +} diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionStateRestoreTests.cs similarity index 69% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionStateRestoreTests.cs index 5c91354d..40c7a9fa 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionStateRestoreTests.cs @@ -1,24 +1,24 @@ using System.Text.Json.Nodes; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; -using static AgentCore.Application.Tests.Transcript.CallSessionResumeTestSupport; +using static AgentCore.Application.Tests.Transcript.ConversationSessionResumeTestSupport; namespace AgentCore.Application.Tests.Transcript; /// -/// What a second session of one call restores from the state a first one left behind. +/// What a second session of one conversation restores from the state a first one left behind. /// -public sealed class CallSessionStateRestoreTests +public sealed class ConversationSessionStateRestoreTests { [Fact] - public async Task ASecondSessionOfOneCall_KeepsTheStageTheFirstOneReached() + public async Task ASecondSessionOfOneConversation_KeepsTheStageTheFirstOneReached() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); using ScriptedChatClient first = new("what model is it?"); var opened = CreateSession(StagedYaml, first, store); @@ -28,7 +28,7 @@ public async Task ASecondSessionOfOneCall_KeepsTheStageTheFirstOneReached() Assert.Equal("help", opened.Stage); using ScriptedChatClient second = new("sure"); - var resumed = CreateSession(StagedYaml, second, store, opened.CallId); + var resumed = CreateSession(StagedYaml, second, store, opened.ConversationId); await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); // StageBefore, and not Stage. The stage is restored when the session OPENS and the session @@ -41,15 +41,15 @@ public async Task ASecondSessionOfOneCall_KeepsTheStageTheFirstOneReached() } [Fact] - public async Task ASecondSessionOfOneCall_MovesTheStageMachineAndNotOnlyItsLabel() + public async Task ASecondSessionOfOneConversation_MovesTheStageMachineAndNotOnlyItsLabel() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-machine", TestContext.Current.CancellationToken); await store.AppendAsync( "C-machine", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "two" }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "two" }, TestContext.Current.CancellationToken); using ScriptedChatClient reply = new("sure"); @@ -67,9 +67,9 @@ await store.AppendAsync( } [Fact] - public async Task ASecondSessionOfOneCall_KeepsTheSlotsTheFirstOneFilled() + public async Task ASecondSessionOfOneConversation_KeepsTheSlotsTheFirstOneFilled() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); using ScriptedChatClient first = new("what model is it?"); var opened = CreateSession(StagedYaml, first, store); @@ -79,7 +79,7 @@ public async Task ASecondSessionOfOneCall_KeepsTheSlotsTheFirstOneFilled() Assert.Equal(1L, opened.State.Read("turnsTaken")!.GetValue()); using ScriptedChatClient second = new("sure"); - var resumed = CreateSession(StagedYaml, second, store, opened.CallId); + var resumed = CreateSession(StagedYaml, second, store, opened.ConversationId); await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); // Two, not one. A session that forgot would count its own turn from zero. @@ -87,16 +87,16 @@ public async Task ASecondSessionOfOneCall_KeepsTheSlotsTheFirstOneFilled() } [Fact] - public async Task ASecondSessionOfOneCall_DropsASlotTheDocumentNoLongerDeclares() + public async Task ASecondSessionOfOneConversation_DropsASlotTheDocumentNoLongerDeclares() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-drift", TestContext.Current.CancellationToken); - // Written as though a build that declared 'retired' had run this call. + // Written as though a build that declared 'retired' had run this conversation. await store.AppendAsync( "C-drift", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "intake", Slots = new Dictionary(StringComparer.Ordinal) @@ -115,25 +115,25 @@ await store.AppendAsync( Assert.Equal(5L, resumed.State.Read("turnsTaken")!.GetValue()); Assert.Null(resumed.State.Read("retired")); - // Dropped, and said so. A document change that quietly costs a call one slot is a change + // Dropped, and said so. A document change that quietly costs a conversation one slot is a change // nobody can price afterwards, so the slot that went is named in the fact. - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + var dropped = Assert.Single(observer.Events, fact => fact.Kind == ConversationEventKind.StateRestorePartial); Assert.Equal( "the document no longer declares the slot 'retired'.", - dropped.Payload[CallEventPayloadKeys.Reason]); + dropped.Payload[ConversationEventPayloadKeys.Reason]); } [Fact] - public async Task ASecondSessionOfOneCall_DropsASlotWhoseDeclaredTypeNoLongerTakesTheStoredValue() + public async Task ASecondSessionOfOneConversation_DropsASlotWhoseDeclaredTypeNoLongerTakesTheStoredValue() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-retyped", TestContext.Current.CancellationToken); - // Written as though 'turnsTaken' had been declared a string when this call ran. + // Written as though 'turnsTaken' had been declared a string when this conversation ran. await store.AppendAsync( "C-retyped", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "intake", Slots = new Dictionary(StringComparer.Ordinal) @@ -153,25 +153,25 @@ await store.AppendAsync( // The other half of what TryWrite answers false for. An operator fixes a retyped slot and a // deleted slot differently, so the two reasons have to read differently. - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + var dropped = Assert.Single(observer.Events, fact => fact.Kind == ConversationEventKind.StateRestorePartial); Assert.Equal( "the slot 'turnsTaken' no longer takes the value it was stored with.", - dropped.Payload[CallEventPayloadKeys.Reason]); + dropped.Payload[ConversationEventPayloadKeys.Reason]); } [Fact] - public async Task ASecondSessionOfOneCall_DropsAReservedSlotRatherThanRefusingTheCall() + public async Task ASecondSessionOfOneConversation_DropsAReservedSlotRatherThanRefusingTheConversation() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-reserved", TestContext.Current.CancellationToken); // No writer produces this, but the blob is arbitrary JSON out of store 0 and a host can hand // one in directly. StateDocument.TryWrite THROWS on a reserved slot rather than answering - // false, so a Restore that just asked it would take the call down on its first turn. + // false, so a Restore that just asked it would take the conversation down on its first turn. await store.AppendAsync( "C-reserved", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "intake", Slots = new Dictionary(StringComparer.Ordinal) @@ -192,24 +192,24 @@ await store.AppendAsync( Assert.NotNull(resumed.LastTurn); Assert.Equal(5L, resumed.State.Read("turnsTaken")!.GetValue()); - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + var dropped = Assert.Single(observer.Events, fact => fact.Kind == ConversationEventKind.StateRestorePartial); Assert.Equal( "the slot 'stage' is reserved, and a reserved slot is never restored.", - dropped.Payload[CallEventPayloadKeys.Reason]); + dropped.Payload[ConversationEventPayloadKeys.Reason]); } [Fact] - public async Task ASecondSessionOfOneCall_IgnoresAStateBlobWrittenInAShapeThisBuildDoesNotKnow() + public async Task ASecondSessionOfOneConversation_IgnoresAStateBlobWrittenInAShapeThisBuildDoesNotKnow() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-future", TestContext.Current.CancellationToken); await store.AppendAsync( "C-future", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { - Version = CallSessionState.CurrentVersion + 1, + Version = ConversationSessionState.CurrentVersion + 1, Stage = "help", Slots = new Dictionary(StringComparer.Ordinal) { @@ -224,35 +224,35 @@ await store.AppendAsync( await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - // Nothing of it is taken, not the stage and not the slot. A call that forgets answers the - // caller; a call that guesses at a shape it does not know answers them wrongly. + // Nothing of it is taken, not the stage and not the slot. A conversation that forgets answers the + // caller; a conversation that guesses at a shape it does not know answers them wrongly. Assert.Equal("intake", resumed.LastTurn!.StageBefore); Assert.Equal(1L, resumed.State.Read("turnsTaken")!.GetValue()); - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + var dropped = Assert.Single(observer.Events, fact => fact.Kind == ConversationEventKind.StateRestorePartial); Assert.Equal( - $"the stored state is version {CallSessionState.CurrentVersion + 1} " - + $"and this build writes {CallSessionState.CurrentVersion}.", - dropped.Payload[CallEventPayloadKeys.Reason]); + $"the stored state is version {ConversationSessionState.CurrentVersion + 1} " + + $"and this build writes {ConversationSessionState.CurrentVersion}.", + dropped.Payload[ConversationEventPayloadKeys.Reason]); } [Fact] - public async Task ASecondSessionOfACallWhoseDocumentLostItsPolicy_DropsTheStoredStage() + public async Task ASecondSessionOfAConversationWhoseDocumentLostItsPolicy_DropsTheStoredStage() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-nopolicy", TestContext.Current.CancellationToken); await store.AppendAsync( "C-nopolicy", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "intake" }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "intake" }, TestContext.Current.CancellationToken); using ScriptedChatClient reply = new("sure"); RecordingObserver observer = new(); // OneAgentYaml declares no policy: at all, which is the shape a document takes when its - // policy section is removed between one session of a call and the next. + // policy section is removed between one session of a conversation and the next. var resumed = CreateSession(OneAgentYaml, reply, store, "C-nopolicy", observer); await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); @@ -261,45 +261,45 @@ await store.AppendAsync( // reserved slot anyway would hand the guards and the audit chain a stage nothing is in. Assert.Equal(string.Empty, resumed.Stage); - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + var dropped = Assert.Single(observer.Events, fact => fact.Kind == ConversationEventKind.StateRestorePartial); Assert.Equal( "the entry declares no policy, so the stage 'intake' has nowhere to go.", - dropped.Payload[CallEventPayloadKeys.Reason]); + dropped.Payload[ConversationEventPayloadKeys.Reason]); } [Fact] - public async Task ASecondSessionOfACallThatAlreadyFinished_RefusesTheTurn() + public async Task ASecondSessionOfAConversationThatAlreadyFinished_RefusesTheTurn() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-finished", TestContext.Current.CancellationToken); await store.AppendAsync( "C-finished", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "help", IsComplete = true }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "help", IsComplete = true }, TestContext.Current.CancellationToken); using ScriptedChatClient reply = new("sure"); var resumed = CreateSession(StagedYaml, reply, store, "C-finished"); // The restore happens in OpenSessionAsync, which RunTurnAsync awaits before it reads - // IsComplete — so a call that reached a terminal stage stays finished across sessions and + // IsComplete — so a conversation that reached a terminal stage stays finished across sessions and // turns the caller away rather than starting again. Worth pinning rather than inferring: it - // is what a chat page reload on a finished call now does. + // is what a chat page reload on a finished conversation now does. await Assert.ThrowsAsync( () => resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken)); } [Fact] - public async Task ASecondSessionOfOneCall_FallsBackWhenTheStageIsGone() + public async Task ASecondSessionOfOneConversation_FallsBackWhenTheStageIsGone() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); await store.CreateAsync("C-nostage", TestContext.Current.CancellationToken); await store.AppendAsync( "C-nostage", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "a-stage-nobody-declares" }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "a-stage-nobody-declares" }, TestContext.Current.CancellationToken); using ScriptedChatClient reply = new("sure"); @@ -308,20 +308,20 @@ await store.AppendAsync( await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - // It ran. Falling back beats refusing: a call that comes back knowing less is worth more than + // It ran. Falling back beats refusing: a conversation that comes back knowing less is worth more than // one that will not come back. Assert.NotNull(resumed.LastTurn); Assert.Equal("intake", resumed.LastTurn!.StageBefore); - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + var dropped = Assert.Single(observer.Events, fact => fact.Kind == ConversationEventKind.StateRestorePartial); Assert.Contains( - "a-stage-nobody-declares", dropped.Payload[CallEventPayloadKeys.Reason], StringComparison.Ordinal); + "a-stage-nobody-declares", dropped.Payload[ConversationEventPayloadKeys.Reason], StringComparison.Ordinal); } [Fact] - public async Task ACallWithNoStoredState_StartsWhereTheDocumentSays() + public async Task AConversationWithNoStoredState_StartsWhereTheDocumentSays() { - InMemoryCallStore store = new(); + InMemoryConversationStore store = new(); using ScriptedChatClient reply = new("what model is it?"); var session = CreateSession(StagedYaml, reply, store); diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionStoreFailureTests.cs similarity index 74% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionStoreFailureTests.cs index fa254583..32bd7c04 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionStoreFailureTests.cs @@ -11,14 +11,14 @@ namespace AgentCore.Application.Tests.Transcript; /// -/// What store 1 owes the chain: the words first, and a dropped write that costs the call nothing. +/// What store 1 owes the chain: the words first, and a dropped write that costs the conversation nothing. /// /// /// The chain stores a hash of the spoken text and store 1 stores the text. That split only works in /// one order — the words have to be there before the row that names their digest — and it only works -/// if a store that refuses a write cannot end the call it is recording. +/// if a store that refuses a write cannot end the conversation it is recording. /// -public sealed class CallSessionStoreFailureTests +public sealed class ConversationSessionStoreFailureTests { private const string OneAgentYaml = """ apiVersion: agentcore/v1 @@ -40,13 +40,13 @@ public sealed class CallSessionStoreFailureTests public async Task Interrupt_MidReply_StoreOneHoldsTheWordsBeforeTheInterruptedFactIsRaised() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); using ScriptedChatClient reply = new("Hello", " there", " caller") { GateAfterFirstFragment = true }; List whenTheFactWasRaised = []; WatchingObserver observer = new( - CallEventKind.ReplyInterrupted, - callEvent => whenTheFactWasRaised.AddRange( - store.Live(callEvent.CallId).Select(row => row.Content.Text))); + ConversationEventKind.ReplyInterrupted, + conversationEvent => whenTheFactWasRaised.AddRange( + store.Live(conversationEvent.ConversationId).Select(row => row.Content.Text))); var session = CreateSession(OneAgentYaml, reply, store, observer); var (turn, spoke) = StartGatedTurn(session, "hi"); await spoke; @@ -61,13 +61,13 @@ public async Task Interrupt_MidReply_StoreOneHoldsTheWordsBeforeTheInterruptedFa Assert.Equal(["hi", "Hello"], whenTheFactWasRaised); } - /// A store 1 write failure never ends a call. + /// A store 1 write failure never ends a conversation. [Fact] - public async Task Append_StoreThrows_CallContinues() + public async Task Append_StoreThrows_ConversationContinues() { // Arrange using RequestRecordingChatClient reply = new("hi there", "it ships Friday"); - var session = CreateSession(OneAgentYaml, reply, new ThrowingCallStore()); + var session = CreateSession(OneAgentYaml, reply, new ThrowingConversationStore()); _ = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); // Act @@ -90,7 +90,7 @@ public async Task Resync_StoreThrows_RaisesDiagnosticAndTheTurnRuns() // Arrange using RequestRecordingChatClient reply = new("hi there", "it ships Friday"); RecordingObserver observer = new(); - var session = CreateSession(OneAgentYaml, reply, new ThrowingCallStore(), observer); + var session = CreateSession(OneAgentYaml, reply, new ThrowingConversationStore(), observer); _ = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); // Act @@ -100,13 +100,13 @@ public async Task Resync_StoreThrows_RaisesDiagnosticAndTheTurnRuns() Assert.Equal("it ships Friday", second.ReplyText); var failed = Assert.Single( observer.Events, - callEvent => callEvent.Kind == CallEventKind.TranscriptResyncFailed); + conversationEvent => conversationEvent.Kind == ConversationEventKind.TranscriptResyncFailed); Assert.Null(failed.EventId); Assert.Equal(1, failed.TurnIndex); } /// - /// A dropped write is a fact about the system and never about the call, so it is counted and + /// A dropped write is a fact about the system and never about the conversation, so it is counted and /// logged and stored nowhere. /// [Fact] @@ -115,7 +115,7 @@ public async Task Append_StoreThrows_RaisesDiagnosticWithNoEventId() // Arrange using RequestRecordingChatClient reply = new("hi there"); RecordingObserver observer = new(); - var session = CreateSession(OneAgentYaml, reply, new ThrowingCallStore(), observer); + var session = CreateSession(OneAgentYaml, reply, new ThrowingConversationStore(), observer); // Act _ = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); @@ -124,7 +124,7 @@ public async Task Append_StoreThrows_RaisesDiagnosticWithNoEventId() await session.FlushTranscriptAsync(); var dropped = Assert.Single( observer.Events, - callEvent => callEvent.Kind == CallEventKind.TranscriptWriteFailed); + conversationEvent => conversationEvent.Kind == ConversationEventKind.TranscriptWriteFailed); Assert.Null(dropped.EventId); Assert.Equal(0, dropped.TurnIndex); @@ -132,20 +132,20 @@ public async Task Append_StoreThrows_RaisesDiagnosticWithNoEventId() // failure at all: only the dropped write itself takes no row. var stored = observer.Events.Where(item => item.EventId is not null).ToArray(); Assert.Equal( - [CallEventKind.CallStarted, CallEventKind.TurnCompleted], + [ConversationEventKind.ConversationStarted, ConversationEventKind.TurnCompleted], stored.Select(item => item.Kind).ToArray()); Assert.Equal(stored.Length, stored.Select(item => item.EventId).Distinct().Count()); } - private static CallSession CreateSession( - string yaml, IChatClient reply, ICallStore store, params ICallObserver[] observers) + private static ConversationSession CreateSession( + string yaml, IChatClient reply, IConversationStore store, params IConversationObserver[] observers) { var document = ConfigurationLoader.LoadYaml(yaml); var compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(new FakeChatClientFactory(reply)) { CallStore = store })["main"]; + new AgentCompilationContext(new FakeChatClientFactory(reply)) { ConversationStore = store })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null, @@ -153,7 +153,7 @@ private static CallSession CreateSession( } /// Starts a streaming turn on a background task and says when the caller can hear it. - private static (Task Turn, Task Spoke) StartGatedTurn(CallSession session, string userInput) + private static (Task Turn, Task Spoke) StartGatedTurn(ConversationSession session, string userInput) { TaskCompletionSource spoke = new(TaskCreationOptions.RunContinuationsAsynchronously); var turn = Task.Run( @@ -171,13 +171,13 @@ private static (Task Turn, Task Spoke) StartGatedTurn(CallSession session, strin return (turn, spoke.Task.WaitAsync(TimeSpan.FromSeconds(10))); } - /// Keeps every fact of the call, in the order the turn loop raised them. - private sealed class RecordingObserver : ICallObserver + /// Keeps every fact of the conversation, in the order the turn loop raised them. + private sealed class RecordingObserver : IConversationObserver { private readonly Lock _gate = new(); - private readonly List _events = []; + private readonly List _events = []; - public IReadOnlyList Events + public IReadOnlyList Events { get { @@ -188,11 +188,11 @@ public IReadOnlyList Events } } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { lock (_gate) { - _events.Add(callEvent); + _events.Add(conversationEvent); } return ValueTask.CompletedTask; @@ -206,22 +206,22 @@ public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancell /// The dispatcher runs an observer that completes at once on the caller's thread, so what this /// reads is what was true when the turn loop raised the fact, and not what became true later. /// - private sealed class WatchingObserver : ICallObserver + private sealed class WatchingObserver : IConversationObserver { - private readonly CallEventKind _kind; - private readonly Action _look; + private readonly ConversationEventKind _kind; + private readonly Action _look; - public WatchingObserver(CallEventKind kind, Action look) + public WatchingObserver(ConversationEventKind kind, Action look) { _kind = kind; _look = look; } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { - if (callEvent.Kind == _kind) + if (conversationEvent.Kind == _kind) { - _look(callEvent); + _look(conversationEvent); } return ValueTask.CompletedTask; diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionTranscriptTests.cs similarity index 89% rename from tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationSessionTranscriptTests.cs index 2332a01b..f4f9717f 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationSessionTranscriptTests.cs @@ -16,9 +16,9 @@ namespace AgentCore.Application.Tests.Transcript; /// -/// Pins the call's move onto one AgentSession: what the run is sent, and what store 1 keeps. +/// Pins the conversation's move onto one AgentSession: what the run is sent, and what store 1 keeps. /// -public sealed class CallSessionTranscriptTests +public sealed class ConversationSessionTranscriptTests { private const string OneAgentYaml = """ apiVersion: agentcore/v1 @@ -79,7 +79,7 @@ public sealed class CallSessionTranscriptTests public async Task Interrupt_MidReply_StoredTranscriptHoldsHeardTextOnly() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); using ScriptedChatClient reply = new("Hello", " there", " caller") { GateAfterFirstFragment = true }; var session = CreateSession(OneAgentYaml, reply, store); var (turn, spoke) = StartGatedTurn(session, "hi"); @@ -93,7 +93,7 @@ public async Task Interrupt_MidReply_StoredTranscriptHoldsHeardTextOnly() await turn; Assert.True(recorded); await session.FlushTranscriptAsync(); - Assert.Equal(["hi", "Hello"], store.Live(session.CallId).Select(row => row.Content.Text)); + Assert.Equal(["hi", "Hello"], store.Live(session.ConversationId).Select(row => row.Content.Text)); } /// @@ -106,7 +106,7 @@ public async Task Interrupt_MidReply_StoredTranscriptHoldsHeardTextOnly() public async Task InterruptAfterTheTurnEnded_ToolTurnWithProse_StoresTheHeardWordsOnce() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); using ProseThenReplyChatClient reply = new("the price is fifty"); var session = CreateSession(ToolYaml, reply, store, new StubToolBuilder(ToolResult).Create); await DrainAsync(session.RunTurnStreamingAsync("how much?", TestContext.Current.CancellationToken)); @@ -117,7 +117,7 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnWithProse_StoresTheHeardWor // Assert Assert.True(recorded); await session.FlushTranscriptAsync(); - var rows = store.Live(session.CallId); + var rows = store.Live(session.ConversationId); Assert.DoesNotContain( rows.SelectMany(row => row.Content.Contents).OfType(), text => text.Text.Contains(ProseThenReplyChatClient.Prose, StringComparison.Ordinal)); @@ -139,7 +139,7 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnWithProse_StoresTheHeardWor public async Task InterruptAfterTheTurnEnded_ToolTurnThatRendered_LeavesTheRenderContentOnTheToolResultRow() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); using ProseThenReplyChatClient reply = new("the price is fifty"); var session = CreateSession(ToolYaml, reply, store, RenderTool); session.SetHasScreen(true); @@ -151,7 +151,7 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnThatRendered_LeavesTheRende // Assert Assert.True(recorded); await session.FlushTranscriptAsync(); - var rows = store.Live(session.CallId); + var rows = store.Live(session.ConversationId); Assert.Equal( ["how much?", "the price"], rows.Select(row => row.Content.Text).Where(text => text.Length > 0)); @@ -162,7 +162,7 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnThatRendered_LeavesTheRende } /// - /// Drives a real turn end to end through , with a screen bound and a + /// Drives a real turn end to end through , with a screen bound and a /// real tool that publishes through it, and reads what store 1 actually kept. Every other render /// test in this suite hand-rolls collectors, so none of them would notice a broken wire between /// the turn's invocation and its renders — this is the one test that goes through that wire @@ -172,7 +172,7 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnThatRendered_LeavesTheRende public async Task ATurnThatRendersWithAScreenBound_StoresTheRenderContentOnTheToolResultRow() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); ToolCallingChatClient reply = new("drew it."); var session = CreateSession(ToolYaml, reply, store, RenderTool); session.SetHasScreen(true); @@ -182,7 +182,7 @@ public async Task ATurnThatRendersWithAScreenBound_StoresTheRenderContentOnTheTo // Assert await session.FlushTranscriptAsync(); - var rows = store.Live(session.CallId); + var rows = store.Live(session.ConversationId); Assert.Contains(rows.SelectMany(row => row.Content.Contents), content => content is RenderContent); } @@ -203,14 +203,14 @@ public async Task ATurnThatRendersWithAScreenBound_StoresTheRenderContentOnTheTo /// /// Step 1's second failure mode: a cut that reached back a turn would replace a sentence the - /// caller heard in full, and nothing would detect it. The guard is CallSession's, so this - /// drives it through rather than through the provider. + /// caller heard in full, and nothing would detect it. The guard is ConversationSession's, so this + /// drives it through rather than through the provider. /// [Fact] public async Task Interrupt_AfterASecondTurn_LeavesTheFirstTurnsReplyWhole() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); RequestRecordingChatClient reply = new("hi there caller", "it ships Friday from the depot"); var session = CreateSession(OneAgentYaml, reply, store); _ = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); @@ -224,15 +224,15 @@ public async Task Interrupt_AfterASecondTurn_LeavesTheFirstTurnsReplyWhole() await session.FlushTranscriptAsync(); Assert.Equal( ["hello", "hi there caller", "order 41?", "it ships"], - store.Live(session.CallId).Select(row => row.Content.Text)); + store.Live(session.ConversationId).Select(row => row.Content.Text)); } [Fact] - public async Task RunTurn_SecondTurn_SendsTheNewCallerMessageAloneAndTheModelStillSeesTheCall() + public async Task RunTurn_SecondTurn_SendsTheNewCallerMessageAloneAndTheModelStillSeesTheConversation() { // Arrange RequestRecordingChatClient reply = new("hi there", "it ships Friday"); - var session = CreateSession(OneAgentYaml, reply, new RecordingCallStore()); + var session = CreateSession(OneAgentYaml, reply, new RecordingConversationStore()); _ = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); // Act @@ -252,7 +252,7 @@ public async Task RunTurn_SecondTurn_SendsTheNewCallerMessageAloneAndTheModelSti public async Task RunTurn_WithAnUnfilledSlot_KeepsTheReminderOutOfTheStoredTranscript() { // Arrange - RecordingCallStore store = new(); + RecordingConversationStore store = new(); RequestRecordingChatClient reply = new("which order?"); var session = CreateSession(SlotYaml, reply, store); @@ -265,11 +265,11 @@ public async Task RunTurn_WithAnUnfilledSlot_KeepsTheReminderOutOfTheStoredTrans Assert.DoesNotContain("", reply.Instructions[0] ?? string.Empty, StringComparison.Ordinal); Assert.Contains(reply.Requests[0], message => message.Contains("", StringComparison.Ordinal)); await session.FlushTranscriptAsync(); - Assert.Equal(["hello", "which order?"], store.Live(session.CallId).Select(row => row.Content.Text)); + Assert.Equal(["hello", "which order?"], store.Live(session.ConversationId).Select(row => row.Content.Text)); } - private static CallSession CreateSession( - string yaml, IChatClient reply, ICallStore store, Func? tools = null) + private static ConversationSession CreateSession( + string yaml, IChatClient reply, IConversationStore store, Func? tools = null) { var document = ConfigurationLoader.LoadYaml(yaml); var chatClients = new FakeChatClientFactory(reply); @@ -277,11 +277,11 @@ private static CallSession CreateSession( document, new AgentCompilationContext(chatClients) { - CallStore = store, + ConversationStore = store, Tools = TestToolRegistry.From(document, tools, TestContext.Current.CancellationToken), })["main"]; - var factory = new CallSessionFactory( + var factory = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null); @@ -290,7 +290,7 @@ private static CallSession CreateSession( } /// Starts a streaming turn on a background task and says when the caller can hear it. - /// The call to run the turn on. + /// The conversation to run the turn on. /// What the caller said. /// The running turn, and a task that completes at its first spoken update. /// @@ -298,7 +298,7 @@ private static CallSession CreateSession( /// before the first update takes the amendment path instead and records nothing. Waiting for that /// update is what makes the cut land in the reply rather than after it. /// - private static (Task Turn, Task Spoke) StartGatedTurn(CallSession session, string userInput) + private static (Task Turn, Task Spoke) StartGatedTurn(ConversationSession session, string userInput) { TaskCompletionSource spoke = new(TaskCreationOptions.RunContinuationsAsynchronously); var turn = Task.Run( @@ -327,14 +327,14 @@ private static async Task DrainAsync(IAsyncEnumerable update /// Writes a line beside the tool call it announces, then answers once the result lands. /// /// This is what a real model produces, and it is the shape a cut has to survive: the prose and - /// the call ride one message, so the words and the side effect cannot be dropped together. + /// the conversation ride one message, so the words and the side effect cannot be dropped together. /// private sealed class ProseThenReplyChatClient : IChatClient { /// The line the model speaks before it calls the tool. public const string Prose = "Let me check that for you"; - private const string ToolCallId = "call_1"; + private const string ToolCallId = "conversation_1"; private readonly string _reply; diff --git a/tests/AgentCore.Application.Tests/Transcript/CallTranscriptEditTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationTranscriptEditTests.cs similarity index 71% rename from tests/AgentCore.Application.Tests/Transcript/CallTranscriptEditTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationTranscriptEditTests.cs index 3841d471..16af0fde 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallTranscriptEditTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationTranscriptEditTests.cs @@ -8,12 +8,12 @@ namespace AgentCore.Application.Tests.Transcript; /// Pins what happens when a caller sends an earlier message again: what is withdrawn, what is kept, /// and which numbers refuse to be wound back with it. /// -public sealed class CallTranscriptEditTests +public sealed class ConversationTranscriptEditTests { [Fact] public void Append_NamesEveryRow_AndKeepsTheNameTheCallerGaveTheFirst() { - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; var rows = transcript.Append([User("hello"), Assistant("hi")], firstMessageId: "caller-1"); @@ -28,7 +28,7 @@ public void Append_NamesEveryRow_AndKeepsTheNameTheCallerGaveTheFirst() [Fact] public void TruncateFrom_DropsTheTailAndLeavesTheMarksWhereTheyAre() { - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.BeginTurn(0); var first = transcript.Append([User("q1"), Assistant("a1")], "caller-1"); transcript.BeginTurn(1); @@ -48,7 +48,7 @@ public void TruncateFrom_DropsTheTailAndLeavesTheMarksWhereTheyAre() [Fact] public void TruncateFrom_AimsTheNextBargeInAtTheReplyThatSurvived() { - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.BeginTurn(0); var first = transcript.Append([User("q1"), Assistant("a1")], "caller-1"); transcript.BeginTurn(1); @@ -62,9 +62,9 @@ public void TruncateFrom_AimsTheNextBargeInAtTheReplyThatSurvived() } [Fact] - public void OrdinalOf_AMessageTheCallDoesNotHold_IsNull() + public void OrdinalOf_AMessageTheConversationDoesNotHold_IsNull() { - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.Append([User("hello")], "caller-1"); Assert.Null(transcript.OrdinalOf("never-stored")); @@ -73,14 +73,14 @@ public void OrdinalOf_AMessageTheCallDoesNotHold_IsNull() [Fact] public void Resume_PrefersTheStoredMarksOverTheRowsThatSurvived() { - // A call that was edited: the rows of turns 1 and 2 are gone, so the rows alone would say the + // A conversation that was edited: the rows of turns 1 and 2 are gone, so the rows alone would say the // next turn is 1 and the next ordinal 2 — both of which a deleted row already used. - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; var next = transcript.Resume( [ - new CallMessage("call-1", 0, 0, User("q1"), "m0"), - new CallMessage("call-1", 1, 0, Assistant("a1"), "m1"), + new ConversationMessage("conversation-1", 0, 0, User("q1"), "m0"), + new ConversationMessage("conversation-1", 1, 0, Assistant("a1"), "m1"), ], new TranscriptMarks(NextOrdinal: 6, NextTurnIndex: 3)); @@ -91,16 +91,16 @@ public void Resume_PrefersTheStoredMarksOverTheRowsThatSurvived() [Fact] public void Resume_SetsTheReplyABargeInWouldCut() { - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.Resume( [ - new CallMessage("call-1", 0, 0, User("q1"), "m0"), - new CallMessage("call-1", 1, 0, Assistant("a1"), "m1"), + new ConversationMessage("conversation-1", 0, 0, User("q1"), "m0"), + new ConversationMessage("conversation-1", 1, 0, Assistant("a1"), "m1"), // A tool-calling turn's textless assistant message is not a reply anybody can be cut // off in the middle of, so it must not be what the next barge-in aims at. - new CallMessage("call-1", 2, 0, new ChatMessage(ChatRole.Assistant, []), "m2"), + new ConversationMessage("conversation-1", 2, 0, new ChatMessage(ChatRole.Assistant, []), "m2"), ], new TranscriptMarks(NextOrdinal: 3, NextTurnIndex: 1)); @@ -110,14 +110,14 @@ public void Resume_SetsTheReplyABargeInWouldCut() [Fact] public void Resume_ThenTruncateLastReply_ActuallyCuts() { - // A resumed call has to know which reply a barge-in aims at. With no ordinal to aim at, + // A resumed conversation has to know which reply a barge-in aims at. With no ordinal to aim at, // TruncateLastReply returns an empty list, which the provider reports as a write it declined // rather than as a cut it lost — so the caller is silently not heard. - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.Resume( [ - new CallMessage("call-1", 0, 0, User("q1"), "m0"), - new CallMessage("call-1", 1, 0, Assistant("it ships on Friday"), "m1"), + new ConversationMessage("conversation-1", 0, 0, User("q1"), "m0"), + new ConversationMessage("conversation-1", 1, 0, Assistant("it ships on Friday"), "m1"), ], new TranscriptMarks(NextOrdinal: 2, NextTurnIndex: 1)); diff --git a/tests/AgentCore.Application.Tests/Transcript/CallTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/ConversationTranscriptTests.cs similarity index 83% rename from tests/AgentCore.Application.Tests/Transcript/CallTranscriptTests.cs rename to tests/AgentCore.Application.Tests/Transcript/ConversationTranscriptTests.cs index b1c468da..7f00e532 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/ConversationTranscriptTests.cs @@ -7,7 +7,7 @@ namespace AgentCore.Application.Tests.Transcript; /// Pins the rules of store 1: ordinals, which reply a barge-in cuts, and what a cut keeps. -public sealed class CallTranscriptTests +public sealed class ConversationTranscriptTests { private static readonly JsonElement Payload = JsonDocument.Parse("""{"x":1}""").RootElement.Clone(); @@ -15,11 +15,11 @@ public sealed class CallTranscriptTests public void Append_ToolResultCarriesARender_RowKeepsItAndMessagesStripsIt() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; var render = new RenderContent { Name = "order-card", RenderId = "order-41", Data = Payload }; var toolResult = new ChatMessage( ChatRole.Tool, - [new FunctionResultContent("call-1", "50"), render]); + [new FunctionResultContent("conversation-1", "50"), render]); var plain = Assistant("the price is fifty"); // Act @@ -48,7 +48,7 @@ public void Append_ToolResultCarriesARender_RowKeepsItAndMessagesStripsIt() public void Append_TwoTurns_AllocatesDenseUniqueOrdinals() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.BeginTurn(0); _ = transcript.Append([User("hello"), Assistant("hi there")]); transcript.BeginTurn(1); @@ -65,7 +65,7 @@ public void Append_TwoTurns_AllocatesDenseUniqueOrdinals() public void Append_ToolCallingTurn_AimsTheCutAtTheSpokenReply() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; var toolCall = new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("id", "lookup")]); // Act @@ -79,7 +79,7 @@ public void Append_ToolCallingTurn_AimsTheCutAtTheSpokenReply() public void TruncateLastReply_ReplyCarryingUsage_KeepsEverythingButTheWords() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; var reply = new ChatMessage( ChatRole.Assistant, [new TextContent("it ships Friday from the depot"), new UsageContent(new UsageDetails { OutputTokenCount = 7 })]); @@ -95,10 +95,10 @@ public void TruncateLastReply_ReplyCarryingUsage_KeepsEverythingButTheWords() } [Fact] - public void TruncateLastReply_TheCallSpokeNothing_RewritesNoRow() + public void TruncateLastReply_TheConversationSpokeNothing_RewritesNoRow() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; _ = transcript.Append([User("hello")]); // Act @@ -114,18 +114,18 @@ public void TruncateLastReply_TheCallSpokeNothing_RewritesNoRow() /// must not survive the cut as words the caller is recorded as having heard. /// [Fact] - public void TruncateLastReply_ProseBesideAToolCall_KeepsTheCallAndDropsTheWords() + public void TruncateLastReply_ProseBesideAToolCall_KeepsTheConversationAndDropsTheWords() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; var announced = new ChatMessage( ChatRole.Assistant, - [new TextContent("Let me check that for you"), new FunctionCallContent("call-1", "lookup")]); + [new TextContent("Let me check that for you"), new FunctionCallContent("conversation-1", "lookup")]); _ = transcript.Append( [ User("how much?"), announced, - new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", "50")]), + new ChatMessage(ChatRole.Tool, [new FunctionResultContent("conversation-1", "50")]), Assistant("the price is fifty"), ]); @@ -141,13 +141,13 @@ public void TruncateLastReply_ProseBesideAToolCall_KeepsTheCallAndDropsTheWords( /// /// The held prompt of item 6a opens turn 1 while the vendor is still speaking turn 0, so the /// reply a barge-in cuts is the one before the turn now open. Whether that turn may still be - /// corrected is CallSession's decision, and this class does not take it away. + /// corrected is ConversationSession's decision, and this class does not take it away. /// [Fact] public void BeginTurn_NextTurnOpens_LeavesThePreviousReplyOpenToACut() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; transcript.BeginTurn(0); _ = transcript.Append([User("hello"), Assistant("hi there")]); @@ -164,7 +164,7 @@ public void BeginTurn_NextTurnOpens_LeavesThePreviousReplyOpenToACut() public void Read_AfterTruncate_ReturnsHeardTextNotProducedText() { // Arrange - var transcript = new CallTranscript { CallId = "call-1" }; + var transcript = new ConversationTranscript { ConversationId = "conversation-1" }; _ = transcript.Append([User("order 41?"), Assistant("it ships Friday from the depot")]); // Act diff --git a/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs index 289f6b9f..e191eb25 100644 --- a/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs @@ -32,20 +32,20 @@ public sealed class InnerAgentTranscriptTests """; /// - /// The inner agent runs on a session of its own, which no BeginCall ever named, so store 1 + /// The inner agent runs on a session of its own, which no BeginConversation ever named, so store 1 /// never sees its rounds. Keeping them would cost tokens on every later turn and would put the /// inner agent's working-out into the audit record, which no consumer asked for. /// [Fact] public async Task ADelegatingTurn_WritesTheOuterRoundsOnly() { - RecordingCallStore store = new(); + RecordingConversationStore store = new(); using ToolCallingChatClient model = new("done"); var compiled = ConfigurationCompiler.CompileAll( ConfigurationLoader.LoadYaml(DelegatingYaml), - new AgentCompilationContext(new FakeChatClientFactory(model)) { CallStore = store })["main"]; + new AgentCompilationContext(new FakeChatClientFactory(model)) { ConversationStore = store })["main"]; - var session = new CallSessionFactory( + var session = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor: null).Create(); await foreach (var _ in session.RunTurnStreamingAsync("hi", TestContext.Current.CancellationToken)) @@ -62,6 +62,6 @@ public async Task ADelegatingTurn_WritesTheOuterRoundsOnly() Assert.Equal( ["user", "assistant", "tool", "assistant"], store.Rows.Select(row => row.Content.Role.Value)); - Assert.All(store.Rows, row => Assert.Equal(session.CallId, row.CallId)); + Assert.All(store.Rows, row => Assert.Equal(session.ConversationId, row.ConversationId)); } } diff --git a/tests/AgentCore.Application.Tests/Transcript/TranscriptJsonTests.cs b/tests/AgentCore.Application.Tests/Transcript/TranscriptJsonTests.cs index 6ed8ee2a..d66b8e15 100644 --- a/tests/AgentCore.Application.Tests/Transcript/TranscriptJsonTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/TranscriptJsonTests.cs @@ -25,8 +25,8 @@ public void Options_RoundTripsAMessageWithOutOfOrderTypeDiscriminators() var message = new ChatMessage(ChatRole.Assistant, [ new TextContent("here's your order"), - new FunctionCallContent("call-1", "lookup_order", new Dictionary { ["orderId"] = "41" }), - new FunctionResultContent("call-1", new { status = "shipped" }), + new FunctionCallContent("conversation-1", "lookup_order", new Dictionary { ["orderId"] = "41" }), + new FunctionResultContent("conversation-1", new { status = "shipped" }), new UsageContent(new UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 }), new RenderContent { Name = "order-card", RenderId = "order-41", Data = data }, ]); diff --git a/tests/AgentCore.AspNetCore.Tests/.editorconfig b/tests/AgentCore.AspNetCore.Tests/.editorconfig index 8fca7846..0b6570d5 100644 --- a/tests/AgentCore.AspNetCore.Tests/.editorconfig +++ b/tests/AgentCore.AspNetCore.Tests/.editorconfig @@ -4,8 +4,8 @@ # underscore is what separates the two halves. dotnet_diagnostic.CA1707.severity = none -# CA1716: "Rename namespace AgentCore.AspNetCore.Tests.Call so that it no longer conflicts with -# the reserved language keyword 'Call'." This assembly does not target VB.NET or other languages -# that reserve the word, and the namespace mirrors src/AgentCore.AspNetCore/Call, which task 0 of -# the call-transport-seam plan named deliberately. +# CA1716: "Rename namespace AgentCore.AspNetCore.Tests.Conversation so that it no longer conflicts with +# the reserved language keyword 'Conversation'." This assembly does not target VB.NET or other languages +# that reserve the word, and the namespace mirrors src/AgentCore.AspNetCore/Conversation, which task 0 of +# the conversation-transport-seam plan named deliberately. dotnet_diagnostic.CA1716.severity = none diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationChannelShapeTests.cs similarity index 59% rename from tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/ConversationChannelShapeTests.cs index 6e6473ad..dad8944a 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationChannelShapeTests.cs @@ -1,9 +1,9 @@ -using AgentCore.Application.Calls; -using AgentCore.AspNetCore.Call; +using AgentCore.Application.Conversation; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.Tests.Fakes; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// /// The arbiter serves a split channel exactly as it serves a bundled one. @@ -12,25 +12,25 @@ namespace AgentCore.AspNetCore.Tests.Call; /// If this file ever needs a Telnyx type to compile, D8 has failed and the seam is in the wrong /// place. That is the whole assertion. /// -public sealed class CallChannelShapeTests +public sealed class ConversationChannelShapeTests { [Fact(Timeout = 30_000)] - public async Task ASplitChannelOfTwoObjects_RunsAScriptedCallThroughTheSameArbiter() + public async Task ASplitChannelOfTwoObjects_RunsAScriptedConversationThroughTheSameArbiter() { var session = new ScriptedConversationPort(); - var output = new FakeCallOutput(); - var input = new FakeCallInput(); - var channel = new CallChannel(input, output); + var output = new FakeConversationOutput(); + var input = new FakeConversationInput(); + var channel = new ConversationChannel(input, output); - var arbiter = new CallTurnArbiter( + var arbiter = new ConversationTurnArbiter( session, channel.Output, - new ConnectionTaskObserver(() => session.CallId, (_, _) => { }, (_, _, _) => { }, (_, _, _) => false), + new ConnectionTaskObserver(() => session.ConversationId, (_, _) => { }, (_, _, _) => { }, (_, _, _) => false), _ => { }, _ => { }, TestContext.Current.CancellationToken); - // The scripted call holds every turn on a gate until a test opens it, so this turn is let + // The scripted conversation holds every turn on a gate until a test opens it, so this turn is let // through before it starts: this test is about the shape of the channel, and never about // the held-prompt window the arbiter's own tests use that gate for. session.ReleaseTurn(); diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationInputPortTests.cs similarity index 61% rename from tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/ConversationInputPortTests.cs index 4a5a0e48..a515e4a5 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationInputPortTests.cs @@ -1,13 +1,13 @@ using AgentCore.Application.Ports; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.AspNetCore.Tests.Fakes; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// -/// The two promises makes that a signature cannot: one consumer for -/// the life of the port, and a cancelled read that throws rather than passing for the end of a call. +/// The two promises makes that a signature cannot: one consumer for +/// the life of the port, and a cancelled read that throws rather than passing for the end of a conversation. /// /// /// Pinned on the test double, which is the only implementation reachable without a live socket. The @@ -16,17 +16,17 @@ namespace AgentCore.AspNetCore.Tests.Call; /// WebSocket and a request's service provider, so nothing here can hold one. What keeps the two /// honest is that both quote the same rule from the port's own doc. /// -public sealed class CallInputPortTests +public sealed class ConversationInputPortTests { [Fact(Timeout = 30_000)] - public async Task ASecondListenAsync_ThrowsRatherThanGivingEachReaderHalfTheCall() + public async Task ASecondListenAsync_ThrowsRatherThanGivingEachReaderHalfTheConversation() { - var input = new FakeCallInput( - new CallInput.Utterance("hello", "en", IsFinal: true), - new CallInput.Keypress("1"), - new CallInput.Barge("hel", TimeSpan.FromMilliseconds(240))); + var input = new FakeConversationInput( + new ConversationInput.Utterance("hello", "en", IsFinal: true), + new ConversationInput.Keypress("1"), + new ConversationInput.Barge("hel", TimeSpan.FromMilliseconds(240))); - var heard = new List(); + var heard = new List(); await foreach (var item in input.ListenAsync(TestContext.Current.CancellationToken)) { heard.Add(item); @@ -35,11 +35,11 @@ public async Task ASecondListenAsync_ThrowsRatherThanGivingEachReaderHalfTheCall // One ordered stream carries every kind, and the reader takes them in the order they // happened rather than one stream per kind. Assert.Equal(3, heard.Count); - Assert.Equal(new CallInput.Utterance("hello", "en", IsFinal: true), heard[0]); - Assert.Equal(new CallInput.Keypress("1"), heard[1]); - Assert.Equal(new CallInput.Barge("hel", TimeSpan.FromMilliseconds(240)), heard[2]); + Assert.Equal(new ConversationInput.Utterance("hello", "en", IsFinal: true), heard[0]); + Assert.Equal(new ConversationInput.Keypress("1"), heard[1]); + Assert.Equal(new ConversationInput.Barge("hel", TimeSpan.FromMilliseconds(240)), heard[2]); - // Thrown by the call itself, and not by enumerating what it returns: an iterator's body + // Thrown by the conversation itself, and not by enumerating what it returns: an iterator's body // does not run until something reads it, so a guard that waited for the first MoveNext // would let a second reader walk away holding a stream that never says no. Assert.Throws( @@ -47,12 +47,12 @@ public async Task ASecondListenAsync_ThrowsRatherThanGivingEachReaderHalfTheCall } [Fact(Timeout = 30_000)] - public async Task ACancelledRead_ThrowsRatherThanPassingForTheEndOfTheCall() + public async Task ACancelledRead_ThrowsRatherThanPassingForTheEndOfTheConversation() { // The difference a consumer cannot see for itself: an await foreach that simply ends means - // the call is over, so a port that swallowed its own consumer's cancellation would report a - // call that ended when the call is still up. - var input = new FakeCallInput(new CallInput.Keypress("1")); + // the conversation is over, so a port that swallowed its own consumer's cancellation would report a + // conversation that ended when the conversation is still up. + var input = new FakeConversationInput(new ConversationInput.Keypress("1")); using var cancellation = new CancellationTokenSource(); await cancellation.CancelAsync(); diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallOptionsFromDocumentTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationOptionsFromDocumentTests.cs similarity index 70% rename from tests/AgentCore.AspNetCore.Tests/Call/CallOptionsFromDocumentTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/ConversationOptionsFromDocumentTests.cs index 002ec569..f7ae4854 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallOptionsFromDocumentTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationOptionsFromDocumentTests.cs @@ -3,10 +3,10 @@ using AgentCore.AspNetCore.Vendors.TelnyxRelay; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// -/// The three socket limits come out of providers.call, and a bad one stops the start. +/// The three socket limits come out of providers.conversation, and a bad one stops the start. /// /// /// These replace the three map-time ArgumentOutOfRangeException facts that used to live in @@ -14,9 +14,9 @@ namespace AgentCore.AspNetCore.Tests.Call; /// carrying the JSON pointer of the offending field rather /// than an exception naming a property: a reader needs the line of the document to fix. Spec §12. /// -public sealed class CallOptionsFromDocumentTests +public sealed class ConversationOptionsFromDocumentTests { - private static CallProviderConfiguration Entry( + private static ConversationProviderConfiguration Entry( int? idle = null, int? close = null, int? frame = null) => new() { @@ -29,7 +29,7 @@ private static CallProviderConfiguration Entry( [Fact] public void TheThreeKnobsReachTheOptions() { - var options = TelnyxRelayCallAdapter.BuildOptions(Entry(idle: 30, close: 5, frame: 4096)); + var options = TelnyxRelayConversationAdapter.BuildOptions(Entry(idle: 30, close: 5, frame: 4096)); Assert.Equal(TimeSpan.FromSeconds(30), options.IdleTimeout); Assert.Equal(TimeSpan.FromSeconds(5), options.CloseTimeout); @@ -41,7 +41,7 @@ public void AnAbsentKnobKeepsTheShippedDefault() { var shipped = new TelnyxRelayOptions(); - var options = TelnyxRelayCallAdapter.BuildOptions(Entry()); + var options = TelnyxRelayConversationAdapter.BuildOptions(Entry()); Assert.Equal(shipped.IdleTimeout, options.IdleTimeout); Assert.Equal(shipped.CloseTimeout, options.CloseTimeout); @@ -51,7 +51,7 @@ public void AnAbsentKnobKeepsTheShippedDefault() [Fact] public void MinusOneMeansInfinite() { - var options = TelnyxRelayCallAdapter.BuildOptions(Entry(idle: -1)); + var options = TelnyxRelayConversationAdapter.BuildOptions(Entry(idle: -1)); Assert.Equal(Timeout.InfiniteTimeSpan, options.IdleTimeout); } @@ -62,7 +62,7 @@ public void MinusOneMeansInfiniteOnTheCloseTimeoutToo() // The two timeouts read the same field of the same document block, and nothing but this // pins that they read it the same way. A close timeout that quietly turned -1 into a // negative TimeSpan would be refused by CancelAfter on the first teardown that used it. - var options = TelnyxRelayCallAdapter.BuildOptions(Entry(close: -1)); + var options = TelnyxRelayConversationAdapter.BuildOptions(Entry(close: -1)); Assert.Equal(Timeout.InfiniteTimeSpan, options.CloseTimeout); } @@ -74,27 +74,27 @@ public void ANegativeSecondsThatIsNotMinusOneFailsTheStartWithAPointer() // negative is a typo, and it must be caught here rather than handed to CancelAfter, which // refuses any negative span but -1 milliseconds at the moment teardown needs it. var failure = Assert.Throws( - () => TelnyxRelayCallAdapter.BuildOptions(Entry(idle: -2))); + () => TelnyxRelayConversationAdapter.BuildOptions(Entry(idle: -2))); - Assert.Equal("/providers/call/idleTimeoutSeconds", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation/idleTimeoutSeconds", failure.Errors[0].Pointer); } [Fact] public void AZeroFrameCapFailsTheStartWithAPointer() { var failure = Assert.Throws( - () => TelnyxRelayCallAdapter.BuildOptions(Entry(frame: 0))); + () => TelnyxRelayConversationAdapter.BuildOptions(Entry(frame: 0))); - Assert.Equal("/providers/call/maxFrameBytes", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation/maxFrameBytes", failure.Errors[0].Pointer); } [Fact] public void ATimeoutPastTheTimerCeilingFailsTheStartWithAPointer() { var failure = Assert.Throws( - () => TelnyxRelayCallAdapter.BuildOptions(Entry(idle: 5_000_000))); + () => TelnyxRelayConversationAdapter.BuildOptions(Entry(idle: 5_000_000))); - Assert.Equal("/providers/call/idleTimeoutSeconds", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation/idleTimeoutSeconds", failure.Errors[0].Pointer); } [Fact] @@ -103,8 +103,8 @@ public void ACloseTimeoutPastTheTimerCeilingFailsTheStartWithItsOwnPointer() // The pointer must name the field the document actually wrote. A shared checker that // reported idleTimeoutSeconds for both would send a reader to the wrong line. var failure = Assert.Throws( - () => TelnyxRelayCallAdapter.BuildOptions(Entry(close: 5_000_000))); + () => TelnyxRelayConversationAdapter.BuildOptions(Entry(close: 5_000_000))); - Assert.Equal("/providers/call/closeTimeoutSeconds", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation/closeTimeoutSeconds", failure.Errors[0].Pointer); } } diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallRegistrationTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationRegistrationTests.cs similarity index 74% rename from tests/AgentCore.AspNetCore.Tests/Call/CallRegistrationTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/ConversationRegistrationTests.cs index 4a430a6d..b3b6107d 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallRegistrationTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationRegistrationTests.cs @@ -9,10 +9,10 @@ using Microsoft.Extensions.Hosting; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// -/// providers.call is selected while the host starts, and the pairing rule runs there too. +/// providers.conversation is selected while the host starts, and the pairing rule runs there too. /// /// /// @@ -22,14 +22,14 @@ namespace AgentCore.AspNetCore.Tests.Call; /// or false whether or not anything is ever routed. /// /// -/// Every test runs offline against a fake model. There is no Telnyx account, no network call, and +/// Every test runs offline against a fake model. There is no Telnyx account, no network conversation, and /// no API key anywhere in this file. /// /// -public sealed class CallRegistrationTests +public sealed class ConversationRegistrationTests { - /// A call transport that is a name and a wire fact, which is all the port asks for. - private sealed class FakeCallAdapter(string kind, bool carriesText) : ICallAdapter + /// A conversation transport that is a name and a wire fact, which is all the port asks for. + private sealed class FakeConversationAdapter(string kind, bool carriesText) : IConversationAdapter { public string Kind { get; } = kind; @@ -40,11 +40,11 @@ private sealed class FakeCallAdapter(string kind, bool carriesText) : ICallAdapt public async Task AMatchingPairStarts() { using var provider = await BuildAsync( - callKind: "telnyx-relay", + conversationKind: "telnyx-relay", speechKind: "telnyx-relay", - new FakeCallAdapter("telnyx-relay", carriesText: true)); + new FakeConversationAdapter("telnyx-relay", carriesText: true)); - Assert.NotNull(provider.Services.GetService>()); + Assert.NotNull(provider.Services.GetService>()); } [Fact] @@ -52,33 +52,33 @@ public async Task AMismatchedPairFailsTheStartEvenWithNoRouteMapped() { var failure = await Assert.ThrowsAsync( async () => await BuildAsync( - callKind: "telnyx-relay", + conversationKind: "telnyx-relay", speechKind: "deepgram", - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); Assert.Equal("/providers/speech/stt/kind", failure.Errors[0].Pointer); } [Fact] - public async Task AHostThatRegistersNoCallAdapterIsNotAskedAnything() + public async Task AHostThatRegistersNoConversationAdapterIsNotAskedAnything() { // The seam is off, exactly as telemetry, knowledge, and moderation are when nothing is // registered for them. A contradictory document is not read, and the start succeeds. - using var provider = await BuildAsync(callKind: "telnyx-relay", speechKind: "deepgram"); + using var provider = await BuildAsync(conversationKind: "telnyx-relay", speechKind: "deepgram"); - Assert.Null(provider.Services.GetService>()); + Assert.Null(provider.Services.GetService>()); } [Fact] - public async Task ADocumentNamingAnUnregisteredCallKindFailsTheStart() + public async Task ADocumentNamingAnUnregisteredConversationKindFailsTheStart() { var failure = await Assert.ThrowsAsync( async () => await BuildAsync( - callKind: "sip", + conversationKind: "sip", speechKind: "sip", - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); - Assert.Equal("/providers/call/kind", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation/kind", failure.Errors[0].Pointer); } // --------------------------------------------------------------------------------------------- @@ -89,7 +89,7 @@ public async Task ADocumentNamingAnUnregisteredCallKindFailsTheStart() // by a message that names the block rather than by a NullReferenceException. // --------------------------------------------------------------------------------------------- [Fact] - public async Task AConfigurationBuiltInCodeWithNoCallBlockFailsTheStart() + public async Task AConfigurationBuiltInCodeWithNoConversationBlockFailsTheStart() { var failure = await Assert.ThrowsAsync( async () => await BuildFromAsync( @@ -102,9 +102,9 @@ public async Task AConfigurationBuiltInCodeWithNoCallBlockFailsTheStart() Tts = new VendorProviderConfiguration { Kind = "telnyx-relay" }, }, }), - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); - Assert.Equal("/providers/call", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation", failure.Errors[0].Pointer); } [Fact] @@ -115,9 +115,9 @@ public async Task AConfigurationBuiltInCodeWithNoSpeechBlockFailsTheStart() InCode(new ProvidersConfiguration { Llm = OneModel, - Call = new CallProviderConfiguration { Kind = "telnyx-relay" }, + Conversation = new ConversationProviderConfiguration { Kind = "telnyx-relay" }, }), - new FakeCallAdapter("telnyx-relay", carriesText: true))); + new FakeConversationAdapter("telnyx-relay", carriesText: true))); Assert.Equal("/providers/speech", failure.Errors[0].Pointer); } @@ -131,14 +131,14 @@ public async Task AConfigurationBuiltInCodeWithNoSpeechBlockFailsTheStart() [new LlmProviderConfiguration { Kind = "openai", Model = "gpt-4.1-mini", As = "reply" }]; /// Writes one document that names both required blocks. - /// The value providers.call.kind carries. + /// The value providers.conversation.kind carries. /// The value both speech roles carry, stt and tts alike. /// The document text. - private static string Document(string callKind, string speechKind) + private static string Document(string conversationKind, string speechKind) => $$""" apiVersion: agentcore/v1 providers: - call: { kind: {{callKind}} } + conversation: { kind: {{conversationKind}} } speech: stt: { kind: {{speechKind}} } tts: { kind: {{speechKind}} } @@ -171,28 +171,28 @@ private static AgentCoreConfiguration InCode(ProvidersConfiguration providers) }; /// Starts a host on a document that names both kinds. - /// The value providers.call.kind carries. + /// The value providers.conversation.kind carries. /// The value both speech roles carry, stt and tts alike. - /// The call transports this host registers, if any. + /// The conversation transports this host registers, if any. /// The composed container. private static Task BuildAsync( - string callKind, + string conversationKind, string speechKind, - params ICallAdapter[] adapters) - => BuildFromAsync(ConfigurationLoader.LoadYaml(Document(callKind, speechKind)), adapters); + params IConversationAdapter[] adapters) + => BuildFromAsync(ConfigurationLoader.LoadYaml(Document(conversationKind, speechKind)), adapters); /// Starts a host on one configuration, however that configuration was made. /// The document, loaded or built in code. - /// The call transports this host registers, if any. + /// The conversation transports this host registers, if any. /// The composed container. /// - /// UseCall is called only when this host has something to register. Calling it with an + /// UseConversation is called only when this host has something to register. Calling it with an /// empty list would turn the seam on for a host that registered no vendor, which is the one /// thing these tests prove does not happen. /// private static async Task BuildFromAsync( AgentCoreConfiguration configuration, - params ICallAdapter[] adapters) + params IConversationAdapter[] adapters) { HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); @@ -204,7 +204,7 @@ private static async Task BuildFromAsync( if (adapters.Length > 0) { - options.UseCall(adapters); + options.UseConversation(adapters); } }); diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationRouteSelectionTests.cs similarity index 70% rename from tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/ConversationRouteSelectionTests.cs index 0739e800..4f88664d 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallRouteSelectionTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationRouteSelectionTests.cs @@ -1,7 +1,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.DependencyInjection.Startup; using Microsoft.AspNetCore.Builder; @@ -13,10 +13,10 @@ using Microsoft.Extensions.Logging; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// -/// providers.call decides which transport answers the one call route, and whether a call +/// providers.conversation decides which transport answers the one conversation route, and whether a conversation /// routes here at all. /// /// @@ -27,27 +27,27 @@ namespace AgentCore.AspNetCore.Tests.Call; /// /// /// The selection happens while the host starts and not while the route is mapped, so these read -/// rather than MapCall. A host maps its routes on a built +/// rather than MapCall. A host maps its routes on a built /// application, which is after the document has been read; deciding there would mean a document /// edit could silently leave the path a 404. /// /// -/// Every test runs offline. There is no account, no network call, and no API key anywhere in this +/// Every test runs offline. There is no account, no network conversation, and no API key anywhere in this /// file. /// /// -public sealed class CallRouteSelectionTests +public sealed class ConversationRouteSelectionTests { [Fact] public void TheTransportTheDocumentNamesIsAskedForItsHandler() { var transport = new FakeTransport("bundled-fake"); - var seams = Build(callKind: "bundled-fake", transport); + var seams = Build(conversationKind: "bundled-fake", transport); Assert.NotNull(seams.Handler); - // The block handed over is the providers.call entry of this document, not null and not some + // The block handed over is the providers.conversation entry of this document, not null and not some // empty stand-in. The kind is what proves which entry it is. Assert.NotNull(transport.Configuration); Assert.Equal("bundled-fake", transport.Configuration.Kind); @@ -60,18 +60,18 @@ public void TheTransportTheDocumentNamesIsAskedForItsHandler() public void AKindNoRegisteredAdapterServesFailsTheStartWithAPointer() { // The host registers a transport, and the document names a different vendor. That is a - // deployment that would otherwise start with no inbound call route and no reason given, so + // deployment that would otherwise start with no inbound conversation route and no reason given, so // the boot must refuse it, with the pointer of the field the reader has to fix. var failure = Assert.Throws( - () => Build(callKind: "no-such-vendor", new FakeTransport("bundled-fake"))); + () => Build(conversationKind: "no-such-vendor", new FakeTransport("bundled-fake"))); - Assert.Equal("/providers/call/kind", failure.Errors[0].Pointer); + Assert.Equal("/providers/conversation/kind", failure.Errors[0].Pointer); } [Fact] public void ADialOutVendorRoutesNothingAndSaysWhy() { - var seams = Build(callKind: "dial-out-fake", new FakeDialOut("dial-out-fake")); + var seams = Build(conversationKind: "dial-out-fake", new FakeDialOut("dial-out-fake")); // Section 12 asks this case to route nothing AND say so. A route that vanishes in silence is // how a deployment loses every call to a 404 with nothing to read. @@ -83,12 +83,12 @@ public void ADialOutVendorRoutesNothingAndSaysWhy() [Fact] public void AHostThatRegisteredNoTransportRoutesNothingAndSaysWhy() { - var seams = CallSeamStartup.Build( + var seams = ConversationSeamStartup.Build( ConfigurationLoader.LoadYaml(Document("bundled-fake")), new AgentCoreOptions()); Assert.Null(seams.Handler); Assert.NotNull(seams.Unroutable); - Assert.Contains("no call adapter", seams.Unroutable, StringComparison.Ordinal); + Assert.Contains("no conversation adapter", seams.Unroutable, StringComparison.Ordinal); } [Fact] @@ -116,7 +116,7 @@ await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken), [Fact] public void TheDefaultPatternIsVendorNeutral() { - Assert.Equal("/v1/{entry}/call", CallEndpointRouteBuilderExtensions.DefaultPattern); + Assert.Equal("/v1/{entry}/call", ConversationEndpointRouteBuilderExtensions.DefaultPattern); } [Fact] @@ -125,7 +125,7 @@ public void ARouteWithNoEntryParameterIsRefused() var builder = WebApplication.CreateSlimBuilder(); using var app = builder.Build(); - var failure = Assert.Throws(() => app.MapCall("/v1/call")); + var failure = Assert.Throws(() => app.MapCall("/v1/conversation")); Assert.Contains("{entry}", failure.Message, StringComparison.Ordinal); } @@ -134,17 +134,17 @@ public void ARouteWithNoEntryParameterIsRefused() // Helpers. // --------------------------------------------------------------------------------------------- - /// Runs the call seam over one document and the adapters a host registered. - /// The value providers.call.kind carries. - /// The call vendors this host registers. + /// Runs the conversation seam over one document and the adapters a host registered. + /// The value providers.conversation.kind carries. + /// The conversation vendors this host registers. /// What the seam produced. - private static CallSeamAdapters Build(string callKind, params ICallAdapter[] adapters) + private static ConversationSeamAdapters Build(string conversationKind, params IConversationAdapter[] adapters) { AgentCoreOptions options = new(); - options.UseCall(adapters); - options.UseSpeech(new FakeSpeech(callKind)); + options.UseConversation(adapters); + options.UseSpeech(new FakeSpeech(conversationKind)); - return CallSeamStartup.Build(ConfigurationLoader.LoadYaml(Document(callKind)), options); + return ConversationSeamStartup.Build(ConfigurationLoader.LoadYaml(Document(conversationKind)), options); } /// Reads back the port the server bound, since the test asked for any free one. @@ -159,22 +159,22 @@ private static string Address(WebApplication app) .First(); /// Writes one document that names both blocks section 8.2 requires of one another. - /// The value providers.call.kind carries. + /// The value providers.conversation.kind carries. /// The document text. /// /// Written line by line here rather than at each call site, because the block sits under - /// providers: and YAML indentation written by hand at a call site is how test documents - /// go wrong. speech names the same kind as call because the schema requires the + /// providers: and YAML indentation written by hand at a conversation site is how test documents + /// go wrong. speech names the same kind as conversation because the schema requires the /// block to exist; nothing in this file selects a speech vendor. /// - private static string Document(string callKind) + private static string Document(string conversationKind) => $$""" apiVersion: agentcore/v1 providers: - call: { kind: {{callKind}} } + conversation: { kind: {{conversationKind}} } speech: - stt: { kind: {{callKind}} } - tts: { kind: {{callKind}} } + stt: { kind: {{conversationKind}} } + tts: { kind: {{conversationKind}} } llm: - { kind: openai, model: gpt-4.1-mini, as: reply } agents: @@ -185,21 +185,21 @@ private static string Document(string callKind) agent: dummy """; - /// A transport that answers a call and names no vendor. + /// A transport that answers a conversation and names no vendor. /// /// It records the block the seam is supposed to hand it. Recording only that /// CreateHandler ran would let a seam that resolved the document block to something other /// than the one the reader wrote still pass. /// - private sealed class FakeTransport(string kind) : ICallTransportAdapter + private sealed class FakeTransport(string kind) : IConversationTransportAdapter { public string Kind { get; } = kind; public bool CarriesText => true; - public CallProviderConfiguration? Configuration { get; private set; } + public ConversationProviderConfiguration? Configuration { get; private set; } - public RequestDelegate CreateHandler(CallProviderConfiguration configuration) + public RequestDelegate CreateHandler(ConversationProviderConfiguration configuration) { Configuration = configuration; return _ => Task.CompletedTask; @@ -207,7 +207,7 @@ public RequestDelegate CreateHandler(CallProviderConfiguration configuration) } /// A vendor this process dials out to. It has no route to answer. - private sealed class FakeDialOut(string kind) : ICallAdapter + private sealed class FakeDialOut(string kind) : IConversationAdapter { public string Kind { get; } = kind; diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationTurnArbiterTests.cs similarity index 89% rename from tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/ConversationTurnArbiterTests.cs index 6dff2b74..22e384d6 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/ConversationTurnArbiterTests.cs @@ -1,26 +1,26 @@ using System.Runtime.CompilerServices; using System.Text.Json; using AgentCore.Application.Ports; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.Tests.Fakes; using AgentCore.Domain; using AgentCore.Domain.Knowledge; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// /// The three questions the arbiter answers, with no socket and no vendor frame in sight. /// -public sealed class CallTurnArbiterTests +public sealed class ConversationTurnArbiterTests { [Fact(Timeout = 30_000)] public async Task ASecondUtteranceDuringATurn_IsHeldAndRunsWhenTheTurnEnds() { // One is held. The turn in flight finishes, and the held one runs inside its own ending. var session = new ScriptedConversationPort(); - var output = new FakeCallOutput(); + var output = new FakeConversationOutput(); var arbiter = NewArbiter(session, output); var first = arbiter.StartTurnAsync("one"); @@ -36,15 +36,15 @@ public async Task ASecondUtteranceDuringATurn_IsHeldAndRunsWhenTheTurnEnds() [Fact(Timeout = 30_000)] public async Task APendingApprovalTurn_SpeaksTheNoticeInsteadOfHangingInSilence() { - // A voice call has no surface to answer an approval on, so the pending turn speaks + // A voice conversation has no surface to answer an approval on, so the pending turn speaks // nothing. The arbiter says so instead of closing the reply in silence. var session = new ScriptedConversationPort(); - var output = new FakeCallOutput(); + var output = new FakeConversationOutput(); var arbiter = NewArbiter(session, output); session.ReleaseTurn(); using var empty = JsonDocument.Parse("{}"); - session.LastTurn = new TurnResult("call-scripted", 0, string.Empty, string.Empty, string.Empty, false, null) + session.LastTurn = new TurnResult("conversation-scripted", 0, string.Empty, string.Empty, string.Empty, false, null) { Approvals = [new PendingApproval("req-1", "send_email", empty.RootElement.Clone())], }; @@ -52,7 +52,7 @@ public async Task APendingApprovalTurn_SpeaksTheNoticeInsteadOfHangingInSilence( await arbiter.StartTurnAsync("one"); await arbiter.CurrentTurn; - Assert.Contains(CallTurnArbiter.PendingApprovalNotice, output.Spoken); + Assert.Contains(ConversationTurnArbiter.PendingApprovalNotice, output.Spoken); } [Fact(Timeout = 30_000)] @@ -60,7 +60,7 @@ public async Task AThirdUtteranceDuringATurn_IsDroppedRatherThanQueued() { // A queue of held prompts would answer questions the caller has already moved past. var session = new ScriptedConversationPort(); - var output = new FakeCallOutput(); + var output = new FakeConversationOutput(); var arbiter = NewArbiter(session, output); var first = arbiter.StartTurnAsync("one"); @@ -80,7 +80,7 @@ public async Task ABargeInDuringTheHeldPromptWindow_CutsTheTurnTheCallerWasHeari // Turn one finished streaming and turn two started inside its ending, but the caller is // still hearing turn one. The record belongs to turn one, and turn two must keep speaking. var session = new ScriptedConversationPort(); - var output = new FakeCallOutput(); + var output = new FakeConversationOutput(); var arbiter = NewArbiter(session, output); // Opened before the first turn, not during it: this test needs turn one to finish streaming @@ -111,7 +111,7 @@ public async Task ABargeInWhileTheHeldTurnHasSaidNothing_BelongsToTheTurnTheCall // hearing turn one. cutsRunningTurn must answer false there — turn two is not the turn to // cut, and it must keep speaking — and true once turn two is itself what the caller heard. var session = new ScriptedConversationPort(); - var output = new FakeCallOutput(); + var output = new FakeConversationOutput(); var arbiter = NewArbiter(session, output); var first = arbiter.StartTurnAsync("one"); @@ -140,14 +140,14 @@ public async Task ABargeInWhileTheHeldTurnHasSaidNothing_BelongsToTheTurnTheCall } [Fact(Timeout = 30_000)] - public async Task ASecondCallNamedMidTurn_StillHoldsTheNextUtteranceBehindTheTurnInFlight() + public async Task ASecondConversationNamedMidTurn_StillHoldsTheNextUtteranceBehindTheTurnInFlight() { - // One transport runs one turn at a time, and a vendor that names the call a second time + // One transport runs one turn at a time, and a vendor that names the conversation a second time // does not get to start a second reply alongside the first. The prompt that arrives after - // the rename is held, and it runs against the call named last. + // the rename is held, and it runs against the conversation named last. var replaced = new ScriptedConversationPort(); var named = new ScriptedConversationPort(); - var output = new FakeCallOutput(); + var output = new FakeConversationOutput(); var arbiter = NewArbiter(replaced, output); var running = arbiter.StartTurnAsync("one"); @@ -166,11 +166,11 @@ public async Task ASecondCallNamedMidTurn_StillHoldsTheNextUtteranceBehindTheTur Assert.Equal(["two"], named.TurnsRun); } - private static CallTurnArbiter NewArbiter(ScriptedConversationPort session, FakeCallOutput output) + private static ConversationTurnArbiter NewArbiter(ScriptedConversationPort session, FakeConversationOutput output) => new( session, output, - new ConnectionTaskObserver(() => session.CallId, (_, _) => { }, (_, _, _) => { }, (_, _, _) => false), + new ConnectionTaskObserver(() => session.ConversationId, (_, _) => { }, (_, _, _) => { }, (_, _, _) => false), _ => { }, _ => { }, CancellationToken.None); @@ -194,7 +194,7 @@ internal sealed class ScriptedConversationPort : IConversationPort private int _turnsStarted; /// - public string CallId => "call-scripted"; + public string ConversationId => "conversation-scripted"; /// public string Stage => string.Empty; diff --git a/tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs b/tests/AgentCore.AspNetCore.Tests/Conversation/TelnyxRelayThroughTheConversationSeamTests.cs similarity index 65% rename from tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs rename to tests/AgentCore.AspNetCore.Tests/Conversation/TelnyxRelayThroughTheConversationSeamTests.cs index cd5577f2..08438310 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/TelnyxRelayThroughTheCallSeamTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Conversation/TelnyxRelayThroughTheConversationSeamTests.cs @@ -1,22 +1,22 @@ using AgentCore.TestSupport; using System.Net; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.Tests.Fakes; using AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; using AgentCore.AspNetCore.Vendors.TelnyxRelay; using Xunit; -namespace AgentCore.AspNetCore.Tests.Call; +namespace AgentCore.AspNetCore.Tests.Conversation; /// /// The one place the shipped vendor and the vendor-neutral route meet in a running host. /// /// /// -/// CallRouteSelectionTests proves the selection over fakes and names no vendor, which is -/// spec §12. CallOptionsFromDocumentTests proves -/// TelnyxRelayCallAdapter.BuildOptions over a document. Neither of them runs -/// TelnyxRelayCallAdapter.Map, and that method is the single executable line joining the +/// ConversationRouteSelectionTests proves the selection over fakes and names no vendor, which is +/// spec §12. ConversationOptionsFromDocumentTests proves +/// TelnyxRelayConversationAdapter.BuildOptions over a document. Neither of them runs +/// TelnyxRelayConversationAdapter.Map, and that method is the single executable line joining the /// shipped vendor to the seam. This file is where it runs. /// /// @@ -24,25 +24,25 @@ namespace AgentCore.AspNetCore.Tests.Call; /// exists to prove, and a version of it written over a fake would prove nothing new. /// /// -/// It runs offline against a fake model. There is no Telnyx account, no network call, and no API +/// It runs offline against a fake model. There is no Telnyx account, no network conversation, and no API /// key here. /// /// -public sealed class TelnyxRelayThroughTheCallSeamTests +public sealed class TelnyxRelayThroughTheConversationSeamTests { [Fact(Timeout = 30_000)] public async Task APlainGetToTheVendorNeutralRoute_ReachesTheRelayHandler() { using FragmentingChatClient reply = new("hello"); - // The host names no vendor at the route. providers.call: { kind: telnyx-relay } is what + // The host names no vendor at the route. providers.conversation: { kind: telnyx-relay } is what // picks this adapter, and app.MapCall() is what asks. - await using var host = await TelnyxRelayHost.StartThroughCallSeamAsync( + await using var host = await TelnyxRelayHost.StartThroughConversationSeamAsync( TelnyxRelayTurnTests.PolicyYaml, reply, - options => options.UseCall(new TelnyxRelayCallAdapter())); + options => options.UseConversation(new TelnyxRelayConversationAdapter())); - var answer = await host.GetAsync(TelnyxRelayHost.MainCall); + var answer = await host.GetAsync(TelnyxRelayHost.MainConversation); // 404 would mean MapCall mapped nothing, and every call to this deployment would be lost // with nothing to read. 400 is the relay's own HandleAsync refusing a request that is not a diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index c0fceb59..4876502a 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -14,8 +14,8 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Secrets; using AgentCore.Application.Tools; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Transcript; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.Sessions; @@ -40,25 +40,25 @@ namespace AgentCore.AspNetCore.Tests.DependencyInjection; /// The composition root. It loads, validates, resolves, compiles, and registers, in that order. /// /// -/// A configuration defect stops the host at start and never on the first call. Every test proves +/// A configuration defect stops the host at start and never on the first conversation. Every test proves /// that by starting a host and nothing else, with no request anywhere. /// public sealed class AddAgentCoreTests { - /// The call and speech providers every document below shares. - private const string SpeechAndCall = + /// The conversation and speech providers every document below shares. + private const string SpeechAndConversation = """ providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } """; - /// plus the single reply model most documents declare. + /// plus the single reply model most documents declare. private const string MinimalProviders = $$""" - {{SpeechAndCall}} + {{SpeechAndConversation}} llm: - { kind: openai, model: gpt-4.1-mini, as: reply } """; @@ -113,7 +113,7 @@ public sealed class AddAgentCoreTests agents: items: - { id: only, instructions: "I answer everything" } - {{SpeechAndCall}} + {{SpeechAndConversation}} llm: - { kind: anthropic, model: claude-sonnet-5, as: reply } entries: @@ -183,7 +183,7 @@ public sealed class AddAgentCoreTests """; // Row 4 of the section 8.2 compile table, with a guarded edge on each exit of the start node. - // Check 5 proves the two guards exclusive, so exactly one edge fires for each call. + // Check 5 proves the two guards exclusive, so exactly one edge fires for each conversation. private const string GuardedGraphYaml = $$""" apiVersion: agentcore/v1 @@ -208,7 +208,7 @@ public sealed class AddAgentCoreTests - { from: route, to: escalated, when: wants_human } - { from: route, to: handled, when: stays_with_bot } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -374,23 +374,23 @@ public async Task AddAgentCore_RegistersTheCompiledAgentAsAProcessSingleton() Assert.Same(first, second); Assert.Equal("main", first.Name); - // The registry compiled once, and every call shares that one result. + // The registry compiled once, and every conversation shares that one result. Assert.Equal(1, provider.GetRequiredService().CompileCount); } [Fact] - public async Task AddAgentCore_RegistersOneSessionFactoryThatBuildsANewSessionForEachCall() + public async Task AddAgentCore_RegistersOneSessionFactoryThatBuildsANewSessionForEachConversation() { using var provider = await BuildAsync(OneAgentYaml); var factory = provider.GetRequiredService().ForFactory("main"); Assert.Same(factory, provider.GetRequiredService().ForFactory("main")); - // A CallSession belongs to one call, so it is not a singleton and the container holds none. + // A ConversationSession belongs to one conversation, so it is not a singleton and the container holds none. var first = factory.Create(); var second = factory.Create(); Assert.NotSame(first, second); - Assert.NotEqual(first.CallId, second.CallId); + Assert.NotEqual(first.ConversationId, second.ConversationId); } [Fact] @@ -439,10 +439,10 @@ public async Task AddAgentCore_RegistersTheAgentShimAsAProcessSingleton() Assert.Same(agent, provider.GetRequiredService().ForAgent("main")); Assert.Equal("main", agent.Name); - // One session of the shim is one call, drawn from the same factory the rest of the host - // uses, so the two seams describe the same calls. + // One session of the shim is one conversation, drawn from the same factory the rest of the host + // uses, so the two seams describe the same conversations. var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - Assert.NotNull(session.GetService()); + Assert.NotNull(session.GetService()); } [Fact] @@ -452,7 +452,7 @@ public async Task AddAgentCore_RegistersTheInMemorySessionsByDefault() var sessions = provider.GetRequiredService().ForSessions("main"); - Assert.IsType(sessions); + Assert.IsType(sessions); Assert.Same(sessions, provider.GetRequiredService().ForSessions("main")); } @@ -460,12 +460,12 @@ public async Task AddAgentCore_RegistersTheInMemorySessionsByDefault() public async Task AddAgentCore_RunsTheIdleSweepForTheDefaultSessions() { // Expiry needs something to drive it. Without this the idle timeout never fires and the - // text path holds every call a caller walked away from for the life of the process. + // text path holds every conversation a caller walked away from for the life of the process. using var provider = await BuildAsync(OneAgentYaml); Assert.Contains( provider.GetServices(), - service => service is CallSessionSweeper); + service => service is ConversationSessionSweeper); } /// @@ -491,10 +491,10 @@ public void AServiceReadFromAProviderNobodyStarted_RefusesAndSaysWhatToDo() [Fact] public async Task AddAgentCore_UsesTheSessionsTheHostBound() { - CountingCallSessions mine = new(); + CountingConversationSessions mine = new(); using var provider = await BuildAsync( - OneAgentYaml, options => options.UseCallSessions((_, _) => mine)); + OneAgentYaml, options => options.UseConversationSessions((_, _) => mine)); // A distributed store replaces the default one, and the default steps aside. Assert.Same(mine, provider.GetRequiredService().ForSessions("main")); @@ -503,19 +503,19 @@ public async Task AddAgentCore_UsesTheSessionsTheHostBound() [Fact] public async Task AddAgentCore_OpensOneStorePerEntry() { - // A vendor call id arriving on two entries opens two isolated calls. That holds only when + // A vendor call id arriving on two entries opens two isolated conversations. That holds only when // each entry has its own store, so the host's opener runs once per entry and is told which. List opened = []; - using var provider = await BuildAsync(TwoEntryYaml, options => options.UseCallSessions( + using var provider = await BuildAsync(TwoEntryYaml, options => options.UseConversationSessions( (entry, factory) => { opened.Add(entry); - return new InMemoryCallSessions( - factory, InMemoryCallSessions.DefaultIdleTimeout, TimeProvider.System); + return new InMemoryConversationSessions( + factory, InMemoryConversationSessions.DefaultIdleTimeout, TimeProvider.System); })); - var registry = provider.GetRequiredService(); + var registry = provider.GetRequiredService(); Assert.Equal(["main", "other"], opened.Order(StringComparer.Ordinal)); Assert.NotSame(registry.ForSessions("main"), registry.ForSessions("other")); @@ -525,16 +525,16 @@ public async Task AddAgentCore_OpensOneStorePerEntry() public async Task AddAgentCore_RegistersTheSessionRegistryAsAPublicPort() { // A consumer reaches an entry's store through the port, never through the internal - // registry, and never through a bare ICallSessions: no store spans the whole host. + // registry, and never through a bare IConversationSessions: no store spans the whole host. using var provider = await BuildAsync(OneAgentYaml); - var registry = provider.GetRequiredService(); + var registry = provider.GetRequiredService(); Assert.Equal(["main"], registry.Entries); Assert.Same( provider.GetRequiredService().ForSessions("main"), registry.ForSessions("main")); - Assert.Null(provider.GetService()); + Assert.Null(provider.GetService()); var failure = Assert.Throws(() => registry.ForSessions("missing")); Assert.Contains("main", failure.Message, StringComparison.Ordinal); @@ -642,14 +642,14 @@ await host.Services } [Fact] - public async Task AddAgentCore_ClosesTheCallStoreWhenTheHostShutsDown() + public async Task AddAgentCore_ClosesTheConversationStoreWhenTheHostShutsDown() { - RecordingCallStore store = new(); + RecordingConversationStore store = new(); HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); ConfigureServices( builder.Services, VendorTranscriptYaml, - options => options.UseCallStores(new TestCallStoreAdapter(store))); + options => options.UseConversationStores(new TestConversationStoreAdapter(store))); IHost host = builder.Build(); await host.StartAsync(TestContext.Current.CancellationToken); @@ -665,7 +665,7 @@ public async Task AddAgentCore_ClosesTheKnowledgePortWhenTheHostShutsDown() // KnowledgeStartup.OpenAsync's result used to be discarded with `_ = await ...`, so a // successful open -- a QdrantClient in production -- was never tracked against the boot and // outlived host shutdown. This proves the port the adapter built is closed the same way the - // call store above is. + // conversation store above is. DisposeTrackingKnowledgeAdapter adapter = new(); HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); ConfigureServices( @@ -863,7 +863,7 @@ public async Task AGuardedGraph_Starts() [Theory] [InlineData(true, "ESCALATED", "HANDLED")] [InlineData(false, "HANDLED", "ESCALATED")] - public async Task AGuardedGraph_TakesTheEdgeTheStateOfTheCallNames(bool escalate, string taken, string refused) + public async Task AGuardedGraph_TakesTheEdgeTheStateOfTheConversationNames(bool escalate, string taken, string refused) { using var provider = await BuildGuardedGraphAsync(); var session = provider.GetRequiredService().ForFactory("main").Create(); @@ -876,7 +876,7 @@ public async Task AGuardedGraph_TakesTheEdgeTheStateOfTheCallNames(bool escalate } [Fact] - public async Task AGuardedGraph_KeepsTwoCallsApartWhenTheyRunAtTheSameTime() + public async Task AGuardedGraph_KeepsTwoConversationsApartWhenTheyRunAtTheSameTime() { using var provider = await BuildGuardedGraphAsync(); var sessions = provider.GetRequiredService().ForFactory("main"); @@ -887,7 +887,7 @@ public async Task AGuardedGraph_KeepsTwoCallsApartWhenTheyRunAtTheSameTime() var handled = sessions.Create(); handled.State.TryWrite("escalate", false); - // One compiled graph, two calls, two edges. Neither call reads the state of the other. + // One compiled graph, two conversations, two edges. Neither conversation reads the state of the other. var turns = await Task.WhenAll( escalated.RunTurnAsync("hello", token), handled.RunTurnAsync("hello", token)); @@ -913,7 +913,7 @@ public async Task AddAgentCore_RegistersTheEvaluationSeamWithTheOnlinePathClosed Assert.True(registry.Contains("fault_code")); // T18: a judge must never block a turn, and the offline gate has not proved the evaluators - // yet. A rate of 0 draws no number and calls nothing. + // yet. A rate of 0 draws no number and conversations nothing. Assert.Equal(0, sampler.Rate); Assert.False(sampler.ShouldSample()); @@ -1015,7 +1015,7 @@ public async Task AddAgentCore_RefusesATurnTheDocumentsModerationVendorFlags() ModeratedYaml, options => options.UseModeration(new FakeModerationAdapter("test", new AlwaysFlagsEvaluator()))); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); var result = await session.RunTurnAsync("...", TestContext.Current.CancellationToken); // The wiring reaches the turn loop, and not only the registry. @@ -1047,7 +1047,7 @@ public async Task AQuietTurn_SpeaksTheFallbackTheDocumentNames() var turn = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); Assert.Equal("One moment please. I will try that again.", turn.ReplyText); - Assert.NotEqual(CallSession.FallbackReply, turn.ReplyText); + Assert.NotEqual(ConversationSession.FallbackReply, turn.ReplyText); } [Fact] @@ -1059,7 +1059,7 @@ public async Task AQuietTurn_SpeaksTheDefaultFallbackWhenTheDocumentNamesNone() var turn = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); - Assert.Equal(CallSession.FallbackReply, turn.ReplyText); + Assert.Equal(ConversationSession.FallbackReply, turn.ReplyText); } [Fact] @@ -1078,7 +1078,7 @@ public async Task AddAgentCore_KeepsAnEvaluationServiceTheHostRegisteredFirst() } // ------------------------------------------------------------------------------------------- - // The call titler: one model, named by the document like every other model. + // The conversation titler: one model, named by the document like every other model. // ------------------------------------------------------------------------------------------- // The same agent, and a document that gives the titler a model of its own. @@ -1103,9 +1103,9 @@ public async Task AddAgentCore_GivesTheTitlerTheModelTheDocumentNames() RecordingChatClientFactory factory = new(); using var provider = await BuildAsync(TitlerYaml, options => options.UseChatClients(_ => factory)); - var titler = provider.GetRequiredService(); + var titler = provider.GetRequiredService(); - Assert.IsType(titler); + Assert.IsType(titler); Assert.Equal("titles", factory.Asked?.Ref); } @@ -1115,7 +1115,7 @@ public async Task AddAgentCore_GivesTheTitlerTheDefaultModelWhenTheDocumentNames RecordingChatClientFactory factory = new(); using var provider = await BuildAsync(OneAgentYaml, options => options.UseChatClients(_ => factory)); - provider.GetRequiredService(); + provider.GetRequiredService(); // A null reference is how the factory is asked for the first declared entry. Assert.Null(factory.Asked); @@ -1124,21 +1124,21 @@ public async Task AddAgentCore_GivesTheTitlerTheDefaultModelWhenTheDocumentNames [Fact] public async Task AddAgentCore_KeepsATitlerTheHostRegisteredFirst() { - SilentCallTitler mine = new(); + SilentConversationTitler mine = new(); HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); - builder.Services.AddSingleton(mine); + builder.Services.AddSingleton(mine); ConfigureServices(builder.Services, TitlerYaml, null); using var provider = await StartAsync(builder.Build()); - Assert.Same(mine, provider.GetRequiredService()); + Assert.Same(mine, provider.GetRequiredService()); } /// A titler that names nothing, for the test that only asks who won the registration. - private sealed class SilentCallTitler : ICallTitler + private sealed class SilentConversationTitler : IConversationTitler { public async IAsyncEnumerable GenerateAsync( - string callId, + string conversationId, [EnumeratorCancellation] CancellationToken cancellationToken = default) { await Task.CompletedTask; @@ -1146,7 +1146,7 @@ public async IAsyncEnumerable GenerateAsync( } public async IAsyncEnumerable GenerateFromAsync( - string callId, + string conversationId, IReadOnlyList messages, [EnumeratorCancellation] CancellationToken cancellationToken = default) { @@ -1192,16 +1192,16 @@ public async Task TheDefaultAuditSink_ReachesTheTurnLoopAndTheChainVerifies() { using var provider = await BuildAsync(OneAgentYaml); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); // The queue is what keeps the append off the turn, so the rows land on a thread of their own // and a reader that wants them now asks for them now. await Queue(provider).FlushAsync(TestContext.Current.CancellationToken); - var events = Sink(provider).EventsOf("call-1"); + var events = Sink(provider).EventsOf("conversation-1"); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted], events.Select(item => item.Kind).ToArray()); Assert.All(events, AuditEventVocabulary.Validate); } @@ -1212,7 +1212,7 @@ public async Task ADocumentThatNamesNoAuditProvider_StillOpensTheMemorySink() using var provider = await BuildAsync(OneAgentYaml); // The turn loop produces the events of D23 whatever a document says, so the seam that receives - // them has a working default rather than a null. That is what lets every reading of a call be + // them has a working default rather than a null. That is what lets every reading of a conversation be // unconditional, and what lets a first run and a test work with no database. Assert.NotNull(provider.GetService()); Assert.IsType(provider.GetRequiredService().Store); @@ -1236,7 +1236,7 @@ public async Task AnAuditVendorTheDocumentNames_IsTheStoreBehindTheQueue() VendorAuditYaml, options => options.UseAuditSinks(new TestAuditSinkAdapter(store))); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); await Queue(provider).FlushAsync(TestContext.Current.CancellationToken); @@ -1244,7 +1244,7 @@ public async Task AnAuditVendorTheDocumentNames_IsTheStoreBehindTheQueue() // seams beside it. Nothing but the document decides which store the chain lands in. Assert.Same(store, provider.GetRequiredService().Store); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted], store.Events.Select(item => item.Kind).ToArray()); } @@ -1252,7 +1252,7 @@ public async Task AnAuditVendorTheDocumentNames_IsTheStoreBehindTheQueue() public async Task AnAuditKindThisHostDoesNotRegister_FailsTheStart() { // A document that asked for something this host cannot give fails while the host starts, and - // never on a call. The message names the kind, exactly as every other vendor seam. + // never on a conversation. The message names the kind, exactly as every other vendor seam. var failure = await Assert.ThrowsAsync( () => BuildAsync(VendorAuditYaml)); @@ -1277,17 +1277,17 @@ private static QueuedAuditSink Queue(IServiceProvider provider) /// Reads back the store itself, which is registered under its own concrete type. /// /// The document builds the store now, not the host, so this is how a test that wants the events - /// of one call reaches the thing that holds them. Resolving gives the + /// of one conversation reaches the thing that holds them. Resolving gives the /// queue instead, because that is the only registration that honours the port's contract. /// private static InMemoryAuditSink Sink(IServiceProvider provider) => Assert.IsType(provider.GetRequiredService().Store); // ------------------------------------------------------------------------------------------- - // The transcript store: named by providers.calls, and never absent. + // The transcript store: named by providers.conversations, and never absent. // ------------------------------------------------------------------------------------------- - // The same agent, served by a call-store vendor the host registers itself. + // The same agent, served by a conversation-store vendor the host registers itself. private const string VendorTranscriptYaml = $$""" apiVersion: agentcore/v1 @@ -1295,7 +1295,7 @@ private static InMemoryAuditSink Sink(IServiceProvider provider) items: - { id: only, instructions: "I answer everything" } {{MinimalProviders}} - calls: { kind: test } + conversations: { kind: test } entries: main: agent: only @@ -1315,17 +1315,17 @@ private static InMemoryAuditSink Sink(IServiceProvider provider) agent: only """; - // The call store opens at step 4c and the moderation vendor is built at step 4c, so a + // The conversation store opens at step 4c and the moderation vendor is built at step 4c, so a // document that names both puts a failure strictly after an open. Nothing else in the boot has // that shape. - private const string CallStoreThenModerationFailureYaml = + private const string ConversationStoreThenModerationFailureYaml = $$""" apiVersion: agentcore/v1 agents: items: - { id: only, instructions: "I answer everything" } {{MinimalProviders}} - calls: { kind: test } + conversations: { kind: test } moderation: { kind: test } entries: main: @@ -1333,65 +1333,65 @@ private static InMemoryAuditSink Sink(IServiceProvider provider) """; [Fact] - public async Task ADocumentThatNamesNoCallStoreProvider_StillOpensTheMemoryStore() + public async Task ADocumentThatNamesNoConversationStoreProvider_StillOpensTheMemoryStore() { using var provider = await BuildAsync(OneAgentYaml); - // The turn loop writes the words of every call whatever a document says, so this seam has a + // The turn loop writes the words of every conversation whatever a document says, so this seam has a // working default rather than a null, and a first run needs no database. - Assert.NotNull(provider.GetService()); - Assert.IsType(provider.GetRequiredService().Store); + Assert.NotNull(provider.GetService()); + Assert.IsType(provider.GetRequiredService().Store); } [Fact] - public async Task ACallStoreVendorTheDocumentNames_IsTheStoreTheTurnWritesTo() + public async Task AConversationStoreVendorTheDocumentNames_IsTheStoreTheTurnWritesTo() { - RecordingCallStore store = new(); + RecordingConversationStore store = new(); using var provider = await BuildAsync( VendorTranscriptYaml, - options => options.UseCallStores(new TestCallStoreAdapter(store))); + options => options.UseConversationStores(new TestConversationStoreAdapter(store))); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); await session.FlushTranscriptAsync(); - // The host lists its vendors once and providers.calls.kind picks one. Nothing but the - // document decides where the words of a call land. - Assert.Same(store, provider.GetRequiredService().Store); + // The host lists its vendors once and providers.conversations.kind picks one. Nothing but the + // document decides where the words of a conversation land. + Assert.Same(store, provider.GetRequiredService().Store); Assert.Equal(["user", "assistant"], store.Roles); } [Fact] - public async Task ACallStoreKindThisHostDoesNotRegister_FailsTheStart() + public async Task AConversationStoreKindThisHostDoesNotRegister_FailsTheStart() { // A document that asked for something this host cannot give fails while the host starts, and - // never on a call. + // never on a conversation. var failure = await Assert.ThrowsAsync( () => BuildAsync(VendorTranscriptYaml)); Assert.Contains("test", failure.Message, StringComparison.Ordinal); } - /// A call-store vendor that hands over the store the test holds. - private sealed class TestCallStoreAdapter(RecordingCallStore store) : ICallStoreAdapter + /// A conversation-store vendor that hands over the store the test holds. + private sealed class TestConversationStoreAdapter(RecordingConversationStore store) : IConversationStoreAdapter { public string Kind => "test"; - public ValueTask OpenAsync( + public ValueTask OpenAsync( VendorProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default) - => ValueTask.FromResult(store); + => ValueTask.FromResult(store); } /// A store 1 backing that keeps the role of every row it accepted. /// - /// Keeps only , with no callId or ordinal, so it cannot rebuild a - /// to answer a read or an erase truthfully. and + /// Keeps only , with no conversationId or ordinal, so it cannot rebuild a + /// to answer a read or an erase truthfully. and /// report empty and 0 even after has recorded /// rows — a test that needs either should use a different double. /// - private sealed class RecordingCallStore() : DelegatingCallStore(new InMemoryCallStore()), IAsyncDisposable + private sealed class RecordingConversationStore() : DelegatingConversationStore(new InMemoryConversationStore()), IAsyncDisposable { private readonly Lock _gate = new(); private readonly List _roles = []; @@ -1411,10 +1411,10 @@ public IReadOnlyList Roles } } - public override ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, + public override ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, CancellationToken cancellationToken = default) { lock (_gate) @@ -1422,23 +1422,23 @@ public override ValueTask> AppendAsync( _roles.AddRange(messages.Select(message => message.Content.Role.Value)); } - IReadOnlyList rows = [.. messages.Select( - (message, index) => new CallMessage(callId, index, message.TurnIndex ?? 0, message.Content, message.MessageId))]; + IReadOnlyList rows = [.. messages.Select( + (message, index) => new ConversationMessage(conversationId, index, message.TurnIndex ?? 0, message.Content, message.MessageId))]; return ValueTask.FromResult(rows); } public override ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) => ValueTask.CompletedTask; - public override ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) + public override ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) { - IReadOnlyList rows = []; + IReadOnlyList rows = []; return ValueTask.FromResult(rows); } - public override ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) => + public override ValueTask EraseAsync(string conversationId, CancellationToken cancellationToken = default) => ValueTask.FromResult(0); public ValueTask DisposeAsync() @@ -1509,22 +1509,22 @@ public async Task NoLoggerAndNoAuditVendor_StillRunsATurn() } // ------------------------------------------------------------------------------------------- - // The host's own observers: the socket behind ICallObserver. + // The host's own observers: the socket behind IConversationObserver. // ------------------------------------------------------------------------------------------- [Fact] public async Task AHostObserver_ReadsTheFactsOfATurn() { - RecordingCallObserver first = new(); - RecordingCallObserver second = new(); + RecordingConversationObserver first = new(); + RecordingConversationObserver second = new(); using var provider = await BuildAsync(OneAgentYaml, options => options.UseObservers(first, second)); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // The port is public, so a host writes one of these and binds it. Every observer of a call + // The port is public, so a host writes one of these and binds it. Every observer of a conversation // reads the same facts, and the library's own three are neither replaced nor bypassed. - Assert.Equal([CallEventKind.CallStarted, CallEventKind.TurnCompleted], first.Seen); - Assert.Equal([CallEventKind.CallStarted, CallEventKind.TurnCompleted], second.Seen); + Assert.Equal([ConversationEventKind.ConversationStarted, ConversationEventKind.TurnCompleted], first.Seen); + Assert.Equal([ConversationEventKind.ConversationStarted, ConversationEventKind.TurnCompleted], second.Seen); } [Fact] @@ -1532,21 +1532,21 @@ public async Task AHostObserverThatThrows_CostsNeitherTheTurnNorTheChain() { using var provider = await BuildAsync( OneAgentYaml, - options => options.UseObservers(new ThrowingCallObserver())); + options => options.UseObservers(new ThrowingConversationObserver())); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); var turn = await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // An observer records the call and is never a part of it. That holds for the host's own, and + // An observer records the conversation and is never a part of it. That holds for the host's own, and // it holds for the readings registered beside it: a broken host observer does not cost the // chain of D23 a single row. Assert.Equal("hello", turn.ReplyText); await Queue(provider).FlushAsync(TestContext.Current.CancellationToken); - var events = Sink(provider).EventsOf("call-1"); + var events = Sink(provider).EventsOf("conversation-1"); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.TurnCompleted], + [AuditEventKind.ConversationStarted, AuditEventKind.TurnCompleted], events.Select(item => item.Kind).ToArray()); Assert.All(events, AuditEventVocabulary.Validate); } @@ -1554,13 +1554,13 @@ public async Task AHostObserverThatThrows_CostsNeitherTheTurnNorTheChain() [Fact] public async Task UseObserversTwice_KeepsBothRegistrations() { - RecordingCallObserver first = new(); - RecordingCallObserver second = new(); + RecordingConversationObserver first = new(); + RecordingConversationObserver second = new(); using var provider = await BuildAsync( OneAgentYaml, options => options.UseObservers(first).UseObservers(second)); - var session = provider.GetRequiredService().ForFactory("main").Create("call-1"); + var session = provider.GetRequiredService().ForFactory("main").Create("conversation-1"); await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); // The seam adds rather than replaces, so a host composes its readings across whatever code @@ -1630,19 +1630,19 @@ await Assert.ThrowsAsync(() => BuildAsync( } /// - /// The call store is opened at step 4c, and the moderation vendor is built after it. A + /// The conversation store is opened at step 4c, and the moderation vendor is built after it. A /// document that names a moderation kind this host does not register therefore fails with the /// store already open, and nothing between the two steps has taken ownership of it. /// [Fact] - public async Task AFailureAfterTheCallStoreOpens_StillClosesTheStore() + public async Task AFailureAfterTheConversationStoreOpens_StillClosesTheStore() { - RecordingCallStore store = new(); + RecordingConversationStore store = new(); await Assert.ThrowsAsync(() => BuildAsync( - CallStoreThenModerationFailureYaml, + ConversationStoreThenModerationFailureYaml, options => options - .UseCallStores(new TestCallStoreAdapter(store)) + .UseConversationStores(new TestConversationStoreAdapter(store)) .UseModeration(new FakeModerationAdapter("other", new AlwaysFlagsEvaluator())))); Assert.True(store.Closed); @@ -1962,7 +1962,7 @@ private static Task BuildGuardedGraphAsync() /// The event. private static AuditEvent AuditRow(long secondsPastEpoch) => new() { - CallId = "call-1", + ConversationId = "conversation-1", EventId = Guid.CreateVersion7(), Kind = AuditEventKind.TurnCompleted, OccurredAt = DateTimeOffset.UnixEpoch.AddSeconds(secondsPastEpoch), @@ -1997,13 +1997,13 @@ public ValueTask DisposeAsync() } /// An observer a host binds, which keeps every fact it was offered, in order. - private sealed class RecordingCallObserver : ICallObserver + private sealed class RecordingConversationObserver : IConversationObserver { private readonly Lock _gate = new(); - private readonly List _seen = []; + private readonly List _seen = []; - /// Gets what this observer read, in the order the call produced it. - public IReadOnlyList Seen + /// Gets what this observer read, in the order the conversation produced it. + public IReadOnlyList Seen { get { @@ -2015,11 +2015,11 @@ public IReadOnlyList Seen } } - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) { lock (_gate) { - _seen.Add(callEvent.Kind); + _seen.Add(conversationEvent.Kind); } return ValueTask.CompletedTask; @@ -2027,9 +2027,9 @@ public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancell } /// An observer that refuses every fact, so the isolation of the seam is observable. - private sealed class ThrowingCallObserver : ICallObserver + private sealed class ThrowingConversationObserver : IConversationObserver { - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + public ValueTask OnConversationEventAsync(ConversationEvent conversationEvent, CancellationToken cancellationToken) => throw new InvalidOperationException("the host's observer is broken"); } @@ -2149,15 +2149,15 @@ public ValueTask EvaluateAsync( } /// Sessions a host registers in place of the default ones. - private sealed class CountingCallSessions : ICallSessions + private sealed class CountingConversationSessions : IConversationSessions { - public ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default) + public ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default) => throw new NotSupportedException(); - public ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default) - => ValueTask.FromResult(null); + public ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default) + => ValueTask.FromResult(null); - public ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default) + public ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default) => ValueTask.CompletedTask; } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AgentCoreHttpClientsTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AgentCoreHttpClientsTests.cs index e28162b4..a59026ac 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AgentCoreHttpClientsTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AgentCoreHttpClientsTests.cs @@ -107,7 +107,7 @@ public void EveryClientCarriesTheDeadlineOfThisPipeline() /// /// /// Guessing shorter than the endpoint asked for gets the next attempt refused as well, and - /// guessing longer holds the call for no reason. + /// guessing longer holds the conversation for no reason. /// [Fact] public void ItWaitsTheRetryAfterAnEndpointAsksFor() diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs index fa0c3305..66befd3e 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs @@ -68,9 +68,9 @@ public async Task BootAsync_MixedScopingOverAnAdapterThatCannotScope_FailsTheSta /// The one document shape that can tell the two questions apart: one scoped agent, one not. /// /// - /// Built as an object rather than parsed from YAML, so it needs no providers.call and no + /// Built as an object rather than parsed from YAML, so it needs no providers.conversation and no /// providers.speech — the schema requires both once a providers: block exists, and a - /// boot that had to register a call vendor and a speech vendor would be testing those instead. + /// boot that had to register a conversation vendor and a speech vendor would be testing those instead. /// private static AgentCoreConfiguration MixedScoping() => new() diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs index bf495a30..f7ea8d2f 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs @@ -11,7 +11,7 @@ namespace AgentCore.AspNetCore.Tests.DependencyInjection; /// Builds a host over one document, which is where the whole boot happens. /// /// Shared by every DI test that only needs a booted host and nothing document-specific — the -/// tests that need their own document still write their own YAML and call +/// tests that need their own document still write their own YAML and conversation /// or directly. /// internal static class StartedHostFixture @@ -24,7 +24,7 @@ internal static class StartedHostFixture items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs index bc2419d7..a26a0521 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs @@ -10,8 +10,8 @@ namespace AgentCore.AspNetCore.Tests.DependencyInjection; /// -/// and the folder it binds a call's -/// to. +/// and the folder it binds a conversation's +/// to. /// public sealed class WorkspaceStartupTests : IDisposable { @@ -27,15 +27,15 @@ public void UseWorkspace_AnEmptyPath_ThrowsArgumentException() } [Fact] - public async Task AHostBoundToAWorkspaceRoot_CreatesTheCallsFolderWhenACallOpens() + public async Task AHostBoundToAWorkspaceRoot_CreatesTheConversationsFolderWhenAConversationOpens() { using var provider = await BuildAsync(OneAgentYaml, options => options.UseWorkspace(_tempRoot)); var sessions = provider.GetRequiredService().ForSessions("main"); - var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + var session = await sessions.OpenAsync("conversation-1", TestContext.Current.CancellationToken); - Assert.Equal(Path.Combine(_tempRoot, "call-1"), session.Workspace); - Assert.True(Directory.Exists(Path.Combine(_tempRoot, "call-1"))); + Assert.Equal(Path.Combine(_tempRoot, "conversation-1"), session.Workspace); + Assert.True(Directory.Exists(Path.Combine(_tempRoot, "conversation-1"))); } [Fact] @@ -44,7 +44,7 @@ public async Task AHostWithNoWorkspaceBound_CreatesNothingAndLeavesWorkspaceNull using var provider = await BuildAsync(OneAgentYaml); var sessions = provider.GetRequiredService().ForSessions("main"); - var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + var session = await sessions.OpenAsync("conversation-1", TestContext.Current.CancellationToken); Assert.Null(session.Workspace); } @@ -70,7 +70,7 @@ public async Task AMemoryAgent_WithAWorkspaceRootBound_Starts() using var provider = await BuildAsync(MemoryAgentYaml, options => options.UseWorkspace(_tempRoot)); var sessions = provider.GetRequiredService().ForSessions("main"); - var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + var session = await sessions.OpenAsync("conversation-1", TestContext.Current.CancellationToken); Assert.StartsWith(_tempRoot, session.Workspace, StringComparison.Ordinal); } @@ -105,7 +105,7 @@ public async Task AFilesAgent_WithAWorkspaceRootBound_Starts() using var provider = await BuildAsync(FilesAgentYaml, options => options.UseWorkspace(_tempRoot)); var sessions = provider.GetRequiredService().ForSessions("main"); - var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + var session = await sessions.OpenAsync("conversation-1", TestContext.Current.CancellationToken); Assert.StartsWith(_tempRoot, session.Workspace, StringComparison.Ordinal); } @@ -134,7 +134,7 @@ public void Dispose() items: - { id: only, instructions: "I answer everything", memory: { store: workspace } } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -152,7 +152,7 @@ public void Dispose() items: - { id: only, instructions: "I answer everything", files: { store: workspace } } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.AspNetCore.Tests/Embeddings/OpenAI/OpenAiEmbeddingGeneratorAdapterTests.cs b/tests/AgentCore.AspNetCore.Tests/Embeddings/OpenAI/OpenAiEmbeddingGeneratorAdapterTests.cs index 26d68492..0b8b204b 100644 --- a/tests/AgentCore.AspNetCore.Tests/Embeddings/OpenAI/OpenAiEmbeddingGeneratorAdapterTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Embeddings/OpenAI/OpenAiEmbeddingGeneratorAdapterTests.cs @@ -27,7 +27,7 @@ public sealed class OpenAiEmbeddingGeneratorAdapterTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs index d49f8f3b..a96c2d0f 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs @@ -34,7 +34,7 @@ public sealed class ApprovalWireTests items: - { id: greeter, instructions: "send the mail", tools: [ send_email ] } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -46,7 +46,7 @@ public sealed class ApprovalWireTests """; [Fact] - public async Task AGatedToolCall_StreamsAnApprovalEventWithTheCallFacts() + public async Task AGatedToolCall_StreamsAnApprovalEventWithTheConversationFacts() { int sent = 0; await using var host = await ResponsesHost.StartAsync( @@ -132,7 +132,7 @@ public async Task ARejection_LeavesTheToolUnrun() } [Fact] - public async Task AnApprovalAnswerForAnUnknownCall_IsNotFound() + public async Task AnApprovalAnswerForAnUnknownConversation_IsNotFound() { await using var host = await ResponsesHost.StartAsync( ApprovalYaml, @@ -145,7 +145,7 @@ public async Task AnApprovalAnswerForAnUnknownCall_IsNotFound() } [Fact] - public async Task AnApprovalAnswerWithNoCall_IsBadRequest() + public async Task AnApprovalAnswerWithNoConversation_IsBadRequest() { await using var host = await ResponsesHost.StartAsync( ApprovalYaml, @@ -246,7 +246,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" })]); yield break; diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs index 4570f4af..9cf66f4f 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/FileWireTests.cs @@ -1,6 +1,6 @@ using System.Runtime.CompilerServices; using System.Text.Json; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Parsing; using AgentCore.AspNetCore.Tests.Fakes; using Microsoft.Extensions.AI; @@ -11,12 +11,12 @@ namespace AgentCore.AspNetCore.Tests.Endpoints; /// /// The whole wire a published file travels: the model calls file.publish on a file in the -/// call's workspace, the blob store keeps it under the call, the browser gets one +/// conversation's workspace, the blob store keeps it under the conversation, the browser gets one /// agentcore_file part with the link, and the transcript links the same file on a later read. /// public sealed class FileWireTests : IDisposable { - private const string CallId = "call-pub-1"; + private const string ConversationId = "conversation-pub-1"; private const string Yaml = """ @@ -32,7 +32,7 @@ public sealed class FileWireTests : IDisposable main: agent: analyst providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -43,7 +43,7 @@ public sealed class FileWireTests : IDisposable private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-filewire-" + Guid.NewGuid().ToString("N")); - public FileWireTests() => Directory.CreateDirectory(Path.Combine(_root, CallId)); + public FileWireTests() => Directory.CreateDirectory(Path.Combine(_root, ConversationId)); public void Dispose() { @@ -56,7 +56,7 @@ public void Dispose() [Fact] public async Task AToolThatPublishes_ReachesTheBrowserAsAFilePartAndTheTranscriptLinksItLater() { - File.WriteAllText(Path.Combine(_root, CallId, "report.csv"), "month,sales\njan,10\n"); + File.WriteAllText(Path.Combine(_root, ConversationId, "report.csv"), "month,sales\njan,10\n"); FakeBlobStoreAdapter blobs = new(); await using var host = await ResponsesHost.StartAsync( @@ -65,7 +65,7 @@ public async Task AToolThatPublishes_ReachesTheBrowserAsAFilePartAndTheTranscrip configure: options => options.UseWorkspace(_root).UseBlobStores(blobs)); using var response = await host.PostAsync( - $$"""{ "stream": true, "conversation": "{{CallId}}", "input": "send me the report", "agentcore": { "message_id": "m1" } }"""); + $$"""{ "stream": true, "conversation": "{{ConversationId}}", "input": "send me the report", "agentcore": { "message_id": "m1" } }"""); var events = await ResponsesHost.ReadEventsAsync(response); var files = events @@ -79,10 +79,10 @@ public async Task AToolThatPublishes_ReachesTheBrowserAsAFilePartAndTheTranscrip Assert.Equal("Quarterly report", file.GetProperty("title").GetString()); Assert.Equal("text/csv", file.GetProperty("media_type").GetString()); Assert.Equal(19, file.GetProperty("length").GetInt64()); - Assert.Equal($"https://blobs.test/{CallId}/report.csv?ttl=900", file.GetProperty("url").GetString()); + Assert.Equal($"https://blobs.test/{ConversationId}/report.csv?ttl=900", file.GetProperty("url").GetString()); - // The bytes are in the store, owned by the call. - var (mediaType, bytes) = blobs.Store.Blobs[(CallId, "report.csv")]; + // The bytes are in the store, owned by the conversation. + var (mediaType, bytes) = blobs.Store.Blobs[(ConversationId, "report.csv")]; Assert.Equal("text/csv", mediaType); Assert.Equal("month,sales\njan,10\n", System.Text.Encoding.UTF8.GetString(bytes)); @@ -94,16 +94,16 @@ public async Task AToolThatPublishes_ReachesTheBrowserAsAFilePartAndTheTranscrip .Select(chunk => chunk.GetProperty("agentcore_tool")) .Single(); Assert.False(toolResult.GetProperty("failed").GetBoolean()); - Assert.Equal($"https://blobs.test/{CallId}/report.csv?ttl=900", toolResult.GetProperty("result").GetProperty("url").GetString()); + Assert.Equal($"https://blobs.test/{ConversationId}/report.csv?ttl=900", toolResult.GetProperty("result").GetProperty("url").GetString()); // And a later read of the transcript links the same file again. - var calls = host.Services.GetRequiredService(); - var stored = await calls.ReadAsync(CallId, TestContext.Current.CancellationToken); - var links = await calls.LinkFilesAsync(CallId, stored.Select(row => row.Content), TestContext.Current.CancellationToken); + var conversations = host.Services.GetRequiredService(); + var stored = await conversations.ReadAsync(ConversationId, TestContext.Current.CancellationToken); + var links = await conversations.LinkFilesAsync(ConversationId, stored.Select(row => row.Content), TestContext.Current.CancellationToken); var link = Assert.Single(links); - Assert.Equal((CallId, "report.csv", "text/csv", 19L), (link.Blob.OwnerId, link.Blob.Name, link.Blob.MediaType, link.Blob.Length)); - Assert.Equal($"https://blobs.test/{CallId}/report.csv?ttl=900", link.Url?.ToString()); + Assert.Equal((ConversationId, "report.csv", "text/csv", 19L), (link.Blob.OwnerId, link.Blob.Name, link.Blob.MediaType, link.Blob.Length)); + Assert.Equal($"https://blobs.test/{ConversationId}/report.csv?ttl=900", link.Url?.ToString()); } [Fact] @@ -117,7 +117,7 @@ public async Task AToolThatPublishesAMissingFile_TellsTheModelAndWritesNoFilePar configure: options => options.UseWorkspace(_root).UseBlobStores(blobs)); using var response = await host.PostAsync( - $$"""{ "stream": true, "conversation": "{{CallId}}", "input": "send me the report", "agentcore": { "message_id": "m1" } }"""); + $$"""{ "stream": true, "conversation": "{{ConversationId}}", "input": "send me the report", "agentcore": { "message_id": "m1" } }"""); var events = await ResponsesHost.ReadEventsAsync(response); Assert.DoesNotContain(events, text => text.Contains("agentcore_file", StringComparison.Ordinal)); @@ -164,7 +164,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - "call_1", + "conversation_1", publish.Name, new Dictionary(StringComparer.Ordinal) { diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs index b454b73c..0c253de7 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs @@ -8,7 +8,7 @@ namespace AgentCore.AspNetCore.Tests.Endpoints; /// -/// The Responses path: one request runs one turn, and the continuation carries the call. +/// The Responses path: one request runs one turn, and the continuation carries the conversation. /// /// /// Every test here runs offline against a fake model. The two-stage document names the @@ -37,7 +37,7 @@ public sealed class ResponsesTests - { id: talking, agent: solo, to: [ { stage: followup, when: second } ] } - { id: followup, agent: duo, to: [ { stage: talking, when: third } ] } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -120,7 +120,7 @@ public async Task SecondTurnStreams_StillContinuesStage() } [Fact] - public async Task UnknownConversation_StartsTheCallUnderThatId() + public async Task UnknownConversation_StartsTheConversationUnderThatId() { using FragmentingChatClient reply = new("answer one", "answer two"); await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); @@ -398,7 +398,7 @@ public async Task PureStream_WritesNoDialectEvents() stages: - { id: done, agent: solo, terminal: true } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -415,7 +415,7 @@ public async Task PureStream_WritesNoDialectEvents() items: - { id: greeter, instructions: "send the mail", tools: [ send_email ] } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -439,7 +439,7 @@ public async Task PureStream_WritesNoDialectEvents() model: { ref: reply } items: - { id: greeter, instructions: "greet the caller", tools: [ draw_it ] } - - { id: closer, instructions: "close the call", tools: [ draw_it ] } + - { id: closer, instructions: "close the conversation", tools: [ draw_it ] } entries: main: policy: @@ -448,7 +448,7 @@ public async Task PureStream_WritesNoDialectEvents() - { id: greeting, agent: greeter, to: [ { stage: close } ] } - { id: close, agent: closer, to: [ { stage: greeting } ] } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -493,7 +493,7 @@ private sealed class GatedToolCallingChatClient : Microsoft.Extensions.AI.IChatC yield return new Microsoft.Extensions.AI.ChatResponseUpdate( Microsoft.Extensions.AI.ChatRole.Assistant, [new Microsoft.Extensions.AI.FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" })]); yield break; @@ -542,7 +542,7 @@ private sealed class RenderChatClient : Microsoft.Extensions.AI.IChatClient yield return new Microsoft.Extensions.AI.ChatResponseUpdate( Microsoft.Extensions.AI.ChatRole.Assistant, [new Microsoft.Extensions.AI.FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { ["what"] = "a card" })]); yield break; diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs index 6f2c95b1..b853d9c6 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs @@ -9,7 +9,7 @@ namespace AgentCore.AspNetCore.Tests.Endpoints; /// -/// The whole wire a source travels: a producer, the call's sources, and one extra SSE field. +/// The whole wire a source travels: a producer, the conversation's sources, and one extra SSE field. /// /// /// Retrieval is the first producer of a source and this test deliberately does not use it. The @@ -31,7 +31,7 @@ public sealed class SourceWireTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller", tools: [ look_it_up ] } - - { id: closer, instructions: "close the call", tools: [ look_it_up ] } + - { id: closer, instructions: "close the conversation", tools: [ look_it_up ] } entries: main: policy: @@ -40,7 +40,7 @@ public sealed class SourceWireTests - { id: greeting, agent: greeter, to: [ { stage: close } ] } - { id: close, agent: closer, to: [ { stage: greeting } ] } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -113,11 +113,11 @@ public async Task AToolThatCitesUnderTwoParallelCalls_StampsEachSourceWithItsOwn // FunctionInvokingChatClient batches every parallel call's results of one round onto ONE // message (and this endpoint turns that message into ONE update), so a fix that reads the // call id off "the first FunctionResultContent on the update" rather than off the source - // itself would silently stamp the second source with the first call's id. This is the + // itself would silently stamp the second source with the first conversation's id. This is the // regression test for exactly that. await using var host = await ResponsesHost.StartAsync( SourceYaml, - new TwoParallelCallsChatClient(), + new TwoParallelConversationsChatClient(), configure: options => options.Bind("LookItUp", (string? what, TurnInvocation? turn) => { turn?.Sources?.Publish(new SourceReference @@ -146,8 +146,8 @@ public async Task AToolThatCitesUnderTwoParallelCalls_StampsEachSourceWithItsOwn var left = Assert.Single(cited, source => source.GetProperty("id").GetString() == "card-left"); var right = Assert.Single(cited, source => source.GetProperty("id").GetString() == "card-right"); - Assert.Equal("call_1", left.GetProperty("call_id").GetString()); - Assert.Equal("call_2", right.GetProperty("call_id").GetString()); + Assert.Equal("conversation_1", left.GetProperty("call_id").GetString()); + Assert.Equal("conversation_2", right.GetProperty("call_id").GetString()); } /// Sends one turn of words and reads the answer as it arrives. @@ -181,7 +181,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { ["what"] = "E03" })]); yield break; @@ -215,11 +215,11 @@ public void Dispose() /// Calls the tool it is offered twice in one round — two parallel calls — then answers in words. /// - /// This is the shape a real model routinely produces and the single-call fakes above cannot + /// This is the shape a real model routinely produces and the single-conversation fakes above cannot /// exercise: FunctionInvokingChatClient batches both tool results of one round onto ONE /// message before this endpoint ever sees it. /// - private sealed class TwoParallelCallsChatClient : IChatClient + private sealed class TwoParallelConversationsChatClient : IChatClient { public async IAsyncEnumerable GetStreamingResponseAsync( IEnumerable messages, @@ -236,11 +236,11 @@ public async IAsyncEnumerable GetStreamingResponseAsync( ChatRole.Assistant, [ new FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { ["what"] = "left" }), new FunctionCallContent( - "call_2", + "conversation_2", tool.Name, new Dictionary(StringComparer.Ordinal) { ["what"] = "right" }), ]); diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs index e18fd0f0..84409e3c 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/TimeZoneHeaderTests.cs @@ -24,7 +24,7 @@ public sealed class TimeZoneHeaderTests main: agent: solo providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/ToolWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/ToolWireTests.cs index 6200eb58..a41c1be9 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/ToolWireTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/ToolWireTests.cs @@ -8,7 +8,7 @@ namespace AgentCore.AspNetCore.Tests.Endpoints; /// -/// The wire a tool call travels: one SSE field that names the call, and a second that answers it. +/// The wire a tool call travels: one SSE field that names the conversation, and a second that answers it. /// /// /// @@ -38,7 +38,7 @@ public sealed class ToolWireTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller", tools: [ look_it_up ] } - - { id: closer, instructions: "close the call", tools: [ look_it_up ] } + - { id: closer, instructions: "close the conversation", tools: [ look_it_up ] } entries: main: policy: @@ -47,7 +47,7 @@ public sealed class ToolWireTests - { id: greeting, agent: greeter, to: [ { stage: close } ] } - { id: close, agent: closer, to: [ { stage: greeting } ] } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -69,7 +69,7 @@ public async Task AToolCall_ReachesTheBrowserOnItsOwnFieldWithTheNameAndTheArgum var call = Assert.Single(tools, tool => tool.GetProperty("phase").GetString() == "call"); - Assert.Equal("call_1", call.GetProperty("call_id").GetString()); + Assert.Equal("conversation_1", call.GetProperty("call_id").GetString()); Assert.Equal("look_it_up", call.GetProperty("name").GetString()); Assert.Equal("a card", call.GetProperty("arguments").GetProperty("what").GetString()); } @@ -88,9 +88,9 @@ public async Task AToolResult_ReachesTheBrowserOnTheSameFieldAndNamesTheCallItAn var result = Assert.Single(tools, tool => tool.GetProperty("phase").GetString() == "result"); - // The id is what pairs the two halves in the browser, so the result carries the call's id + // The id is what pairs the two halves in the browser, so the result carries the conversation's id // and not one of its own. - Assert.Equal("call_1", result.GetProperty("call_id").GetString()); + Assert.Equal("conversation_1", result.GetProperty("call_id").GetString()); Assert.Equal("look_it_up", result.GetProperty("name").GetString()); Assert.False(result.GetProperty("failed").GetBoolean()); Assert.Contains("42 rows", result.GetProperty("result").GetString(), StringComparison.Ordinal); @@ -182,8 +182,8 @@ public async Task AnAnswerThatIsJson_RidesTheWireAsJsonRatherThanAsEscapedText() // it whatever the shape it sits in, and the browser turns it back on parse. var events = await ResponsesHost.ReadEventsAsync(response); - // The framework's own function-call frames carry the model's raw argument string with its - // quotes escaped — that is the protocol's shape for a call. The complaint was ever about + // The framework's own function-conversation frames carry the model's raw argument string with its + // quotes escaped — that is the protocol's shape for a conversation. The complaint was ever about // the answer, so the assertion reads the result line alone: on our field it travels as // itself, not as escaped text. var line = Assert.Single(events, text => JsonDocument.Parse(text).RootElement @@ -276,7 +276,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( yield return new ChatResponseUpdate( ChatRole.Assistant, [new FunctionCallContent( - "call_1", + "conversation_1", tool.Name, new Dictionary(StringComparer.Ordinal) { ["what"] = "a card" })]); yield break; diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs index bf1e3685..5262ff99 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/TurnStreamFilesTests.cs @@ -1,7 +1,7 @@ using AgentCore.Application.Transcript; using AgentCore.Application.Blobs; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Ports; using AgentCore.AspNetCore.Endpoints; using Microsoft.Extensions.AI; @@ -23,7 +23,7 @@ private static FileContent Kept(string name, string mediaType, long length) public async Task ResolveAsync_NotedFileTheCaptureKept_YieldsOnePartWithTheLink() { // Arrange: the same content passes twice, as a re-yielded update would; a refused one passes too. - CallRepository calls = new(new InMemoryCallStore(), new StubBlobStore()); + Conversations conversations = new(new InMemoryConversationStore(), new StubBlobStore()); TurnStreamFiles files = new(); var chart = Kept("chart.png", "image/png", 48213); FileContent refused = new() { Name = "refused.png", FileId = "cfile_2" }; @@ -32,26 +32,26 @@ public async Task ResolveAsync_NotedFileTheCaptureKept_YieldsOnePartWithTheLink( files.Note(UpdateWith(refused)); // Act - var parts = await files.ResolveAsync(calls, "call-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); + var parts = await files.ResolveAsync(conversations, "conversation-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); // Assert: once, linked, and the refused file is not there. var part = Assert.Single(parts); Assert.Equal("chart.png", part.Payload.Name); Assert.Equal("image/png", part.Payload.MediaType); Assert.Equal(48213, part.Payload.Length); - Assert.Equal("https://blobs.test/call-1/chart.png?ttl=900", part.Payload.Url); + Assert.Equal("https://blobs.test/conversation-1/chart.png?ttl=900", part.Payload.Url); } [Fact] public async Task ResolveAsync_StoreWithNoWebDoor_YieldsThePartWithoutAUrl() { // Arrange - CallRepository calls = new(new InMemoryCallStore(), new StubBlobStore { Links = false }); + Conversations conversations = new(new InMemoryConversationStore(), new StubBlobStore { Links = false }); TurnStreamFiles files = new(); files.Note(UpdateWith(Kept("rows.csv", "text/csv", 8))); // Act - var parts = await files.ResolveAsync(calls, "call-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); + var parts = await files.ResolveAsync(conversations, "conversation-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); // Assert Assert.Null(Assert.Single(parts).Payload.Url); @@ -61,10 +61,10 @@ public async Task ResolveAsync_StoreWithNoWebDoor_YieldsThePartWithoutAUrl() public async Task ResolveAsync_NothingNoted_YieldsNothing() { // Arrange - CallRepository calls = new(new InMemoryCallStore(), blobs: null); + Conversations conversations = new(new InMemoryConversationStore(), blobs: null); // Act - var parts = await new TurnStreamFiles().ResolveAsync(calls, "call-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); + var parts = await new TurnStreamFiles().ResolveAsync(conversations, "conversation-1", TestContext.Current.CancellationToken).ToListAsync(TestContext.Current.CancellationToken); // Assert Assert.Empty(parts); diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeConversationInput.cs similarity index 75% rename from tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs rename to tests/AgentCore.AspNetCore.Tests/Fakes/FakeConversationInput.cs index 1b7501f4..fd1afdfb 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeConversationInput.cs @@ -1,12 +1,12 @@ using System.Runtime.CompilerServices; using AgentCore.Application.Ports; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; namespace AgentCore.AspNetCore.Tests.Fakes; /// An input port that replays a scripted stream, refuses a second reader, and counts its disposals. -/// What the caller does, in order. Empty is a call the caller never spoke on. -internal sealed class FakeCallInput(params CallInput[] script) : ICallInputPort +/// What the caller does, in order. Empty is a conversation the caller never spoke on. +internal sealed class FakeConversationInput(params ConversationInput[] script) : IConversationInputPort { private int _listening; @@ -17,18 +17,18 @@ internal sealed class FakeCallInput(params CallInput[] script) : ICallInputPort /// /// /// The refusal is the point of this fake as much as the script is: one socket read twice would - /// give each reader half the call, and the port promises a second call throws rather than - /// splitting one call in two. + /// give each reader half the conversation, and the port promises a second call throws rather than + /// splitting one conversation in two. /// /// - /// The script running out is this fake's end of the call, and it completes the stream. A - /// cancelled read throws instead, which is the rule + /// The script running out is this fake's end of the conversation, and it completes the stream. A + /// cancelled read throws instead, which is the rule /// sets and which the real relay connection obeys the same way — a double that ended quietly /// where the real port throws would teach a consumer a catch it does not need, and hide /// the one it does. /// /// - public IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default) + public IAsyncEnumerable ListenAsync(CancellationToken cancellationToken = default) { // Thrown from here, not from the iterator below: an iterator's body does not run until // something enumerates it, so a guard inside it would let a second ListenAsync return a @@ -50,7 +50,7 @@ public ValueTask DisposeAsync() /// Replays the script, one item at a time. /// Ends the stream. /// Every scripted item, in order. - private async IAsyncEnumerable ReplayAsync( + private async IAsyncEnumerable ReplayAsync( [EnumeratorCancellation] CancellationToken cancellationToken) { foreach (var input in script) @@ -61,7 +61,7 @@ private async IAsyncEnumerable ReplayAsync( await Task.Yield(); // Throws rather than breaking out of the loop: a cancelled read is not the end of a - // call, and this fake must not be the one place a consumer learns otherwise. + // conversation, and this fake must not be the one place a consumer learns otherwise. cancellationToken.ThrowIfCancellationRequested(); yield return input; diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallOutput.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeConversationOutput.cs similarity index 95% rename from tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallOutput.cs rename to tests/AgentCore.AspNetCore.Tests/Fakes/FakeConversationOutput.cs index e4e30110..5e5cfb6c 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallOutput.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeConversationOutput.cs @@ -3,7 +3,7 @@ namespace AgentCore.AspNetCore.Tests.Fakes; /// An output port that records what it was told to say, and when it was stopped. -internal sealed class FakeCallOutput : ICallOutputPort +internal sealed class FakeConversationOutput : IConversationOutputPort { private readonly List _spoken = []; private readonly Lock _gate = new(); diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeRelayClient.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeRelayClient.cs index 257aca99..680c1929 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeRelayClient.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeRelayClient.cs @@ -173,7 +173,7 @@ public async Task> ReadFramesForAsync(TimeSpan window) } } - /// Drops the socket with no close frame, exactly like a call that died. + /// Drops the socket with no close frame, exactly like a conversation that died. public void Abort() => _socket.Abort(); /// Stops the pump and closes the socket. @@ -207,7 +207,7 @@ public async ValueTask DisposeAsync() } catch (WebSocketException) { - // The host already went away. That is the end of a call, not a test failure. + // The host already went away. That is the end of a conversation, not a test failure. } } diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs index 2c529543..45d7d2d9 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeWebSocket.cs @@ -3,7 +3,7 @@ using System.Text; using System.Threading.Channels; using AgentCore.Application.Configuration.Parsing; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.Vendors.TelnyxRelay; using Microsoft.AspNetCore.Http; @@ -222,7 +222,7 @@ public override Task CloseOutputAsync( /// /// /// The connection never calls this: CloseAsync waits for the peer's close frame, and a - /// call that already dropped never sends one. A call that reaches here is a defect worth a red + /// conversation that already dropped never sends one. A conversation that reaches here is a defect worth a red /// test rather than a silent pass. /// public override Task CloseAsync( @@ -295,7 +295,7 @@ public void Dispose() /// /// RunAsync takes the abstract , so nothing here needs Kestrel, a /// port, or a client socket. The service provider is the real one AddAgentCore builds, so -/// the session factory, the store, and the clock behave exactly as they do on a live call. +/// the session factory, the store, and the clock behave exactly as they do on a live conversation. /// internal sealed class RelayConnectionHarness : IAsyncDisposable { @@ -336,10 +336,10 @@ private RelayConnectionHarness( /// Anything a test binds on the relay endpoint's own options. /// /// Anything else the test binds on the container's own options, for example the clock every - /// call and every connection then runs on. + /// conversation and every connection then runs on. /// /// - /// Anything a test registers over what AddAgentCore registered. It runs after that call, + /// Anything a test registers over what AddAgentCore registered. It runs after that conversation, /// so a registration here is the last one and the connection resolves it. /// /// The running harness. @@ -380,7 +380,7 @@ public static async Task StartAsync( } DefaultHttpContext http = new() { RequestServices = provider }; - http.Request.RouteValues[CallEndpointRouteBuilderExtensions.EntryRouteParameter] = "main"; + http.Request.RouteValues[ConversationEndpointRouteBuilderExtensions.EntryRouteParameter] = "main"; TelnyxRelayOptions options = new(); relay?.Invoke(options); diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/HostFakes.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/HostFakes.cs index 60e0a4e6..d97e76c1 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/HostFakes.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/HostFakes.cs @@ -22,7 +22,7 @@ internal sealed class FragmentingChatClient : IChatClient /// Gets how many requests this client answered. public int Calls => Volatile.Read(ref _calls); - /// Gets the messages of the most recent request, oldest first, or null before any call. + /// Gets the messages of the most recent request, oldest first, or null before any conversation. /// /// A test reads this to prove which text actually reached the model — for example that an /// interim transcript never substitutes for the final one, rather than only counting how many @@ -205,7 +205,7 @@ private static IEnumerable Fragments(string reply) /// before it says a word. /// /// -/// This is the shape a held prompt produces on a real call. Turn one pauses long enough for a +/// This is the shape a held prompt produces on a real conversation. Turn one pauses long enough for a /// second final prompt to be held, then finishes streaming; RunPendingPrompt starts turn two /// inside turn one's own finally; and the vendor is still speaking turn one while turn two /// has produced nothing at all. No other fake here can hold the second turn apart from the first. @@ -231,7 +231,7 @@ public HeldPromptChatClient(string first, string second) /// Gets whether the second turn opens with one update the relay can never speak. /// /// - /// CallSession calls a run audible at its first piece of content, and content is not + /// ConversationSession calls a run audible at its first piece of content, and content is not /// the same thing as a word. A tool call, a tool result, and a line of reasoning all count, and /// none of them carries text, so none of them ever reaches the vendor as a text frame. Set /// this, and turn two yields exactly one such update — a , the @@ -272,7 +272,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( { // Yielded before SecondTurnStarted is set, and the line after a yield only runs once // the consumer comes back for the next update. Waiting on that signal therefore - // proves this update has already travelled the whole way through CallSession — which + // proves this update has already travelled the whole way through ConversationSession — which // is where it raises the audible flag this fake exists to raise — and through the // connection's own update loop, which reads no text on it and so leaves // _spokenTurnId naming turn one. diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/RelayFrames.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/RelayFrames.cs index 4475f896..f66cd3c0 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/RelayFrames.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/RelayFrames.cs @@ -10,14 +10,14 @@ namespace AgentCore.AspNetCore.Tests.Fakes; /// internal static class RelayFrames { - /// Builds the first frame of a call. - public static string Setup(string callSessionId = "call-one", string callControlId = "v2:leg-one") + /// Builds the first frame of a conversation. + public static string Setup(string conversationSessionId = "conversation-one", string callControlId = "v2:leg-one") => $$""" {"type":"setup","sessionId":"session-one","accountSid":"account-one", "callSid":"{{callControlId}}","callControlId":"{{callControlId}}", - "callSessionId":"{{callSessionId}}","callLegId":"leg-one", + "conversationSessionId":"{{conversationSessionId}}","callLegId":"leg-one", "from":"+13122010094","to":"+13122123456","direction":"inbound", - "callerName":"","customParameters":{},"callStatus":"active"} + "callerName":"","customParameters":{},"conversationStatus":"active"} """; /// Builds one transcript frame. diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs index c1384eb0..0cb0037f 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/TelnyxRelayHost.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.AspNetCore.Call; +using AgentCore.AspNetCore.Conversation; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.DependencyInjection.Startup; using AgentCore.AspNetCore.Vendors.TelnyxRelay; @@ -28,8 +28,8 @@ namespace AgentCore.AspNetCore.Tests.Fakes; /// internal sealed class TelnyxRelayHost : IAsyncDisposable { - /// The vendor-neutral call route, with the document's one entry filled in. - public const string MainCall = "/v1/main/call"; + /// The vendor-neutral conversation route, with the document's one entry filled in. + public const string MainConversation = "/v1/main/call"; /// The relay's own route, with the document's one entry filled in. public const string MainRelay = "/v1/main/telnyx/relay"; @@ -48,7 +48,7 @@ private TelnyxRelayHost(WebApplication app, Uri socketAddress, HttpClient client } /// Gets the sessions the host resolved, so a test reads the live ones. - public ICallSessions Sessions => _app.Services.GetRequiredService().ForSessions("main"); + public IConversationSessions Sessions => _app.Services.GetRequiredService().ForSessions("main"); /// Gets the ws:// address of the relay route. /// @@ -87,30 +87,30 @@ public static Task StartAsync( Action? configure = null, Action? logging = null, Action? relay = null) - => StartCoreAsync(yaml, reply, configure, logging, relay, useWebSockets: true, useCallSeam: false); + => StartCoreAsync(yaml, reply, configure, logging, relay, useWebSockets: true, useConversationSeam: false); /// Starts one host that maps its route through app.MapCall() rather than the vendor extension. - /// The document, as YAML. It must name providers.call and providers.speech. + /// The document, as YAML. It must name providers.conversation and providers.speech. /// The model behind every agent. /// - /// Anything else the test binds on the options. A test using this overload calls - /// options.UseCall(new TelnyxRelayCallAdapter()) here, because nothing else registers the + /// Anything else the test binds on the options. A test using this overload conversations + /// options.UseConversation(new TelnyxRelayConversationAdapter()) here, because nothing else registers the /// transport the seam is meant to pick. /// /// Anything a test adds to the logging pipeline. - /// The started host, answering on . + /// The started host, answering on . /// /// maps the relay through the internal MapTelnyxRelay and so /// bypasses the seam entirely, which is right for the several dozen frame-level tests that use /// it and wrong for proving that the shipped vendor is reachable from the vendor-neutral route. /// This overload is the one that joins the two. /// - public static Task StartThroughCallSeamAsync( + public static Task StartThroughConversationSeamAsync( string yaml, IChatClient reply, Action? configure = null, Action? logging = null) - => StartCoreAsync(yaml, reply, configure, logging, relay: null, useWebSockets: true, useCallSeam: true); + => StartCoreAsync(yaml, reply, configure, logging, relay: null, useWebSockets: true, useConversationSeam: true); /// Starts one host the same way does, but never calls app.UseWebSockets(). /// The document, as YAML. @@ -127,7 +127,7 @@ public static Task StartWithoutWebSocketsAsync( IChatClient reply, Action? configure = null, Action? logging = null) - => StartCoreAsync(yaml, reply, configure, logging, relay: null, useWebSockets: false, useCallSeam: false); + => StartCoreAsync(yaml, reply, configure, logging, relay: null, useWebSockets: false, useConversationSeam: false); private static async Task StartCoreAsync( string yaml, @@ -136,7 +136,7 @@ private static async Task StartCoreAsync( Action? logging, Action? relay, bool useWebSockets, - bool useCallSeam) + bool useConversationSeam) { var builder = WebApplication.CreateSlimBuilder(); builder.WebHost.UseUrls("http://127.0.0.1:0"); @@ -169,11 +169,11 @@ private static async Task StartCoreAsync( } string route; - if (useCallSeam) + if (useConversationSeam) { - // The vendor-neutral seam picks the transport out of providers.call and the adapter the + // The vendor-neutral seam picks the transport out of providers.conversation and the adapter the // test registered. Nothing here names a route or a vendor. - route = MainCall; + route = MainConversation; app.MapCall(); } else @@ -212,21 +212,21 @@ private static async Task StartCoreAsync( public Task GetAsync(string pattern) => _client.GetAsync(pattern, TestContext.Current.CancellationToken); - /// Reads the session of one call, or null when the store dropped it. - /// The call id, which is the callSessionId of the setup frame. + /// Reads the session of one conversation, or null when the store dropped it. + /// The conversation id, which is the conversationSessionId of the setup frame. /// The session, or null. - public async Task FindSessionAsync(string callId) - => await Sessions.TryGetAsync(callId, TestContext.Current.CancellationToken); + public async Task FindSessionAsync(string conversationId) + => await Sessions.TryGetAsync(conversationId, TestContext.Current.CancellationToken); - /// Waits until the store no longer holds one call. - /// The call id. + /// Waits until the store no longer holds one conversation. + /// The conversation id. /// A task that completes when the session is gone. /// The session was still there after two seconds. - public async Task WaitForCallEndAsync(string callId) + public async Task WaitForConversationEndAsync(string conversationId) { for (var attempt = 0; attempt < 200; attempt++) { - if (await FindSessionAsync(callId) is null) + if (await FindSessionAsync(conversationId) is null) { return; } @@ -234,11 +234,11 @@ public async Task WaitForCallEndAsync(string callId) await Task.Delay(10, TestContext.Current.CancellationToken); } - throw new TimeoutException($"the session of call '{callId}' outlived its socket."); + throw new TimeoutException($"the session of conversation '{conversationId}' outlived its socket."); } - /// Waits until the store holds one call. - /// The call id. + /// Waits until the store holds one conversation. + /// The conversation id. /// A task that completes once the session appears. /// /// A setup frame's SendAsync completing on the client only means the bytes left the @@ -247,11 +247,11 @@ public async Task WaitForCallEndAsync(string callId) /// creation, and a pass would not prove the removal it meant to prove. /// /// The session never appeared within two seconds. - public async Task WaitForSessionAsync(string callId) + public async Task WaitForSessionAsync(string conversationId) { for (var attempt = 0; attempt < 200; attempt++) { - if (await FindSessionAsync(callId) is not null) + if (await FindSessionAsync(conversationId) is not null) { return; } @@ -259,7 +259,7 @@ public async Task WaitForSessionAsync(string callId) await Task.Delay(10, TestContext.Current.CancellationToken); } - throw new TimeoutException($"the session of call '{callId}' never appeared."); + throw new TimeoutException($"the session of conversation '{conversationId}' never appeared."); } /// Stops the host and releases the socket. diff --git a/tests/AgentCore.AspNetCore.Tests/Llm/OpenAI/OpenAiChatClientAdapterTests.cs b/tests/AgentCore.AspNetCore.Tests/Llm/OpenAI/OpenAiChatClientAdapterTests.cs index 20b22a62..09674a4c 100644 --- a/tests/AgentCore.AspNetCore.Tests/Llm/OpenAI/OpenAiChatClientAdapterTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Llm/OpenAI/OpenAiChatClientAdapterTests.cs @@ -28,7 +28,7 @@ public sealed class OpenAiChatClientAdapterTests items: - { id: only, instructions: "I answer everything" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.AspNetCore.Tests/Sessions/CallSessionsRelayTests.cs b/tests/AgentCore.AspNetCore.Tests/Sessions/ConversationSessionsRelayTests.cs similarity index 56% rename from tests/AgentCore.AspNetCore.Tests/Sessions/CallSessionsRelayTests.cs rename to tests/AgentCore.AspNetCore.Tests/Sessions/ConversationSessionsRelayTests.cs index 8bd2aa2e..c2e43b65 100644 --- a/tests/AgentCore.AspNetCore.Tests/Sessions/CallSessionsRelayTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Sessions/ConversationSessionsRelayTests.cs @@ -14,32 +14,32 @@ namespace AgentCore.AspNetCore.Tests.Sessions; /// -/// What the relay socket asks of over the life of one call. +/// What the relay socket asks of over the life of one conversation. /// /// /// The unit tests of the store itself live in AgentCore.Application.Tests beside the store. This /// file holds only what needs a real socket to prove. /// -public sealed class CallSessionsRelayTests +public sealed class ConversationSessionsRelayTests { private static CancellationToken Token => TestContext.Current.CancellationToken; [Fact(Timeout = 30_000)] - public async Task ATurnTellsTheStoreItsCallIsStillBeingHad() + public async Task ATurnTellsTheStoreItsConversationIsStillBeingHad() { - // The relay opens its session once and holds it for the whole call, so nothing else reads - // it back. A read is the one sign a store gets that a call is still live, so without one + // The relay opens its session once and holds it for the whole conversation, so nothing else reads + // it back. A read is the one sign a store gets that a conversation is still live, so without one // the idle sweep drops a long call out from under the turn about to run. using FragmentingChatClient reply = new("your order ships Friday"); var factory = Factory(TelnyxRelayTurnTests.PolicyYaml, reply); - CountingCallSessions sessions = new(factory); + CountingConversationSessions sessions = new(factory); await using var harness = await RelayConnectionHarness.StartAsync( TelnyxRelayTurnTests.PolicyYaml, reply, - configure: options => options.UseCallSessions((_, _) => sessions)); + configure: options => options.UseConversationSessions((_, _) => sessions)); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-live")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-live")); harness.Socket.Queue(RelayFrames.Prompt("when does my order ship?", last: true)); for (var attempt = 0; attempt < 400 && sessions.Reads == 0; attempt++) @@ -47,40 +47,40 @@ public async Task ATurnTellsTheStoreItsCallIsStillBeingHad() await Task.Delay(10, Token); } - Assert.True(sessions.Reads > 0, "the turn never told the store its call is still being had."); + Assert.True(sessions.Reads > 0, "the turn never told the store its conversation is still being had."); } - private static CallSessionFactory Factory(string yaml, IChatClient reply) + private static ConversationSessionFactory Factory(string yaml, IChatClient reply) { var document = ConfigurationLoader.LoadYaml(yaml); RoutingChatClientFactory chatClients = new(reply); var compiled = ConfigurationCompiler.CompileAll(document, new AgentCompilationContext(chatClients))["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients)); + ConversationSessionFactory.CreateExtractor(compiled, chatClients)); } - private sealed class CountingCallSessions(ICallSessionFactory factory) : ICallSessions + private sealed class CountingConversationSessions(IConversationSessionFactory factory) : IConversationSessions { - private readonly InMemoryCallSessions _inner = - new(factory, InMemoryCallSessions.DefaultIdleTimeout, TimeProvider.System); + private readonly InMemoryConversationSessions _inner = + new(factory, InMemoryConversationSessions.DefaultIdleTimeout, TimeProvider.System); private int _reads; public int Reads => Volatile.Read(ref _reads); - public ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default) - => _inner.OpenAsync(callId, cancellationToken); + public ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default) + => _inner.OpenAsync(conversationId, cancellationToken); - public ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default) + public ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default) { Interlocked.Increment(ref _reads); - return _inner.TryGetAsync(callId, cancellationToken); + return _inner.TryGetAsync(conversationId, cancellationToken); } - public ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default) - => _inner.CloseAsync(callId, cancellationToken); + public ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default) + => _inner.CloseAsync(conversationId, cancellationToken); } } diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayBargeInTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayBargeInTests.cs index f3f01123..b3093d85 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayBargeInTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayBargeInTests.cs @@ -15,7 +15,7 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// /// /// Every test here runs offline against a fake model and a fake relay. There is no Telnyx account, -/// no network call, and no API key anywhere in this file. +/// no network conversation, and no API key anywhere in this file. /// public sealed class TelnyxRelayBargeInTests { @@ -43,7 +43,7 @@ public async Task AnInterruptDuringAReply_RecordsWhatTheCallerHeard() try { - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-barge")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-barge")); await relay.SendAsync(RelayFrames.Prompt("hi", last: true)); try @@ -55,7 +55,7 @@ public async Task AnInterruptDuringAReply_RecordsWhatTheCallerHeard() // SendAsync completing only means the bytes left this client, the same way // TelnyxRelayHost.WaitForSessionAsync's own remark explains for a setup frame. The - // connection must actually raise the turn id and call CallSession.Interrupt before + // connection must actually raise the turn id and conversation ConversationSession.Interrupt before // the gate below opens, or a fragment already queued behind the gate could still // beat the guard onto the wire. await capture.Observed.WaitAsync(bounded.Token); @@ -70,7 +70,7 @@ public async Task AnInterruptDuringAReply_RecordsWhatTheCallerHeard() reply.Release(); } - var session = await host.FindSessionAsync("call-barge"); + var session = await host.FindSessionAsync("conversation-barge"); Assert.NotNull(session); var turn = await WaitForTurnAsync(session!); @@ -106,7 +106,7 @@ public async Task AfterAnInterrupt_NoFurtherTextFrameReachesTheRelay() try { - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-race")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-race")); await relay.SendAsync(RelayFrames.Prompt("hi", last: true)); try @@ -185,7 +185,7 @@ public async Task AnItemAlreadyQueuedBehindAStuckSend_IsRemovedByTheUnconditiona using var bounded = CancellationTokenSource.CreateLinkedTokenSource( deadline.Token, TestContext.Current.CancellationToken); - await SendRawAsync(socket, RelayFrames.Setup(callSessionId: "call-held")); + await SendRawAsync(socket, RelayFrames.Setup(conversationSessionId: "conversation-held")); await SendRawAsync(socket, RelayFrames.Prompt("hi", last: true)); await Task.Delay(300, TestContext.Current.CancellationToken); @@ -284,13 +284,13 @@ public async Task AnInterruptWithNoTurnRunning_ChangesNothing() } [Fact(Timeout = 30_000)] - public async Task AnInterruptWithNoUtteranceUntilInterrupt_IsRefusedAndTheCallContinues() + public async Task AnInterruptWithNoUtteranceUntilInterrupt_IsRefusedAndTheConversationContinues() { // Section 7.1's rule for an unknown frame type applies here too: a frame the vendor got - // wrong must not drop the call. RelayFrames.Interrupt always emits both fields, so a raw + // wrong must not drop the conversation. RelayFrames.Interrupt always emits both fields, so a raw // frame is sent by hand here, missing utteranceUntilInterrupt entirely — the one shape // HandleInterrupt's own guard exists to survive, since System.Text.Json deserializes a - // missing non-nullable string as null rather than throwing, and CallSession.Interrupt + // missing non-nullable string as null rather than throwing, and ConversationSession.Interrupt // itself would otherwise take an ArgumentNullException straight into the read loop. using FragmentingChatClient reply = new("hello"); EventObservedLoggerProvider capture = new("MalformedInterruptFrame"); @@ -329,11 +329,11 @@ public async Task AnInterruptWithNoUtteranceUntilInterrupt_IsRefusedAndTheCallCo } [Fact(Timeout = 30_000)] - public async Task AnInterruptWithANegativeDuration_IsRefusedAndTheCallContinues() + public async Task AnInterruptWithANegativeDuration_IsRefusedAndTheConversationContinues() { // The same guard, the other malformed shape it exists for: System.Text.Json enforces no // range check on durationUntilInterruptMs, so a negative value would otherwise reach - // CallSession.Interrupt's own ArgumentOutOfRangeException uncaught and take the read loop + // ConversationSession.Interrupt's own ArgumentOutOfRangeException uncaught and take the read loop // down with it. D28 forbids clamping it into something plausible instead of refusing it. using FragmentingChatClient reply = new("hello"); EventObservedLoggerProvider capture = new("MalformedInterruptFrame"); @@ -377,9 +377,9 @@ public async Task ASecondFinalPromptDuringATurn_RunsAfterTheFirstTurnEnds() { // The caller can finish a second sentence before the agent speaks. There is no interrupt // frame, so there is no heard text, and IConversationPort throws on a second turn. Holding - // one prompt keeps the caller's words; throwing would drop the call. + // one prompt keeps the caller's words; throwing would drop the conversation. // - // reply.Calls == 2 alone cannot tell the held path from an accident: if the release below + // reply.Conversations == 2 alone cannot tell the held path from an accident: if the release below // happened to win the race against the server actually dispatching "two" while the first // turn was still running, "two" would just start its own ordinary second turn instead of // being held — and Calls would still read 2, the same as it would against code with no @@ -441,7 +441,7 @@ public async Task AThirdFinalPromptDuringATurn_IsDroppedAndLoggedOnce() // Item 6a of section 11 draws the line at one held prompt. This proves the line actually // holds: a third and a fourth final prompt, arriving while one is already held, both run no // turn of their own, and PendingPromptDropped — which the connection only ever logs once - // for the call — fires exactly once despite two drops, not once per dropped frame. + // for the conversation — fires exactly once despite two drops, not once per dropped frame. using BlockingChatClient reply = new("first reply"); EventObservedLoggerProvider heldCapture = new("PromptHeld"); EventObservedLoggerProvider droppedCapture = new("PendingPromptDropped"); @@ -515,7 +515,7 @@ public async Task AThirdFinalPromptDuringATurn_IsDroppedAndLoggedOnce() public async Task ATurnAfterABargeIn_AnswersNormally() { // Item 6a is half proved by AfterAnInterrupt_NoFurtherTextFrameReachesTheRelay: a barge-in - // ends one turn cleanly. The other half — the call itself goes on — needs its own proof, + // ends one turn cleanly. The other half — the conversation itself goes on — needs its own proof, // because nothing else here shows the caller can speak again and get a real answer rather // than silence or a leftover interrupted reply. using BlockingChatClient reply = new("hello there caller"); @@ -532,7 +532,7 @@ public async Task ATurnAfterABargeIn_AnswersNormally() try { - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-continues")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-continues")); await relay.SendAsync(RelayFrames.Prompt("hi", last: true)); try @@ -553,7 +553,7 @@ public async Task ATurnAfterABargeIn_AnswersNormally() reply.Release(); } - var session = await host.FindSessionAsync("call-continues"); + var session = await host.FindSessionAsync("conversation-continues"); Assert.NotNull(session); var firstTurn = await WaitForTurnAsync(session!); @@ -600,7 +600,7 @@ public async Task AnInterruptWhileAHeldTurnHasSaidNothing_LeavesThatTurnFreeToSp try { - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-held-turn")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-held-turn")); await relay.SendAsync(RelayFrames.Prompt("one", last: true)); try @@ -668,11 +668,11 @@ public async Task AnInterruptWhileAHeldTurnHasOnlyThoughtAloud_StillAmendsTheTur { // The sibling test above holds turn two before it produces anything at all, and both sides // of the seam then agree on their own: the connection marks _spokenTurnId, which still names - // turn one, and CallSession finds its own run not audible. This test closes the gap between - // those two answers. A run becomes audible to CallSession at its first piece of *content*, + // turn one, and ConversationSession finds its own run not audible. This test closes the gap between + // those two answers. A run becomes audible to ConversationSession at its first piece of *content*, // and content is not a word: a tool call, a tool result, or a line of reasoning makes turn // two audible to the core while not one syllable of it has reached the relay. The connection - // still marks turn one, correctly, and still lets turn two speak — but CallSession, asked + // still marks turn one, correctly, and still lets turn two speak — but ConversationSession, asked // nothing about which turn was heard, would cut turn two at its first thought and write the // caller's heard text onto a turn nobody heard. cutsRunningTurn is the answer the connection // already has, carried across the seam so the core stops guessing. @@ -698,7 +698,7 @@ public async Task AnInterruptWhileAHeldTurnHasOnlyThoughtAloud_StillAmendsTheTur try { - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-thinking-turn")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-thinking-turn")); await relay.SendAsync(RelayFrames.Prompt("one", last: true)); try @@ -718,7 +718,7 @@ public async Task AnInterruptWhileAHeldTurnHasOnlyThoughtAloud_StillAmendsTheTur reply.ReleaseFirstTurn(); } - var session = await host.FindSessionAsync("call-thinking-turn"); + var session = await host.FindSessionAsync("conversation-thinking-turn"); Assert.NotNull(session); try @@ -777,7 +777,7 @@ public async Task AnInterruptWhileAHeldTurnHasOnlyThoughtAloud_StillAmendsTheTur } /// Polls for the turn a barge-in ends, bounded the same way TelnyxRelayHost's own waits are. - private static async Task WaitForTurnAsync(CallSession session) + private static async Task WaitForTurnAsync(ConversationSession session) { for (var attempt = 0; attempt < 1_000; attempt++) { diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayCallEndTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayConversationEndTests.cs similarity index 68% rename from tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayCallEndTests.cs rename to tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayConversationEndTests.cs index 8c7a15aa..1ae2b455 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayCallEndTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayConversationEndTests.cs @@ -8,7 +8,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Sessions.Memory; using AgentCore.Application.Transcript; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation.Memory; using AgentCore.AspNetCore.DependencyInjection.Startup; using AgentCore.AspNetCore.Tests.Fakes; using AgentCore.Domain.Audit; @@ -20,20 +20,20 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// -/// How the chain of one call closes when the socket ends. +/// How the chain of one conversation closes when the socket ends. /// /// /// -/// Section 11, item 6 and T55/T56: every call writes hash-chained events ending in -/// call.ended, and the reason is one member of the closed set -/// names. The turn loop closes its own chain when the stage machine +/// Section 11, item 6 and T55/T56: every conversation writes hash-chained events ending in +/// conversation.ended, and the reason is one member of the closed set +/// names. The turn loop closes its own chain when the stage machine /// reaches a terminal stage, and that is the only ending the core can see. Every other ending is /// the adapter's to write, because only the adapter sees the socket end — which is what -/// says in its own remarks. +/// says in its own remarks. /// /// /// Every test here drives TelnyxRelayConnection.RunAsync over -/// rather than over a real port. The close of a call is exactly the moment a real socket stops +/// rather than over a real port. The close of a conversation is exactly the moment a real socket stops /// being observable — aborts its own socket on the way out, so a /// graceful vendor close cannot be scripted over the wire at all — and the fake is what lets a test /// script the vendor's own close frame, a faulting write loop, and a host that stops, each on its @@ -41,11 +41,11 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// store, the observers, and the audit queue AddAgentCore registers. /// /// -/// Every test here runs offline against a fake model. There is no Telnyx account, no network call, +/// Every test here runs offline against a fake model. There is no Telnyx account, no network conversation, /// and no API key anywhere in this file. That is T59. /// /// -public sealed class TelnyxRelayCallEndTests +public sealed class TelnyxRelayConversationEndTests { /// A document whose first turn moves the machine into a terminal stage. /// @@ -61,7 +61,7 @@ public sealed class TelnyxRelayCallEndTests model: { ref: reply } items: - { id: greeter, instructions: "greet the caller" } - - { id: closer, instructions: "close the call" } + - { id: closer, instructions: "close the conversation" } entries: main: policy: @@ -70,7 +70,7 @@ public sealed class TelnyxRelayCallEndTests - { id: greeting, agent: greeter, to: [ { stage: close } ] } - { id: close, agent: closer, terminal: true } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -79,9 +79,9 @@ public sealed class TelnyxRelayCallEndTests """; [Fact(Timeout = 30_000)] - public async Task ASocketTheRelayEnds_WritesOneCallEndedThatNamesTheCallerHangup() + public async Task ASocketTheRelayEnds_WritesOneConversationEndedThatNamesTheCallerHangup() { - // The ordinary end of a call. The read loop sees the vendor's own close frame, teardown + // The ordinary end of a conversation. The read loop sees the vendor's own close frame, teardown // picks NormalClosure, and the chain has to close on the reason a report counts years // later — not stop mid-chain with no terminal event at all. using FragmentingChatClient reply = new("hello"); @@ -89,24 +89,24 @@ public async Task ASocketTheRelayEnds_WritesOneCallEndedThatNamesTheCallerHangup TelnyxRelayTurnTests.PolicyYaml, reply); - // One channel, read in order, and DispatchAsync awaits StartCallAsync: the session exists + // One channel, read in order, and DispatchAsync awaits StartConversationAsync: the session exists // before the read loop ever sees the close behind it, so nothing here has to poll for it. - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-hangup")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-hangup")); harness.Socket.QueueClose(); await WaitForTeardownAsync(harness); - var events = await ReadChainAsync(harness, "call-hangup"); + var events = await ReadChainAsync(harness, "conversation-hangup"); Assert.Equal( - [AuditEventKind.CallStarted, AuditEventKind.CallEnded], + [AuditEventKind.ConversationStarted, AuditEventKind.ConversationEnded], events.Select(item => item.Kind).ToArray()); Assert.Equal("caller.hangup", EndReasonOf(events)); Assert.All(events, AuditEventVocabulary.Validate); } [Fact(Timeout = 30_000)] - public async Task AConnectionWhoseWriteLoopFaulted_WritesOneCallEndedThatNamesTheFault() + public async Task AConnectionWhoseWriteLoopFaulted_WritesOneConversationEndedThatNamesTheFault() { // Nothing on a healthy socket makes a send throw, so the fault is injected. The write loop // faults, teardown picks InternalServerError, and the ending recorded must be the fault @@ -117,21 +117,21 @@ public async Task AConnectionWhoseWriteLoopFaulted_WritesOneCallEndedThatNamesTh reply); harness.Socket.FailEverySend(new InvalidOperationException("the send failed.")); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-write-faulted")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-write-faulted")); harness.Socket.Queue(RelayFrames.Prompt("hi", last: true)); await WaitForTeardownAsync(harness); - var events = await ReadChainAsync(harness, "call-write-faulted"); + var events = await ReadChainAsync(harness, "conversation-write-faulted"); - Assert.Equal(AuditEventKind.CallEnded, events[^1].Kind); - Assert.Single(events, item => item.Kind == AuditEventKind.CallEnded); - Assert.Equal("call.faulted", EndReasonOf(events)); + Assert.Equal(AuditEventKind.ConversationEnded, events[^1].Kind); + Assert.Single(events, item => item.Kind == AuditEventKind.ConversationEnded); + Assert.Equal("conversation.faulted", EndReasonOf(events)); Assert.All(events, AuditEventVocabulary.Validate); } [Fact(Timeout = 30_000)] - public async Task AHostThatStopsUnderALiveCall_WritesOneCallEndedThatNamesTheFault() + public async Task AHostThatStopsUnderALiveConversation_WritesOneConversationEndedThatNamesTheFault() { // The caller did not hang up: the process went away underneath them. The closed set of // section 4 holds four endings and this is not one of the other three, so the honest one is @@ -142,44 +142,44 @@ public async Task AHostThatStopsUnderALiveCall_WritesOneCallEndedThatNamesTheFau TelnyxRelayTurnTests.PolicyYaml, reply); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-host-stopping")); - await WaitForSessionAsync(harness, "call-host-stopping"); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-host-stopping")); + await WaitForSessionAsync(harness, "conversation-host-stopping"); harness.StopApplication(); await WaitForTeardownAsync(harness); - var events = await ReadChainAsync(harness, "call-host-stopping"); + var events = await ReadChainAsync(harness, "conversation-host-stopping"); - Assert.Equal(AuditEventKind.CallEnded, events[^1].Kind); - Assert.Equal("call.faulted", EndReasonOf(events)); + Assert.Equal(AuditEventKind.ConversationEnded, events[^1].Kind); + Assert.Equal("conversation.faulted", EndReasonOf(events)); Assert.All(events, AuditEventVocabulary.Validate); } [Fact(Timeout = 30_000)] - public async Task ACallThatAlreadyReachedItsTerminalStage_GetsNoSecondTerminalEvent() + public async Task AConversationThatAlreadyReachedItsTerminalStage_GetsNoSecondTerminalEvent() { // The turn loop closed this chain itself, with agent.completed and the stage that ended it. - // EndCall is idempotent, and this is the proof that the idempotence really holds through - // the adapter's path: one call.ended in the chain, and the reason is the agent's, not the + // EndConversation is idempotent, and this is the proof that the idempotence really holds through + // the adapter's path: one conversation.ended in the chain, and the reason is the agent's, not the // socket's. using FragmentingChatClient reply = new("goodbye then"); await using var harness = await RelayConnectionHarness.StartAsync(TerminalStageYaml, reply); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-completed")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-completed")); harness.Socket.Queue(RelayFrames.Prompt("hi", last: true)); // The session's own completion flag, and never the last frame on the wire: the reply's // closing frame leaves before the turn loop commits the turn, so a test that closed the // socket on that frame would race the very event it is about to assert on. - var session = await WaitForCompletedCallAsync(harness, "call-completed"); + var session = await WaitForCompletedConversationAsync(harness, "conversation-completed"); Assert.True(session.IsComplete); harness.Socket.QueueClose(); await WaitForTeardownAsync(harness); - var events = await ReadChainAsync(harness, "call-completed"); + var events = await ReadChainAsync(harness, "conversation-completed"); - Assert.Single(events, item => item.Kind == AuditEventKind.CallEnded); + Assert.Single(events, item => item.Kind == AuditEventKind.ConversationEnded); Assert.Equal("agent.completed", EndReasonOf(events)); Assert.All(events, AuditEventVocabulary.Validate); } @@ -187,8 +187,8 @@ public async Task ACallThatAlreadyReachedItsTerminalStage_GetsNoSecondTerminalEv [Fact(Timeout = 30_000)] public async Task ASocketThatEndedBeforeTheSetupFrame_WritesNothingAndTearsDownCleanly() { - // No setup frame ever arrived, so there is no call, no session, and nothing to close. A - // chain with a call.ended and no call.started would be a record of a call that never + // No setup frame ever arrived, so there is no conversation, no session, and nothing to close. A + // chain with a conversation.ended and no conversation.started would be a record of a conversation that never // happened, and teardown must not throw its way out of the request handler either. using FragmentingChatClient reply = new("hello"); await using var harness = await RelayConnectionHarness.StartAsync( @@ -210,7 +210,7 @@ public async Task AClockThatThrowsWhileTheChainCloses_StillTearsDownAndStillRele // Section 7.1: teardown never throws out of the request handler. The one input the closing // event reads that can throw is the clock, so it is the one a test can make throw. A throw // here must cost the chain its last event and nothing else — never the session close behind - // it, which is what waits for the words the call's last turn still owed store 1. + // it, which is what waits for the words the conversation's last turn still owed store 1. FaultingClock clock = new(); using FragmentingChatClient reply = new("hello"); await using var harness = await RelayConnectionHarness.StartAsync( @@ -218,8 +218,8 @@ public async Task AClockThatThrowsWhileTheChainCloses_StillTearsDownAndStillRele reply, configure: options => options.TimeProvider = clock); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-broken-clock")); - await WaitForSessionAsync(harness, "call-broken-clock"); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-broken-clock")); + await WaitForSessionAsync(harness, "conversation-broken-clock"); // Armed only once the session exists: the session reads the clock as it is built, and a // clock that failed that read would end the test before the path it is meant to reach. @@ -229,29 +229,29 @@ public async Task AClockThatThrowsWhileTheChainCloses_StillTearsDownAndStillRele await WaitForTeardownAsync(harness); Assert.True(harness.Connection.IsCompletedSuccessfully); - Assert.Null(await Sessions(harness).TryGetAsync("call-broken-clock", TestContext.Current.CancellationToken)); + Assert.Null(await Sessions(harness).TryGetAsync("conversation-broken-clock", TestContext.Current.CancellationToken)); } [Fact(Timeout = 30_000)] - public async Task EndCall_HangUp_FlushesTranscriptBeforeSessionRemoval() + public async Task EndConversation_HangUp_FlushesTranscriptBeforeSessionRemoval() { // Arrange // - // Store 1 is written off the turn, so a call can end with its last words still in flight. + // Store 1 is written off the turn, so a conversation can end with its last words still in flight. // The session is the only thing that can wait for them, so once it leaves the store nothing // can: the record of that call would lose the turn the caller just had, and no error would // say so. Same shape as the teardown that removed a session without closing its chain. - ParkingCallStore transcript = new(); + ParkingConversationStore transcript = new(); using FragmentingChatClient reply = new("your order ships Friday"); var factory = TranscriptBackedSessions(TelnyxRelayTurnTests.PolicyYaml, reply, transcript); - OrderedCallSessions sessions = new(factory, () => transcript.Landed); + OrderedConversationSessions sessions = new(factory, () => transcript.Landed); await using var harness = await RelayConnectionHarness.StartAsync( TelnyxRelayTurnTests.PolicyYaml, reply, relay: options => options.CloseTimeout = TimeSpan.FromSeconds(30), - configure: options => options.UseCallSessions((_, _) => sessions)); + configure: options => options.UseConversationSessions((_, _) => sessions)); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-flush")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-flush")); harness.Socket.Queue(RelayFrames.Prompt("when does my order ship?", last: true)); await transcript.Parked.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken); @@ -268,68 +268,68 @@ public async Task EndCall_HangUp_FlushesTranscriptBeforeSessionRemoval() // Assert Assert.True( sessions.TranscriptLandedAtClose, - "the close returned while store 1 still owed the call its last turn."); - Assert.Null(await sessions.TryGetAsync("call-flush", TestContext.Current.CancellationToken)); + "the close returned while store 1 still owed the conversation its last turn."); + Assert.Null(await sessions.TryGetAsync("conversation-flush", TestContext.Current.CancellationToken)); } [Fact(Timeout = 30_000)] - public async Task StartCall_SecondSetupFrame_FlushesTheReplacedTranscriptBeforeDroppingIt() + public async Task StartConversation_SecondSetupFrame_FlushesTheReplacedTranscriptBeforeDroppingIt() { // Arrange // // A second setup frame replaces the session rather than refusing the socket, and the first // one is dropped there and then. It is dropped by the same rule teardown obeys: the session - // is the only thing that can wait for the words it queued, so the first call's record would + // is the only thing that can wait for the words it queued, so the first conversation's record would // lose its last turn. - ParkingCallStore transcript = new(); + ParkingConversationStore transcript = new(); using FragmentingChatClient reply = new("your order ships Friday"); var factory = TranscriptBackedSessions(TelnyxRelayTurnTests.PolicyYaml, reply, transcript); - OrderedCallSessions sessions = new(factory, () => transcript.Landed); + OrderedConversationSessions sessions = new(factory, () => transcript.Landed); await using var harness = await RelayConnectionHarness.StartAsync( TelnyxRelayTurnTests.PolicyYaml, reply, relay: options => options.CloseTimeout = TimeSpan.FromSeconds(30), - configure: options => options.UseCallSessions((_, _) => sessions)); + configure: options => options.UseConversationSessions((_, _) => sessions)); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-first")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-first")); harness.Socket.Queue(RelayFrames.Prompt("when does my order ship?", last: true)); await transcript.Parked.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken); // Act - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-second")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-second")); - // Read as in EndCall_HangUp_FlushesTranscriptBeforeSessionRemoval: the wait runs out while + // Read as in EndConversation_HangUp_FlushesTranscriptBeforeSessionRemoval: the wait runs out while // the write is parked, and ends early when the drop did not wait for it. await WaitQuietlyAsync(sessions.Closed, TimeSpan.FromSeconds(2)); transcript.Release(); // Assert - await WaitForSessionAsync(harness, "call-second"); + await WaitForSessionAsync(harness, "conversation-second"); Assert.True( sessions.TranscriptLandedAtClose, "the close returned while store 1 still owed its call the last turn."); } [Fact(Timeout = 30_000)] - public async Task EndCall_StoreThatThrowsOnTheClose_LogsItAndStillTearsDown() + public async Task EndConversation_StoreThatThrowsOnTheClose_LogsItAndStillTearsDown() { // Arrange // - // ICallSessions is a public seam, and the close is the last thing teardown does. The + // IConversationSessions is a public seam, and the close is the last thing teardown does. The // in-memory store never fails, so a store held over the network is the only one that can // fail here — and its failure must not leave the request handler, which section 7.1 forbids. - EventObservedLoggerProvider capture = new("CallCloseFaulted"); + EventObservedLoggerProvider capture = new("ConversationCloseFaulted"); using FragmentingChatClient reply = new("your order ships Friday"); - FaultingCallSessions sessions = new( + FaultingConversationSessions sessions = new( SessionsFor(TelnyxRelayTurnTests.PolicyYaml, reply), new InvalidOperationException("the store is gone.")); await using var harness = await RelayConnectionHarness.StartAsync( TelnyxRelayTurnTests.PolicyYaml, reply, logging: logging => logging.AddProvider(capture), - configure: options => options.UseCallSessions((_, _) => sessions)); + configure: options => options.UseConversationSessions((_, _) => sessions)); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-store-faulted")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-store-faulted")); // Act harness.Socket.QueueClose(); @@ -346,25 +346,25 @@ public async Task EndCall_StoreThatThrowsOnTheClose_LogsItAndStillTearsDown() } [Fact(Timeout = 30_000)] - public async Task EndCall_StoreThatNeverAnswersTheClose_TimesOutRatherThanWedgingTeardown() + public async Task EndConversation_StoreThatNeverAnswersTheClose_TimesOutRatherThanWedgingTeardown() { // Arrange // // The other half of the same seam. A store that stops answering is not a store that throws: // an unbounded wait here would hold this connection, its Kestrel request, and its - // registration on ApplicationStopping for the life of the process, and every call after it + // registration on ApplicationStopping for the life of the process, and every conversation after it // would do the same. EventObservedLoggerProvider capture = new("TeardownTimedOut"); using FragmentingChatClient reply = new("your order ships Friday"); - HangingCallSessions sessions = new(SessionsFor(TelnyxRelayTurnTests.PolicyYaml, reply)); + HangingConversationSessions sessions = new(SessionsFor(TelnyxRelayTurnTests.PolicyYaml, reply)); await using var harness = await RelayConnectionHarness.StartAsync( TelnyxRelayTurnTests.PolicyYaml, reply, logging: logging => logging.AddProvider(capture), relay: options => options.CloseTimeout = TimeSpan.FromSeconds(1), - configure: options => options.UseCallSessions((_, _) => sessions)); + configure: options => options.UseConversationSessions((_, _) => sessions)); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-store-hung")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-store-hung")); try { @@ -375,7 +375,7 @@ public async Task EndCall_StoreThatNeverAnswersTheClose_TimesOutRatherThanWedgin // Assert // // The text is read rather than the line alone: TeardownTimedOut is written about - // whichever task ran out of time, and nothing else in this call is slow, so a match on + // whichever task ran out of time, and nothing else in this conversation is slow, so a match on // the name alone would still pass if the close were left unbounded and some other wait // timed out instead. await capture.Observed.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); @@ -392,33 +392,33 @@ public async Task EndCall_StoreThatNeverAnswersTheClose_TimesOutRatherThanWedgin /// The document to compile. /// The model behind every reference in it. /// The factory. - private static CallSessionFactory SessionsFor(string yaml, IChatClient reply) - => TranscriptBackedSessions(yaml, reply, new InMemoryCallStore()); + private static ConversationSessionFactory SessionsFor(string yaml, IChatClient reply) + => TranscriptBackedSessions(yaml, reply, new InMemoryConversationStore()); /// Builds the session factory of one document over a given store 1. /// The document, as YAML. /// The model behind every agent. - /// Where the words of a call are written. + /// Where the words of a conversation are written. /// The factory, ready to register over the one AddAgentCore built. /// - /// A document that names no providers.calls compiles onto the memory store, so this is the - /// only seam a test has for putting a slow store behind a call. It is why the whole factory is + /// A document that names no providers.conversations compiles onto the memory store, so this is the + /// only seam a test has for putting a slow store behind a conversation. It is why the whole factory is /// rebuilt rather than decorated: the store is compiled into the agent, and the factory holds /// the compiled agent. /// - private static CallSessionFactory TranscriptBackedSessions( - string yaml, IChatClient reply, ICallStore transcript) + private static ConversationSessionFactory TranscriptBackedSessions( + string yaml, IChatClient reply, IConversationStore transcript) { var document = ConfigurationLoader.LoadYaml(yaml); RoutingChatClientFactory chatClients = new(reply); var compiled = ConfigurationCompiler.CompileAll( document, - new AgentCompilationContext(chatClients) { CallStore = transcript })["main"]; + new AgentCompilationContext(chatClients) { ConversationStore = transcript })["main"]; - return new CallSessionFactory( + return new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), - CallSessionFactory.CreateExtractor(compiled, chatClients)); + ConversationSessionFactory.CreateExtractor(compiled, chatClients)); } /// Waits for one task, and treats running out of time as an answer rather than a fault. @@ -465,15 +465,15 @@ private static async Task WaitForTeardownAsync(RelayConnectionHarness harness) } } - /// Waits until the store holds one call. + /// Waits until the store holds one conversation. /// The running connection. - /// The id of the call. + /// The id of the conversation. /// A task that completes once the session appears. - private static async Task WaitForSessionAsync(RelayConnectionHarness harness, string callId) + private static async Task WaitForSessionAsync(RelayConnectionHarness harness, string conversationId) { for (var attempt = 0; attempt < 200; attempt++) { - if (await Sessions(harness).TryGetAsync(callId, TestContext.Current.CancellationToken) is not null) + if (await Sessions(harness).TryGetAsync(conversationId, TestContext.Current.CancellationToken) is not null) { return; } @@ -481,18 +481,18 @@ private static async Task WaitForSessionAsync(RelayConnectionHarness harness, st await Task.Delay(10, TestContext.Current.CancellationToken); } - Assert.Fail($"the session of call '{callId}' never appeared."); + Assert.Fail($"the session of conversation '{conversationId}' never appeared."); } - /// Waits until one call has closed its own chain from the terminal stage. + /// Waits until one conversation has closed its own chain from the terminal stage. /// The running connection. - /// The id of the call. + /// The id of the conversation. /// The completed session. - private static async Task WaitForCompletedCallAsync(RelayConnectionHarness harness, string callId) + private static async Task WaitForCompletedConversationAsync(RelayConnectionHarness harness, string conversationId) { for (var attempt = 0; attempt < 400; attempt++) { - if (await Sessions(harness).TryGetAsync(callId, TestContext.Current.CancellationToken) + if (await Sessions(harness).TryGetAsync(conversationId, TestContext.Current.CancellationToken) is { IsComplete: true } session) { return session; @@ -501,14 +501,14 @@ private static async Task WaitForCompletedCallAsync(RelayConnection await Task.Delay(10, TestContext.Current.CancellationToken); } - Assert.Fail($"the call '{callId}' never reached its terminal stage."); + Assert.Fail($"the conversation '{conversationId}' never reached its terminal stage."); throw new InvalidOperationException("unreachable: Assert.Fail always throws."); } - /// Flushes the queue and reads back the chain of one call. + /// Flushes the queue and reads back the chain of one conversation. /// The connection that has already torn down. - /// The id of the call. - /// The events of that call, oldest first. + /// The id of the conversation. + /// The events of that conversation, oldest first. /// /// The queue is what keeps the append off the turn, so a reader that wants the rows now asks /// for them now. Nothing here waits on the chain being non-empty: every test that calls this @@ -516,10 +516,10 @@ private static async Task WaitForCompletedCallAsync(RelayConnection /// private static async Task> ReadChainAsync( RelayConnectionHarness harness, - string callId) + string conversationId) { await Queue(harness).FlushAsync(TestContext.Current.CancellationToken); - return Sink(harness).EventsOf(callId); + return Sink(harness).EventsOf(conversationId); } /// Reads the end reason of the last event of one chain. @@ -527,7 +527,7 @@ private static async Task> ReadChainAsync( /// The wire token under . private static string EndReasonOf(IReadOnlyList events) { - var ended = Assert.Single(events, item => item.Kind == AuditEventKind.CallEnded); + var ended = Assert.Single(events, item => item.Kind == AuditEventKind.ConversationEnded); return ended.Payload[AuditPayloadKeys.EndReason]; } @@ -540,7 +540,7 @@ private static InMemoryAuditSink Sink(RelayConnectionHarness harness) => Assert.IsType(harness.Services.GetRequiredService().Store); /// Reads back the live sessions. - private static ICallSessions Sessions(RelayConnectionHarness harness) + private static IConversationSessions Sessions(RelayConnectionHarness harness) => harness.Services.GetRequiredService().ForSessions("main"); } @@ -548,7 +548,7 @@ private static ICallSessions Sessions(RelayConnectionHarness harness) /// A clock a test breaks on demand. /// /// - /// is the one call CallSession.EndCall makes that can + /// is the one call ConversationSession.EndConversation makes that can /// throw at all: the reason is a member of a closed set the connection picks itself, and the /// dispatcher behind the event swallows everything an observer raises. Breaking the clock is /// therefore the only way a test can reach the guard that keeps section 7.1's promise — teardown @@ -575,32 +575,32 @@ public override DateTimeOffset GetUtcNow() /// /// The live sessions, with a note of what store 1 had done by the time a close returned. /// - internal sealed class OrderedCallSessions(ICallSessionFactory factory, Func transcriptLanded) - : ICallSessions + internal sealed class OrderedConversationSessions(IConversationSessionFactory factory, Func transcriptLanded) + : IConversationSessions { - private readonly InMemoryCallSessions _inner = - new(factory, InMemoryCallSessions.DefaultIdleTimeout, TimeProvider.System); + private readonly InMemoryConversationSessions _inner = + new(factory, InMemoryConversationSessions.DefaultIdleTimeout, TimeProvider.System); private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); /// Gets a task that completes when a session has finished closing. public Task Closed => _closed.Task; - /// Gets whether store 1 had written the call's words by the time the close returned. + /// Gets whether store 1 had written the conversation's words by the time the close returned. public bool? TranscriptLandedAtClose { get; private set; } /// - public ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default) - => _inner.OpenAsync(callId, cancellationToken); + public ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default) + => _inner.OpenAsync(conversationId, cancellationToken); /// - public ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default) - => _inner.TryGetAsync(callId, cancellationToken); + public ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default) + => _inner.TryGetAsync(conversationId, cancellationToken); /// - public async ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default) { - await _inner.CloseAsync(callId, cancellationToken); + await _inner.CloseAsync(conversationId, cancellationToken); TranscriptLandedAtClose ??= transcriptLanded(); _closed.TrySetResult(); } @@ -612,26 +612,26 @@ public async ValueTask CloseAsync(string callId, CancellationToken cancellationT /// /// It throws before its first await rather than from inside an async body, which is the harder of /// the two for teardown to catch: a synchronous throw out of a method lands - /// at the call site, not on the returned task. + /// at the conversation site, not on the returned task. /// - internal sealed class FaultingCallSessions(ICallSessionFactory factory, Exception fault) : ICallSessions + internal sealed class FaultingConversationSessions(IConversationSessionFactory factory, Exception fault) : IConversationSessions { - private readonly InMemoryCallSessions _inner = - new(factory, InMemoryCallSessions.DefaultIdleTimeout, TimeProvider.System); + private readonly InMemoryConversationSessions _inner = + new(factory, InMemoryConversationSessions.DefaultIdleTimeout, TimeProvider.System); /// Gets whether teardown ever reached the close. public bool CloseAttempted { get; private set; } /// - public ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default) - => _inner.OpenAsync(callId, cancellationToken); + public ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default) + => _inner.OpenAsync(conversationId, cancellationToken); /// - public ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default) - => _inner.TryGetAsync(callId, cancellationToken); + public ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default) + => _inner.TryGetAsync(conversationId, cancellationToken); /// - public ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default) + public ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default) { CloseAttempted = true; throw fault; @@ -639,20 +639,20 @@ public ValueTask CloseAsync(string callId, CancellationToken cancellationToken = } /// Sessions whose close never answers until a test releases it. - internal sealed class HangingCallSessions(ICallSessionFactory factory) : ICallSessions + internal sealed class HangingConversationSessions(IConversationSessionFactory factory) : IConversationSessions { - private readonly InMemoryCallSessions _inner = - new(factory, InMemoryCallSessions.DefaultIdleTimeout, TimeProvider.System); + private readonly InMemoryConversationSessions _inner = + new(factory, InMemoryConversationSessions.DefaultIdleTimeout, TimeProvider.System); private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); /// - public ValueTask OpenAsync(string? callId, CancellationToken cancellationToken = default) - => _inner.OpenAsync(callId, cancellationToken); + public ValueTask OpenAsync(string? conversationId, CancellationToken cancellationToken = default) + => _inner.OpenAsync(conversationId, cancellationToken); /// - public ValueTask TryGetAsync(string callId, CancellationToken cancellationToken = default) - => _inner.TryGetAsync(callId, cancellationToken); + public ValueTask TryGetAsync(string conversationId, CancellationToken cancellationToken = default) + => _inner.TryGetAsync(conversationId, cancellationToken); /// /// @@ -660,10 +660,10 @@ public ValueTask OpenAsync(string? callId, CancellationToken cancel /// there, so a store that honoured a token would prove /// nothing about the bound teardown puts on the wait itself. /// - public async ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default) + public async ValueTask CloseAsync(string conversationId, CancellationToken cancellationToken = default) { await _release.Task; - await _inner.CloseAsync(callId, CancellationToken.None); + await _inner.CloseAsync(conversationId, CancellationToken.None); } /// Lets the parked close finish. diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs index 1d5adbea..f7142a4e 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs @@ -9,11 +9,11 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// -/// How the route behaves before a call, and how the socket ends. +/// How the route behaves before a conversation, and how the socket ends. /// /// /// Every test here runs offline against a fake model and a fake relay. There is no Telnyx account, -/// no network call, and no API key anywhere in this file. +/// no network conversation, and no API key anywhere in this file. /// public sealed class TelnyxRelayEndpointTests { @@ -48,8 +48,8 @@ public async Task AHostThatForgotUseWebSockets_FailsWithAMessageThatNamesTheFix( // --------------------------------------------------------------------------------------------- // The three option-range facts that stood here are now in - // AgentCore.AspNetCore.Tests/Call/CallOptionsFromDocumentTests. The limits come out of - // providers.call rather than out of a C# argument, so the same three ranges are refused by a + // AgentCore.AspNetCore.Tests/Conversation/ConversationOptionsFromDocumentTests. The limits come out of + // providers.conversation rather than out of a C# argument, so the same three ranges are refused by a // ConfigurationLoadException carrying the pointer of the offending field, and there is no // longer a map-time ArgumentOutOfRangeException for this file to assert. Spec §12. // --------------------------------------------------------------------------------------------- @@ -120,24 +120,24 @@ public async Task AFrameOverTheLimit_ClosesWithMessageTooBig() [Fact(Timeout = 30_000)] public async Task AClientThatVanishesWithNoCloseFrame_ReleasesTheSession() { - // The vendor never reconnects, so a dead socket is a finished call. + // The vendor never reconnects, so a dead socket is a finished conversation. using FragmentingChatClient reply = new("hello"); await using var host = await TelnyxRelayHost.StartAsync(TelnyxRelayTurnTests.PolicyYaml, reply); var relay = await host.ConnectAsync(); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-dropped")); - await host.WaitForSessionAsync("call-dropped"); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-dropped")); + await host.WaitForSessionAsync("conversation-dropped"); relay.Abort(); - await host.WaitForCallEndAsync("call-dropped"); - Assert.Null(await host.FindSessionAsync("call-dropped")); + await host.WaitForConversationEndAsync("conversation-dropped"); + Assert.Null(await host.FindSessionAsync("conversation-dropped")); } [Fact(Timeout = 30_000)] - public async Task ASocketThatGoesSilent_EndsTheCallAtTheIdleDeadline() + public async Task ASocketThatGoesSilent_EndsTheConversationAtTheIdleDeadline() { - // The vendor never reconnects, so a silent socket is a call that already ended. Nothing + // The vendor never reconnects, so a silent socket is a conversation that already ended. Nothing // else notices it: the keep-alive ping only catches a peer the network itself stopped // answering. The clock is a FakeTimeProvider, moved forward below with no real sleep at // all, so this test proves the idle deadline fires rather than passing because the @@ -154,8 +154,8 @@ public async Task ASocketThatGoesSilent_EndsTheCallAtTheIdleDeadline() relay: options => options.IdleTimeout = TimeSpan.FromSeconds(30)); await using var relay = await host.ConnectAsync(); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-silent")); - await host.WaitForSessionAsync("call-silent"); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-silent")); + await host.WaitForSessionAsync("conversation-silent"); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10)); using var bounded = CancellationTokenSource.CreateLinkedTokenSource( @@ -169,8 +169,8 @@ public async Task ASocketThatGoesSilent_EndsTheCallAtTheIdleDeadline() // about whether the read loop has already armed its next idle deadline against this // clock by the time this runs. Advancing once could land before that deadline exists // and move nothing that matters. Advancing repeatedly instead closes that race: - // whichever call lands after the deadline is armed pushes the clock straight past its - // due time, however many earlier calls landed too early to move anything. + // whichever conversation lands after the deadline is armed pushes the clock straight past its + // due time, however many earlier conversations landed too early to move anything. while (!closing.IsCompleted) { clock.Advance(TimeSpan.FromSeconds(31)); @@ -189,16 +189,16 @@ public async Task ASocketThatGoesSilent_EndsTheCallAtTheIdleDeadline() Assert.True(capture.Observed.IsCompletedSuccessfully, "the idle deadline closed the socket without logging IdleTimeoutReached."); Assert.Equal(LogLevel.Information, capture.Level); - await host.WaitForCallEndAsync("call-silent"); + await host.WaitForConversationEndAsync("conversation-silent"); } [Fact(Timeout = 30_000)] - public async Task ABusyCall_NeverTimesOutBetweenMessages() + public async Task ABusyConversation_NeverTimesOutBetweenMessages() { // Task 8: each inbound frame resets the idle clock. Proven here by advancing the fake // clock five times, each step under IdleTimeout on its own but well over it summed — a // clock that failed to reset on every dtmf frame between the steps would have closed this - // call by the second step at the latest. Dtmf is the frame to drive this with because + // conversation by the second step at the latest. Dtmf is the frame to drive this with because // TelnyxRelayLog.DtmfReceived logs no argument at all, so counting it never risks logging // the digit itself. const int steps = 5; @@ -213,8 +213,8 @@ public async Task ABusyCall_NeverTimesOutBetweenMessages() relay: options => options.IdleTimeout = TimeSpan.FromSeconds(2)); await using var relay = await host.ConnectAsync(); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-busy")); - await host.WaitForSessionAsync("call-busy"); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-busy")); + await host.WaitForSessionAsync("conversation-busy"); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10)); using var bounded = CancellationTokenSource.CreateLinkedTokenSource( @@ -236,7 +236,7 @@ public async Task ABusyCall_NeverTimesOutBetweenMessages() // before the server had a chance to rearm it for the next one — a false close that // would have nothing to do with whether resets actually work. Watching the count // reach this step, the same way the interrupt tests wait on a log line rather than - // sleeping, is what keeps every Advance call behind the message it depends on. + // sleeping, is what keeps every Advance conversation behind the message it depends on. var expected = step + 1; while (dtmf.Count < expected) { @@ -246,10 +246,10 @@ public async Task ABusyCall_NeverTimesOutBetweenMessages() } catch (OperationCanceledException) when (deadline.IsCancellationRequested) { - Assert.Fail($"only {dtmf.Count} of {steps} dtmf frames were processed within ten seconds; the call likely closed early."); + Assert.Fail($"only {dtmf.Count} of {steps} dtmf frames were processed within ten seconds; the conversation likely closed early."); return; } - Assert.NotNull(await host.FindSessionAsync("call-busy")); + Assert.NotNull(await host.FindSessionAsync("conversation-busy")); } } diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameCostTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameCostTests.cs index 26d51a56..083de507 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameCostTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameCostTests.cs @@ -17,15 +17,15 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// anywhere in this solution — item 6c holds "no audio buffer, codec, sample rate, or playback /// clock" by construction, and the Conversation Relay carries text frames over a WebSocket instead — /// so the frame is what that rule is actually about. It is the thing that arrives many times a -/// second on a live call, and it is the thing that must not cost a log line or a metric point. +/// second on a live conversation, and it is the thing that must not cost a log line or a metric point. /// /// /// The proof is a comparison rather than a threshold, because a threshold would have to guess how -/// many lines a call is allowed. One connection is driven twice, once with a few frames and once +/// many lines a conversation is allowed. One connection is driven twice, once with a few frames and once /// with ten times as many, and the two runs must leave exactly the same number of log records and /// exactly the same number of metric measurements behind. A signal that fires once for each frame -/// grows with the frame count and fails here; a signal that fires once for the call or once for the -/// turn does not, because both runs run one call and no turn at all. +/// grows with the frame count and fails here; a signal that fires once for the conversation or once for the +/// turn does not, because both runs run one conversation and no turn at all. /// /// /// The frames are interim transcripts — prompt with last: false — which T70 drops @@ -36,7 +36,7 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// /// /// Every test here runs offline against a fake model and a fake relay. There is no Telnyx account, -/// no network call, and no API key anywhere in this file. +/// no network conversation, and no API key anywhere in this file. /// /// [Collection(TelnyxRelayFrameCostSuite.Name)] @@ -51,8 +51,8 @@ public sealed class TelnyxRelayFrameCostTests [Fact(Timeout = 60_000)] public async Task TenTimesTheInboundFrames_CostNoMoreLogRecordsAndNoMoreMetricMeasurements() { - var few = await MeasureAsync(FewFrames, "call-frame-cost-few"); - var many = await MeasureAsync(ManyFrames, "call-frame-cost-many"); + var few = await MeasureAsync(FewFrames, "conversation-frame-cost-few"); + var many = await MeasureAsync(ManyFrames, "conversation-frame-cost-many"); // The listener really found this library's meter. Without this the measurement assertion // below could pass on two empty subscriptions and prove nothing at all. @@ -63,7 +63,7 @@ public async Task TenTimesTheInboundFrames_CostNoMoreLogRecordsAndNoMoreMetricMe Assert.NotEqual(0, few.Records); // Section 3.1, both halves of it. Ten times the frames, and not one line and not one - // measurement more. The counts are not zero — a call still logs what a call costs, and the + // measurement more. The counts are not zero — a conversation still logs what a conversation costs, and the // one dtmf frame each run ends with is one line in both — but nothing here is charged to a // frame, so nothing here moves when the frame count does. Assert.Equal(few.Records, many.Records); @@ -72,9 +72,9 @@ public async Task TenTimesTheInboundFrames_CostNoMoreLogRecordsAndNoMoreMetricMe /// Drives one connection over interim prompts and counts what it cost. /// How many prompt frames with last: false to send. - /// The callSessionId of this run's setup frame. + /// The conversationSessionId of this run's setup frame. /// What the run wrote, metered, and subscribed to. - private static async Task MeasureAsync(int frames, string callId) + private static async Task MeasureAsync(int frames, string conversationId) { // The instruments are static fields of AgentCoreTelemetry, and a const never touches a type // initializer, so nothing this file references would otherwise create the meter. Forcing @@ -97,8 +97,8 @@ void RecordMeasurement() using MeterListener listener = new(); listener.InstrumentPublished = (instrument, active) => { - // Meter name and nothing else. T61 forbids a call id on a metric attribute, so there is - // deliberately no tag on any of these instruments that could narrow this to one call — + // Meter name and nothing else. T61 forbids a conversation id on a metric attribute, so there is + // deliberately no tag on any of these instruments that could narrow this to one conversation — // which is why this collection runs alone, below. if (!string.Equals(instrument.Meter.Name, AgentCoreTelemetry.MeterName, StringComparison.Ordinal)) { @@ -148,8 +148,8 @@ void RecordMeasurement() { await using var relay = await host.ConnectAsync(); - await relay.SendAsync(RelayFrames.Setup(callSessionId: callId)); - await host.WaitForSessionAsync(callId); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: conversationId)); + await host.WaitForSessionAsync(conversationId); for (var frame = 0; frame < frames; frame++) { @@ -173,12 +173,12 @@ void RecordMeasurement() Assert.Fail($"the connection never read past the {frames} interim prompts within twenty seconds."); } - // Counted here, with the call still up, rather than after the socket and the host are - // torn down. Teardown is once for a call and never once for a frame, so it is not what + // Counted here, with the conversation still up, rather than after the socket and the host are + // torn down. Teardown is once for a conversation and never once for a frame, so it is not what // this test is about, and it is the one part of a run that is not reproducible line for // line: FakeRelayClient.DisposeAsync cancels its own pending receive, which — as that // class documents — leaves the socket Aborted rather than closed, so the connection - // sometimes reaches CallDroppedWithNoCloseFrame before the host stops and sometimes does + // sometimes reaches ConversationDroppedWithNoCloseFrame before the host stops and sometimes does // not, and the host's own shutdown lines interleave with Kestrel's either way. Every // line up to and including the one the sentinel just waited for is fixed. listener.Dispose(); @@ -202,9 +202,9 @@ void RecordMeasurement() /// /// /// A subscribes to a meter for the whole process, and T61 is the reason -/// it cannot narrow that to one call: no instrument of this library carries a call id, a session id, +/// it cannot narrow that to one conversation: no instrument of this library carries a conversation id, a session id, /// or a turn id, because one such attribute is one permanent series. A turn running in another test -/// class at the same moment would therefore land on this listener and be counted as this call's +/// class at the same moment would therefore land on this listener and be counted as this conversation's /// cost. Parallelisation is switched off for this collection so that never happens; xUnit runs a /// collection marked this way apart from every other collection in the assembly. /// diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameReaderTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameReaderTests.cs index e451b1c0..02053cbf 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameReaderTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayFrameReaderTests.cs @@ -10,7 +10,7 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// /// /// Every JSON body below is copied from the Telnyx Conversation Relay page, so these are golden -/// inputs and not invented ones. Every test here runs offline. There is no network call and no API +/// inputs and not invented ones. Every test here runs offline. There is no network conversation and no API /// key anywhere in this file. /// public sealed class TelnyxRelayFrameReaderTests @@ -25,9 +25,9 @@ public void ASetupFrame_ReadsTheIdsTheTransferWillNeed() const string Json = """ {"type":"setup","sessionId":"7a7e6a4f","accountSid":"1f1a8b6f", - "callSid":"v2:abc","callControlId":"v2:abc","callSessionId":"ff55a038", + "callSid":"v2:abc","callControlId":"v2:abc","conversationSessionId":"ff55a038", "callLegId":"428c31b6","from":"+13122010094","to":"+13122123456", - "direction":"inbound","callerName":"","callStatus":"active", + "direction":"inbound","callerName":"","conversationStatus":"active", "customParameters":{"customer_id":"customer_123"}} """; @@ -37,7 +37,7 @@ public void ASetupFrame_ReadsTheIdsTheTransferWillNeed() Assert.Equal("7a7e6a4f", setup.SessionId); Assert.Equal("v2:abc", setup.CallSid); Assert.Equal("v2:abc", setup.CallControlId); - Assert.Equal("ff55a038", setup.CallSessionId); + Assert.Equal("ff55a038", setup.ConversationSessionId); Assert.Equal("+13122010094", setup.From); Assert.Equal("+13122123456", setup.To); Assert.Equal("customer_123", setup.CustomParameters!["customer_id"]); @@ -98,7 +98,7 @@ public void AnErrorFrame_ReadsTheDescription() [Fact] public void AnUnknownType_IsRefusedAndNamed() { - // A vendor that adds a frame must not be able to drop a call. Section 7.1. + // A vendor that adds a frame must not be able to drop a conversation. Section 7.1. Assert.False(Read("""{"type":"whisper","text":"x"}""", out var frame, out var unknown)); Assert.Null(frame); Assert.Equal("whisper", unknown); @@ -117,7 +117,7 @@ public void AMalformedBody_IsRefusedAndThrowsNothing() public void ADecimalInterruptDuration_IsARefusedBodyAndNotAnUnreadableFrame() { // The wire carries an integer of milliseconds, and the record binds one. A vendor that - // starts sending 1820.5 must not thereby end a call at the exact moment of a barge-in, so + // starts sending 1820.5 must not thereby end a conversation at the exact moment of a barge-in, so // the type is named on refusedType and the caller keeps the socket. Section 7.1. const string Json = """ @@ -135,11 +135,11 @@ public void ADecimalInterruptDuration_IsARefusedBodyAndNotAnUnreadableFrame() public void ANonStringCustomParameter_IsARefusedBodyAndNotAnUnreadableFrame() { // customParameters binds to a dictionary of strings, and the host chooses what goes in it. - // A number there would otherwise end the call on the setup frame, before it ever began. + // A number there would otherwise end the conversation on the setup frame, before it ever began. const string Json = """ {"type":"setup","sessionId":"7a7e6a4f","callSid":"v2:abc","callControlId":"v2:abc", - "callSessionId":"ff55a038","from":"+13122010094","to":"+13122123456", + "conversationSessionId":"ff55a038","from":"+13122010094","to":"+13122123456", "customParameters":{"a":7}} """; diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs index 133ae79f..86957bcc 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs @@ -6,11 +6,11 @@ namespace AgentCore.AspNetCore.Tests.Vendors.TelnyxRelay; /// -/// One relay socket runs one call, and one final prompt runs one turn. +/// One relay socket runs one conversation, and one final prompt runs one turn. /// /// /// Every test here runs offline against a fake model and a fake relay. There is no Telnyx account, -/// no network call, and no API key anywhere in this file. +/// no network conversation, and no API key anywhere in this file. /// public sealed class TelnyxRelayTurnTests { @@ -23,7 +23,7 @@ public sealed class TelnyxRelayTurnTests items: - { id: greeter, instructions: "greet the caller" } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -55,21 +55,21 @@ public async Task AFinalPrompt_RunsOneTurnAndSendsOneTextFrameForEachUpdate() } [Fact] - public async Task ASetupFrame_NamesTheCallAfterTheCallSessionId() + public async Task ASetupFrame_NamesTheConversationAfterTheConversationSessionId() { - // callSessionId groups the legs of one logical call, so it survives the warm transfer of + // conversationSessionId groups the legs of one logical conversation, so it survives the warm transfer of // slice 2. A leg id would not. using FragmentingChatClient reply = new("hello"); await using var host = await TelnyxRelayHost.StartAsync(PolicyYaml, reply); await using var relay = await host.ConnectAsync(); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "logical-call-7")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "logical-conversation-7")); await relay.SendAsync(RelayFrames.Prompt("hi", last: true)); await relay.ReadTextFramesUntilLastAsync(); - var session = await host.FindSessionAsync("logical-call-7"); + var session = await host.FindSessionAsync("logical-conversation-7"); Assert.NotNull(session); - Assert.Equal("logical-call-7", session.CallId); + Assert.Equal("logical-conversation-7", session.ConversationId); } // ------------------------------------------------------------------------------------------- @@ -151,7 +151,7 @@ public async Task AnInterimPrompt_RunsNoTurn() // The relay sends many interim transcripts per turn. One turn per partial word would run // the model many times over and speak nonsense. // - // Calls == 1 alone would not catch a reader that started a turn on every prompt frame: the + // Conversations == 1 alone would not catch a reader that started a turn on every prompt frame: the // later interim prompts would then hit the in-flight guard and be dropped for the wrong // reason, and Calls would still read 1. Asserting on the text the model actually saw is // what tells the two apart — the model must see the final transcript, never an interim one. @@ -186,7 +186,7 @@ public async Task APromptSplitAcrossThreeFragments_ArrivesAsOneFrame() } [Fact] - public async Task AnUnknownFrameType_IsIgnoredAndTheCallGoesOn() + public async Task AnUnknownFrameType_IsIgnoredAndTheConversationGoesOn() { using FragmentingChatClient reply = new("hello"); await using var host = await TelnyxRelayHost.StartAsync(PolicyYaml, reply); @@ -200,11 +200,11 @@ public async Task AnUnknownFrameType_IsIgnoredAndTheCallGoesOn() } [Fact(Timeout = 30_000)] - public async Task ADecimalDurationOnAnInterruptFrame_IsRefusedAndTheCallGoesOn() + public async Task ADecimalDurationOnAnInterruptFrame_IsRefusedAndTheConversationGoesOn() { - // Section 7.1: a vendor that changes a frame must not be able to drop a call. The type is + // Section 7.1: a vendor that changes a frame must not be able to drop a conversation. The type is // known and only one field will not bind, so the frame is refused and the socket lives. - // A decimal here would otherwise end a live call at the exact moment of a barge-in. + // A decimal here would otherwise end a live conversation at the exact moment of a barge-in. using FragmentingChatClient reply = new("hello"); EventObservedLoggerProvider capture = new("FrameBodyRefused"); await using var host = await TelnyxRelayHost.StartAsync( @@ -245,11 +245,11 @@ await relay.SendRawAsync( } [Fact(Timeout = 30_000)] - public async Task ANonStringCustomParameterOnASetupFrame_IsRefusedAndTheCallGoesOn() + public async Task ANonStringCustomParameterOnASetupFrame_IsRefusedAndTheConversationGoesOn() { - // The same rule, on the one frame that starts a call. customParameters binds to a + // The same rule, on the one frame that starts a conversation. customParameters binds to a // dictionary of strings, so a number in it will not bind, and refusing the whole socket - // would kill the call before it ever began. + // would kill the conversation before it ever began. using FragmentingChatClient reply = new("hello"); EventObservedLoggerProvider capture = new("FrameBodyRefused"); await using var host = await TelnyxRelayHost.StartAsync( @@ -265,9 +265,9 @@ public async Task ANonStringCustomParameterOnASetupFrame_IsRefusedAndTheCallGoes await relay.SendRawAsync( """ {"type":"setup","sessionId":"session-one","callSid":"v2:leg-one", - "callControlId":"v2:leg-one","callSessionId":"call-bad-parameters","callLegId":"leg-one", + "callControlId":"v2:leg-one","conversationSessionId":"conversation-bad-parameters","callLegId":"leg-one", "from":"+13122010094","to":"+13122123456","direction":"inbound", - "customParameters":{"a":7},"callStatus":"active"} + "customParameters":{"a":7},"conversationStatus":"active"} """); try @@ -280,7 +280,7 @@ await relay.SendRawAsync( } // The socket is still usable, which is the whole point: the vendor gets another chance. - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-after-bad-setup")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-after-bad-setup")); await relay.SendAsync(RelayFrames.Prompt("hi", last: true)); try @@ -296,7 +296,7 @@ await relay.SendRawAsync( [Fact] public async Task AnErrorFrame_KeepsTheSocketOpen() { - // This frame reports our defect, not a call fault. Dropping the call would be worse. + // This frame reports our defect, not a conversation fault. Dropping the conversation would be worse. using FragmentingChatClient reply = new("hello"); await using var host = await TelnyxRelayHost.StartAsync(PolicyYaml, reply); await using var relay = await host.ConnectAsync(); @@ -311,8 +311,8 @@ public async Task AnErrorFrame_KeepsTheSocketOpen() [Fact(Timeout = 30_000)] public async Task ASecondSetupFrame_ReplacesTheFirstSessionAndReleasesIt() { - // One socket carries one call, so a second setup frame is the vendor's defect. Section 7.1 - // still forbids dropping a call over one, so it replaces rather than refuses. Teardown only + // One socket carries one conversation, so a second setup frame is the vendor's defect. Section 7.1 + // still forbids dropping a conversation over one, so it replaces rather than refuses. Teardown only // ever closes the session the connection currently holds, so a first session left behind // would never have anything wait for the words it still owed store 1. using FragmentingChatClient reply = new("hello"); @@ -327,10 +327,10 @@ public async Task ASecondSetupFrame_ReplacesTheFirstSessionAndReleasesIt() using var bounded = CancellationTokenSource.CreateLinkedTokenSource( deadline.Token, TestContext.Current.CancellationToken); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-first")); - await host.WaitForSessionAsync("call-first"); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-first")); + await host.WaitForSessionAsync("conversation-first"); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-second")); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-second")); try { @@ -341,10 +341,10 @@ public async Task ASecondSetupFrame_ReplacesTheFirstSessionAndReleasesIt() Assert.Fail("the connection never reported the second setup frame within ten seconds."); } - await host.WaitForSessionAsync("call-second"); - Assert.Null(await host.FindSessionAsync("call-first")); + await host.WaitForSessionAsync("conversation-second"); + Assert.Null(await host.FindSessionAsync("conversation-first")); - // The call itself goes on, on the session the vendor's latest word named. + // The conversation itself goes on, on the session the vendor's latest word named. await relay.SendAsync(RelayFrames.Prompt("hi", last: true)); try @@ -364,7 +364,7 @@ public async Task ASecondSetupFrame_ReplacesTheFirstSessionAndReleasesIt() [Fact(Timeout = 30_000)] public async Task ARelayThatVanishesWithNoCloseFrame_ReleasesTheSession() { - // The vendor never reconnects, so a dead socket is a finished call. Abort sends no close + // The vendor never reconnects, so a dead socket is a finished conversation. Abort sends no close // frame at all, so this is what proves the read loop unblocks on the connection's own // cancellation rather than on the close handshake, and that the session store drops the // call once it does. WaitForSessionAsync first makes sure the server actually created the @@ -374,13 +374,13 @@ public async Task ARelayThatVanishesWithNoCloseFrame_ReleasesTheSession() await using var host = await TelnyxRelayHost.StartAsync(PolicyYaml, reply); await using var relay = await host.ConnectAsync(); - await relay.SendAsync(RelayFrames.Setup(callSessionId: "call-dropped")); - await host.WaitForSessionAsync("call-dropped"); + await relay.SendAsync(RelayFrames.Setup(conversationSessionId: "conversation-dropped")); + await host.WaitForSessionAsync("conversation-dropped"); relay.Abort(); - await host.WaitForCallEndAsync("call-dropped"); - Assert.Null(await host.FindSessionAsync("call-dropped")); + await host.WaitForConversationEndAsync("conversation-dropped"); + Assert.Null(await host.FindSessionAsync("conversation-dropped")); } } diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayWriteLoopTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayWriteLoopTests.cs index e1f90061..ccfc3f11 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayWriteLoopTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayWriteLoopTests.cs @@ -39,7 +39,7 @@ public async Task AnItemParkedBetweenTheDequeueAndTheGate_NeverReachesTheSocket( // Armed before the first frame, because the write loop reads State for the first time only // once a turn has actually queued something. harness.Socket.ParkNextStateRead(); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-gate")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-gate")); harness.Socket.Queue(RelayFrames.Prompt("hi", last: true)); try @@ -98,7 +98,7 @@ public async Task AHostThatStops_ClosesWithEndpointUnavailable() using var bounded = CancellationTokenSource.CreateLinkedTokenSource( deadline.Token, TestContext.Current.CancellationToken); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-stopping")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-stopping")); harness.StopApplication(); try @@ -119,7 +119,7 @@ public async Task AHostThatStops_ClosesWithEndpointUnavailable() public async Task AWriteLoopThatFaults_ClosesWithInternalServerError() { // Nothing on a healthy loopback socket makes a send throw, so the fault is injected here. - // The status is this endpoint's own report of its own defect, and a real call would see it. + // The status is this endpoint's own report of its own defect, and a real conversation would see it. using FragmentingChatClient reply = new("hello there caller"); await using var harness = await RelayConnectionHarness.StartAsync(TelnyxRelayTurnTests.PolicyYaml, reply); @@ -128,7 +128,7 @@ public async Task AWriteLoopThatFaults_ClosesWithInternalServerError() deadline.Token, TestContext.Current.CancellationToken); harness.Socket.FailEverySend(new InvalidOperationException("the send failed.")); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-write-fault")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-write-fault")); harness.Socket.Queue(RelayFrames.Prompt("hi", last: true)); try @@ -162,7 +162,7 @@ public async Task ManyFragmentsInOneTurn_EachArriveIntactWhenTheWriterIsReused() using var bounded = CancellationTokenSource.CreateLinkedTokenSource( deadline.Token, TestContext.Current.CancellationToken); - harness.Socket.Queue(RelayFrames.Setup(callSessionId: "call-reused-writer")); + harness.Socket.Queue(RelayFrames.Setup(conversationSessionId: "conversation-reused-writer")); harness.Socket.Queue(RelayFrames.Prompt("hi", last: true)); try diff --git a/tests/AgentCore.Domain.Tests/Audit/AuditEventVocabularyTests.cs b/tests/AgentCore.Domain.Tests/Audit/AuditEventVocabularyTests.cs index b81eedc9..d82754cc 100644 --- a/tests/AgentCore.Domain.Tests/Audit/AuditEventVocabularyTests.cs +++ b/tests/AgentCore.Domain.Tests/Audit/AuditEventVocabularyTests.cs @@ -18,12 +18,12 @@ public sealed class AuditEventVocabularyTests private static readonly DateTimeOffset Start = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000); [Theory] - [InlineData(AuditEventKind.CallStarted, "call.started")] + [InlineData(AuditEventKind.ConversationStarted, "conversation.started")] [InlineData(AuditEventKind.TurnCompleted, "turn.completed")] [InlineData(AuditEventKind.ReplyInterrupted, "reply.interrupted")] [InlineData(AuditEventKind.ToolFailed, "tool.failed")] [InlineData(AuditEventKind.PromptFlagged, "prompt.flagged")] - [InlineData(AuditEventKind.CallEnded, "call.ended")] + [InlineData(AuditEventKind.ConversationEnded, "conversation.ended")] public void EachKind_HasItsToken(AuditEventKind kind, string token) { // The token is stable forever. A C# rename must not change a hash PostgreSQL already stored. @@ -48,40 +48,40 @@ public void TheVocabulary_IsClosed() } Assert.Throws(() => AuditEventKinds.ToToken((AuditEventKind)99)); - Assert.False(AuditEventKinds.TryParse("call.transferred", out _)); + Assert.False(AuditEventKinds.TryParse("conversation.transferred", out _)); } [Theory] - [InlineData(CallEndReason.CallerHungUp, "caller.hangup")] - [InlineData(CallEndReason.AgentCompleted, "agent.completed")] - [InlineData(CallEndReason.TransferredToHuman, "agent.transferred")] - [InlineData(CallEndReason.Faulted, "call.faulted")] - public void EachEndReason_HasItsToken(CallEndReason reason, string token) + [InlineData(ConversationEndReason.CallerHungUp, "caller.hangup")] + [InlineData(ConversationEndReason.AgentCompleted, "agent.completed")] + [InlineData(ConversationEndReason.TransferredToHuman, "agent.transferred")] + [InlineData(ConversationEndReason.Faulted, "conversation.faulted")] + public void EachEndReason_HasItsToken(ConversationEndReason reason, string token) { // The token is stable forever, for the reason a kind token is. A report counts these years - // after the call, and the count breaks when a token moves. - Assert.Equal(token, CallEndReasons.ToToken(reason)); - Assert.True(CallEndReasons.TryParse(token, out CallEndReason parsed)); + // after the conversation, and the count breaks when a token moves. + Assert.Equal(token, ConversationEndReasons.ToToken(reason)); + Assert.True(ConversationEndReasons.TryParse(token, out ConversationEndReason parsed)); Assert.Equal(reason, parsed); } [Fact] public void TheEndReasons_AreClosed() { - CallEndReason[] declared = Enum.GetValues(); + ConversationEndReason[] declared = Enum.GetValues(); - // Section 4 names four ways a call ends, and the set holds those four and no more. + // Section 4 names four ways a conversation ends, and the set holds those four and no more. Assert.Equal(4, declared.Length); - foreach (CallEndReason reason in declared) + foreach (ConversationEndReason reason in declared) { - Assert.NotEmpty(CallEndReasons.ToToken(reason)); + Assert.NotEmpty(ConversationEndReasons.ToToken(reason)); } - Assert.Throws(() => CallEndReasons.ToToken((CallEndReason)99)); - Assert.False(CallEndReasons.TryParse("hangup", out _)); - Assert.False(CallEndReasons.TryParse("caller hung up", out _)); - Assert.False(CallEndReasons.TryParse("CallerHungUp", out _)); - Assert.False(CallEndReasons.TryParse("0", out _)); + Assert.Throws(() => ConversationEndReasons.ToToken((ConversationEndReason)99)); + Assert.False(ConversationEndReasons.TryParse("hangup", out _)); + Assert.False(ConversationEndReasons.TryParse("caller hung up", out _)); + Assert.False(ConversationEndReasons.TryParse("CallerHungUp", out _)); + Assert.False(ConversationEndReasons.TryParse("0", out _)); } [Theory] @@ -90,7 +90,7 @@ public void TheEndReasons_AreClosed() public void EachToolFailureKind_HasItsToken(ToolFailureKind kind, string token) { // The token is stable forever, for the reason an end reason's is. A report that counts how - // often the model invented a tool name reads this token years after the call. + // often the model invented a tool name reads this token years after the conversation. Assert.Equal(token, ToolFailureKinds.ToToken(kind)); Assert.True(ToolFailureKinds.TryParse(token, out ToolFailureKind parsed)); Assert.Equal(kind, parsed); @@ -117,7 +117,7 @@ public void TheToolFailureKinds_AreClosed() /// The reason is counted, so the chain refuses free text under it. [Fact] - public void ACallEndedEventWithAFreeTextReason_IsRefused() + public void AConversationEndedEventWithAFreeTextReason_IsRefused() { AuditEvent free = Ended() with { @@ -134,7 +134,7 @@ public void ACallEndedEventWithAFreeTextReason_IsRefused() } [Fact] - public void ACallEndedEventWithoutAReason_IsRefused() + public void AConversationEndedEventWithoutAReason_IsRefused() { AuditEvent silent = Ended() with { @@ -157,7 +157,7 @@ public void AnAmendment_ReferencesTheEventItAmends() Assert.All(run, AuditEventVocabulary.Validate); Assert.Equal(turn.EventId, interruption.AmendsEventId); - Assert.Equal(turn.CallId, interruption.CallId); + Assert.Equal(turn.ConversationId, interruption.ConversationId); Assert.Equal(turn.TurnIndex, interruption.TurnIndex); // The first event is untouched. Nothing rewrote the turn, and both events stand. @@ -284,9 +284,9 @@ public void Validate_AcceptsAnAmendmentThatNamesAnotherEvent() } [Fact] - public void AnEventWithoutACallId_IsRefused() + public void AnEventWithoutAConversationId_IsRefused() { - AuditEvent nameless = Turn(eventId: Guid.CreateVersion7(), turnIndex: 0) with { CallId = string.Empty }; + AuditEvent nameless = Turn(eventId: Guid.CreateVersion7(), turnIndex: 0) with { ConversationId = string.Empty }; Assert.Throws(() => AuditEventVocabulary.Validate(nameless)); } @@ -382,7 +382,7 @@ public void AFlaggedPromptKeepsTheOrderTheEndpointReturned() /// /// The taxonomy belongs to the moderation endpoint and it is open, unlike - /// . A closed set would make throw on a + /// . A closed set would make throw on a /// category OpenAI added, and destroy the record the chain exists to protect. /// [Fact] @@ -415,7 +415,7 @@ public void AFlaggedPrompt_MayStillCarryAnAmendment() private static AuditEvent Turn(Guid eventId, int turnIndex) => new() { - CallId = "call-1", + ConversationId = "conversation-1", EventId = eventId, Kind = AuditEventKind.TurnCompleted, OccurredAt = Start, @@ -430,7 +430,7 @@ public void AFlaggedPrompt_MayStillCarryAnAmendment() private static AuditEvent Interruption(Guid eventId, Guid amends, int turnIndex) => new() { - CallId = "call-1", + ConversationId = "conversation-1", EventId = eventId, Kind = AuditEventKind.ReplyInterrupted, OccurredAt = Start.AddMilliseconds(1_820), @@ -445,7 +445,7 @@ public void AFlaggedPrompt_MayStillCarryAnAmendment() private static AuditEvent FlaggedPrompt(Guid eventId, int turnIndex, string categories = "harassment") => new() { - CallId = "call-1", + ConversationId = "conversation-1", EventId = eventId, Kind = AuditEventKind.PromptFlagged, OccurredAt = Start.AddMilliseconds(2_400), @@ -458,13 +458,13 @@ public void AFlaggedPrompt_MayStillCarryAnAmendment() private static AuditEvent Ended() => new() { - CallId = "call-1", + ConversationId = "conversation-1", EventId = Guid.CreateVersion7(), - Kind = AuditEventKind.CallEnded, + Kind = AuditEventKind.ConversationEnded, OccurredAt = Start.AddMilliseconds(9_000), Payload = new Dictionary(StringComparer.Ordinal) { - [AuditPayloadKeys.EndReason] = CallEndReasons.ToToken(CallEndReason.CallerHungUp), + [AuditPayloadKeys.EndReason] = ConversationEndReasons.ToToken(ConversationEndReason.CallerHungUp), }, }; } diff --git a/tests/AgentCore.Domain.Tests/TurnResultTests.cs b/tests/AgentCore.Domain.Tests/TurnResultTests.cs index d204ad0d..3caf87a8 100644 --- a/tests/AgentCore.Domain.Tests/TurnResultTests.cs +++ b/tests/AgentCore.Domain.Tests/TurnResultTests.cs @@ -11,8 +11,8 @@ public sealed class TurnResultTests [Fact] public void TwoResultsWithTheSameContent_AreEqual() { - TurnResult first = new("call-1", 0, "greeting", "identify", "hello", false, null); - TurnResult second = new("call-1", 0, "greeting", "identify", "hello", false, null); + TurnResult first = new("conversation-1", 0, "greeting", "identify", "hello", false, null); + TurnResult second = new("conversation-1", 0, "greeting", "identify", "hello", false, null); Assert.Equal(first, second); Assert.Equal(first.GetHashCode(), second.GetHashCode()); @@ -21,7 +21,7 @@ public void TwoResultsWithTheSameContent_AreEqual() [Fact] public void AFailedExtraction_IsCarriedAndNotThrown() { - TurnResult result = new("call-1", 2, "resolve", "resolve", "one moment", false, "the extractor returned an empty reply"); + TurnResult result = new("conversation-1", 2, "resolve", "resolve", "one moment", false, "the extractor returned an empty reply"); Assert.Equal("the extractor returned an empty reply", result.ExtractionFailure); Assert.False(result.IsTerminal); @@ -30,7 +30,7 @@ public void AFailedExtraction_IsCarriedAndNotThrown() [Fact] public void ATerminalTurn_ReportsItself() { - TurnResult result = new("call-1", 4, "escalate", "close", "goodbye", true, null); + TurnResult result = new("conversation-1", 4, "escalate", "close", "goodbye", true, null); Assert.True(result.IsTerminal); Assert.Equal("close", result.StageAfter); diff --git a/tests/AgentCore.Evals/DatasetFixture.cs b/tests/AgentCore.Evals/DatasetFixture.cs index 50b554b4..5b5930fa 100644 --- a/tests/AgentCore.Evals/DatasetFixture.cs +++ b/tests/AgentCore.Evals/DatasetFixture.cs @@ -6,7 +6,7 @@ namespace AgentCore.Evals; /// Builds the golden-set harness once for a test class. /// /// -/// Opening the knowledge base costs a socket, a secret read, and an embedding call, and every row of +/// Opening the knowledge base costs a socket, a secret read, and an embedding conversation, and every row of /// a suite reads the same one. The fixture builds it once and holds it for the class. /// public sealed class DatasetFixture : IAsyncLifetime diff --git a/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs b/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs index 8a64c09d..ef1b4653 100644 --- a/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs +++ b/tests/AgentCore.Hosting.Tests/AgentCoreHostTests.cs @@ -1,8 +1,8 @@ using System.Text.Json.Nodes; using AgentCore.Application.Audit; using AgentCore.Application.Audit.Memory; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; @@ -12,7 +12,7 @@ using AgentCore.AspNetCore.Endpoints; using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Audit.Postgres; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.AI; @@ -33,7 +33,7 @@ namespace AgentCore.Hosting.Tests; /// seam is a setter, so defaults written after a host's callback would silently replace it. /// /// -/// Every test runs offline against a fake model. There is no OpenAI account, no network call, and +/// Every test runs offline against a fake model. There is no OpenAI account, no network conversation, and /// no API key anywhere in this file — which is itself the proof that the default vendor list costs /// nothing until a document names it. /// @@ -111,10 +111,10 @@ public async Task ProvidersAuditPostgresReachesTheAdapterRatherThanTheSelector() } [Fact] - public async Task ProvidersCallsPostgresReachesTheAdapterRatherThanTheSelector() + public async Task ProvidersConversationsPostgresReachesTheAdapterRatherThanTheSelector() { var failure = await Assert.ThrowsAsync( - () => StartAsync(options => options.SecretResolver = new EmptySecretResolver(), Calls)); + () => StartAsync(options => options.SecretResolver = new EmptySecretResolver(), Conversations)); Assert.Contains(KnownSecrets.PostgresConnectionString.Name, failure.Message, StringComparison.Ordinal); } @@ -127,8 +127,8 @@ public async Task ADocumentNamingNoDurableVendorStillGetsTheInProcessStores() using var host = await StartAsync(); Assert.IsType(host.Services.GetRequiredService().Store); - Assert.IsType(host.Services.GetRequiredService().Store); - Assert.IsType(host.Services.GetRequiredService().Store); + Assert.IsType(host.Services.GetRequiredService().Store); + Assert.IsType(host.Services.GetRequiredService().Store); } [Fact] @@ -145,13 +145,13 @@ public async Task AHostAuditSinkWinsOverTheDefaultVendorOnTheSameKind() } [Fact] - public async Task AHostCallStoreWinsOverTheDefaultVendorOnTheSameKind() + public async Task AHostConversationStoreWinsOverTheDefaultVendorOnTheSameKind() { using var host = await StartAsync( - options => options.UseCallStores(new FakeCallStoreAdapter()), - Calls); + options => options.UseConversationStores(new FakeConversationStoreAdapter()), + Conversations); - Assert.IsType(host.Services.GetRequiredService().Store); + Assert.IsType(host.Services.GetRequiredService().Store); } // --------------------------------------------------------------------------------------------- @@ -221,7 +221,7 @@ public async Task AHostKnowledgePointMapperReachesTheDefaultAdapter() command: ["/definitely-not-a-real-binary-agentcore-test"] allow: ["*"] providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -386,7 +386,7 @@ public async Task ResponsesMovesWhenTheHostNamesAnotherRoute() } [Fact] - public async Task CallRefusesAnEntryTheDocumentDoesNotDeclare() + public async Task ConversationRefusesAnEntryTheDocumentDoesNotDeclare() { await using var app = await StartMappedAsync(); using HttpClient client = new() { BaseAddress = Address(app) }; @@ -415,8 +415,8 @@ public async Task ResponsesRefusesARouteWithNoEntryParameter() /// The smallest document the schema accepts: one agent, one model, and the required pair. /// - /// A document that writes a providers block at all must write call and - /// speech too, and both speech roles must name the same vendor the call does. Those kinds + /// A document that writes a providers block at all must write conversation and + /// speech too, and both speech roles must name the same vendor the conversation does. Those kinds /// resolve here because the default list this library registers already names that transport — /// which is the point: a test writes no vendor of its own except the model. /// @@ -429,7 +429,7 @@ public async Task ResponsesRefusesARouteWithNoEntryParameter() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } @@ -442,8 +442,8 @@ public async Task ResponsesRefusesARouteWithNoEntryParameter() /// The providers line that asks for the durable transcript vendor. - /// The providers line that asks for the durable call store vendor. - private const string Calls = " calls: { kind: postgres }"; + /// The providers line that asks for the durable conversation store vendor. + private const string Conversations = " conversations: { kind: postgres }"; /// /// The providers lines for a knowledge store on an endpoint nothing listens on, so the @@ -540,16 +540,16 @@ public ValueTask OpenAsync( } - /// A call store vendor answering to the same kind the default list names. - private sealed class FakeCallStoreAdapter : ICallStoreAdapter + /// A conversation store vendor answering to the same kind the default list names. + private sealed class FakeConversationStoreAdapter : IConversationStoreAdapter { - public string Kind => PostgresCallStoreAdapter.ProviderKind; + public string Kind => PostgresConversationStoreAdapter.ProviderKind; - public ValueTask OpenAsync( + public ValueTask OpenAsync( VendorProviderConfiguration entry, ISecretResolverPort? secrets, CancellationToken cancellationToken = default) - => ValueTask.FromResult(new InMemoryCallStore()); + => ValueTask.FromResult(new InMemoryConversationStore()); } /// An embedding vendor whose generator is never actually asked to embed anything. diff --git a/tests/AgentCore.Hosting.Tests/ConfigurationSecretResolverTests.cs b/tests/AgentCore.Hosting.Tests/ConfigurationSecretResolverTests.cs index f5163987..e2ab91aa 100644 --- a/tests/AgentCore.Hosting.Tests/ConfigurationSecretResolverTests.cs +++ b/tests/AgentCore.Hosting.Tests/ConfigurationSecretResolverTests.cs @@ -27,7 +27,7 @@ namespace AgentCore.Hosting.Tests; /// unrelated host settings, and the environment provider that WebApplicationBuilder already /// installs would make this link answer for variables the first link owns. /// -/// Every test here runs offline. There is no network call and no API key in this file. +/// Every test here runs offline. There is no network conversation and no API key in this file. /// public sealed class ConfigurationSecretResolverTests { @@ -124,7 +124,7 @@ public async Task AnEnvironmentVariableWinsOverTheSameNameInConfiguration() main: agent: only providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs index a939abbb..8c89b8cb 100644 --- a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs @@ -73,9 +73,9 @@ public async Task OpenAsync_UnmigratedDatabase_ReturnsASinkThatAppends() await sink.AppendAsync( new() { - CallId = "C1", + ConversationId = "C1", EventId = Guid.CreateVersion7(), - Kind = AgentCore.Domain.Audit.AuditEventKind.CallStarted, + Kind = AgentCore.Domain.Audit.AuditEventKind.ConversationStarted, OccurredAt = new DateTimeOffset(2026, 8, 19, 9, 0, 0, TimeSpan.Zero), }, Token); diff --git a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs index 15575229..7549cd70 100644 --- a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs @@ -42,7 +42,7 @@ public async Task AppendManyAsync_ARun_WritesEveryEventInOrder() await sink.AppendManyAsync(run, Token); // Assert — write_position is insertion order, and it lines up with the sequence the store - // assigned because a single-call batch is numbered in submission order. + // assigned because a single-conversation batch is numbered in submission order. var sequences = await ReadSequencesAsync(); Assert.Equal([0L, 1L, 2L], sequences); } @@ -92,7 +92,7 @@ public async Task AppendManyAsync_RunHoldingAMalformedEvent_WritesNoneOfIt() } [PostgresFact] - public async Task AppendAsync_ConcurrentWritersOnSeparateCalls_WriteEveryRow() + public async Task AppendAsync_ConcurrentWritersOnSeparateConversations_WriteEveryRow() { // Arrange — four hosts on one table. Nothing serialises them: there is no head to claim. var connectionString = Database.ConnectionString; @@ -130,15 +130,15 @@ public async Task TheStoreNumbersTheChainFromZero() await sink.AppendManyAsync( [ - Event("C1", AuditEventKind.CallStarted), + Event("C1", AuditEventKind.ConversationStarted), Event("C1", AuditEventKind.TurnCompleted), - Event("C1", AuditEventKind.CallEnded), + Event("C1", AuditEventKind.ConversationEnded), ], Token); var sequences = await SequencesOfAsync("C1"); var kinds = await KindsOfAsync("C1"); Assert.Equal([0L, 1L, 2L], sequences); - Assert.Equal(["call.started", "turn.completed", "call.ended"], kinds); + Assert.Equal(["conversation.started", "turn.completed", "conversation.ended"], kinds); } [PostgresFact] @@ -146,7 +146,7 @@ public async Task ASecondBatchContinuesTheChain() { PostgresAuditSink sink = new(DataSource); - await sink.AppendManyAsync([Event("C1", AuditEventKind.CallStarted)], Token); + await sink.AppendManyAsync([Event("C1", AuditEventKind.ConversationStarted)], Token); await sink.AppendManyAsync([Event("C1", AuditEventKind.TurnCompleted)], Token); var sequences = await SequencesOfAsync("C1"); @@ -160,8 +160,8 @@ public async Task OneBatchNumbersTwoCallsIndependently() await sink.AppendManyAsync( [ - Event("C1", AuditEventKind.CallStarted), - Event("C2", AuditEventKind.CallStarted), + Event("C1", AuditEventKind.ConversationStarted), + Event("C2", AuditEventKind.ConversationStarted), Event("C1", AuditEventKind.TurnCompleted), ], Token); @@ -175,7 +175,7 @@ await sink.AppendManyAsync( public async Task AReplayedBatchWritesNothingTwice() { PostgresAuditSink sink = new(DataSource); - AuditEvent[] run = [Event("C1", AuditEventKind.CallStarted)]; + AuditEvent[] run = [Event("C1", AuditEventKind.ConversationStarted)]; await sink.AppendManyAsync(run, Token); await sink.AppendManyAsync(run, Token); @@ -192,9 +192,9 @@ public async Task APartiallyReplayedBatchLeavesNoGap() // numbering them would reserve a sequence — here, 2 and 3 — that no row ever lands on, and c // would land at 4 instead of 2. The NOT EXISTS filter is what keeps this dense. PostgresAuditSink sink = new(DataSource); - AuditEvent a = Event("C1", AuditEventKind.CallStarted); + AuditEvent a = Event("C1", AuditEventKind.ConversationStarted); AuditEvent b = Event("C1", AuditEventKind.TurnCompleted); - AuditEvent c = Event("C1", AuditEventKind.CallEnded); + AuditEvent c = Event("C1", AuditEventKind.ConversationEnded); await sink.AppendManyAsync([a, b], Token); @@ -207,9 +207,9 @@ public async Task APartiallyReplayedBatchLeavesNoGap() } [PostgresFact] - public async Task ConcurrentWritersOnTheSameCall_NumberDenselyWithNoGapOrDuplicate() + public async Task ConcurrentWritersOnTheSameConversation_NumberDenselyWithNoGapOrDuplicate() { - // Arrange — one call id, several writers. Without the advisory lock two writers can both + // Arrange — one conversation id, several writers. Without the advisory lock two writers can both // read the same max(sequence) and both compute the same numbers; one of them then loses a // unique-violation race that QueuedAuditSink would swallow as a dropped batch. The lock is // what makes that race impossible instead of merely unlikely. @@ -237,7 +237,7 @@ public async Task ConcurrentWritersOnTheSameCall_NumberDenselyWithNoGapOrDuplica // Assert — dense from zero with no gap and no duplicate. A gap or a short count means a // writer's row was silently dropped; a duplicate cannot reach the table at all, because - // audit_event_call_sequence_unique refuses it, so either failure mode shows up here as the + // audit_event_conversation_sequence_unique refuses it, so either failure mode shows up here as the // read sequences failing to equal the full contiguous range. var sequences = await SequencesOfAsync("C1"); Assert.Equal( @@ -245,17 +245,17 @@ public async Task ConcurrentWritersOnTheSameCall_NumberDenselyWithNoGapOrDuplica sequences); } - private static AuditEvent Started(string callId) => new() + private static AuditEvent Started(string conversationId) => new() { - CallId = callId, + ConversationId = conversationId, EventId = Guid.CreateVersion7(), - Kind = AuditEventKind.CallStarted, + Kind = AuditEventKind.ConversationStarted, OccurredAt = new DateTimeOffset(2026, 8, 19, 9, 0, 0, TimeSpan.Zero), }; - private static AuditEvent TurnCompleted(string callId, int turnIndex) => new() + private static AuditEvent TurnCompleted(string conversationId, int turnIndex) => new() { - CallId = callId, + ConversationId = conversationId, EventId = Guid.CreateVersion7(), Kind = AuditEventKind.TurnCompleted, OccurredAt = new DateTimeOffset(2026, 8, 19, 9, 0, 1, TimeSpan.Zero), @@ -266,28 +266,28 @@ public async Task ConcurrentWritersOnTheSameCall_NumberDenselyWithNoGapOrDuplica }, }; - private static AuditEvent Ended(string callId) => new() + private static AuditEvent Ended(string conversationId) => new() { - CallId = callId, + ConversationId = conversationId, EventId = Guid.CreateVersion7(), - Kind = AuditEventKind.CallEnded, + Kind = AuditEventKind.ConversationEnded, OccurredAt = new DateTimeOffset(2026, 8, 19, 9, 0, 2, TimeSpan.Zero), Payload = new Dictionary(StringComparer.Ordinal) { - [AuditPayloadKeys.EndReason] = CallEndReasons.ToToken(CallEndReason.CallerHungUp), + [AuditPayloadKeys.EndReason] = ConversationEndReasons.ToToken(ConversationEndReason.CallerHungUp), }, }; - private static AuditEvent Event(string callId, AuditEventKind kind) => new() + private static AuditEvent Event(string conversationId, AuditEventKind kind) => new() { - CallId = callId, + ConversationId = conversationId, EventId = Guid.CreateVersion7(), Kind = kind, OccurredAt = DateTimeOffset.UnixEpoch, - Payload = kind == AuditEventKind.CallEnded + Payload = kind == AuditEventKind.ConversationEnded ? new Dictionary(StringComparer.Ordinal) { - [AuditPayloadKeys.EndReason] = CallEndReasons.ToToken(CallEndReason.AgentCompleted), + [AuditPayloadKeys.EndReason] = ConversationEndReasons.ToToken(ConversationEndReason.AgentCompleted), } : new Dictionary(StringComparer.Ordinal), }; @@ -309,11 +309,11 @@ private async Task> ReadSequencesAsync() return sequences; } - private async Task SequencesOfAsync(string callId) + private async Task SequencesOfAsync(string conversationId) { await using var command = DataSource.CreateCommand( - "SELECT sequence FROM agentcore.audit_event WHERE call_id = $1 ORDER BY sequence"); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + "SELECT sequence FROM agentcore.audit_event WHERE conversation_id = $1 ORDER BY sequence"); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); List sequences = []; await using var reader = await command.ExecuteReaderAsync(Token); @@ -326,11 +326,11 @@ private async Task SequencesOfAsync(string callId) } /// Reads the kinds back in sequence order, so a test can pin which fact landed where. - private async Task KindsOfAsync(string callId) + private async Task KindsOfAsync(string conversationId) { await using var command = DataSource.CreateCommand( - "SELECT kind FROM agentcore.audit_event WHERE call_id = $1 ORDER BY sequence"); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); + "SELECT kind FROM agentcore.audit_event WHERE conversation_id = $1 ORDER BY sequence"); + command.Parameters.Add(new NpgsqlParameter { Value = conversationId }); List kinds = []; await using var reader = await command.ExecuteReaderAsync(Token); diff --git a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs index 8bda1461..49420f53 100644 --- a/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Blobs/S3/S3BlobStoreLinkTests.cs @@ -33,7 +33,7 @@ public async Task LinkAsync_PlainHttpEndpoint_LinksOverHttp() using var store = Open("http://localhost:59000"); // Act - var url = await store.LinkAsync(new BlobRef("call-1", "rows.csv", "text/csv", 8), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); + var url = await store.LinkAsync(new BlobRef("conversation-1", "rows.csv", "text/csv", 8), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); // Assert Assert.NotNull(url); @@ -47,7 +47,7 @@ public async Task LinkAsync_SignsHostOnly_AndCarriesTheResponseOverrides() { // Arrange using var store = Open(); - BlobRef blob = new("call-1", "chart.png", "image/png", 48213); + BlobRef blob = new("conversation-1", "chart.png", "image/png", 48213); // Act var url = await store.LinkAsync(blob, TimeSpan.FromMinutes(15), TestContext.Current.CancellationToken); @@ -56,7 +56,7 @@ public async Task LinkAsync_SignsHostOnly_AndCarriesTheResponseOverrides() Assert.NotNull(url); Assert.Equal("https", url.Scheme); Assert.Equal("s3.us-east-005.backblazeb2.com", url.Host); - Assert.Equal("/SpiritAI/call-1/chart.png", url.AbsolutePath); + Assert.Equal("/SpiritAI/conversation-1/chart.png", url.AbsolutePath); var query = HttpUtility.ParseQueryString(url.Query); Assert.Equal("host", query["X-Amz-SignedHeaders"]); @@ -74,7 +74,7 @@ public async Task LinkAsync_Csv_IsServedAsAnAttachment() using var store = Open(); // Act - var url = await store.LinkAsync(new BlobRef("call-1", "rows.csv", "text/csv", 8), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); + var url = await store.LinkAsync(new BlobRef("conversation-1", "rows.csv", "text/csv", 8), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); // Assert var query = HttpUtility.ParseQueryString(url!.Query); @@ -90,6 +90,6 @@ public async Task LinkAsync_UnsafeName_Throws() // Act + Assert await Assert.ThrowsAsync(async () => - await store.LinkAsync(new BlobRef("call-1", "../x.png", "image/png", 1), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken)); + await store.LinkAsync(new BlobRef("conversation-1", "../x.png", "image/png", 1), TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken)); } } diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/ContinuationStoreTests.cs similarity index 80% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/ContinuationStoreTests.cs index 055a5481..ebe63b75 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/ContinuationStoreTests.cs @@ -1,11 +1,11 @@ using System.Text.Json; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; -/// The continuation map beside the calls: one envelope per opaque id. +/// The continuation map beside the conversations: one envelope per opaque id. public sealed class ContinuationStoreTests : PostgresDatabaseTest { /// @@ -29,8 +29,8 @@ SELECT count(*) FROM information_schema.tables public async Task RoundTrip_SaveGetDelete() { // Arrange - PostgresCallStore store = new(DataSource); - using var document = JsonDocument.Parse("""{ "callId": "c1", "state": {} }"""); + PostgresConversationStore store = new(DataSource); + using var document = JsonDocument.Parse("""{ "conversationId": "c1", "state": {} }"""); // Act await store.SaveContinuationAsync("conv_1", document.RootElement, Token); @@ -59,7 +59,7 @@ public async Task RoundTrip_SaveGetDelete() public async Task GetContinuation_UnknownId_AnswersNull() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); // Act var found = await store.GetContinuationAsync("conv_missing", Token); diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/ConversationThreadSchemaTests.cs similarity index 51% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/ConversationThreadSchemaTests.cs index e51f0e4e..4ff12240 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/ConversationThreadSchemaTests.cs @@ -2,18 +2,18 @@ using Npgsql; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// Store 0's shape, and what the running role may do to it. /// -/// call and role are both non-reserved keywords in PostgreSQL and need no quoting. That +/// conversation and role are both non-reserved keywords in PostgreSQL and need no quoting. That /// is what the first test proves: the migration would fail to apply at all if it were untrue. /// /// The primary key's column order is read from the catalogue rather than inferred from behaviour. A /// listing filters by principal, so principal has to lead, and either order satisfies uniqueness. /// /// -public sealed class CallThreadSchemaTests : PostgresDatabaseTest +public sealed class ConversationThreadSchemaTests : PostgresDatabaseTest { /// protected override bool Migrated => true; @@ -25,7 +25,7 @@ public async Task Migration_Applied_MakesBothTables() var tables = await ScalarAsync( """ SELECT count(*) FROM information_schema.tables - WHERE table_schema = 'agentcore' AND table_name IN ('call', 'call_principal') + WHERE table_schema = 'agentcore' AND table_name IN ('conversation', 'conversation_principal') """); // Assert @@ -33,47 +33,47 @@ SELECT count(*) FROM information_schema.tables } [PostgresFact] - public async Task Call_AStatusOutsideTheTwo_IsRefused() + public async Task Conversation_AStatusOutsideTheTwo_IsRefused() { // Act var refusal = await Record.ExceptionAsync( - () => ExecuteAsync("INSERT INTO agentcore.call (call_id, status) VALUES ('c1', 'nonsense')")); + () => ExecuteAsync("INSERT INTO agentcore.conversation (conversation_id, status) VALUES ('c1', 'nonsense')")); // Assert Assert.Equal("23514", Assert.IsType(refusal).SqlState); } [PostgresFact] - public async Task CallPrincipal_ItsCallDeleted_GoesWithIt() + public async Task ConversationPrincipal_ItsConversationDeleted_GoesWithIt() { // Arrange - await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('c1')"); - await ExecuteAsync("INSERT INTO agentcore.call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'caller')"); + await ExecuteAsync("INSERT INTO agentcore.conversation (conversation_id) VALUES ('c1')"); + await ExecuteAsync("INSERT INTO agentcore.conversation_principal (conversation_id, principal_key, role) VALUES ('c1', 'p1', 'caller')"); // Act - await ExecuteAsync("DELETE FROM agentcore.call WHERE call_id = 'c1'"); + await ExecuteAsync("DELETE FROM agentcore.conversation WHERE conversation_id = 'c1'"); // Assert - Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_principal")); } [PostgresFact] - public async Task CallPrincipal_TheSamePairTwice_IsRefusedByThePrimaryKey() + public async Task ConversationPrincipal_TheSamePairTwice_IsRefusedByThePrimaryKey() { // Arrange - await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('c1')"); - await ExecuteAsync("INSERT INTO agentcore.call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'caller')"); + await ExecuteAsync("INSERT INTO agentcore.conversation (conversation_id) VALUES ('c1')"); + await ExecuteAsync("INSERT INTO agentcore.conversation_principal (conversation_id, principal_key, role) VALUES ('c1', 'p1', 'caller')"); // Act var refusal = await Record.ExceptionAsync( - () => ExecuteAsync("INSERT INTO agentcore.call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'agent')")); + () => ExecuteAsync("INSERT INTO agentcore.conversation_principal (conversation_id, principal_key, role) VALUES ('c1', 'p1', 'agent')")); // Assert Assert.Equal("23505", Assert.IsType(refusal).SqlState); } [PostgresFact] - public async Task CallPrincipal_ItsPrimaryKey_LeadsWithThePrincipal() + public async Task ConversationPrincipal_ItsPrimaryKey_LeadsWithThePrincipal() { // Act var columns = await ScalarAsync( @@ -82,23 +82,23 @@ SELECT string_agg(a.attname, ',' ORDER BY k.ord) FROM pg_index i JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) ON true JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum - WHERE i.indrelid = 'agentcore.call_principal'::regclass AND i.indisprimary + WHERE i.indrelid = 'agentcore.conversation_principal'::regclass AND i.indisprimary """); // Assert - Assert.Equal("principal_key,call_id", columns); + Assert.Equal("principal_key,conversation_id", columns); } [PostgresFact] - public async Task CallPrincipal_TheOtherDirection_HasItsOwnIndex() + public async Task ConversationPrincipal_TheOtherDirection_HasItsOwnIndex() { // Act var indexes = await ScalarAsync( """ SELECT count(*) FROM pg_indexes WHERE schemaname = 'agentcore' - AND tablename = 'call_principal' - AND indexname = 'call_principal_call_idx' + AND tablename = 'conversation_principal' + AND indexname = 'conversation_principal_conversation_idx' """); // Assert @@ -106,14 +106,14 @@ SELECT count(*) FROM pg_indexes } [PostgresTheory] - [InlineData("agentcore.call", "SELECT")] - [InlineData("agentcore.call", "INSERT")] - [InlineData("agentcore.call", "UPDATE")] - [InlineData("agentcore.call", "DELETE")] - [InlineData("agentcore.call_principal", "SELECT")] - [InlineData("agentcore.call_principal", "INSERT")] - [InlineData("agentcore.call_principal", "UPDATE")] - [InlineData("agentcore.call_principal", "DELETE")] + [InlineData("agentcore.conversation", "SELECT")] + [InlineData("agentcore.conversation", "INSERT")] + [InlineData("agentcore.conversation", "UPDATE")] + [InlineData("agentcore.conversation", "DELETE")] + [InlineData("agentcore.conversation_principal", "SELECT")] + [InlineData("agentcore.conversation_principal", "INSERT")] + [InlineData("agentcore.conversation_principal", "UPDATE")] + [InlineData("agentcore.conversation_principal", "DELETE")] public async Task Writer_EachStoreZeroPrivilege_IsGranted(string table, string privilege) { // Act diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallListTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationListTests.cs similarity index 59% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallListTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationListTests.cs index 57d216a0..5e26e917 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallListTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationListTests.cs @@ -1,36 +1,36 @@ -using AgentCore.Application.Calls; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Application.Conversation; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// The listing behind a thread sidebar. -public sealed class PostgresCallListTests : PostgresDatabaseTest +public sealed class PostgresConversationListTests : PostgresDatabaseTest { /// protected override bool Migrated => true; [PostgresFact] - public async Task ListAsync_APrincipalWithNoCalls_IsEmptyAndHasNoCursor() + public async Task ListAsync_APrincipalWithNoConversations_IsEmptyAndHasNoCursor() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act var page = await store.ListAsync("nobody", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Empty(page.Calls); + Assert.Empty(page.Conversations); Assert.Null(page.NextCursor); } [PostgresFact] - public async Task ListAsync_AnotherPrincipalsCall_IsNotReturned() + public async Task ListAsync_AnotherPrincipalsConversation_IsNotReturned() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "mine", "person-a"); await Claim(store, "theirs", "person-b"); @@ -38,14 +38,14 @@ public async Task ListAsync_AnotherPrincipalsCall_IsNotReturned() var page = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Equal(["mine"], page.Calls.Select(call => call.CallId)); + Assert.Equal(["mine"], page.Conversations.Select(conversation => conversation.ConversationId)); } [PostgresFact] - public async Task ListAsync_ACallWithTwoKeys_IsFoundByEither() + public async Task ListAsync_AConversationWithTwoKeys_IsFoundByEither() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "tenant-a", "tenant", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -55,15 +55,15 @@ public async Task ListAsync_ACallWithTwoKeys_IsFoundByEither() var byPerson = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Single(byTenant.Calls); - Assert.Single(byPerson.Calls); + Assert.Single(byTenant.Conversations); + Assert.Single(byPerson.Conversations); } [PostgresFact] public async Task ListAsync_MostRecentlySpokenFirst_IsTheOrder() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "old", "person-a"); await Claim(store, "new", "person-a"); await Spoke("old", "-2 hours"); @@ -73,14 +73,14 @@ public async Task ListAsync_MostRecentlySpokenFirst_IsTheOrder() var page = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Equal(["new", "old"], page.Calls.Select(call => call.CallId)); + Assert.Equal(["new", "old"], page.Conversations.Select(conversation => conversation.ConversationId)); } [PostgresFact] - public async Task ListAsync_ACallWithNoMessages_IsListedByItsCreationTime() + public async Task ListAsync_AConversationWithNoMessages_IsListedByItsCreationTime() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "spoken", "person-a"); await Spoke("spoken", "-2 hours"); await Claim(store, "silent", "person-a"); @@ -89,46 +89,46 @@ public async Task ListAsync_ACallWithNoMessages_IsListedByItsCreationTime() var page = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Equal(["silent", "spoken"], page.Calls.Select(call => call.CallId)); + Assert.Equal(["silent", "spoken"], page.Conversations.Select(conversation => conversation.ConversationId)); } [PostgresFact] public async Task ListAsync_ArchivedByDefault_IsStillListed() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "c1", "person-a"); - await store.SetStatusAsync("c1", CallStatus.Archived, Token); + await store.SetStatusAsync("c1", ConversationStatus.Archived, Token); // Act var page = await store.ListAsync("person-a", after: null, limit: 10, cancellationToken: Token); // Assert - Assert.Single(page.Calls); - Assert.Equal(CallStatus.Archived, page.Calls[0].Status); + Assert.Single(page.Conversations); + Assert.Equal(ConversationStatus.Archived, page.Conversations[0].Status); } [PostgresFact] public async Task ListAsync_NarrowedToRegular_LeavesArchivedOut() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "kept", "person-a"); await Claim(store, "filed", "person-a"); - await store.SetStatusAsync("filed", CallStatus.Archived, Token); + await store.SetStatusAsync("filed", ConversationStatus.Archived, Token); // Act - var page = await store.ListAsync("person-a", after: null, limit: 10, CallStatus.Regular, Token); + var page = await store.ListAsync("person-a", after: null, limit: 10, ConversationStatus.Regular, Token); // Assert - Assert.Equal(["kept"], page.Calls.Select(call => call.CallId)); + Assert.Equal(["kept"], page.Conversations.Select(conversation => conversation.ConversationId)); } [PostgresFact] - public async Task ListAsync_PagedToTheEnd_ReturnsEveryCallExactlyOnce() + public async Task ListAsync_PagedToTheEnd_ReturnsEveryConversationExactlyOnce() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); for (var i = 0; i < 25; i++) { await Claim(store, $"c{i:D2}", "person-a"); @@ -141,7 +141,7 @@ public async Task ListAsync_PagedToTheEnd_ReturnsEveryCallExactlyOnce() do { var page = await store.ListAsync("person-a", cursor, limit: 7, cancellationToken: Token); - seen.AddRange(page.Calls.Select(call => call.CallId)); + seen.AddRange(page.Conversations.Select(conversation => conversation.ConversationId)); cursor = page.NextCursor; } while (cursor is not null); @@ -152,16 +152,16 @@ public async Task ListAsync_PagedToTheEnd_ReturnsEveryCallExactlyOnce() } [PostgresFact] - public async Task ListAsync_CallsSharingOneTimestamp_AreStillPagedWithoutLoss() + public async Task ListAsync_ConversationsSharingOneTimestamp_AreStillPagedWithoutLoss() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); for (var i = 0; i < 6; i++) { await Claim(store, $"c{i}", "person-a"); } - await ExecuteAsync("UPDATE agentcore.call SET created_at = timestamptz '2026-01-01 00:00:00+00'"); + await ExecuteAsync("UPDATE agentcore.conversation SET created_at = timestamptz '2026-01-01 00:00:00+00'"); // Act List seen = []; @@ -169,7 +169,7 @@ public async Task ListAsync_CallsSharingOneTimestamp_AreStillPagedWithoutLoss() do { var page = await store.ListAsync("person-a", cursor, limit: 2, cancellationToken: Token); - seen.AddRange(page.Calls.Select(call => call.CallId)); + seen.AddRange(page.Conversations.Select(conversation => conversation.ConversationId)); cursor = page.NextCursor; } while (cursor is not null); @@ -183,7 +183,7 @@ public async Task ListAsync_CallsSharingOneTimestamp_AreStillPagedWithoutLoss() public async Task ListAsync_AnExactlyFullLastPage_EndsOnTheFollowingEmptyOne() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "c1", "person-a"); await Claim(store, "c2", "person-a"); @@ -193,7 +193,7 @@ public async Task ListAsync_AnExactlyFullLastPage_EndsOnTheFollowingEmptyOne() // Assert Assert.NotNull(first.NextCursor); - Assert.Empty(second.Calls); + Assert.Empty(second.Conversations); Assert.Null(second.NextCursor); } @@ -201,26 +201,26 @@ public async Task ListAsync_AnExactlyFullLastPage_EndsOnTheFollowingEmptyOne() public async Task ListAsync_ACursorThatIsNotOne_ServesTheFirstPage() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await Claim(store, "c1", "person-a"); // Act var page = await store.ListAsync("person-a", "not-a-cursor", limit: 10, cancellationToken: Token); // Assert - Assert.Single(page.Calls); + Assert.Single(page.Conversations); } - private static async Task Claim(PostgresCallStore store, string callId, string principalKey) + private static async Task Claim(PostgresConversationStore store, string conversationId, string principalKey) { - await store.CreateAsync(callId, Token); - await store.AttachPrincipalAsync(callId, principalKey, "caller", Token); + await store.CreateAsync(conversationId, Token); + await store.AttachPrincipalAsync(conversationId, principalKey, "caller", Token); } - private Task Spoke(string callId, string ago) => + private Task Spoke(string conversationId, string ago) => ExecuteAsync( $$""" - INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) - VALUES ('{{callId}}', 1, 0, 'user', '{}'::jsonb, 'm1', now(), now() + interval '{{ago}}') + INSERT INTO agentcore.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) + VALUES ('{{conversationId}}', 1, 0, 'user', '{}'::jsonb, 'm1', now(), now() + interval '{{ago}}') """); } diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationPrincipalTests.cs similarity index 73% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationPrincipalTests.cs index 14c9638a..4d37c7c1 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationPrincipalTests.cs @@ -1,11 +1,11 @@ -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; -/// Who may see a call. -public sealed class PostgresCallPrincipalTests : PostgresDatabaseTest +/// Who may see a conversation. +public sealed class PostgresConversationPrincipalTests : PostgresDatabaseTest { /// protected override bool Migrated => true; @@ -14,21 +14,21 @@ public sealed class PostgresCallPrincipalTests : PostgresDatabaseTest public async Task AttachPrincipalAsync_AKey_WritesOneRow() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); // Assert - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_principal")); } [PostgresFact] public async Task AttachPrincipalAsync_TheSamePairTwice_IsNotAThrowAndStaysOneRow() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -38,30 +38,30 @@ public async Task AttachPrincipalAsync_TheSamePairTwice_IsNotAThrowAndStaysOneRo // Assert Assert.Null(thrown); - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_principal")); } [PostgresFact] public async Task AttachPrincipalAsync_TheSamePairTwice_KeepsTheFirstAttachedAt() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); - var first = await ScalarAsync("SELECT attached_at FROM agentcore.call_principal"); + var first = await ScalarAsync("SELECT attached_at FROM agentcore.conversation_principal"); // Act await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); // Assert - Assert.Equal(first, await ScalarAsync("SELECT attached_at FROM agentcore.call_principal")); + Assert.Equal(first, await ScalarAsync("SELECT attached_at FROM agentcore.conversation_principal")); } [PostgresFact] - public async Task AttachPrincipalAsync_TwoKeysOnOneCall_BothStay() + public async Task AttachPrincipalAsync_TwoKeysOnOneConversation_BothStay() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act @@ -69,14 +69,14 @@ public async Task AttachPrincipalAsync_TwoKeysOnOneCall_BothStay() await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); // Assert - Assert.Equal(2, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(2, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_principal")); } [PostgresFact] public async Task DetachPrincipalAsync_OneOfTwoKeys_LeavesTheOther() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "tenant-a", "tenant", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -85,14 +85,14 @@ public async Task DetachPrincipalAsync_OneOfTwoKeys_LeavesTheOther() await store.DetachPrincipalAsync("c1", "person-a", Token); // Assert - Assert.Equal("tenant-a", await ScalarAsync("SELECT principal_key FROM agentcore.call_principal")); + Assert.Equal("tenant-a", await ScalarAsync("SELECT principal_key FROM agentcore.conversation_principal")); } [PostgresFact] public async Task DetachPrincipalAsync_AKeyThatWasNeverAttached_IsNotAThrow() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreAppendTests.cs similarity index 77% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreAppendTests.cs index 34573360..139b7276 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreAppendTests.cs @@ -1,31 +1,31 @@ using System.Text.RegularExpressions; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Ports; using AgentCore.Application.Transcript; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// -/// The store numbers every row from the call's own counter, in PostgreSQL: the seam that lets a -/// host append to a call from outside any turn, on any machine, without colliding with the call's +/// The store numbers every row from the conversation's own counter, in PostgreSQL: the seam that lets a +/// host append to a conversation from outside any turn, on any machine, without colliding with the conversation's /// live session. /// -#pragma warning disable CA1859 // store is typed as ICallStore throughout: AppendAsync(callId, message, ct) +#pragma warning disable CA1859 // store is typed as IConversationStore throughout: AppendAsync(conversationId, message, ct) // is a default interface method, and only resolves through the interface type. -public sealed partial class PostgresCallStoreAppendTests : PostgresDatabaseTest +public sealed partial class PostgresConversationStoreAppendTests : PostgresDatabaseTest { /// protected override bool Migrated => true; [PostgresFact] - public async Task AppendAsync_OneMessage_OnAFreshCall_IsOrdinalZeroAndTurnZero() + public async Task AppendAsync_OneMessage_OnAFreshConversation_IsOrdinalZeroAndTurnZero() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); // Act @@ -41,7 +41,7 @@ public async Task AppendAsync_OneMessage_OnAFreshCall_IsOrdinalZeroAndTurnZero() public async Task AppendAsync_OneMessage_WithItsOwnId_KeepsIt() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); ChatMessage message = new(ChatRole.User, "hello") { MessageId = "caller-named" }; @@ -56,7 +56,7 @@ public async Task AppendAsync_OneMessage_WithItsOwnId_KeepsIt() public async Task AppendAsync_TwoOutsideAppends_AreNumberedZeroThenOne() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); // Act @@ -66,19 +66,19 @@ public async Task AppendAsync_TwoOutsideAppends_AreNumberedZeroThenOne() // Assert Assert.Equal(0, first.Ordinal); Assert.Equal(1, second.Ordinal); - var call = await store.GetAsync("c1", Token); - Assert.Equal(2, call?.NextOrdinal); + var conversation = await store.GetAsync("c1", Token); + Assert.Equal(2, conversation?.NextOrdinal); } [PostgresFact] public async Task AppendAsync_ABatchWithAnExplicitTurnIndex_NumbersThreeConsecutiveRowsInDraftOrder() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "outside"), Token); - CallMessageDraft[] drafts = + ConversationMessageDraft[] drafts = [ new(4, new ChatMessage(ChatRole.User, "a"), "m-a"), new(4, new ChatMessage(ChatRole.Assistant, "b"), "m-b"), @@ -98,12 +98,12 @@ public async Task AppendAsync_ABatchWithAnExplicitTurnIndex_NumbersThreeConsecut public async Task AppendAsync_OutsideAppend_AfterABatchThatWroteState_IsStampedWithTheStoredNextTurnIndex() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); await store.AppendAsync( "c1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { NextTurnIndex = 7 }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { NextTurnIndex = 7 }, Token); // Act @@ -119,7 +119,7 @@ public async Task AppendAsync_TwoWritersFiftyEach_LandsOneHundredRowsWithNoColli // Arrange — the shape the owner proved under concurrency in a probe: 2 writers x 50 appends // -> 100 rows, 0..99, 0 retries. The store's data source pools connections, so two tasks // running concurrently naturally reach PostgreSQL on separate physical connections. - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); async Task WriteFiftyAsync(string label) @@ -140,10 +140,10 @@ async Task WriteFiftyAsync(string label) } [PostgresFact] - public async Task AppendAsync_ACallThatDoesNotExist_ThrowsNamingIt() + public async Task AppendAsync_AConversationThatDoesNotExist_ThrowsNamingIt() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); // Act var failure = await Record.ExceptionAsync( @@ -158,7 +158,7 @@ public async Task AppendAsync_ACallThatDoesNotExist_ThrowsNamingIt() public async Task RewriteAsync_OneRow_ChangesOnlyThatRowsContent() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "first") { MessageId = "m0" }, Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "second") { MessageId = "m1" }, Token); @@ -175,7 +175,7 @@ public async Task RewriteAsync_OneRow_ChangesOnlyThatRowsContent() public async Task AppendAsync_AfterATruncate_NeverReusesTheOrdinalsItTook() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "zero"), Token); await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "one"), Token); @@ -193,7 +193,7 @@ public async Task AppendAsync_AfterATruncate_NeverReusesTheOrdinalsItTook() public async Task ReadAsync_ARowWithAdditionalProperties_KeepsThemAcrossTheRoundTrip() { // Arrange - ICallStore store = new PostgresCallStore(DataSource); + IConversationStore store = new PostgresConversationStore(DataSource); await store.CreateAsync("c1", Token); ChatMessage message = new(ChatRole.User, "hello") { diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreSweepTests.cs similarity index 58% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreSweepTests.cs index f86c52a3..f7b8a61c 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreSweepTests.cs @@ -1,56 +1,56 @@ using AgentCore.Application.Transcript; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// -/// Retention, which deletes the call and lets the cascade take the words. +/// Retention, which deletes the conversation and lets the cascade take the words. /// -public sealed class PostgresCallStoreSweepTests : PostgresDatabaseTest +public sealed class PostgresConversationStoreSweepTests : PostgresDatabaseTest { private static readonly TimeSpan Window = TimeSpan.FromDays(30); /// protected override bool Migrated => true; - private static CallMessageDraft Word() => + private static ConversationMessageDraft Word() => new(0, new ChatMessage(ChatRole.User, "hello"), "m0"); [PostgresFact] - public async Task SweepAsync_ACallWhoseLastMessageIsOld_TakesTheCallAndItsWords() + public async Task SweepAsync_AConversationWhoseLastMessageIsOld_TakesTheConversationAndItsWords() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("old", Token); await store.AppendAsync("old", [Word()], cancellationToken: Token); - await ExecuteAsync("UPDATE agentcore.call_message SET updated_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.conversation_message SET updated_at = now() - interval '90 days'"); // Act var swept = await store.SweepAsync(Window, cancellationToken: Token); // Assert Assert.Equal(1, swept); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_message")); } [PostgresFact] - public async Task SweepAsync_ACallWithNoWordsAtAll_TakesItOnCreatedAt() + public async Task SweepAsync_AConversationWithNoWordsAtAll_TakesItOnCreatedAt() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("empty", Token); - await ExecuteAsync("UPDATE agentcore.call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.conversation SET created_at = now() - interval '90 days'"); // Act var swept = await store.SweepAsync(Window, cancellationToken: Token); // Assert Assert.Equal(1, swept); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); } /// @@ -58,33 +58,33 @@ public async Task SweepAsync_ACallWithNoWordsAtAll_TakesItOnCreatedAt() /// point of coalescing rather than reading either column alone. /// [PostgresFact] - public async Task SweepAsync_ACallSpokenOnInsideTheWindow_LeavesIt() + public async Task SweepAsync_AConversationSpokenOnInsideTheWindow_LeavesIt() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("fresh", Token); await store.AppendAsync("fresh", [Word()], cancellationToken: Token); - await ExecuteAsync("UPDATE agentcore.call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.conversation SET created_at = now() - interval '90 days'"); // Act var swept = await store.SweepAsync(Window, cancellationToken: Token); // Assert Assert.Equal(0, swept); - Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); } [PostgresFact] - public async Task SweepAsync_ASweptCall_LeavesItsAuditEvents() + public async Task SweepAsync_ASweptConversation_LeavesItsAuditEvents() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("old", Token); - await ExecuteAsync("UPDATE agentcore.call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.conversation SET created_at = now() - interval '90 days'"); await ExecuteAsync( """ - INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) - VALUES ('old', gen_random_uuid(), 0, 'call.started', now()) + INSERT INTO agentcore.audit_event (conversation_id, event_id, sequence, kind, occurred_at) + VALUES ('old', gen_random_uuid(), 0, 'conversation.started', now()) """); // Act @@ -95,30 +95,30 @@ INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_a } [PostgresFact] - public async Task SweepAsync_MoreExpiredCallsThanOneBatch_LoopsUntilNoneAreLeft() + public async Task SweepAsync_MoreExpiredConversationsThanOneBatch_LoopsUntilNoneAreLeft() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); for (var i = 0; i < 5; i++) { await store.CreateAsync($"c{i}", Token); } - await ExecuteAsync("UPDATE agentcore.call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.conversation SET created_at = now() - interval '90 days'"); // Act var swept = await store.SweepAsync(Window, batchSize: 2, cancellationToken: Token); // Assert Assert.Equal(5, swept); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); } [PostgresFact] - public async Task EraseAsync_ACallsWords_LeavesTheCallItselfListed() + public async Task EraseAsync_AConversationsWords_LeavesTheConversationItselfListed() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AppendAsync("c1", [Word()], cancellationToken: Token); @@ -127,7 +127,7 @@ public async Task EraseAsync_ACallsWords_LeavesTheCallItselfListed() // Assert — erase empties a thread that stays; delete takes the thread and the words with it. Assert.Equal(1, erased); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_message")); Assert.NotNull(await store.GetAsync("c1", Token)); } } diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreTests.cs similarity index 67% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreTests.cs index de9f8eb8..3e2fda2f 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreTests.cs @@ -1,39 +1,39 @@ using System.Text.Json; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Ports; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// Store 0, in PostgreSQL. -public sealed class PostgresCallStoreTests : PostgresDatabaseTest +public sealed class PostgresConversationStoreTests : PostgresDatabaseTest { /// protected override bool Migrated => true; [PostgresFact] - public async Task CreateAsync_ANewCall_WritesOneRow() + public async Task CreateAsync_ANewConversation_WritesOneRow() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); // Act - var call = await store.CreateAsync("c1", Token); + var conversation = await store.CreateAsync("c1", Token); // Assert - Assert.Equal("c1", call.CallId); - Assert.Null(call.Title); - Assert.Equal(CallStatus.Regular, call.Status); - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal("c1", conversation.ConversationId); + Assert.Null(conversation.Title); + Assert.Equal(ConversationStatus.Regular, conversation.Status); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); } [PostgresFact] public async Task CreateAsync_TheSameIdTwice_StaysOneRowAndKeepsTheFirst() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); // Act var first = await store.CreateAsync("c1", Token); @@ -43,14 +43,14 @@ public async Task CreateAsync_TheSameIdTwice_StaysOneRowAndKeepsTheFirst() // Assert Assert.Equal(first.CreatedAt, second.CreatedAt); Assert.Equal("kept", second.Title); - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); } [PostgresFact] - public async Task GetAsync_ACallThatWasNeverMade_IsNull() + public async Task GetAsync_AConversationThatWasNeverMade_IsNull() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); // Act var found = await store.GetAsync("missing", Token); @@ -60,10 +60,10 @@ public async Task GetAsync_ACallThatWasNeverMade_IsNull() } [PostgresFact] - public async Task GetAsync_ACallWithNoMessages_ReportsNoLastActivity() + public async Task GetAsync_AConversationWithNoMessages_ReportsNoLastActivity() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act @@ -74,14 +74,14 @@ public async Task GetAsync_ACallWithNoMessages_ReportsNoLastActivity() } [PostgresFact] - public async Task GetAsync_ACallWithMessages_ReportsTheNewestMessageTime() + public async Task GetAsync_AConversationWithMessages_ReportsTheNewestMessageTime() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await ExecuteAsync( """ - INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) + INSERT INTO agentcore.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) VALUES ('c1', 1, 0, 'user', '{}'::jsonb, 'm1', now(), now() + interval '1 hour') """); @@ -93,10 +93,10 @@ INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, } [PostgresFact] - public async Task RenameAsync_ACall_ChangesOnlyItsTitle() + public async Task RenameAsync_AConversation_ChangesOnlyItsTitle() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act @@ -105,28 +105,28 @@ public async Task RenameAsync_ACall_ChangesOnlyItsTitle() // Assert var found = await store.GetAsync("c1", Token); Assert.Equal("A squeaky belt", found!.Title); - Assert.Equal(CallStatus.Regular, found.Status); + Assert.Equal(ConversationStatus.Regular, found.Status); } [PostgresFact] public async Task SetStatusAsync_Archived_IsReadBack() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act - await store.SetStatusAsync("c1", CallStatus.Archived, Token); + await store.SetStatusAsync("c1", ConversationStatus.Archived, Token); // Assert - Assert.Equal(CallStatus.Archived, (await store.GetAsync("c1", Token))!.Status); + Assert.Equal(ConversationStatus.Archived, (await store.GetAsync("c1", Token))!.Status); } [PostgresFact] public async Task SetCustomAsync_SomeFields_AreReadBackWhole() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); using var document = JsonDocument.Parse("""{"crmId":"A-1","tags":["belt"]}"""); @@ -142,7 +142,7 @@ public async Task SetCustomAsync_SomeFields_AreReadBackWhole() public async Task SetCustomAsync_Null_ClearsTheFields() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); using var document = JsonDocument.Parse("""{"crmId":"A-1"}"""); await store.SetCustomAsync("c1", document.RootElement, Token); @@ -158,7 +158,7 @@ public async Task SetCustomAsync_Null_ClearsTheFields() public async Task SetExternalIdAsync_AConsumersOwnId_IsReadBack() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); // Act @@ -172,7 +172,7 @@ public async Task SetExternalIdAsync_AConsumersOwnId_IsReadBack() public async Task SetExternalIdAsync_Null_ClearsTheId() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.SetExternalIdAsync("c1", "crm-77", Token); @@ -184,10 +184,10 @@ public async Task SetExternalIdAsync_Null_ClearsTheId() } [PostgresFact] - public async Task DeleteAsync_ACall_LeavesNoRowAndNoClaim() + public async Task DeleteAsync_AConversation_LeavesNoRowAndNoClaim() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); @@ -195,19 +195,19 @@ public async Task DeleteAsync_ACall_LeavesNoRowAndNoClaim() await store.DeleteAsync("c1", Token); // Assert - Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.call")); - Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.conversation")); + Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_principal")); } [PostgresFact] - public async Task DeleteAsync_ACall_TakesItsSameIdContinuationWithIt() + public async Task DeleteAsync_AConversation_TakesItsSameIdContinuationWithIt() { // Arrange — one id plays three roles now, so the row delete takes the key with it. Per-turn // response ids are gone with their own rows only through DeleteContinuationAsync; nothing // here enumerates them. - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("c1", Token); - using var document = System.Text.Json.JsonDocument.Parse("""{ "callId": "c1" }"""); + using var document = System.Text.Json.JsonDocument.Parse("""{ "conversationId": "c1" }"""); await store.SaveContinuationAsync("c1", document.RootElement, Token); // Act @@ -218,10 +218,10 @@ public async Task DeleteAsync_ACall_TakesItsSameIdContinuationWithIt() } [PostgresFact] - public async Task DeleteAsync_ACallThatWasNeverMade_IsNotAThrow() + public async Task DeleteAsync_AConversationThatWasNeverMade_IsNotAThrow() { // Arrange - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); // Act var thrown = await Record.ExceptionAsync(() => store.DeleteAsync("missing", Token).AsTask()); diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreTruncateTests.cs similarity index 65% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreTruncateTests.cs index d3af79fd..58cc2e00 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreTruncateTests.cs @@ -1,25 +1,25 @@ -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Transcript; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; using Microsoft.Extensions.AI; using Npgsql; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// /// What an edit does to store 1 in PostgreSQL: which rows go, which stay, and what the names the /// caller knows its messages by are good for. /// -public sealed class PostgresCallStoreTruncateTests : PostgresDatabaseTest +public sealed class PostgresConversationStoreTruncateTests : PostgresDatabaseTest { /// protected override bool Migrated => true; - private async Task OpenAsync() + private async Task OpenAsync() { - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("C1", Token); return store; } @@ -31,10 +31,10 @@ public async Task Truncate_TakesTheNamedOrdinalAndEverythingAfterIt() await store.AppendAsync( "C1", [ - new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0"), - new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "a1"), "m1"), - new CallMessageDraft(1, new ChatMessage(ChatRole.User, "q2"), "m2"), - new CallMessageDraft(1, new ChatMessage(ChatRole.Assistant, "a2"), "m3"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.Assistant, "a1"), "m1"), + new ConversationMessageDraft(1, new ChatMessage(ChatRole.User, "q2"), "m2"), + new ConversationMessageDraft(1, new ChatMessage(ChatRole.Assistant, "a2"), "m3"), ], state: null, Token); @@ -56,9 +56,9 @@ public async Task Truncate_LeavesTheNextAppendFreeToClimbPastTheGap() await store.AppendAsync( "C1", [ - new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0"), - new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "a1"), "m1"), - new CallMessageDraft(1, new ChatMessage(ChatRole.User, "q2"), "m2"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0"), + new ConversationMessageDraft(0, new ChatMessage(ChatRole.Assistant, "a1"), "m1"), + new ConversationMessageDraft(1, new ChatMessage(ChatRole.User, "q2"), "m2"), ], state: null, Token); @@ -66,7 +66,7 @@ await store.AppendAsync( await store.AppendAsync( "C1", - [new CallMessageDraft(2, new ChatMessage(ChatRole.User, "q2 again"), "m3")], + [new ConversationMessageDraft(2, new ChatMessage(ChatRole.User, "q2 again"), "m3")], state: null, Token); @@ -76,12 +76,12 @@ await store.AppendAsync( } [PostgresFact] - public async Task AMessageName_RoundTripsAndIsUniqueWithinTheCall() + public async Task AMessageName_RoundTripsAndIsUniqueWithinTheConversation() { var store = await OpenAsync(); await store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0")], + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0")], state: null, Token); @@ -90,7 +90,7 @@ await store.AppendAsync( var clash = await Record.ExceptionAsync( () => store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q2"), "m0")], + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "q2"), "m0")], state: null, Token).AsTask()); @@ -98,15 +98,15 @@ await store.AppendAsync( } [PostgresFact] - public async Task Truncate_LeavesTheStateAndTheCallRowAlone() + public async Task Truncate_LeavesTheStateAndTheConversationRowAlone() { - // An edit withdraws words. It does not withdraw how far the call has got — the marks in the + // An edit withdraws words. It does not withdraw how far the conversation has got — the marks in the // state are what stop the next turn standing where a deleted row stood. var store = await OpenAsync(); await store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0")], - new CallSessionState { Stage = "collecting", NextTurnIndex = 1 }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0")], + new ConversationSessionState { Stage = "collecting", NextTurnIndex = 1 }, Token); await store.TruncateAsync("C1", 0, Token); diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreWordsTests.cs similarity index 79% rename from tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs rename to tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreWordsTests.cs index da6b3f5e..a073182f 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Conversation/Postgres/PostgresConversationStoreWordsTests.cs @@ -1,28 +1,28 @@ using System.Text.Json; using System.Text.Json.Nodes; -using AgentCore.Application.Calls; +using AgentCore.Application.Conversation; using AgentCore.Application.Runtime; using AgentCore.Application.Transcript; using AgentCore.Domain.Audit; using AgentCore.Infrastructure.Audit.Postgres; using AgentCore.Infrastructure.Tests.Database.Postgres; -using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Conversation.Postgres; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Infrastructure.Tests.Calls.Postgres; +namespace AgentCore.Infrastructure.Tests.Conversation.Postgres; /// /// The words half of the store, in PostgreSQL. /// -public sealed class PostgresCallStoreWordsTests : PostgresDatabaseTest +public sealed class PostgresConversationStoreWordsTests : PostgresDatabaseTest { private static readonly TimeSpan NinetyDays = TimeSpan.FromDays(90); - /// Opens the store with the call rows these tests write words against already made. - private async Task OpenAsync() + /// Opens the store with the conversation rows these tests write words against already made. + private async Task OpenAsync() { - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); await store.CreateAsync("C1", Token); await store.CreateAsync("C2", Token); return store; @@ -44,7 +44,7 @@ public async Task AppendAsync_ATurn_WritesOneRowForEachMessage() await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // Assert - Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); + Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_message")); } [PostgresFact] @@ -59,7 +59,7 @@ public async Task AppendAsync_ATurn_LiftsTheRoleOutOfTheContent() // Assert — retention and redaction read the role, and never parse the content to find it. Assert.Equal( "user,assistant", - await ScalarAsync("SELECT string_agg(role, ',' ORDER BY ordinal) FROM agentcore.call_message")); + await ScalarAsync("SELECT string_agg(role, ',' ORDER BY ordinal) FROM agentcore.conversation_message")); } [PostgresFact] @@ -77,8 +77,8 @@ public async Task AppendAsync_AToolCallingTurn_RoundTripsEveryContentPart() await store.AppendAsync( "C1", [ - new CallMessageDraft(0, announced, "m0"), - new CallMessageDraft(0, result, "m1"), + new ConversationMessageDraft(0, announced, "m0"), + new ConversationMessageDraft(0, result, "m1"), ], cancellationToken: Token); @@ -103,7 +103,7 @@ public async Task AppendAsync_NoMessages_TouchesNothing() await store.AppendAsync("C1", [], cancellationToken: Token); // Assert - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_message")); } [PostgresFact] @@ -111,7 +111,7 @@ public async Task ItWritesTheStateBesideTheWords() { var store = await OpenAsync(); - CallSessionState state = new() + ConversationSessionState state = new() { Stage = "collecting", Slots = new Dictionary(StringComparer.Ordinal) @@ -122,7 +122,7 @@ public async Task ItWritesTheStateBesideTheWords() await store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], state, Token); @@ -134,9 +134,9 @@ await store.AppendAsync( } [PostgresFact] - public async Task ACallWithNoStateReadsAsNull() + public async Task AConversationWithNoStateReadsAsNull() { - PostgresCallStore store = new(DataSource); + PostgresConversationStore store = new(DataSource); var record = await store.CreateAsync("C3", Token); @@ -150,12 +150,12 @@ public async Task AnAppendWithNoStateLeavesTheStoredStateAlone() await store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "collecting" }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "collecting" }, Token); await store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "hi"), "m1")], + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.Assistant, "hi"), "m1")], state: null, Token); @@ -176,26 +176,26 @@ public async Task AnAppendThatFails_LandsNeitherTheWordsNorTheState() var store = await OpenAsync(); await store.AppendAsync( "C1", - [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "a" }, + [new ConversationMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new ConversationSessionState { Stage = "a" }, Token); - // Act — a batch whose FIRST row is new and whose second repeats a message id the call + // Act — a batch whose FIRST row is new and whose second repeats a message id the conversation // already holds. The store owns ordinal assignment now, so a caller can no longer force an - // ordinal collision; the unique constraint on (call_id, message_id) is what fails instead, + // ordinal collision; the unique constraint on (conversation_id, message_id) is what fails instead, // and "m2" landing would be what a batch that was never one transaction looks like. var failure = await Record.ExceptionAsync( () => store.AppendAsync( "C1", [ - new CallMessageDraft(1, new ChatMessage(ChatRole.User, "lands first"), "m2"), - new CallMessageDraft(1, new ChatMessage(ChatRole.User, "again"), "m0"), + new ConversationMessageDraft(1, new ChatMessage(ChatRole.User, "lands first"), "m2"), + new ConversationMessageDraft(1, new ChatMessage(ChatRole.User, "again"), "m0"), ], - new CallSessionState { Stage = "b" }, + new ConversationSessionState { Stage = "b" }, Token).AsTask()); // Assert — the throw, then the row that had already succeeded, then the state the failed - // batch tried to write. A stage of "b" beside one message would be a call whose blob had + // batch tried to write. A stage of "b" beside one message would be a conversation whose blob had // moved on without its words; a surviving "m2" would be a batch that was never one // transaction. Assert.NotNull(failure); @@ -208,29 +208,29 @@ await store.AppendAsync( } [PostgresFact] - public async Task AStateBlobThatWillNotParse_ReadsAsNoBlobRatherThanClosingTheCall() + public async Task AStateBlobThatWillNotParse_ReadsAsNoBlobRatherThanClosingTheConversation() { // Arrange — jsonb refuses malformed JSON, so a bad blob is well-formed JSON of the wrong // shape: an older or newer build's column, or a hand-edited row. Version cannot save this // one, because Version is only readable after the deserialize has already succeeded. var store = await OpenAsync(); - await ExecuteAsync("UPDATE agentcore.call SET state = '[1, 2, 3]'::jsonb WHERE call_id = 'C1'"); + await ExecuteAsync("UPDATE agentcore.conversation SET state = '[1, 2, 3]'::jsonb WHERE conversation_id = 'C1'"); // Act var record = await store.GetAsync("C1", Token); // Assert — no throw, and no state. A throw here would escape GetAsync, CreateAsync and - // OpenSessionAsync, and the call could never be opened again by anyone: one bad row would + // OpenSessionAsync, and the conversation could never be opened again by anyone: one bad row would // refuse every turn of that call forever, with no diagnostic and no way back. Assert.NotNull(record); Assert.Null(record.State); } // --------------------------------------------------------------------------------------------- - // Read. It runs at call start, on a resume, and nowhere else. + // Read. It runs at conversation start, on a resume, and nowhere else. // --------------------------------------------------------------------------------------------- [PostgresFact] - public async Task ReadAsync_AWrittenCall_ReturnsEveryRowInOrdinalOrder() + public async Task ReadAsync_AWrittenConversation_ReturnsEveryRowInOrdinalOrder() { // Arrange var store = await OpenAsync(); @@ -245,7 +245,7 @@ public async Task ReadAsync_AWrittenCall_ReturnsEveryRowInOrdinalOrder() } [PostgresFact] - public async Task ReadAsync_AnotherCall_ReturnsNothing() + public async Task ReadAsync_AnotherConversation_ReturnsNothing() { // Arrange var store = await OpenAsync(); @@ -283,14 +283,14 @@ public async Task RewriteAsync_ARow_MovesUpdatedAtAndLeavesCreatedAt() // correction. var store = await OpenAsync(); await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); - await ExecuteAsync("UPDATE agentcore.call_message SET created_at = now() - interval '1 hour', updated_at = created_at"); + await ExecuteAsync("UPDATE agentcore.conversation_message SET created_at = now() - interval '1 hour', updated_at = created_at"); // Act await store.RewriteAsync("C1", "m1", new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); // Assert Assert.True(await ScalarAsync( - "SELECT updated_at > created_at FROM agentcore.call_message WHERE call_id = 'C1' AND message_id = 'm1'")); + "SELECT updated_at > created_at FROM agentcore.conversation_message WHERE conversation_id = 'C1' AND message_id = 'm1'")); } [PostgresFact] @@ -305,14 +305,14 @@ public async Task RewriteAsync_AMessageIdThatIsNotThere_WritesNothing() await store.RewriteAsync("C1", "does-not-exist", new ChatMessage(ChatRole.Assistant, "never spoken"), Token); // Assert - Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); + Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_message")); } // --------------------------------------------------------------------------------------------- // Erase, and the sweep. // --------------------------------------------------------------------------------------------- [PostgresFact] - public async Task EraseAsync_OneCall_DeletesItsRowsAndLeavesTheOthers() + public async Task EraseAsync_OneConversation_DeletesItsRowsAndLeavesTheOthers() { // Arrange var store = await OpenAsync(); @@ -339,7 +339,7 @@ public async Task EraseAsync_OneCall_DeletesItsRowsAndLeavesTheOthers() public async Task ReadSpokenTurnsAsync_AToolCallingTurn_ReturnsOneRowForThatTurn() { // Arrange — the DISTINCT ON guard. The turn writes an assistant message carrying the tool - // call and another carrying the reply; without it both come back, and the textless one + // conversation and another carrying the reply; without it both come back, and the textless one // reports a false tamper on every tool-calling turn. var store = await OpenAsync(); await WriteToolCallingTurnAsync(store, "C1", turnIndex: 0, spoken: "Order 41 ships Friday."); @@ -420,18 +420,18 @@ public async Task ReadSpokenTurnsAsync_ATurnAmendedInTheChain_ReturnsOneRowHoldi /// /// One ordinary turn: what the caller said, and what the caller heard. - /// only keeps message ids unique across appends to the same call — the store assigns the + /// only keeps message ids unique across appends to the same conversation — the store assigns the /// ordinal, so it no longer says where the turn lands. /// - private static CallMessageDraft[] Turn(int turnIndex, int idSeed) => + private static ConversationMessageDraft[] Turn(int turnIndex, int idSeed) => [ - new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), $"m{idSeed}"), - new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.Assistant, "Order 41 ships Friday."), $"m{idSeed + 1}"), + new ConversationMessageDraft(turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), $"m{idSeed}"), + new ConversationMessageDraft(turnIndex, new ChatMessage(ChatRole.Assistant, "Order 41 ships Friday."), $"m{idSeed + 1}"), ]; /// Writes a tool-calling turn to store 1 and its turn.completed row to store 3. private async Task WriteToolCallingTurnAsync( - PostgresCallStore store, string callId, int turnIndex, string spoken, bool drew = false) + PostgresConversationStore store, string conversationId, int turnIndex, string spoken, bool drew = false) { List toolResultContents = [new FunctionResultContent("id1", "Friday")]; if (drew) @@ -445,13 +445,13 @@ private async Task WriteToolCallingTurnAsync( } await store.AppendAsync( - callId, + conversationId, [ - new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), "m0"), - new CallMessageDraft(turnIndex, new ChatMessage( + new ConversationMessageDraft(turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), "m0"), + new ConversationMessageDraft(turnIndex, new ChatMessage( ChatRole.Assistant, [new FunctionCallContent("id1", "lookup", null)]), "m1"), - new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.Tool, toolResultContents), "m2"), - new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.Assistant, spoken), "m3"), + new ConversationMessageDraft(turnIndex, new ChatMessage(ChatRole.Tool, toolResultContents), "m2"), + new ConversationMessageDraft(turnIndex, new ChatMessage(ChatRole.Assistant, spoken), "m3"), ], cancellationToken: Token); @@ -461,7 +461,7 @@ await store.AppendAsync( await chain.AppendAsync( new AuditEvent { - CallId = callId, + ConversationId = conversationId, EventId = eventId, Kind = AuditEventKind.TurnCompleted, OccurredAt = new DateTimeOffset(2026, 8, 19, 9, 0, 1, TimeSpan.Zero), @@ -477,14 +477,14 @@ await chain.AppendAsync( } /// Writes a second turn.completed that corrects the first, as a barge-in does. - private async Task AmendTurnAsync(string callId, int turnIndex, Guid amends, string spoken) + private async Task AmendTurnAsync(string conversationId, int turnIndex, Guid amends, string spoken) { // Not disposed: the sink would take the test's own pool with it. PostgresAuditSink chain = new(DataSource); await chain.AppendAsync( new AuditEvent { - CallId = callId, + ConversationId = conversationId, EventId = Guid.CreateVersion7(), Kind = AuditEventKind.TurnCompleted, OccurredAt = new DateTimeOffset(2026, 8, 19, 9, 0, 2, TimeSpan.Zero), @@ -498,7 +498,7 @@ await chain.AppendAsync( Token); } - /// Moves one call's rows back in time, so the sweep can be asked about them. - private Task AgeAsync(string callId, TimeSpan age) => ExecuteAsync( - $"UPDATE agentcore.call_message SET updated_at = now() - interval '{age.TotalDays} days' WHERE call_id = '{callId}'"); + /// Moves one conversation's rows back in time, so the sweep can be asked about them. + private Task AgeAsync(string conversationId, TimeSpan age) => ExecuteAsync( + $"UPDATE agentcore.conversation_message SET updated_at = now() - interval '{age.TotalDays} days' WHERE conversation_id = '{conversationId}'"); } diff --git a/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresDatabaseTest.cs b/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresDatabaseTest.cs index 9f0f8e4b..a98723aa 100644 --- a/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresDatabaseTest.cs +++ b/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresDatabaseTest.cs @@ -19,7 +19,7 @@ public abstract class PostgresDatabaseTest : IAsyncLifetime /// Whether the schema is applied before the test body runs. protected abstract bool Migrated { get; } - /// The token every call in a test body carries. + /// The token every conversation in a test body carries. protected static CancellationToken Token => TestContext.Current.CancellationToken; /// The database this test owns. diff --git a/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs b/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs index 380287a6..d3c7eac4 100644 --- a/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs @@ -13,9 +13,9 @@ public sealed class PostgresSchemaTests : PostgresDatabaseTest protected override bool Migrated => false; [PostgresTheory] - [InlineData("agentcore.call")] - [InlineData("agentcore.call_principal")] - [InlineData("agentcore.call_message")] + [InlineData("agentcore.conversation")] + [InlineData("agentcore.conversation_principal")] + [InlineData("agentcore.conversation_message")] [InlineData("agentcore.audit_event")] [InlineData("agentcore.schema_migration")] public async Task ApplyAsync_FreshDatabase_CreatesTheTable(string table) @@ -31,7 +31,7 @@ public async Task ApplyAsync_FreshDatabase_CreatesTheTable(string table) } [PostgresFact] - public async Task ApplyAsync_FreshDatabase_GivesCallANextOrdinalColumn() + public async Task ApplyAsync_FreshDatabase_GivesConversationANextOrdinalColumn() { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); @@ -41,7 +41,7 @@ public async Task ApplyAsync_FreshDatabase_GivesCallANextOrdinalColumn() """ SELECT is_nullable || ',' || column_default FROM information_schema.columns - WHERE table_schema = 'agentcore' AND table_name = 'call' AND column_name = 'next_ordinal' + WHERE table_schema = 'agentcore' AND table_name = 'conversation' AND column_name = 'next_ordinal' """); // Assert @@ -149,8 +149,8 @@ public async Task AuditEvent_SuppliedWritePosition_IsRefused() // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( """ - INSERT INTO agentcore.audit_event (write_position, call_id, event_id, sequence, kind, occurred_at) - VALUES (1, 'C1', gen_random_uuid(), 1, 'call.started', now()) + INSERT INTO agentcore.audit_event (write_position, conversation_id, event_id, sequence, kind, occurred_at) + VALUES (1, 'C1', gen_random_uuid(), 1, 'conversation.started', now()) """)); // Assert @@ -158,18 +158,18 @@ INSERT INTO agentcore.audit_event (write_position, call_id, event_id, sequence, } [PostgresFact] - public async Task AuditEvent_SecondRowOnTheSameCallAndSequence_IsRefused() + public async Task AuditEvent_SecondRowOnTheSameConversationAndSequence_IsRefused() { // Arrange — raw SQL stands in for the store here, so the table itself is what catches two - // rows landing on the same call and sequence. + // rows landing on the same conversation and sequence. await PostgresSchema.ApplyAsync(DataSource, Token); await InsertOneEventAsync(); // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( """ - INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) - VALUES ('C1', gen_random_uuid(), 1, 'call.ended', now()) + INSERT INTO agentcore.audit_event (conversation_id, event_id, sequence, kind, occurred_at) + VALUES ('C1', gen_random_uuid(), 1, 'conversation.ended', now()) """)); // Assert @@ -184,34 +184,34 @@ public async Task AuditEvent_SessionReplicationRoleIsReplica_BypassesEveryTrigge await PostgresSchema.ApplyAsync(DataSource, Token); await ExecuteAsync( """ - INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) - VALUES ('C1', gen_random_uuid(), 0, 'call.started', now()) + INSERT INTO agentcore.audit_event (conversation_id, event_id, sequence, kind, occurred_at) + VALUES ('C1', gen_random_uuid(), 0, 'conversation.started', now()) """); // Act await ExecuteAsync( """ SET session_replication_role = replica; - UPDATE agentcore.audit_event SET kind = 'call.ended' WHERE sequence = 0; + UPDATE agentcore.audit_event SET kind = 'conversation.ended' WHERE sequence = 0; SET session_replication_role = origin; """); // Assert - Assert.Equal("call.ended", await ScalarAsync("SELECT kind FROM agentcore.audit_event WHERE sequence = 0")); + Assert.Equal("conversation.ended", await ScalarAsync("SELECT kind FROM agentcore.audit_event WHERE sequence = 0")); } [PostgresFact] - public async Task CallMessage_SecondMessageOnTheSameOrdinal_IsRefused() + public async Task ConversationMessage_SecondMessageOnTheSameOrdinal_IsRefused() { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); - await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('C1')"); + await ExecuteAsync("INSERT INTO agentcore.conversation (conversation_id) VALUES ('C1')"); await ExecuteAsync( - "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); + "INSERT INTO agentcore.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( - "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'assistant', '{}', 'm1')")); + "INSERT INTO agentcore.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'assistant', '{}', 'm1')")); // Assert Assert.Equal("23505", Assert.IsType(refusal).SqlState); @@ -222,50 +222,50 @@ public async Task Versions_AreTheOneMigrationThisAssemblyCarries() => Assert.Equal(["001_agentcore"], PostgresSchema.Versions); [PostgresFact] - public async Task CallMessage_WithNoCallRow_IsRefused() + public async Task ConversationMessage_WithNoConversationRow_IsRefused() { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); - await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('present')"); + await ExecuteAsync("INSERT INTO agentcore.conversation (conversation_id) VALUES ('present')"); // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( - "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('absent', 0, 0, 'user', '{}', 'm0')")); + "INSERT INTO agentcore.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id) VALUES ('absent', 0, 0, 'user', '{}', 'm0')")); // Assert Assert.Equal("23503", Assert.IsType(refusal).SqlState); } /// - /// The cascade is the whole reason one store holds both. It reaches call_message and - /// call_principal, and it deliberately does not reach audit_event: a trigger refuses every + /// The cascade is the whole reason one store holds both. It reaches conversation_message and + /// conversation_principal, and it deliberately does not reach audit_event: a trigger refuses every /// DELETE there, and the trail outlives the conversation on purpose. /// [PostgresFact] - public async Task DeletingACall_TakesItsMessagesAndPrincipals_AndLeavesItsAuditEvents() + public async Task DeletingAConversation_TakesItsMessagesAndPrincipals_AndLeavesItsAuditEvents() { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); - await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('C1')"); + await ExecuteAsync("INSERT INTO agentcore.conversation (conversation_id) VALUES ('C1')"); await ExecuteAsync( - "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); + "INSERT INTO agentcore.conversation_message (conversation_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); await ExecuteAsync( - "INSERT INTO agentcore.call_principal (call_id, principal_key, role) VALUES ('C1', 'p1', 'owner')"); + "INSERT INTO agentcore.conversation_principal (conversation_id, principal_key, role) VALUES ('C1', 'p1', 'owner')"); await InsertOneEventAsync(); // Act - await ExecuteAsync("DELETE FROM agentcore.call WHERE call_id = 'C1'"); + await ExecuteAsync("DELETE FROM agentcore.conversation WHERE conversation_id = 'C1'"); // Assert - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.conversation_principal")); Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } private Task InsertOneEventAsync() => ExecuteAsync( """ - INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) - VALUES ('C1', gen_random_uuid(), 1, 'call.started', now()) + INSERT INTO agentcore.audit_event (conversation_id, event_id, sequence, kind, occurred_at) + VALUES ('C1', gen_random_uuid(), 1, 'conversation.started', now()) """); /// Opens a pool that logs in as an ordinary member of agentcore_writer. diff --git a/tests/AgentCore.Infrastructure.Tests/Evaluation/OpenAiModeration/OpenAiModerationEvaluatorTests.cs b/tests/AgentCore.Infrastructure.Tests/Evaluation/OpenAiModeration/OpenAiModerationEvaluatorTests.cs index 551dcdaa..27e576cd 100644 --- a/tests/AgentCore.Infrastructure.Tests/Evaluation/OpenAiModeration/OpenAiModerationEvaluatorTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Evaluation/OpenAiModeration/OpenAiModerationEvaluatorTests.cs @@ -404,7 +404,7 @@ await Assert.ThrowsAsync( /// The build opens the named client on the pipeline of the host, and reads the shared OpenAI key. /// /// - /// D13 says one key serves all four OpenAI calls, so this adapter declares no name of its own and + /// D13 says one key serves all four OpenAI conversations, so this adapter declares no name of its own and /// asks for the constant OpenAiChatClientAdapter owns. /// [Fact] @@ -492,7 +492,7 @@ public async Task CreateAsyncOpensNoSocket() } /// - /// The moderation call gives the turn back, rather than holding it for the default 100 seconds. + /// The moderation conversation gives the turn back, rather than holding it for the default 100 seconds. /// [Fact] public async Task TheDeadlineIsShorterThanTheShippedDefault() diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs index 37908bfd..6cacf1e4 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs @@ -23,12 +23,12 @@ namespace AgentCore.Infrastructure.Tests.Knowledge.VectorData.Qdrant; /// are internal to AgentCore.Application, and this project carries no grant to reach them. Every /// row here is instead driven through the same seam a production host uses: a real YAML document /// compiled by with a real handed -/// in as , and a real turn. The +/// in as , and a real turn. The /// turn's own "reply" model is a fake that calls the compiled agent's own Search tool with the /// row's question, the way a model that needs the cards would; the framework's own tool-calling loop /// then runs the real search with the running turn. Reading the tool's answer back off the transcript /// is what keeps every row on the production path: the loop's own flow is only entered around -/// CallSession's call into the reply model. +/// ConversationSession's call into the reply model. /// /// /// The store fuses a plain dense leg with a required-term leg by RRF (K49's amendment): a card the @@ -72,7 +72,7 @@ public async ValueTask InitializeAsync() Client = QdrantServer.CreateClient(); - // The 30-card synthetic corpus, unmodified, plus the multi-machine card the brief calls for. + // The 30-card synthetic corpus, unmodified, plus the multi-machine card the brief conversations for. // Composing with KbShapedCorpus rather than inventing a second one: A4's own facet-read tests // already proved this corpus's payload shape works, and a wrong facet path is this design's // own central failure mode (section 12), so reusing the shape that is already proven is the @@ -91,7 +91,7 @@ await Client.CreatePayloadIndexAsync( }; await Client.UpsertAsync(Name, added, cancellationToken: TestContext.Current.CancellationToken); - // One call sets facets.audience on every point already in the collection -- the 30 base cards + // One conversation sets facets.audience on every point already in the collection -- the 30 base cards // and the two just added -- rather than 32 individual patches. The all-points overload sends // no points_selector at all, which this server version refuses ("points_selector is // expected"); an empty filter is what Qdrant treats as "every point", and this client always @@ -198,7 +198,7 @@ public sealed class AmbiguityIntegrationTests : IClassFixture - /// A probe spread publishes no sources. TurnSources is internal to CallSession and + /// A probe spread publishes no sources. TurnSources is internal to ConversationSession and /// unreachable without a grant this project does not have, so this reads the same fact at its /// outer edge instead: nothing card-shaped reached the model at all, only the notice -- which is /// exactly what "published no sources" requires, since only a card-shaped result is ever cited. @@ -504,10 +504,10 @@ private async Task RunAsync( Loggers = loggers, })["main"]; - var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - var session = new CallSessionFactory( + var extractor = ConversationSessionFactory.CreateExtractor(compiled, chatClients); + var session = new ConversationSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor) - .Create($"call-{Guid.NewGuid():N}"); + .Create($"conversation-{Guid.NewGuid():N}"); await session.RunTurnAsync(callerQuestion, TestContext.Current.CancellationToken); @@ -545,7 +545,7 @@ private static string BuildTwoFacetYaml(int maxCandidates = 6) /// The caller generates and opens its own try **before** /// calling this -- never the reverse. Collection creation, every index, and the upsert can each /// throw against a live, sometimes-contended server, and if that happened inside an un-tried - /// helper the collection this call already created on the server would be orphaned with nothing + /// helper the collection this conversation already created on the server would be orphaned with nothing /// left to drop it. Creation, indexing and upsert all sit inside one try, with one /// unconditional DeleteCollectionAsync in the caller's own finally. /// @@ -609,8 +609,8 @@ public ValueTask> SearchAsync( /// Stands in for the turn's reply model. Rather than answer, its first round calls the compiled /// agent's own Search tool with the row's question, the way a model that needs the cards /// would; the framework's own tool-calling loop then invokes the real search with the running - /// turn filed in its arguments, from inside the same flow scope opened - /// around this call. Its second round reads the tool's own answer back off the transcript and + /// turn filed in its arguments, from inside the same flow scope opened + /// around this conversation. Its second round reads the tool's own answer back off the transcript and /// keeps it, so every row asserts on what the production search actually returned. /// private sealed class SearchCapturingChatClient : IChatClient diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs index e4946c4e..d3fc1dd5 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs @@ -106,17 +106,17 @@ public async Task CreateSearchAsync_DisposingTheReturnedPort_DisposesTheClient() entry, secrets: null, embeddings: null, requireScope: true, TestContext.Current.CancellationToken); Assert.NotNull(captured); - var isDisposedBeforeCall = typeof(QdrantClient) + var isDisposedBeforeConversation = typeof(QdrantClient) .GetField("_isDisposed", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(captured); - Assert.False((bool)isDisposedBeforeCall!); + Assert.False((bool)isDisposedBeforeConversation!); ((IDisposable)port).Dispose(); - var isDisposedAfterCall = typeof(QdrantClient) + var isDisposedAfterConversation = typeof(QdrantClient) .GetField("_isDisposed", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(captured); - Assert.True((bool)isDisposedAfterCall!); + Assert.True((bool)isDisposedAfterConversation!); } finally { diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs index 9ad75fb1..dd5c6225 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs @@ -291,7 +291,7 @@ public async Task SearchAsync_CallerCancels_Cancels() Fields = KbShapedCorpus.Fields, // Longer than the channel hangs for, so nothing but the caller's own token can end - // this call. At the default 10 s the store's deadline ends it instead and the test + // this conversation. At the default 10 s the store's deadline ends it instead and the test // passes whether or not the caller's token was ever linked in. Deadline = TimeSpan.FromMinutes(5), }); diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantServer.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantServer.cs index f77c974c..d3e44a90 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantServer.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantServer.cs @@ -31,7 +31,7 @@ public static QdrantClient CreateClient() var endpoint = Endpoint ?? throw new InvalidOperationException(SkipReason); var parts = endpoint.Split(':', 2); - // The timeout is per call and the connector never sets one. A schema call on a slow disk + // The timeout is per conversation and the connector never sets one. A schema conversation on a slow disk // can take 20 s; a query takes single-digit milliseconds. return new QdrantClient(parts[0], int.Parse(parts[1]), grpcTimeout: TimeSpan.FromSeconds(30)); } diff --git a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs index eb59c6cc..e30fc848 100644 --- a/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Llm/OpenAiReasoningEffortTests.cs @@ -65,7 +65,7 @@ public async Task TheLevelThatSendsNoReasoningAtAll_IsTheOneNamedNone() [Fact] public async Task RawOptionsTheCallerBuiltItself_KeepTheValuesTheyAlreadyHold() { - // A default for the entry, not an override of the call. The caller's own object is the one + // A default for the entry, not an override of the conversation. The caller's own object is the one // the vendor sees, and every value it already carries survives. CapturingChatClient inner = new(); CreateResponseOptions mine = new() @@ -93,7 +93,7 @@ await client.GetResponseAsync( [InlineData(null)] public async Task EveryRequest_TellsTheVendorNotToStoreTheConversation(string? effort) { - // The call store owns the transcript. A stored response comes back with a conversation id, + // The conversation store owns the transcript. A stored response comes back with a conversation id, // and ChatClientAgent refuses that next to the ChatHistoryProvider every agent carries. CapturingChatClient inner = new(); diff --git a/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs b/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs index 1aab8740..054c5535 100644 --- a/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs @@ -19,7 +19,7 @@ namespace AgentCore.Infrastructure.Tests; /// -/// The whole seam, from the document to the call: secrets, then tools, then the compile table. +/// The whole seam, from the document to the conversation: secrets, then tools, then the compile table. /// /// /// The worked example of section 8.1 declares all four tool kinds. This test walks the three that @@ -65,7 +65,7 @@ public sealed class ToolSeamTests - { id: resolve, agent: resolver, to: [ { stage: escalate } ] } - { id: escalate, agent: escalator, terminal: true } providers: - call: { kind: telnyx-relay } + conversation: { kind: telnyx-relay } speech: stt: { kind: telnyx-relay } tts: { kind: telnyx-relay } diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs b/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs index 7dab24a0..ac8b920d 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs @@ -12,7 +12,7 @@ namespace AgentCore.Infrastructure.Tests.Tools.Fakes; /// /// /// answers one connection and never changes. The session tests need -/// the opposite: a server that refuses the first attempts, that dies between two calls, and that +/// the opposite: a server that refuses the first attempts, that dies between two conversations, and that /// withdraws a tool it had offered. Each is a fresh pipe pair and a fresh /// , which is what a real reconnect gets. /// @@ -41,7 +41,7 @@ private sealed record Connection(McpServer Server, Pipe ClientToServer, Pipe Ser /// public bool RefuseToList { get; set; } - /// Gets the argument names the newest call carried, in order. + /// Gets the argument names the newest conversation carried, in order. public IReadOnlyList LastArgumentNames { get; private set; } = []; /// diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs b/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs index a7d1b600..4cc00b10 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs @@ -60,7 +60,7 @@ public async Task TheDeclaredSchema_ReachesTheModelUnchanged() } // --------------------------------------------------------------------------------------------- - // The call. + // The conversation. // --------------------------------------------------------------------------------------------- [Fact] public async Task ThePlaceholderTakesItsValueFromTheArguments() diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs b/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs index 0b8a1dd2..c747cdba 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs @@ -150,7 +150,7 @@ public async Task AToolStillWorks_AfterTheServerItWasDiscoveredOnHasDied() var result = await tool.InvokeAsync([], Token); Assert.Equal(2, fake.ConnectionsOpened); - Assert.False(IsError(result), $"the call returned an error result: {result}"); + Assert.False(IsError(result), $"the conversation returned an error result: {result}"); // The CallToolResult envelope is protocol and not answer, so what comes back is the text the // server put in it and never the box it arrived in. @@ -249,9 +249,9 @@ public async Task AToolWithdrawnWhileTheServerWasDown_ReturnsAnErrorResult() fake.Withdraw("close_issue"); await fake.KillNewestConnectionAsync(); - // Closing the pipes is not instant, so a call made in the moment after the kill can still be + // Closing the pipes is not instant, so a conversation made in the moment after the kill can still be // answered by the connection that is on its way out. Calling until one of them reaches the - // dead connection is what puts the reconnect under test; every call after that must land on + // dead connection is what puts the reconnect under test; every conversation after that must land on // the same answer, which is what the assertion below checks. object? result = null; await WaitForAsync(async () => @@ -267,7 +267,7 @@ await WaitForAsync(async () => error[ToolErrorResult.MessageProperty]!.GetValue(), StringComparison.Ordinal); - // It stays gone: the guard is on the call, not on one unlucky moment. + // It stays gone: the guard is on the conversation, not on one unlucky moment. Assert.True(IsError(await tool.InvokeAsync([], Token))); } @@ -319,7 +319,7 @@ public async Task AnEntryTheServerNeverDeclared_NeverCrossesTheWire() Token); // Assert - Assert.False(IsError(result), "the call failed instead of reaching the server."); + Assert.False(IsError(result), "the conversation failed instead of reaching the server."); Assert.Equal([Declared], fake.LastArgumentNames); } diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/McpToolSourceTests.cs b/tests/AgentCore.Infrastructure.Tests/Tools/McpToolSourceTests.cs index 9f12b525..02c31c9e 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/McpToolSourceTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/McpToolSourceTests.cs @@ -137,7 +137,7 @@ public async Task ProvideAsync_TheServerListsOneNameTwice_FailsTheBootSayingList public async Task DisposeAsync_AfterProvide_ClosesTheClient() { // Measured against the real SDK: disposing McpClient does not complete the streams a - // StreamClientTransport was given, and a call made on a disposed client hangs forever rather + // StreamClientTransport was given, and a conversation made on a disposed client hangs forever rather // than failing — neither signal is observable here. await using InProcessMcpServer fake = new("create_issue"); DisposalObservingTransport transport = new(fake.ClientTransport); diff --git a/tests/AgentCore.TestSupport/DelegatingCallStore.cs b/tests/AgentCore.TestSupport/DelegatingCallStore.cs deleted file mode 100644 index 56e78c36..00000000 --- a/tests/AgentCore.TestSupport/DelegatingCallStore.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System.Text.Json; -using AgentCore.Application.Calls; -using AgentCore.Application.Ports; -using AgentCore.Application.Transcript; -using Microsoft.Extensions.AI; - -namespace AgentCore.TestSupport; - -/// -/// A store that forwards every call to another one, so a fake overrides only what it is testing. -/// -/// Where an un-overridden call goes. -public abstract class DelegatingCallStore(ICallStore inner) : ICallStore -{ - /// Gets the store behind this one. - protected ICallStore Inner { get; } = inner; - - /// - public virtual ValueTask CreateAsync( - string callId, CancellationToken cancellationToken = default) - => Inner.CreateAsync(callId, cancellationToken); - - /// - public virtual ValueTask GetAsync( - string callId, CancellationToken cancellationToken = default) - => Inner.GetAsync(callId, cancellationToken); - - /// - public virtual ValueTask ListAsync( - string principalKey, - string? after, - int limit, - CallStatus? status = null, - CancellationToken cancellationToken = default) - => Inner.ListAsync(principalKey, after, limit, status, cancellationToken); - - /// - public virtual ValueTask RenameAsync( - string callId, string title, CancellationToken cancellationToken = default) - => Inner.RenameAsync(callId, title, cancellationToken); - - /// - public virtual ValueTask SetStatusAsync( - string callId, CallStatus status, CancellationToken cancellationToken = default) - => Inner.SetStatusAsync(callId, status, cancellationToken); - - /// - public virtual ValueTask SetCustomAsync( - string callId, JsonElement? custom, CancellationToken cancellationToken = default) - => Inner.SetCustomAsync(callId, custom, cancellationToken); - - /// - public virtual ValueTask SetExternalIdAsync( - string callId, string? externalId, CancellationToken cancellationToken = default) - => Inner.SetExternalIdAsync(callId, externalId, cancellationToken); - - /// - public virtual ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default) - => Inner.DeleteAsync(callId, cancellationToken); - - /// - public virtual ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - => Inner.AppendAsync(callId, messages, state, cancellationToken); - - /// - public virtual ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) - => Inner.RewriteAsync(callId, messageId, content, cancellationToken); - - /// - public virtual ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default) - => Inner.ReadAsync(callId, cancellationToken); - - /// - public virtual ValueTask TruncateAsync( - string callId, int fromOrdinal, CancellationToken cancellationToken = default) - => Inner.TruncateAsync(callId, fromOrdinal, cancellationToken); - - /// - public virtual ValueTask EraseAsync( - string callId, CancellationToken cancellationToken = default) - => Inner.EraseAsync(callId, cancellationToken); - - /// - public virtual ValueTask SweepAsync( - TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) - => Inner.SweepAsync(retention, batchSize, cancellationToken); - - /// - public virtual ValueTask AttachPrincipalAsync( - string callId, string principalKey, string role, CancellationToken cancellationToken = default) - => Inner.AttachPrincipalAsync(callId, principalKey, role, cancellationToken); - - /// - public virtual ValueTask DetachPrincipalAsync( - string callId, string principalKey, CancellationToken cancellationToken = default) - => Inner.DetachPrincipalAsync(callId, principalKey, cancellationToken); - - /// - public virtual ValueTask SaveContinuationAsync( - string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) - => Inner.SaveContinuationAsync(continuationId, envelope, cancellationToken); - - /// - public virtual ValueTask GetContinuationAsync( - string continuationId, CancellationToken cancellationToken = default) - => Inner.GetContinuationAsync(continuationId, cancellationToken); - - /// - public virtual ValueTask DeleteContinuationAsync( - string continuationId, CancellationToken cancellationToken = default) - => Inner.DeleteContinuationAsync(continuationId, cancellationToken); -} diff --git a/tests/AgentCore.TestSupport/DelegatingConversationStore.cs b/tests/AgentCore.TestSupport/DelegatingConversationStore.cs new file mode 100644 index 00000000..aa83e20d --- /dev/null +++ b/tests/AgentCore.TestSupport/DelegatingConversationStore.cs @@ -0,0 +1,118 @@ +using System.Text.Json; +using AgentCore.Application.Conversation; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; + +namespace AgentCore.TestSupport; + +/// +/// A store that forwards every call to another one, so a fake overrides only what it is testing. +/// +/// Where an un-overridden conversation goes. +public abstract class DelegatingConversationStore(IConversationStore inner) : IConversationStore +{ + /// Gets the store behind this one. + protected IConversationStore Inner { get; } = inner; + + /// + public virtual ValueTask CreateAsync( + string conversationId, CancellationToken cancellationToken = default) + => Inner.CreateAsync(conversationId, cancellationToken); + + /// + public virtual ValueTask GetAsync( + string conversationId, CancellationToken cancellationToken = default) + => Inner.GetAsync(conversationId, cancellationToken); + + /// + public virtual ValueTask ListAsync( + string principalKey, + string? after, + int limit, + ConversationStatus? status = null, + CancellationToken cancellationToken = default) + => Inner.ListAsync(principalKey, after, limit, status, cancellationToken); + + /// + public virtual ValueTask RenameAsync( + string conversationId, string title, CancellationToken cancellationToken = default) + => Inner.RenameAsync(conversationId, title, cancellationToken); + + /// + public virtual ValueTask SetStatusAsync( + string conversationId, ConversationStatus status, CancellationToken cancellationToken = default) + => Inner.SetStatusAsync(conversationId, status, cancellationToken); + + /// + public virtual ValueTask SetCustomAsync( + string conversationId, JsonElement? custom, CancellationToken cancellationToken = default) + => Inner.SetCustomAsync(conversationId, custom, cancellationToken); + + /// + public virtual ValueTask SetExternalIdAsync( + string conversationId, string? externalId, CancellationToken cancellationToken = default) + => Inner.SetExternalIdAsync(conversationId, externalId, cancellationToken); + + /// + public virtual ValueTask DeleteAsync(string conversationId, CancellationToken cancellationToken = default) + => Inner.DeleteAsync(conversationId, cancellationToken); + + /// + public virtual ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, + CancellationToken cancellationToken = default) + => Inner.AppendAsync(conversationId, messages, state, cancellationToken); + + /// + public virtual ValueTask RewriteAsync( + string conversationId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => Inner.RewriteAsync(conversationId, messageId, content, cancellationToken); + + /// + public virtual ValueTask> ReadAsync( + string conversationId, CancellationToken cancellationToken = default) + => Inner.ReadAsync(conversationId, cancellationToken); + + /// + public virtual ValueTask TruncateAsync( + string conversationId, int fromOrdinal, CancellationToken cancellationToken = default) + => Inner.TruncateAsync(conversationId, fromOrdinal, cancellationToken); + + /// + public virtual ValueTask EraseAsync( + string conversationId, CancellationToken cancellationToken = default) + => Inner.EraseAsync(conversationId, cancellationToken); + + /// + public virtual ValueTask SweepAsync( + TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default) + => Inner.SweepAsync(retention, batchSize, cancellationToken); + + /// + public virtual ValueTask AttachPrincipalAsync( + string conversationId, string principalKey, string role, CancellationToken cancellationToken = default) + => Inner.AttachPrincipalAsync(conversationId, principalKey, role, cancellationToken); + + /// + public virtual ValueTask DetachPrincipalAsync( + string conversationId, string principalKey, CancellationToken cancellationToken = default) + => Inner.DetachPrincipalAsync(conversationId, principalKey, cancellationToken); + + /// + public virtual ValueTask SaveContinuationAsync( + string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) + => Inner.SaveContinuationAsync(continuationId, envelope, cancellationToken); + + /// + public virtual ValueTask GetContinuationAsync( + string continuationId, CancellationToken cancellationToken = default) + => Inner.GetContinuationAsync(continuationId, cancellationToken); + + /// + public virtual ValueTask DeleteContinuationAsync( + string continuationId, CancellationToken cancellationToken = default) + => Inner.DeleteContinuationAsync(continuationId, cancellationToken); +} diff --git a/tests/AgentCore.TestSupport/ParkingCallStore.cs b/tests/AgentCore.TestSupport/ParkingConversationStore.cs similarity index 72% rename from tests/AgentCore.TestSupport/ParkingCallStore.cs rename to tests/AgentCore.TestSupport/ParkingConversationStore.cs index 81ac1da0..f14a732f 100644 --- a/tests/AgentCore.TestSupport/ParkingCallStore.cs +++ b/tests/AgentCore.TestSupport/ParkingConversationStore.cs @@ -1,5 +1,5 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Conversation; +using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; @@ -13,7 +13,7 @@ namespace AgentCore.TestSupport; /// every other test runs on lands a write before the next line reads it, and would let teardown drop /// a session with a write still owing without any test noticing. /// -public sealed class ParkingCallStore() : DelegatingCallStore(new InMemoryCallStore()) +public sealed class ParkingConversationStore() : DelegatingConversationStore(new InMemoryConversationStore()) { private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -29,15 +29,15 @@ public sealed class ParkingCallStore() : DelegatingCallStore(new InMemoryCallSto public void Release() => _release.TrySetResult(); /// - public override async ValueTask> AppendAsync( - string callId, - IReadOnlyList messages, - CallSessionState? state = null, + public override async ValueTask> AppendAsync( + string conversationId, + IReadOnlyList messages, + ConversationSessionState? state = null, CancellationToken cancellationToken = default) { _entered.TrySetResult(); await _release.Task.WaitAsync(cancellationToken); _landed = true; - return await base.AppendAsync(callId, messages, state, cancellationToken); + return await base.AppendAsync(conversationId, messages, state, cancellationToken); } } \ No newline at end of file diff --git a/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs b/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs index eb4e63bb..b02bef35 100644 --- a/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs +++ b/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs @@ -17,8 +17,8 @@ public sealed class RecordingChatClientFactory : IChatClientFactory /// stub that always replies "ok" and calls no tool. public RecordingChatClientFactory(IChatClient? client = null) => _client = client ?? new StubChatClient(); - /// Gets the reference the last call passed, or when no call has - /// happened yet or the last call asked for the host default. + /// Gets the reference the last conversation passed, or when no conversation has + /// happened yet or the last conversation asked for the host default. public ModelReference? Asked { get; private set; } public IChatClient GetChatClient(ModelReference? model) diff --git a/tests/AgentCore.TestSupport/SkillFolder.cs b/tests/AgentCore.TestSupport/SkillFolder.cs index fe381128..b49d1922 100644 --- a/tests/AgentCore.TestSupport/SkillFolder.cs +++ b/tests/AgentCore.TestSupport/SkillFolder.cs @@ -32,7 +32,7 @@ public static SkillFolder Create() /// Where to put it, relative to the root. May contain one '/'. /// The name to write in the frontmatter, or null to use the directory name. /// The description the prompt advertises. - /// This folder, so a test chains its calls. + /// This folder, so a test chains its conversations. public SkillFolder WithSkill( string relativePath, string? frontmatterName = null, @@ -52,7 +52,7 @@ public SkillFolder WithSkill( /// Adds a script to a skill written earlier, so a test can prove scripts stay hidden. /// The skill's path, relative to the root. /// The script file name. - /// This folder, so a test chains its calls. + /// This folder, so a test chains its conversations. public SkillFolder WithScript(string relativePath, string fileName = "hello.py") { var scripts = Path.Combine(Root, relativePath.Replace('/', Path.DirectorySeparatorChar), "scripts"); @@ -65,7 +65,7 @@ public SkillFolder WithScript(string relativePath, string fileName = "hello.py") /// Adds a reference document to a skill written earlier. /// The skill's path, relative to the root. /// The file name. - /// This folder, so a test chains its calls. + /// This folder, so a test chains its conversations. public SkillFolder WithReference(string relativePath, string fileName = "notes.md") { var references = Path.Combine(Root, relativePath.Replace('/', Path.DirectorySeparatorChar), "references"); From ba5659989593edf8e92a398e427c458b4bf47510 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 18 Sep 2026 23:38:21 -0600 Subject: [PATCH 20/35] feat(transcript): add ReaderContent and ReaderContentFilterProvider to manage reader-specific content --- .../AgentContextProviderCompiler.cs | 4 +- .../Compaction/ReaderContentFilterProvider.cs | 30 +++++++ .../Transcript/ReaderContent.cs | 65 ++++++++++++++ .../Transcript/TranscriptJson.cs | 13 +-- .../Compilation/CompactionCompilationTests.cs | 90 ++++++++++++++++--- .../Transcript/ReaderContentTests.cs | 38 ++++++++ 6 files changed, 215 insertions(+), 25 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/Compaction/ReaderContentFilterProvider.cs create mode 100644 src/AgentCore.Application/Transcript/ReaderContent.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/ReaderContentTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index bb40f203..18625611 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -62,10 +62,10 @@ public static List Build( exception.Message); } - // Bound ahead of the knowledge early-return below, for the same reason: a compaction: block - // is independent of whether this agent composes a knowledge: block. if (compaction is { } resolved) { + providers.Add(new ReaderContentFilterProvider()); + #pragma warning disable MAAI001 // Compaction is evaluation-only in Microsoft.Agents.AI 1.17.0. providers.Add(new CompactionProvider( CompactionStrategyFactory.Create(resolved), diff --git a/src/AgentCore.Application/Runtime/Compaction/ReaderContentFilterProvider.cs b/src/AgentCore.Application/Runtime/Compaction/ReaderContentFilterProvider.cs new file mode 100644 index 00000000..7a0aa99e --- /dev/null +++ b/src/AgentCore.Application/Runtime/Compaction/ReaderContentFilterProvider.cs @@ -0,0 +1,30 @@ +using AgentCore.Application.Transcript; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime.Compaction; + +/// +/// Removes reader content () from the messages bound for the model. +/// +internal sealed class ReaderContentFilterProvider : AIContextProvider +{ + /// + protected override ValueTask InvokingCoreAsync( + InvokingContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + + var input = context.AIContext; + if (input.Messages is null) + { + return new(input); + } + + return new(new AIContext + { + Instructions = input.Instructions, + Messages = ReaderContent.Strip(input.Messages).ToList(), + Tools = input.Tools, + }); + } +} diff --git a/src/AgentCore.Application/Transcript/ReaderContent.cs b/src/AgentCore.Application/Transcript/ReaderContent.cs new file mode 100644 index 00000000..a668122c --- /dev/null +++ b/src/AgentCore.Application/Transcript/ReaderContent.cs @@ -0,0 +1,65 @@ +using System.Text.Json; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Transcript; + +/// +/// The content types AgentCore adds to a message for the person reading the transcript, not for +/// the model: a drawing, a citation, a published file. This is the one list of them. It decides +/// how a store encodes them and what is stripped before a message reaches the model. +/// +internal static class ReaderContent +{ + /// The discriminator a stored RenderContent is written with. It is a wire format. + private const string RenderContentTypeId = "agentcore.render"; + + /// The discriminator a stored SourceContent is written with. It is a wire format. + private const string SourceContentTypeId = "agentcore.source"; + + /// The discriminator a stored FileContent is written with. It is a wire format. + private const string FileContentTypeId = "agentcore.file"; + + /// Whether is for the reader and not the model. + /// The content to test. + public static bool Is(AIContent content) => content is RenderContent or SourceContent or FileContent; + + /// Teaches to encode and decode every reader content type. + /// A writable options instance. + public static void Register(JsonSerializerOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + options.AddAIContentType(RenderContentTypeId); + options.AddAIContentType(SourceContentTypeId); + options.AddAIContentType(FileContentTypeId); + } + + /// + /// The same messages with every reader content removed. A message that holds none is returned + /// as-is; one that does is copied, so the transcript's own instance keeps what it had. + /// + /// The messages bound for the model. + public static IEnumerable Strip(IEnumerable messages) + { + ArgumentNullException.ThrowIfNull(messages); + + return messages.Select(Strip); + } + + private static ChatMessage Strip(ChatMessage message) + { + if (!message.Contents.Any(Is)) + { + return message; + } + + return new ChatMessage(message.Role, message.Contents.Where(content => !Is(content)).ToList()) + { + AuthorName = message.AuthorName, + MessageId = message.MessageId, + CreatedAt = message.CreatedAt, + AdditionalProperties = message.AdditionalProperties, + RawRepresentation = message.RawRepresentation, + }; + } +} diff --git a/src/AgentCore.Application/Transcript/TranscriptJson.cs b/src/AgentCore.Application/Transcript/TranscriptJson.cs index 8d4abf6c..fdb98218 100644 --- a/src/AgentCore.Application/Transcript/TranscriptJson.cs +++ b/src/AgentCore.Application/Transcript/TranscriptJson.cs @@ -21,20 +21,9 @@ private static JsonSerializerOptions Build() AllowOutOfOrderMetadataProperties = true, }; - options.AddAIContentType(RenderContentTypeId); - options.AddAIContentType(SourceContentTypeId); - options.AddAIContentType(FileContentTypeId); + ReaderContent.Register(options); options.MakeReadOnly(); return options; } - - /// The discriminator a stored RenderContent is written with. It is a wire format. - private const string RenderContentTypeId = "agentcore.render"; - - /// The discriminator a stored SourceContent is written with. It is a wire format. - private const string SourceContentTypeId = "agentcore.source"; - - /// The discriminator a stored FileContent is written with. It is a wire format. - private const string FileContentTypeId = "agentcore.file"; } diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs index 04e7cea2..18911e92 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs @@ -1,8 +1,12 @@ +using System.Text.Json; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Transcript; +using AgentCore.Domain.Sources; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Compaction; using Microsoft.Extensions.AI; @@ -14,17 +18,6 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// The compaction: block reaching a compiled agent's context providers, and the trimming /// reaching the model. /// -/// -/// Built from hand-constructed objects, not YAML text: these -/// tests exercise and at -/// the layer that turns a resolved compaction: block into a -/// (or turns a bad trigger into a load error), which needs no schema validation or YAML parsing to -/// reach. takes the parsed record tree directly and never -/// re-runs check 1, which is the same route AgentCompactionTests uses to exercise -/// itself. Schema-level rejection of a bad trigger is covered -/// separately, through , -/// in ConfigurationSchemaValidatorTests. -/// #pragma warning disable MAAI001 // Compaction is evaluation-only in Microsoft.Agents.AI 1.17.0. public sealed class CompactionCompilationTests { @@ -135,6 +128,81 @@ public async Task Compile_CompactionBlock_TrimsWhatTheModelSeesAcrossTurns() + $"{sizeBeforeTheLastCompaction} before compaction ran."); } + [Fact] + public async Task Compile_CompactionBlock_KeepsReaderContentOutOfTheStateBag() + { + // CompactionProvider copies every message it saw into the session state bag, and the bag + // serialises with MAF's default options, which know none of AgentCore's content types. A + // tool-result message carrying a FileContent, RenderContent or SourceContent therefore made + // the end-of-turn state capture throw NotSupportedException at + // $.MessageGroups.Messages.Contents, and the compaction state for that turn was lost. + using SequencedChatClient reply = new("noted."); + var compiled = CompileCompactingAgent(reply); + var agent = Assert.Single(compiled.Agents.Values); + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + + ChatMessage published = new(ChatRole.Tool, [new FunctionResultContent("call-1", "published")]); + published.Contents.Add(new FileContent { Name = "report.md", FileId = "out/report.md", Kept = true }); + published.Contents.Add(new RenderContent + { + Name = "card", + RenderId = "card-1", + Data = JsonSerializer.SerializeToElement(new { title = "Report" }), + }); + published.Contents.Add(new SourceContent + { + Source = new SourceReference { SourceId = "doc-1", Kind = SourceKind.Document, Title = "Doc", Origin = "knowledge" }, + CallId = "call-1", + }); + List conversation = + [ + new ChatMessage(ChatRole.User, "make me a report"), + new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("call-1", "file.publish")]), + published, + new ChatMessage(ChatRole.User, "thanks"), + ]; + + await agent.RunAsync(conversation, session, cancellationToken: token); + + // Capture serialises the whole bag before it picks keys, so any non-empty key set walks + // past the compaction state. The harness keys are empty here: no harness: block. + var compactionKey = Assert.Single(Assert.Single(Providers(agent).OfType()).StateKeys); + var captured = HarnessSessionState.Capture(session, new HashSet([compactionKey], StringComparer.Ordinal)); + + Assert.Contains(compactionKey, captured.Keys); + Assert.DoesNotContain( + reply.Requests[^1].SelectMany(message => message.Contents), + content => content is FileContent or RenderContent or SourceContent); + } + + private static CompiledAgent CompileCompactingAgent(SequencedChatClient reply) => ConfigurationCompiler.CompileAll( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Agents = new AgentsConfiguration + { + Items = + [ + new AgentConfiguration + { + Id = "only", + Compaction = new CompactionConfiguration + { + Strategy = CompactionStrategyKind.Truncate, + Trigger = new CompactionTriggerConfiguration { Messages = 4 }, + Keep = 2, + }, + }, + ], + }, + Entries = new Dictionary + { + ["main"] = new EntryConfiguration { Agent = "only" }, + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(reply)))["main"]; + private static AgentCoreConfiguration TwoTriggerConditions() => new() { ApiVersion = AgentCoreConfiguration.SupportedApiVersion, diff --git a/tests/AgentCore.Application.Tests/Transcript/ReaderContentTests.cs b/tests/AgentCore.Application.Tests/Transcript/ReaderContentTests.cs new file mode 100644 index 00000000..281e347c --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/ReaderContentTests.cs @@ -0,0 +1,38 @@ +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Transcript; + +public sealed class ReaderContentTests +{ + [Fact] + public void Strip_MessageWithoutReaderContent_ReturnsTheSameInstance() + { + ChatMessage plain = new(ChatRole.User, "hello"); + + var stripped = Assert.Single(ReaderContent.Strip([plain])); + + Assert.Same(plain, stripped); + } + + [Fact] + public void Strip_MessageWithReaderContent_CopiesItWithoutThatContentAndLeavesTheOriginalWhole() + { + ChatMessage published = new(ChatRole.Tool, [new FunctionResultContent("call-1", "published")]) + { + MessageId = "m-7", + AuthorName = "tool", + }; + published.Contents.Add(new FileContent { Name = "report.md", FileId = "out/report.md", Kept = true }); + + var stripped = Assert.Single(ReaderContent.Strip([published])); + + Assert.NotSame(published, stripped); + Assert.Equal("m-7", stripped.MessageId); + Assert.Equal("tool", stripped.AuthorName); + Assert.Equal(ChatRole.Tool, stripped.Role); + Assert.IsType(Assert.Single(stripped.Contents)); + Assert.Equal(2, published.Contents.Count); + } +} From a75c8c52f87559af7a4a166e99f795ae6e245a35 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 00:03:21 -0600 Subject: [PATCH 21/35] feat(skills): add pinned skills support and validation logic --- .../AgentContextProviderCompiler.cs | 29 +++-- .../Schema/AgentsConfiguration.cs | 5 + .../Schema/agentcore-v1.schema.json | 7 ++ .../Validation/ConfigurationValidator.cs | 7 +- .../Validation/ServedReferenceCheck.cs | 52 ++++++++- .../PublicAPI.Unshipped.txt | 2 + .../Skills/PinnedSkillsProvider.cs | 106 ++++++++++++++++++ .../Validation/ConfigurationValidatorTests.cs | 52 +++++++++ .../Skills/PinnedSkillsProviderTests.cs | 89 +++++++++++++++ 9 files changed, 329 insertions(+), 20 deletions(-) create mode 100644 src/AgentCore.Application/Skills/PinnedSkillsProvider.cs create mode 100644 tests/AgentCore.Application.Tests/Skills/PinnedSkillsProviderTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index 18625611..374edb47 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -34,20 +34,18 @@ public static List Build( Func resolve, ICollection? background = null) { - List providers = [new TurnContextProvider()]; + List providers = []; - if (item.Skills.Count > 0) + if (item.Pinned.Count > 0) { - if (context.Skills is not { } catalog) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "skills"), - $"the agent '{item.Id}' declares a skills: list and this host bound no skills " - + "folder, so there is nothing to load. Call options.UseSkills(...) with the " - + "folder that holds the SKILL.md directories, or remove the skills: list."); - } + providers.Add(new PinnedSkillsProvider(RequireCatalog(item, context, pointer, "pinned"), item.Pinned)); + } - providers.Add(SkillsProviderFactory.Create(catalog, item.Skills, context.Loggers)); + providers.Add(new TurnContextProvider()); + + if (item.Skills.Count > 0) + { + providers.Add(SkillsProviderFactory.Create(RequireCatalog(item, context, pointer, "skills"), item.Skills, context.Loggers)); } ResolvedCompaction? compaction; @@ -105,4 +103,13 @@ public static List Build( return providers; } #pragma warning restore MAAI001 + + private static SkillCatalog RequireCatalog(AgentConfiguration item, AgentCompilationContext context, string pointer, string key) + { + return context.Skills ?? throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, key), + $"the agent '{item.Id}' declares a {key}: list and this host bound no skills " + + "folder, so there is nothing to load. Call options.UseSkills(...) with the " + + $"folder that holds the SKILL.md directories, or remove the {key}: list."); + } } diff --git a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs index 5d0e5fab..988985be 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs @@ -93,6 +93,11 @@ public sealed record AgentConfiguration /// Gets the names of the skills this agent may load. public IReadOnlyList Skills { get; init; } = []; + /// + /// Gets the names of the skills whose body sits in this agent's system prompt on every turn, + /// + public IReadOnlyList Pinned { get; init; } = []; + /// Gets this agent's knowledge: block, or to inherit key by key. public AgentKnowledgeConfiguration? Knowledge { get; init; } diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index aad758cf..2f585c7b 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -784,6 +784,13 @@ "items": { "$ref": "#/$defs/skillName" } + }, + "pinned": { + "type": "array", + "description": "Skills whose body sits in the system prompt on every turn, with no load_skill call. A name here cannot also be in skills.", + "items": { + "$ref": "#/$defs/skillName" + } } } }, diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index 043a139e..7a21dab1 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -108,12 +108,12 @@ public static void ValidateToolReferences(AgentCoreConfiguration configuration, } /// - /// Resolves every skills: entry against the names the bound skills folder serves, and - /// throws when one names a skill nothing serves. + /// Resolves every skills: and pinned: entry against the names the bound skills + /// folder serves. /// /// The bound document. /// Every skill name the bound folder serves. - /// A reference names a skill nothing serves. + /// A reference names a skill nothing serves, or a skill is both pinned and loadable. public static void ValidateSkillReferences(AgentCoreConfiguration configuration, IReadOnlySet servedSkillNames) { ArgumentNullException.ThrowIfNull(configuration); @@ -121,6 +121,7 @@ public static void ValidateSkillReferences(AgentCoreConfiguration configuration, var errors = new List(); ServedReferenceCheck.Skills(configuration, servedSkillNames, errors); + ServedReferenceCheck.PinnedSkills(configuration, errors); ThrowOnErrors(errors); } diff --git a/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs b/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs index 105c72e5..55e15631 100644 --- a/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/ServedReferenceCheck.cs @@ -39,7 +39,7 @@ public static void Tools(AgentCoreConfiguration configuration, IReadOnlySetResolves every agent's skills: entry against what the bound folder serves. + /// Resolves every agent's skills: and pinned: entry against what the bound folder serves. public static void Skills(AgentCoreConfiguration configuration, IReadOnlySet servedSkillNames, List errors) { var served = string.Join(", ", servedSkillNames.Order(StringComparer.Ordinal)); @@ -48,23 +48,63 @@ public static void Skills(AgentCoreConfiguration configuration, IReadOnlySet + /// Refuses a skill that is both pinned and loadable. Its body would sit in the prompt and be + /// offered to load_skill at once, and the second copy is pure cost. + /// + public static void PinnedSkills(AgentCoreConfiguration configuration, List errors) + { + var items = configuration.Agents.Items; + + for (var index = 0; index < items.Count; index++) + { + var agent = items[index]; + var loadable = new HashSet(agent.Skills, StringComparer.Ordinal); - for (var slot = 0; slot < agent.Skills.Count; slot++) + for (var slot = 0; slot < agent.Pinned.Count; slot++) { - if (servedSkillNames.Contains(agent.Skills[slot])) + if (!loadable.Contains(agent.Pinned[slot])) { continue; } errors.Add(Reference( ConfigurationError.AppendPointer( - ConfigurationError.AppendPointer(ValidationPointer.Agent(index), "skills"), slot), - $"the skill '{agent.Skills[slot]}' is not in the bound skills folder. " - + $"The folder serves: {served}.")); + ConfigurationError.AppendPointer(ValidationPointer.Agent(index), "pinned"), slot), + $"the skill '{agent.Pinned[slot]}' is both pinned and in the skills: list. " + + "A pinned skill is already in the prompt, so drop it from skills:.")); } } } + private static void SkillNames( + IReadOnlyList names, + string key, + int agentIndex, + IReadOnlySet servedSkillNames, + string served, + List errors) + { + for (var slot = 0; slot < names.Count; slot++) + { + if (servedSkillNames.Contains(names[slot])) + { + continue; + } + + errors.Add(Reference( + ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer(ValidationPointer.Agent(agentIndex), key), slot), + $"the skill '{names[slot]}' is not in the bound skills folder. " + + $"The folder serves: {served}.")); + } + } + /// /// Refuses a declared tool id that the skills provider registers under the same name. The /// provider's tools are added per agent and never pass through the tool registry, so a diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index d2671d74..d389d455 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -341,6 +341,8 @@ AgentCore.Application.Configuration.Schema.AgentConfiguration.Shell.get -> Agent AgentCore.Application.Configuration.Schema.AgentConfiguration.Shell.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Skills.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Configuration.Schema.AgentConfiguration.Skills.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Pinned.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Configuration.Schema.AgentConfiguration.Pinned.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Todos.get -> bool? AgentCore.Application.Configuration.Schema.AgentConfiguration.Todos.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Tools.get -> System.Collections.Generic.IReadOnlyList! diff --git a/src/AgentCore.Application/Skills/PinnedSkillsProvider.cs b/src/AgentCore.Application/Skills/PinnedSkillsProvider.cs new file mode 100644 index 00000000..daff3faf --- /dev/null +++ b/src/AgentCore.Application/Skills/PinnedSkillsProvider.cs @@ -0,0 +1,106 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Skills; + +/// +/// The bodies of an agent's pinned: skills, appended to its instructions on every turn. +/// +internal sealed class PinnedSkillsProvider : AIContextProvider +{ + private const string FrontmatterFence = "---"; + + private const string ManifestStart = "\n _names; + + private string? _instructions; + + /// Creates the provider. + /// The skills the host bound, shared by every agent. + /// The names this agent pins, in the order their bodies appear. + /// An argument is . + /// is empty. + internal PinnedSkillsProvider(SkillCatalog catalog, IReadOnlyList names) + { + ArgumentNullException.ThrowIfNull(catalog); + ArgumentNullException.ThrowIfNull(names); + + if (names.Count == 0) + { + throw new ArgumentException("A pinned skills provider needs at least one skill name.", nameof(names)); + } + + _catalog = catalog; + _names = names; + } + + /// + protected override async ValueTask ProvideAIContextAsync( + InvokingContext context, + CancellationToken cancellationToken = default) + { + return new AIContext + { + Instructions = _instructions ?? await ReadAsync(context, cancellationToken).ConfigureAwait(false), + }; + } + + /// + /// Reads every pinned body once. Two first turns racing here both read the files and store + /// the same text, so there is no lock. + /// + private async ValueTask ReadAsync(InvokingContext context, CancellationToken cancellationToken) + { + var skills = await _catalog.Source + .GetSkillsAsync(new AgentSkillsSourceContext(context.Agent, context.Session), cancellationToken) + .ConfigureAwait(false); + + var bodies = new List(_names.Count); + foreach (var name in _names) + { + var skill = skills.FirstOrDefault(candidate => string.Equals(candidate.Frontmatter.Name, name, StringComparison.Ordinal)) + ?? throw new InvalidOperationException( + $"The pinned skill '{name}' is not in the bound skills folder. Validation should have refused it."); + + var content = await skill.GetContentAsync(cancellationToken).ConfigureAwait(false); + bodies.Add($"\n{StripManifests(StripFrontmatter(content)).Trim()}\n"); + } + + _instructions = string.Join("\n\n", bodies); + return _instructions; + } + + /// + /// Drops the <available_resources> and <available_scripts> blocks MAF + /// appends to a file skill's content. They list what read_skill_resource can fetch, and a + /// pinned skill has no such tool, so the list would only tempt the model. + /// + private static string StripManifests(string content) + { + var start = content.LastIndexOf(ManifestStart, StringComparison.Ordinal); + return start < 0 ? content : content[..start]; + } + + /// + /// Drops the YAML frontmatter. Its name and description serve skill discovery, which a pinned + /// skill never goes through, so the model gets the body alone. + /// + private static string StripFrontmatter(string content) + { + if (!content.StartsWith(FrontmatterFence, StringComparison.Ordinal)) + { + return content; + } + + var close = content.IndexOf("\n" + FrontmatterFence, FrontmatterFence.Length, StringComparison.Ordinal); + if (close < 0) + { + return content; + } + + var bodyStart = content.IndexOf('\n', close + 1); + return bodyStart < 0 ? string.Empty : content[(bodyStart + 1)..]; + } +} diff --git a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs index 1bc0e3f6..3c7a6657 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs @@ -1630,6 +1630,58 @@ public void ValidateSkillReferences_EveryNameServed_DoesNotThrow() Assert.Null(exception); } + [Fact] + public void ValidateSkillReferences_APinnedNameTheFolderDoesNotServe_FailsAtThePinnedSlot() + { + const string document = """ + apiVersion: agentcore/v1 + agents: + items: + - { id: support, pinned: [openui] } + entries: + main: + agent: support + """; + + var configuration = ConfigurationLoader.LoadYaml(document); + var served = new HashSet(["warranty-returns"], StringComparer.Ordinal); + + var failure = Assert.Throws( + () => ConfigurationValidator.ValidateSkillReferences(configuration, served)); + + var error = Assert.Single(failure.Errors); + Assert.Equal("/agents/items/0/pinned/0", error.Pointer); + Assert.Equal( + "the skill 'openui' is not in the bound skills folder. The folder serves: warranty-returns.", + error.Message); + } + + [Fact] + public void ValidateSkillReferences_ASkillBothPinnedAndLoadable_Fails() + { + const string document = """ + apiVersion: agentcore/v1 + agents: + items: + - { id: support, skills: [openui], pinned: [openui] } + entries: + main: + agent: support + """; + + var configuration = ConfigurationLoader.LoadYaml(document); + var served = new HashSet(["openui"], StringComparer.Ordinal); + + var failure = Assert.Throws( + () => ConfigurationValidator.ValidateSkillReferences(configuration, served)); + + var error = Assert.Single(failure.Errors); + Assert.Equal("/agents/items/0/pinned/0", error.Pointer); + Assert.Equal( + "the skill 'openui' is both pinned and in the skills: list. A pinned skill is already in the prompt, so drop it from skills:.", + error.Message); + } + [Theory] [InlineData("load_skill")] [InlineData("read_skill_resource")] diff --git a/tests/AgentCore.Application.Tests/Skills/PinnedSkillsProviderTests.cs b/tests/AgentCore.Application.Tests/Skills/PinnedSkillsProviderTests.cs new file mode 100644 index 00000000..61325498 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Skills/PinnedSkillsProviderTests.cs @@ -0,0 +1,89 @@ +using AgentCore.Application.Skills; +using AgentCore.Application.Tests.Runtime; +using AgentCore.TestSupport; +using Microsoft.Agents.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Skills; + +/// +/// A pinned skill's body must reach the prompt on every turn without a tool call, with the +/// discovery frontmatter stripped, and in the order the agent listed it. +/// +public sealed class PinnedSkillsProviderTests +{ + [Fact] + public async Task Invoke_PutsTheBodyInTheInstructionsAndRegistersNoTool() + { + var result = await InvokeAsync(["warranty-returns"]); + + Assert.Equal("\nDo the thing.\n", result.Instructions); + Assert.Null(result.Tools); + } + + [Fact] + public async Task Invoke_StripsTheFrontmatter() + { + var result = await InvokeAsync(["warranty-returns"]); + + Assert.DoesNotContain("---", result.Instructions, StringComparison.Ordinal); + Assert.DoesNotContain("description:", result.Instructions, StringComparison.Ordinal); + } + + [Fact] + public async Task Invoke_TwoSkills_KeepsTheListedOrder() + { + var result = await InvokeAsync(["shipping-claims", "warranty-returns"]); + + var shipping = result.Instructions!.IndexOf("name=\"shipping-claims\"", StringComparison.Ordinal); + var warranty = result.Instructions.IndexOf("name=\"warranty-returns\"", StringComparison.Ordinal); + Assert.True(shipping >= 0 && warranty > shipping); + } + + [Fact] + public async Task Invoke_AppendsBelowTheInstructionsAlreadyThere() + { + using var folder = SkillFolder.Create().WithSkill("warranty-returns"); + using AgentFileSkillsSource source = new(folder.Root); + SkillCatalog catalog = new(source, new HashSet(["warranty-returns"], StringComparer.Ordinal)); + PinnedSkillsProvider provider = new(catalog, ["warranty-returns"]); + + var result = await InvokeAsync(provider, new AIContext { Instructions = "You are support." }); + + Assert.StartsWith("You are support.", result.Instructions, StringComparison.Ordinal); + Assert.EndsWith("Do the thing.\n", result.Instructions, StringComparison.Ordinal); + } + + [Fact] + public void Constructor_NoNames_Throws() + { + using var folder = SkillFolder.Create().WithSkill("warranty-returns"); + using AgentFileSkillsSource source = new(folder.Root); + SkillCatalog catalog = new(source, new HashSet(["warranty-returns"], StringComparer.Ordinal)); + + Assert.Throws(() => new PinnedSkillsProvider(catalog, [])); + } + + private static async Task InvokeAsync(IReadOnlyList pinned) + { + using var folder = SkillFolder.Create() + .WithSkill("warranty-returns") + .WithSkill("shipping-claims"); + + using AgentFileSkillsSource source = new(folder.Root); + SkillCatalog catalog = new(source, new HashSet(["warranty-returns", "shipping-claims"], StringComparer.Ordinal)); + + return await InvokeAsync(new PinnedSkillsProvider(catalog, pinned), new AIContext()); + } + + private static async Task InvokeAsync(AIContextProvider provider, AIContext existing) + { + using SequencedChatClient client = new("hello there."); + ChatClientAgent agent = new(client, new ChatClientAgentOptions { Name = "support" }); + +#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. + AIContextProvider.InvokingContext context = new(agent, null, existing); +#pragma warning restore MAAI001 + return await provider.InvokingAsync(context, TestContext.Current.CancellationToken); + } +} From 8ea471b9e520557bb0c64cba782aca661674cefd Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 00:32:47 -0600 Subject: [PATCH 22/35] feat(websocket): implement FrameOutcome and FrameParser for message handling --- .../Conversation/FrameOutcome.cs | 7 + .../Conversation/FrameParser.cs | 6 + .../Conversation/JsonWebSocketPump.cs | 191 ++++++++---------- .../Conversation/JsonWebSocketPumpOptions.cs | 30 +++ 4 files changed, 128 insertions(+), 106 deletions(-) create mode 100644 src/AgentCore.AspNetCore/Conversation/FrameOutcome.cs create mode 100644 src/AgentCore.AspNetCore/Conversation/FrameParser.cs create mode 100644 src/AgentCore.AspNetCore/Conversation/JsonWebSocketPumpOptions.cs diff --git a/src/AgentCore.AspNetCore/Conversation/FrameOutcome.cs b/src/AgentCore.AspNetCore/Conversation/FrameOutcome.cs new file mode 100644 index 00000000..ef1cf2b1 --- /dev/null +++ b/src/AgentCore.AspNetCore/Conversation/FrameOutcome.cs @@ -0,0 +1,7 @@ +namespace AgentCore.AspNetCore.Conversation; + +/// What reading one inbound message produced. +/// The parsed frame, or when none was read. +/// The discriminator no case matched, or . +/// The known discriminator whose body would not bind, or . +internal readonly record struct FrameOutcome(object? Frame, string? UnknownType, string? RefusedType); diff --git a/src/AgentCore.AspNetCore/Conversation/FrameParser.cs b/src/AgentCore.AspNetCore/Conversation/FrameParser.cs new file mode 100644 index 00000000..ea90df8d --- /dev/null +++ b/src/AgentCore.AspNetCore/Conversation/FrameParser.cs @@ -0,0 +1,6 @@ +namespace AgentCore.AspNetCore.Conversation; + +/// Reads one reassembled inbound message into a . +/// The whole message, already reassembled. +/// What the adapter's own reader made of those bytes. +internal delegate FrameOutcome FrameParser(ReadOnlySpan utf8); diff --git a/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs b/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs index c753c765..d0bf691d 100644 --- a/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs +++ b/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPump.cs @@ -5,53 +5,6 @@ namespace AgentCore.AspNetCore.Conversation; -/// What reading one inbound message produced. -/// The parsed frame, or when none was read. -/// The discriminator no case matched, or . -/// The known discriminator whose body would not bind, or . -/// -/// All three is the only unreadable case, and the only one a caller may -/// close the socket over. -/// -internal readonly record struct FrameOutcome(object? Frame, string? UnknownType, string? RefusedType); - -/// Reads one reassembled inbound message into a . -/// The whole message, already reassembled. -/// What the adapter's own reader made of those bytes. -/// -/// A delegate of its own, rather than a : a ref struct cannot be a -/// type argument, and the span is the whole point — it is what keeps the pooled buffer behind the -/// message from ever being aliased by something async. -/// -internal delegate FrameOutcome FrameParser(ReadOnlySpan utf8); - -/// What one pump may do, and for how long. -/// The largest inbound message the pump accepts, in bytes. -/// How long the pump waits with no inbound message before it ends the conversation. -/// How long the close handshake may take before the socket is aborted. -/// -/// Builds the exception the pump throws when the peer broke the contract. The adapter supplies it, -/// so the pump raises the adapter's own exception type and the adapter's own close-status rules -/// still recognise it. -/// -/// -/// Logs a discriminator no case matched. The pump calls it once for the conversation, not once for the -/// frame, and passes the name; the line itself names the vendor, which is why it is a callback. -/// -/// -/// Logs a known discriminator whose body would not bind, on the same once-for-the-conversation rule as -/// . -/// -/// Logs that the idle deadline, rather than teardown, ended the conversation. -internal sealed record JsonWebSocketPumpOptions( - int MaxFrameBytes, - TimeSpan IdleTimeout, - TimeSpan CloseTimeout, - Func ProtocolFault, - Action LogUnknownFrameType, - Action LogRefusedFrameBody, - Action LogIdleTimeout); - /// /// The read loop, the write loop, and the close of one duplex JSON-over-WebSocket connection. /// @@ -115,7 +68,6 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) while (!connectionToken.IsCancellationRequested) { message.ResetWrittenCount(); - ValueWebSocketReceiveResult result; // The vendor never reconnects, so a socket with no inbound frame for IdleTimeout is // a conversation that already ended, not a fault. The first receive of every message races @@ -169,37 +121,11 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) // sending faster than IdleTimeout — CancelAfter is never involved, so this touches // nothing outside this one local source. await idleCancel.CancelAsync().ConfigureAwait(false); - result = await receiving.ConfigureAwait(false); - - // The rest of one message, however many more fragments the vendor chose. A loop - // that parsed each receive on its own would fail on a fragment, and it would cut a - // multi-byte character in half. Only the first fragment above raced the idle - // deadline: the vendor is, by definition, no longer silent once one fragment of a - // message has already arrived. - while (true) - { - if (result.MessageType == WebSocketMessageType.Close) - { - return; - } - - if (message.WrittenCount + result.Count > options.MaxFrameBytes) - { - throw options.ProtocolFault( - WebSocketCloseStatus.MessageTooBig, - "the relay frame passes the size limit."); - } + var first = await receiving.ConfigureAwait(false); - message.Write(rented.AsSpan(0, result.Count)); - - if (result.EndOfMessage) - { - break; - } - - result = await socket - .ReceiveAsync(rented.AsMemory(), connectionToken) - .ConfigureAwait(false); + if (!await AssembleMessageAsync(first, rented, message).ConfigureAwait(false)) + { + return; } // Parsed here, synchronously, before any await sees this iteration again. Passing @@ -211,34 +137,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) if (outcome.Frame is null) { - if (outcome.UnknownType is null && outcome.RefusedType is null) - { - // Neither name is set, so the bytes carried no readable type at all: not - // JSON, not an object, or a type that is not a string. That is the only - // shape this endpoint closes a socket over. - throw options.ProtocolFault( - WebSocketCloseStatus.InvalidPayloadData, - "the relay sent a frame this endpoint cannot parse."); - } - - // Log once for the conversation, not once for the frame. Section 3.1. - if (outcome.UnknownType is { } unmodelled) - { - if (!_loggedUnknownFrame) - { - _loggedUnknownFrame = true; - options.LogUnknownFrameType(unmodelled); - } - } - else if (!_loggedRefusedFrameBody) - { - // A known type whose body will not bind. Section 7.1 treats a vendor that - // changes a frame exactly as it treats one that adds a frame: the frame is - // refused, and the conversation goes on. - _loggedRefusedFrameBody = true; - options.LogRefusedFrameBody(outcome.RefusedType!); - } - + RefuseFrame(outcome); continue; } @@ -260,6 +159,86 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) } } + /// Collects the rest of one message into , fragment by fragment. + /// The fragment that already won the idle race. + /// The array every fragment lands in before it is copied out. + /// The writer the whole message is assembled into. + /// + /// once the whole message is in ; + /// when the peer sent a close frame instead. + /// + /// + /// A loop that parsed each receive on its own would fail on a fragment, and it would cut a + /// multi-byte character in half. Only the first fragment raced the idle deadline: the vendor + /// is, by definition, no longer silent once one fragment of a message has already arrived. + /// + private async Task AssembleMessageAsync( + ValueWebSocketReceiveResult first, + byte[] rented, + ArrayBufferWriter message) + { + var result = first; + + while (true) + { + if (result.MessageType == WebSocketMessageType.Close) + { + return false; + } + + if (message.WrittenCount + result.Count > options.MaxFrameBytes) + { + throw options.ProtocolFault( + WebSocketCloseStatus.MessageTooBig, + "the relay frame passes the size limit."); + } + + message.Write(rented.AsSpan(0, result.Count)); + + if (result.EndOfMessage) + { + return true; + } + + result = await socket + .ReceiveAsync(rented.AsMemory(), connectionToken) + .ConfigureAwait(false); + } + } + + /// Logs, or closes the socket over, a message the parser produced no frame for. + /// An outcome whose is . + private void RefuseFrame(FrameOutcome outcome) + { + if (outcome.UnknownType is null && outcome.RefusedType is null) + { + // Neither name is set, so the bytes carried no readable type at all: not + // JSON, not an object, or a type that is not a string. That is the only + // shape this endpoint closes a socket over. + throw options.ProtocolFault( + WebSocketCloseStatus.InvalidPayloadData, + "the relay sent a frame this endpoint cannot parse."); + } + + // Log once for the conversation, not once for the frame. Section 3.1. + if (outcome.UnknownType is { } unmodelled) + { + if (!_loggedUnknownFrame) + { + _loggedUnknownFrame = true; + options.LogUnknownFrameType(unmodelled); + } + } + else if (!_loggedRefusedFrameBody) + { + // A known type whose body will not bind. Section 7.1 treats a vendor that + // changes a frame exactly as it treats one that adds a frame: the frame is + // refused, and the conversation goes on. + _loggedRefusedFrameBody = true; + options.LogRefusedFrameBody(outcome.RefusedType!); + } + } + /// Sends whatever the caller queues, one item at a time, until the conversation ends. /// Whatever the caller queues. This pump never looks inside one. /// The queue the caller's own writers fill. diff --git a/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPumpOptions.cs b/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPumpOptions.cs new file mode 100644 index 00000000..fa039c0e --- /dev/null +++ b/src/AgentCore.AspNetCore/Conversation/JsonWebSocketPumpOptions.cs @@ -0,0 +1,30 @@ +using System.Net.WebSockets; + +namespace AgentCore.AspNetCore.Conversation; + +/// What one pump may do, and for how long. +/// The largest inbound message the pump accepts, in bytes. +/// How long the pump waits with no inbound message before it ends the conversation. +/// How long the close handshake may take before the socket is aborted. +/// +/// Builds the exception the pump throws when the peer broke the contract. The adapter supplies it, +/// so the pump raises the adapter's own exception type and the adapter's own close-status rules +/// still recognise it. +/// +/// +/// Logs a discriminator no case matched. The pump calls it once for the conversation, not once for the +/// frame, and passes the name; the line itself names the vendor, which is why it is a callback. +/// +/// +/// Logs a known discriminator whose body would not bind, on the same once-for-the-conversation rule as +/// . +/// +/// Logs that the idle deadline, rather than teardown, ended the conversation. +internal sealed record JsonWebSocketPumpOptions( + int MaxFrameBytes, + TimeSpan IdleTimeout, + TimeSpan CloseTimeout, + Func ProtocolFault, + Action LogUnknownFrameType, + Action LogRefusedFrameBody, + Action LogIdleTimeout); From 55553f0339063f491e00cfab8ab65e122120e47d Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 00:37:46 -0600 Subject: [PATCH 23/35] feat(responses): refactor request handling and introduce ResponsesRunInput and ResponsesTurn records --- .../Endpoints/ResponsesEndpoints.cs | 284 +++++++++--------- .../Endpoints/ResponsesRequestReader.cs | 80 ++++- .../Endpoints/ResponsesRunInput.cs | 15 + .../Endpoints/ResponsesTurn.cs | 30 ++ .../Endpoints/ResponsesTurnReply.cs | 35 +-- .../Endpoints/ResponsesTurnStream.cs | 35 +-- 6 files changed, 283 insertions(+), 196 deletions(-) create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesRunInput.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesTurn.cs diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs index 9370cafe..af6dacec 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -35,9 +35,6 @@ public static class ResponsesEndpointRouteBuilderExtensions /// public const string TimeZoneHeaderName = "X-AgentCore-Time-Zone"; - /// The OpenAI error type every refused request reports. - private const string InvalidRequestError = "invalid_request_error"; - /// Maps every entry on , with the URL naming the entry. /// The route builder of the host. /// The mapped endpoint, so a host adds its own conventions. @@ -66,64 +63,30 @@ public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder } /// Runs one turn of one conversation, and files the session under the ids the answer carries. + /// + /// Every step answers its own refusal and returns , so this reads as + /// the happy path alone. + /// private static async Task HandleAsync(HttpContext http) { var cancellationToken = http.RequestAborted; var entry = http.Request.RouteValues[EntryRouteParameter] as string ?? string.Empty; - JsonElement body; - try - { - body = await JsonSerializer - .DeserializeAsync(http.Request.Body, cancellationToken: cancellationToken) - .ConfigureAwait(false); - } - catch (JsonException exception) + if (await ResponsesRequestReader.ReadBodyAsync(http, cancellationToken).ConfigureAwait(false) is not { } body) { - await ResponsesRequestReader.WriteErrorAsync( - http, - StatusCodes.Status400BadRequest, - "the request body is not well-formed JSON: " + exception.Message, - InvalidRequestError, - "malformed_body", - cancellationToken).ConfigureAwait(false); return; } var agentcore = ResponsesAgentCore.ReadRequest(body); + var approval = agentcore?.Approval; - OpenAIResponsesRunRequest? runRequest; - - string? conversationId; + var run = await ResponsesRequestReader + .ReadRunInputAsync(http, body, approving: approval is not null, cancellationToken) + .ConfigureAwait(false); - IReadOnlyList messages; - - try + if (run is null) { - runRequest = OpenAIResponses.ToAgentRunRequest(body); - conversationId = runRequest.ConversationId; - messages = [.. runRequest.Messages]; - } - catch (ArgumentException exception) - { - // An approval answer carries no words, only the request it answers — and the - // protocol parse refuses a turn with no input. The continuation still names the - // conversation, so read it off the body and run the answer alone. - if (agentcore?.Approval is null) - { - await ResponsesRequestReader.WriteErrorAsync( - http, - StatusCodes.Status400BadRequest, - "the request is not a Responses request: " + exception.Message, - InvalidRequestError, - "invalid_body", - cancellationToken).ConfigureAwait(false); - return; - } - - runRequest = null; - messages = []; - conversationId = ResponsesRequestReader.ReadConversationId(body); + return; } var entries = http.RequestServices.GetRequiredService().Entries; @@ -133,7 +96,6 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status404NotFound, EntryRegistry.UnknownEntryMessage(entry, entries.Entries), - InvalidRequestError, "unknown_entry", cancellationToken).ConfigureAwait(false); return; @@ -141,25 +103,62 @@ await ResponsesRequestReader.WriteErrorAsync( var sessions = http.RequestServices.GetRequiredService(); - // The continuation this turn hangs off, or null for the first turn of a conversation. - // A conversation id names the conversation itself; a response id names one past turn of it. - // The helper prefers the response chain over the conversation, exactly as the - // protocol treats them as mutually exclusive; the refused-parse fallback reads - // the same precedence off the body. - var key = runRequest is not null - ? OpenAIResponses.GetSessionStoreId(runRequest) - : ResponsesRequestReader.ReadContinuationId(body); + var opened = await OpenSessionAsync(http, agent, sessions, run, approving: approval is not null, cancellationToken) + .ConfigureAwait(false); + + if (opened is null) + { + return; + } + + var (session, conversationId) = opened.Value; - if (string.IsNullOrWhiteSpace(key)) + if (session.GetService() is not { } conversation) { - key = null; + throw new InvalidOperationException( + "The session is not one this agent created, so it names no call to run."); } - if (string.IsNullOrWhiteSpace(conversationId)) + var input = await ReadInputAsync(http, conversation, approval, run.Messages, cancellationToken) + .ConfigureAwait(false); + + if (input is null) { - conversationId = null; + return; } + // A conversation the request named stays the conversation; a keyless first turn minted + // one alongside the session above. A response id is minted every turn either way, so a + // chain can start from any answer. + ResponsesTurn turn = new( + agent, + sessions, + session, + conversation, + input, + ResponsesAgentCore.OriginOf(agentcore), + OpenAIResponses.CreateResponseId(), + conversationId); + + await RunTurnAsync(http, body, turn, dialect: agentcore is not null, cancellationToken).ConfigureAwait(false); + } + + /// Opens the session the turn runs on: a new one, or the one the continuation names. + /// + /// The session and the conversation id it runs under, or once a + /// refusal has been answered. + /// + private static async Task<(AgentSession Session, string? ConversationId)?> OpenSessionAsync( + HttpContext http, + AgentCoreAgent agent, + AgentCoreAgentSessionStore sessions, + ResponsesRunInput run, + bool approving, + CancellationToken cancellationToken) + { + var key = run.ContinuationKey; + var conversationId = run.ConversationId; + var known = key is not null && await sessions.ContainsAsync(key, cancellationToken).ConfigureAwait(false); @@ -167,54 +166,35 @@ await ResponsesRequestReader.WriteErrorAsync( && !known && string.Equals(key, conversationId, StringComparison.Ordinal) && conversationId is not null - && agentcore?.Approval is null; + && !approving; - AgentSession session; if (key is null) { - if (agentcore?.Approval is not null) + if (approving) { await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "an approval answer names the conversation it resumes. Send it with the conversation " + "or previous response id the asking turn answered with.", - InvalidRequestError, "missing_session", cancellationToken).ConfigureAwait(false); - return; + return null; } conversationId = ResponsesRequestReader.NewConversationId(); - session = await agent.CreateSessionAsync(conversationId, cancellationToken).ConfigureAwait(false); + return (await agent.CreateSessionAsync(conversationId, cancellationToken).ConfigureAwait(false), conversationId); } - else if (namesNewConversation) + + if (namesNewConversation) { - // Unknown conversation with words: start the conversation under that id, so the conversation, - // the conversation, and the continuation key are one id. Unknown response ids stay 404 below: - // they name a turn, not a conversation. - session = await agent.CreateSessionAsync(key, cancellationToken).ConfigureAwait(false); + // Unknown conversation with words: start the conversation under that id, so the conversation + // and the continuation key are one id. Unknown response ids stay 404 below: they name + // a turn, not a conversation. + return (await agent.CreateSessionAsync(key, cancellationToken).ConfigureAwait(false), conversationId); } - else if (known) - { - try - { - session = await sessions.GetSessionAsync(agent, key, cancellationToken).ConfigureAwait(false); - } - catch (InvalidOperationException failure) - { - // A key minted by another entry is unknown to this one, never a cross-entry read. - await ResponsesRequestReader.WriteErrorAsync( - http, - StatusCodes.Status404NotFound, - failure.Message, - InvalidRequestError, - "continuation_not_found", - cancellationToken).ConfigureAwait(false); - return; - } - } - else + + if (!known) { // Either an unknown response id — a turn no answer ever carried — or an unknown // conversation beside an approval-only body the parse refused. A conversation with words @@ -224,86 +204,101 @@ await ResponsesRequestReader.WriteErrorAsync( StatusCodes.Status404NotFound, $"no conversation opens under '{key}'. Send the request with neither a conversation nor a " + "previous response id to start one.", - InvalidRequestError, "continuation_not_found", cancellationToken).ConfigureAwait(false); - - return; + return null; } - if (session.GetService() is not { } conversation) + try { - throw new InvalidOperationException( - "The session is not one this agent created, so it names no call to run."); + return (await sessions.GetSessionAsync(agent, key, cancellationToken).ConfigureAwait(false), conversationId); } - - ChatMessage input; - if (agentcore?.Approval is { } approval) + catch (InvalidOperationException failure) { - if (ResponsesRequestReader.LastUserText(messages) is { Length: > 0 }) - { - await ResponsesRequestReader.WriteErrorAsync( - http, - StatusCodes.Status400BadRequest, - "the request carries both a user message and an approval answer. One turn carries " - + "either words or an answer, never both.", - InvalidRequestError, - "mixed_turn", - cancellationToken).ConfigureAwait(false); - return; - } + // A key minted by another entry is unknown to this one, never a cross-entry read. + await ResponsesRequestReader.WriteErrorAsync( + http, + StatusCodes.Status404NotFound, + failure.Message, + "continuation_not_found", + cancellationToken).ConfigureAwait(false); + return null; + } + } - // Async: a resumed conversation has run no turn in this process, so its ledger session — - // and the queue the suspending turn filed — is still closed. This opens it first. - if (await conversation.TryCreateApprovalAnswerAsync(approval.RequestId, approval.Approved, cancellationToken).ConfigureAwait(false) is not { } answer) + /// Picks what the turn runs on: the approval answer, or the last user message with words. + /// The input, or once a refusal has been answered. + private static async Task ReadInputAsync( + HttpContext http, + ConversationSession conversation, + ResponsesApprovalAnswer? approval, + IReadOnlyList messages, + CancellationToken cancellationToken) + { + if (approval is null) + { + if (ResponsesRequestReader.LastUserMessage(messages) is { } user) { - await ResponsesRequestReader.WriteErrorAsync( - http, - StatusCodes.Status409Conflict, - $"the conversation queues no approval under id '{approval.RequestId}'. It was " - + "answered already, belongs to another conversation, or was never asked.", - InvalidRequestError, - "no_pending_approval", - cancellationToken).ConfigureAwait(false); - return; + return user; } - input = answer; - } - else if (ResponsesRequestReader.LastUserMessage(messages) is not { } user) - { await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request carries no user message with text, so there is no turn to run.", - InvalidRequestError, "no_user_message", cancellationToken).ConfigureAwait(false); - return; + return null; + } + + if (ResponsesRequestReader.LastUserText(messages) is { Length: > 0 }) + { + await ResponsesRequestReader.WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the request carries both a user message and an approval answer. One turn carries " + + "either words or an answer, never both.", + "mixed_turn", + cancellationToken).ConfigureAwait(false); + return null; } - else + + // Async: a resumed conversation has run no turn in this process, so its ledger session — + // and the queue the suspending turn filed — is still closed. This opens it first. + if (await conversation.TryCreateApprovalAnswerAsync(approval.RequestId, approval.Approved, cancellationToken).ConfigureAwait(false) is { } answer) { - input = user; + return answer; } - var origin = ResponsesAgentCore.OriginOf(agentcore); + await ResponsesRequestReader.WriteErrorAsync( + http, + StatusCodes.Status409Conflict, + $"the conversation queues no approval under id '{approval.RequestId}'. It was " + + "answered already, belongs to another conversation, or was never asked.", + "no_pending_approval", + cancellationToken).ConfigureAwait(false); + return null; + } + /// Runs the turn on the branch the body asked for, and answers a refused turn as 409. + private static async Task RunTurnAsync( + HttpContext http, + JsonElement body, + ResponsesTurn turn, + bool dialect, + CancellationToken cancellationToken) + { var streaming = body.TryGetProperty("stream", out var streamFlag) && streamFlag.ValueKind == JsonValueKind.True; - // A conversation the request named stays the conversation; a keyless first turn minted - // one alongside the session above. A response id is minted every turn either way, so a - // chain can start from any answer. - var responseId = OpenAIResponses.CreateResponseId(); - // Only the stream has a frame to carry a drawing, so only the stream gets a screen. Binding // one on the whole-reply branch would let the tool report a picture the caller never sees. // Set per request, not once: the session outlives a request and the branch can differ per turn. - conversation.SetHasScreen(streaming); + turn.Conversation.SetHasScreen(streaming); if (CallerTimeZone.Parse(http.Request.Headers[TimeZoneHeaderName]) is { } zone) { - CallerTimeZone.Set(session, zone); + CallerTimeZone.Set(turn.Session, zone); } try @@ -312,13 +307,11 @@ await ResponsesRequestReader.WriteErrorAsync( { // The dialect is opt-in by the member only our clients send: an OpenAI SDK // never carries agentcore, so its stream stays the framework's pure shapes. - await ResponsesTurnStream.WriteAsync(http, agent, sessions, session, conversation, input, origin, responseId, conversationId, agentcore is not null, cancellationToken) - .ConfigureAwait(false); + await ResponsesTurnStream.WriteAsync(http, turn, dialect, cancellationToken).ConfigureAwait(false); } else { - await ResponsesTurnReply.WriteAsync(http, agent, sessions, session, conversation, input, origin, responseId, conversationId, cancellationToken) - .ConfigureAwait(false); + await ResponsesTurnReply.WriteAsync(http, turn, cancellationToken).ConfigureAwait(false); } } catch (InvalidOperationException exception) @@ -329,7 +322,6 @@ await ResponsesRequestReader.WriteErrorAsync( http, StatusCodes.Status409Conflict, exception.Message, - InvalidRequestError, "turn_refused", cancellationToken).ConfigureAwait(false); } diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs index ed50f27c..a6e3828a 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesRequestReader.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; +using Microsoft.Agents.AI.Hosting.OpenAI; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.AI; @@ -9,6 +10,82 @@ namespace AgentCore.AspNetCore.Endpoints; /// What the Responses path reads off a request body, and how it answers a bad one. internal static class ResponsesRequestReader { + /// The OpenAI error type every refused request reports. + private const string InvalidRequestError = "invalid_request_error"; + + /// Reads the request body as JSON. + /// The body, or once a 400 has been answered for a body that is not JSON. + internal static async Task ReadBodyAsync(HttpContext http, CancellationToken cancellationToken) + { + try + { + return await JsonSerializer + .DeserializeAsync(http.Request.Body, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + catch (JsonException exception) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the request body is not well-formed JSON: " + exception.Message, + "malformed_body", + cancellationToken).ConfigureAwait(false); + return null; + } + } + + /// + /// Reads what the body asks to run, through the protocol parse. + /// says the body carries an approval answer, which the parse alone refuses. + /// + /// The run, or once a 400 has been answered for a body the parse refused. + /// + /// The protocol treats a conversation id and a response id as mutually exclusive, and the + /// helper prefers the response chain; the refused-parse fallback reads the same precedence off + /// the body. + /// + internal static async Task ReadRunInputAsync( + HttpContext http, + JsonElement body, + bool approving, + CancellationToken cancellationToken) + { + try + { + var runRequest = OpenAIResponses.ToAgentRunRequest(body); + + return new ResponsesRunInput( + NullIfBlank(runRequest.ConversationId), + [.. runRequest.Messages], + NullIfBlank(OpenAIResponses.GetSessionStoreId(runRequest))); + } + catch (ArgumentException exception) + { + // An approval answer carries no words, only the request it answers — and the + // protocol parse refuses a turn with no input. The continuation still names the + // conversation, so read it off the body and run the answer alone. + if (!approving) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the request is not a Responses request: " + exception.Message, + "invalid_body", + cancellationToken).ConfigureAwait(false); + return null; + } + + return new ResponsesRunInput( + NullIfBlank(ReadConversationId(body)), + [], + NullIfBlank(ReadContinuationId(body))); + } + } + + private static string? NullIfBlank(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value; + /// Reads the last user message that carries words, the session owning the rest. internal static ChatMessage? LastUserMessage(IReadOnlyList messages) { @@ -67,7 +144,6 @@ internal static async Task WriteErrorAsync( HttpContext http, int status, string message, - string type, string code, CancellationToken cancellationToken) { @@ -79,7 +155,7 @@ await http.Response.WriteAsJsonAsync( ["error"] = new JsonObject { ["message"] = message, - ["type"] = type, + ["type"] = InvalidRequestError, ["code"] = code, ["param"] = null, }, diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesRunInput.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesRunInput.cs new file mode 100644 index 00000000..7a39271c --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesRunInput.cs @@ -0,0 +1,15 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// What one Responses request asks to run, read off the body. +/// The conversation the request named, or . +/// The messages of the run. Empty for an approval-only body. +/// +/// The session-store key this turn hangs off, or for the first turn of a +/// conversation. A response id names one past turn; a conversation id names the conversation itself. +/// +internal sealed record ResponsesRunInput( + string? ConversationId, + IReadOnlyList Messages, + string? ContinuationKey); diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurn.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurn.cs new file mode 100644 index 00000000..af6864dd --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurn.cs @@ -0,0 +1,30 @@ +using AgentCore.Application.Runtime; +using AgentCore.AspNetCore.Sessions; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// One turn the Responses path is about to run, and every id the answer files under. +/// The entry the URL named. +/// The store the session is filed in after the turn. +/// The session the turn advances. +/// The conversation inside . +/// The user words, or the approval answer, the turn runs on. +/// Where the request said the turn came from, or . +/// The id minted for this turn's answer. +/// The id of the conversation, or when none names it. +internal sealed record ResponsesTurn( + AgentCoreAgent Agent, + AgentCoreAgentSessionStore Sessions, + AgentSession Session, + ConversationSession Conversation, + ChatMessage Input, + ConversationTurnOrigin? Origin, + string ResponseId, + string? ConversationId) +{ + /// Files the session, under every id that names it now. + public Task FileAsync(CancellationToken cancellationToken) + => ResponsesSessionFiling.SaveAsync(Sessions, Agent, Session, ResponseId, ConversationId, cancellationToken); +} diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs index 467ba580..640f9f37 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnReply.cs @@ -1,6 +1,4 @@ using System.Text.Json.Nodes; -using AgentCore.Application.Runtime; -using AgentCore.AspNetCore.Sessions; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Hosting.OpenAI; using Microsoft.AspNetCore.Http; @@ -12,33 +10,22 @@ namespace AgentCore.AspNetCore.Endpoints; internal static class ResponsesTurnReply { /// Runs one turn and answers the whole reply, filed under its ids. - internal static async Task WriteAsync( - HttpContext http, - AgentCoreAgent agent, - AgentCoreAgentSessionStore sessions, - AgentSession session, - ConversationSession conversation, - ChatMessage input, - ConversationTurnOrigin? origin, - string responseId, - string? conversationId, - CancellationToken cancellationToken) + internal static async Task WriteAsync(HttpContext http, ResponsesTurn turn, CancellationToken cancellationToken) { - var turn = await conversation - .RunTurnMessageAtOriginAsync(input, origin, cancellationToken) + var result = await turn.Conversation + .RunTurnMessageAtOriginAsync(turn.Input, turn.Origin, cancellationToken) .ConfigureAwait(false); - await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) - .ConfigureAwait(false); + await turn.FileAsync(cancellationToken).ConfigureAwait(false); - var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, turn.ReplyText)) + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, result.ReplyText)) { - AgentId = agent.Id, - ResponseId = responseId, - CreatedAt = turn.EndedAt, + AgentId = turn.Agent.Id, + ResponseId = turn.ResponseId, + CreatedAt = result.EndedAt, }; - var rendered = OpenAIResponses.WriteResponse(response, responseId, conversationId); + var rendered = OpenAIResponses.WriteResponse(response, turn.ResponseId, turn.ConversationId); // The render is a closed JsonElement, so the turn facts go on as JSON: the object // the framework wrote, with the metadata member replaced by ours beside its own. @@ -46,7 +33,7 @@ await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, con var node = JsonNode.Parse(rendered.GetRawText())!.AsObject(); JsonObject metadata = node["metadata"]?.AsObject() ?? []; - foreach (var (name, value) in ResponsesAgentCore.TurnMetadata(conversation, turn)) + foreach (var (name, value) in ResponsesAgentCore.TurnMetadata(turn.Conversation, result)) { metadata[name] = value; } @@ -54,7 +41,7 @@ await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, con node["metadata"] = metadata; http.Response.StatusCode = StatusCodes.Status200OK; - http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = turn.StageAfter; + http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = result.StageAfter; await http.Response .WriteAsJsonAsync(node, cancellationToken) diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs index ce60a653..266fcb26 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesTurnStream.cs @@ -1,9 +1,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using AgentCore.Application.Conversation; -using AgentCore.Application.Runtime; using AgentCore.Application.Tools; -using AgentCore.AspNetCore.Sessions; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Hosting.OpenAI; using Microsoft.AspNetCore.Http; @@ -28,14 +26,7 @@ internal static class ResponsesTurnStream /// internal static async Task WriteAsync( HttpContext http, - AgentCoreAgent agent, - AgentCoreAgentSessionStore sessions, - AgentSession session, - ConversationSession conversation, - ChatMessage input, - ConversationTurnOrigin? origin, - string responseId, - string? conversationId, + ResponsesTurn turn, bool dialect, CancellationToken cancellationToken) { @@ -44,15 +35,15 @@ internal static async Task WriteAsync( http.Response.Headers.CacheControl = "no-cache"; // The headers leave before the turn ends, so this one names the stage the turn speaks in. - http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = conversation.Stage; + http.Response.Headers[ResponsesEndpointRouteBuilderExtensions.StageHeaderName] = turn.Conversation.Stage; // One turn's worth of ids: the pairing dies with the stream. ToolCallNames toolNames = new(); - var updates = StreamAgentUpdatesAsync(http, agent, conversation, input, origin, dialect, toolNames, cancellationToken); - + var updates = StreamAgentUpdatesAsync(http, turn, dialect, toolNames, cancellationToken); + await foreach (var frame in OpenAIResponses - .WriteResponseStreamAsync(updates, responseId, conversationId, cancellationToken) + .WriteResponseStreamAsync(updates, turn.ResponseId, turn.ConversationId, cancellationToken) .ConfigureAwait(false)) { await http.Response.WriteAsync(frame, cancellationToken).ConfigureAwait(false); @@ -61,8 +52,7 @@ internal static async Task WriteAsync( await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); } - await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, conversationId, cancellationToken) - .ConfigureAwait(false); + await turn.FileAsync(cancellationToken).ConfigureAwait(false); } /// Runs one streaming turn on the conversation, wrapping each update with the agent's id. @@ -72,18 +62,15 @@ await ResponsesSessionFiling.SaveAsync(sessions, agent, session, responseId, con /// private static async IAsyncEnumerable StreamAgentUpdatesAsync( HttpContext http, - AgentCoreAgent agent, - ConversationSession conversation, - ChatMessage input, - ConversationTurnOrigin? origin, + ResponsesTurn turn, bool dialect, ToolCallNames toolNames, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) { TurnStreamFiles files = new(); - await foreach (var update in conversation - .RunTurnMessageStreamingAtOriginAsync(input, origin, cancellationToken) + await foreach (var update in turn.Conversation + .RunTurnMessageStreamingAtOriginAsync(turn.Input, turn.Origin, cancellationToken) .ConfigureAwait(false)) { if (dialect) @@ -96,7 +83,7 @@ private static async IAsyncEnumerable StreamAgentUpdatesAsy files.Note(update); } - yield return new AgentResponseUpdate(update) { AgentId = agent.Id }; + yield return new AgentResponseUpdate(update) { AgentId = turn.Agent.Id }; } if (dialect) @@ -105,7 +92,7 @@ private static async IAsyncEnumerable StreamAgentUpdatesAsy // inside it: by here the bytes are in the store or never will be. var conversations = http.RequestServices.GetRequiredService(); - await foreach (var part in files.ResolveAsync(conversations, conversation.ConversationId, cancellationToken).ConfigureAwait(false)) + await foreach (var part in files.ResolveAsync(conversations, turn.Conversation.ConversationId, cancellationToken).ConfigureAwait(false)) { await WritePartLineAsync(http, part, cancellationToken).ConfigureAwait(false); } From de95bd8d84160270cdb6dec8b976823bb4ed2698 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 01:00:22 -0600 Subject: [PATCH 24/35] feat(qdrant): implement QdrantCollectionProof for collection validation and refactor QdrantKnowledgeAdapter --- .../Qdrant/QdrantCollectionProof.cs | 275 +++++++++++++++ .../Qdrant/QdrantKnowledgeAdapter.cs | 314 +++--------------- 2 files changed, 313 insertions(+), 276 deletions(-) create mode 100644 src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantCollectionProof.cs diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantCollectionProof.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantCollectionProof.cs new file mode 100644 index 00000000..6909a6ed --- /dev/null +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantCollectionProof.cs @@ -0,0 +1,275 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Knowledge; +using Google.Protobuf.Collections; +using Microsoft.Extensions.AI; +using Qdrant.Client; +using Qdrant.Client.Grpc; + +namespace AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; + +/// +/// The startup proof of one collection: it exists, its vector is as wide as this host embeds, and +/// one point read back carries what the store reads off it. Every failure is a refusal to start +/// rather than a deployment that silently returns nothing. +/// +internal static class QdrantCollectionProof +{ + // Embedded once at startup, only to measure the deployment's embedder width against the + // collection's own. Its content is never a real query and is never sent to Qdrant. + private const string DimensionProbeText = "agentcore-qdrant-startup-probe"; + + /// Runs every proof against the live collection. + /// One proof failed. + internal static async ValueTask AssertAsync( + QdrantClient client, + KnowledgeProviderConfiguration entry, + IEmbeddingGenerator> embedder, + IKnowledgePointMapper? mapper, + Guid linkNamespace, + CancellationToken cancellationToken) + { + if (!await client.CollectionExistsAsync(entry.Collection, cancellationToken).ConfigureAwait(false)) + { + throw new InvalidOperationException( + $"providers.knowledge.collection names '{entry.Collection}', and no such collection or " + + "alias exists on this cluster. AgentCore reads a knowledge base and never creates " + + "one: run whatever ingests your cards, or correct the name."); + } + + var info = await client.GetCollectionInfoAsync(entry.Collection, cancellationToken).ConfigureAwait(false); + var width = VectorWidth(info.Config.Params.VectorsConfig, entry); + var dimensions = await EmbedderWidthAsync(embedder, entry, cancellationToken).ConfigureAwait(false); + + if (width != dimensions) + { + var label = entry.Vector is { Length: > 0 } named ? $"a '{named}' vector" : "an anonymous vector"; + throw new InvalidOperationException( + $"'{entry.Collection}' has {label} of {width} dimensions and this " + + $"host embeds at {dimensions}. Every score would be meaningless. Either set " + + "providers.embeddings to the model this collection was built with, or rebuild the " + + "collection with this host's model."); + } + + await AssertPayloadAsync(client, entry, mapper, linkNamespace, cancellationToken).ConfigureAwait(false); + } + + /// Reads the width of the vector the document names, or of the one anonymous vector. + private static ulong VectorWidth(VectorsConfig vectors, KnowledgeProviderConfiguration entry) + { + if (entry.Vector is { Length: > 0 } vectorName) + { + if (vectors.ConfigCase != VectorsConfig.ConfigOneofCase.ParamsMap + || !vectors.ParamsMap.Map.TryGetValue(vectorName, out var dense)) + { + throw new InvalidOperationException( + $"'{entry.Collection}' carries no named vector '{vectorName}'. A collection whose " + + "vector is unnamed, or named something else, misses every point on search with no " + + "error — and it still fetches by key, so a smoke test would not notice. Set " + + "providers.knowledge.vector to the name the collection was built with, or drop " + + "the setting for a collection with a single anonymous vector."); + } + + return dense.Size; + } + + if (vectors.ConfigCase != VectorsConfig.ConfigOneofCase.Params) + { + throw new InvalidOperationException( + $"'{entry.Collection}' carries named vectors and providers.knowledge.vector names " + + "none, so every query would search an anonymous vector this collection does not " + + "have and miss every point with no error. Set providers.knowledge.vector to the " + + "name the collection was built with."); + } + + return vectors.Params.Size; + } + + /// Embeds the probe text once, only to measure how wide this host's vectors are. + private static async ValueTask EmbedderWidthAsync( + IEmbeddingGenerator> embedder, + KnowledgeProviderConfiguration entry, + CancellationToken cancellationToken) + { + try + { + var probe = await embedder + .GenerateAsync(DimensionProbeText, cancellationToken: cancellationToken) + .ConfigureAwait(false); + return (ulong)probe.Vector.Length; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + throw new InvalidOperationException( + $"'{entry.Collection}' could not be checked against this host's embedder: the startup " + + "width probe failed before it produced a vector. This is not a schema problem with " + + "the collection; check the embedding generator's own configuration and credentials.", + ex); + } + } + + /// + /// Reads one point back and proves the payload still carries what the store reads off it. + /// + private static async ValueTask AssertPayloadAsync( + QdrantClient client, + KnowledgeProviderConfiguration entry, + IKnowledgePointMapper? mapper, + Guid linkNamespace, + CancellationToken cancellationToken) + { + var scrolled = await client + .ScrollAsync(entry.Collection, limit: 1, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + if (scrolled.Result.Count == 0) + { + return; + } + + var point = scrolled.Result[0]; + + if (mapper is not null) + { + // A custom mapper owns the payload shape, so no key list can be asserted — but the + // refuse-to-start property survives: map the one scrolled point and demand text. + var card = mapper.Map(QdrantPointConverter.ToPoint(point.Id, point.Payload, score: null)); + if (card is not { Text.Length: > 0 }) + { + throw new InvalidOperationException( + $"'{entry.Collection}' holds points that mapper '{mapper.Name}' reads as empty: it " + + "returned no card, or a card with no text, for a point scrolled at startup. " + + "AgentCore would then inject blank cards into every turn without failing anything. " + + "Correct the mapper, or point this host at the collection it was written for."); + } + + return; + } + + foreach (var (role, key, numeric) in DeclaredKeys(entry.Fields!)) + { + if (!Carries(point.Payload, key, numeric)) + { + throw new InvalidOperationException( + $"'{entry.Collection}' holds points whose payload has no {(numeric ? "numeric" : "non-empty")} " + + $"'{key}', which providers.knowledge.fields.{role} names. AgentCore reads every field " + + "that block maps off every point and treats a missing key as absent, so this role " + + "would be silently empty on every card. Map the path this collection really uses, " + + "declare the role with an explicit null if the collection does not carry it, or " + + "point this host at the collection whose payload matches."); + } + } + + if (entry.Links is { } links && links.Lookup != KnowledgeLinkLookup.Filter) + { + AssertPointKey(point, entry, links, linkNamespace); + } + } + + /// + /// Every payload key the document actually mapped, with the role that named it and whether that + /// role holds a number rather than text. + /// + /// + /// All six roles, not the two the built-in mapping cannot do without. A wrong path under + /// source, locator or authority throws nothing and returns nothing: the + /// citation is simply blank on every card, on every turn, for the life of the deployment. That is + /// exactly the failure a startup proof exists to convert into a refusal to start. + /// + private static IEnumerable<(string Role, string Key, bool Numeric)> DeclaredKeys( + KnowledgeFieldsConfiguration fields) + { + if (fields.Body is { Length: > 0 } body) + { + yield return ("body", body, false); + } + + if (fields.Id is { Length: > 0 } id) + { + yield return ("id", id, false); + } + + if (fields.Lexical is { Length: > 0 } lexical) + { + yield return ("lexical", lexical, false); + } + + if (fields.Source is { Length: > 0 } source) + { + yield return ("source", source, false); + } + + if (fields.Locator is { Length: > 0 } locator) + { + yield return ("locator", locator, false); + } + + // Authority ranks trust, so a collection writes it as an integer. Demanding a string here + // would refuse every correctly built collection there is. + if (fields.Authority is { Length: > 0 } authority) + { + yield return ("authority", authority, true); + } + } + + /// Whether one point really carries the role a mapped key claims. + private static bool Carries(MapField payload, string key, bool numeric) + => QdrantPayload.Read(payload, key) switch + { + { KindCase: Value.KindOneofCase.StringValue } value => !numeric && value.StringValue.Length > 0, + { KindCase: Value.KindOneofCase.IntegerValue } => numeric, + { KindCase: Value.KindOneofCase.DoubleValue } => numeric, + _ => false, + }; + + /// Proves a linked id resolves back to the point that holds it. + private static void AssertPointKey( + RetrievedPoint point, + KnowledgeProviderConfiguration entry, + KnowledgeLinksConfiguration links, + Guid linkNamespace) + { + if (QdrantPayload.Read(point.Payload, links.Field!) is null) + { + return; + } + + var cardId = QdrantPayload.Read(point.Payload, entry.Fields!.Id!)!.StringValue; + + if (point.Id.PointIdOptionsCase != PointId.PointIdOptionsOneofCase.Uuid) + { + throw new InvalidOperationException( + $"'{entry.Collection}' holds points keyed by number, and providers.knowledge.links.lookup " + + $"is {links.Lookup.ToString().ToLowerInvariant()}, which builds a UUID key. Every " + + "link expansion would silently return nothing. Set links.lookup: filter to match on " + + $"'{entry.Fields.Id}' instead."); + } + + Guid expected; + if (links.Lookup == KnowledgeLinkLookup.Direct) + { + if (!Guid.TryParse(cardId, out expected)) + { + throw new InvalidOperationException( + $"'{entry.Collection}' holds a point whose '{entry.Fields.Id}' is '{cardId}', which is " + + "not a GUID, but providers.knowledge.links.lookup is direct. Qdrant's point key is a " + + "GUID or an unsigned integer, so a free-form id cannot be one. Set links.lookup: " + + $"filter to match on '{entry.Fields.Id}' instead."); + } + } + else + { + expected = Uuid5PointId.For(cardId, linkNamespace, links.Prefix); + } + + if (Guid.Parse(point.Id.Uuid) != expected) + { + throw new InvalidOperationException( + $"'{entry.Collection}' holds a point whose '{entry.Fields.Id}' is '{cardId}' and whose " + + $"point key is {point.Id.Uuid}, but providers.knowledge.links.lookup is " + + $"{links.Lookup.ToString().ToLowerInvariant()} with namespace " + + $"'{links.Namespace}' and prefix '{links.Prefix}', which derives {expected}. " + + $"Every '{links.Field}' expansion would silently return nothing. Correct the " + + $"namespace or prefix, or set links.lookup: filter to match on '{entry.Fields.Id}'."); + } + } +} diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs index 0d6c8ed6..55cbd46f 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs @@ -3,10 +3,8 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Secrets; -using Google.Protobuf.Collections; using Microsoft.Extensions.AI; using Qdrant.Client; -using Qdrant.Client.Grpc; namespace AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; @@ -33,13 +31,8 @@ public sealed class QdrantKnowledgeAdapter : IKnowledgeStoreAdapter // The deadline of one gRPC call. The connector never sets one on its own. private static readonly TimeSpan CallDeadline = TimeSpan.FromSeconds(30); - // Embedded once at startup, only to measure the deployment's embedder width against the - // collection's own. Its content is never a real query and is never sent to Qdrant. - private const string DimensionProbeText = "agentcore-qdrant-startup-probe"; - private readonly Func? _clientFactory; - private readonly IEmbeddingGenerator>? _embeddings; private IReadOnlyList _analyzers = [new NoQueryAnalyzer()]; @@ -126,53 +119,10 @@ public async ValueTask CreateSearchAsync( + "with a generator."); var analyzer = ResolveAnalyzer(entry.Analyzer); - var mapper = ResolveMapper(entry.Mapper); - if (entry.Mapper is null && entry.Fields?.Body is not { Length: > 0 }) - { - throw Fail( - "/providers/knowledge/fields/body", - "providers.knowledge names no mapper, so the built-in fields: mapping reads every " - + "card, and it maps no body. AgentCore has no default field names, so every card " - + "would reach the model empty. Map providers.knowledge.fields.body, or name an " - + "IKnowledgePointMapper with mapper:."); - } - - if (entry.Links is not null && entry.Fields?.Id is not { Length: > 0 }) - { - throw Fail( - "/providers/knowledge/fields/id", - "providers.knowledge.links is configured, and every links.lookup mode resolves a " - + "linked id through providers.knowledge.fields.id, which this document does not map. " - + "Map the id field, or remove the links block."); - } - - if (entry.Links is { } declaredLinks && declaredLinks.Field is not { Length: > 0 }) - { - throw Fail( - "/providers/knowledge/links/field", - "providers.knowledge.links is configured and names no field. AgentCore has no default " - + "link field: it cannot guess which payload key holds this collection's outbound ids. " - + "Write links.field, or remove the links block."); - } - - var linkNamespace = Guid.Empty; - - if (entry.Links is { Lookup: KnowledgeLinkLookup.Uuid5 } uuid5Links) - { - try - { - linkNamespace = Uuid5PointId.Namespace(uuid5Links.Namespace); - } - catch (FormatException) - { - throw Fail( - "/providers/knowledge/links/namespace", - $"providers.knowledge.links.namespace is '{uuid5Links.Namespace}', which is neither a " - + "known name (url, dns, oid, x500) nor a GUID."); - } - } + AssertFieldsMapped(entry); + var linkNamespace = LinkNamespace(entry); var client = _clientFactory is not null ? _clientFactory(entry) @@ -180,78 +130,9 @@ public async ValueTask CreateSearchAsync( try { - if (!await client.CollectionExistsAsync(entry.Collection, cancellationToken).ConfigureAwait(false)) - { - throw new InvalidOperationException( - $"providers.knowledge.collection names '{entry.Collection}', and no such collection or " - + "alias exists on this cluster. AgentCore reads a knowledge base and never creates " - + "one: run whatever ingests your cards, or correct the name."); - } - - var info = await client.GetCollectionInfoAsync(entry.Collection, cancellationToken).ConfigureAwait(false); - - var vectors = info.Config.Params.VectorsConfig; - - ulong width; - - if (entry.Vector is { Length: > 0 } vectorName) - { - if (vectors.ConfigCase != VectorsConfig.ConfigOneofCase.ParamsMap - || !vectors.ParamsMap.Map.TryGetValue(vectorName, out var dense)) - { - throw new InvalidOperationException( - $"'{entry.Collection}' carries no named vector '{vectorName}'. A collection whose " - + "vector is unnamed, or named something else, misses every point on search with no " - + "error — and it still fetches by key, so a smoke test would not notice. Set " - + "providers.knowledge.vector to the name the collection was built with, or drop " - + "the setting for a collection with a single anonymous vector."); - } - - width = dense.Size; - } - else - { - if (vectors.ConfigCase != VectorsConfig.ConfigOneofCase.Params) - { - throw new InvalidOperationException( - $"'{entry.Collection}' carries named vectors and providers.knowledge.vector names " - + "none, so every query would search an anonymous vector this collection does not " - + "have and miss every point with no error. Set providers.knowledge.vector to the " - + "name the collection was built with."); - } - - width = vectors.Params.Size; - } - - ulong dimensions; - - try - { - var probe = await embedder - .GenerateAsync(DimensionProbeText, cancellationToken: cancellationToken) - .ConfigureAwait(false); - dimensions = (ulong)probe.Vector.Length; - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - throw new InvalidOperationException( - $"'{entry.Collection}' could not be checked against this host's embedder: the startup " - + "width probe failed before it produced a vector. This is not a schema problem with " - + "the collection; check the embedding generator's own configuration and credentials.", - ex); - } - - if (width != dimensions) - { - var label = entry.Vector is { Length: > 0 } named ? $"a '{named}' vector" : "an anonymous vector"; - throw new InvalidOperationException( - $"'{entry.Collection}' has {label} of {width} dimensions and this " - + $"host embeds at {dimensions}. Every score would be meaningless. Either set " - + "providers.embeddings to the model this collection was built with, or rebuild the " - + "collection with this host's model."); - } - - await AssertPayloadAsync(client, entry, mapper, linkNamespace, cancellationToken).ConfigureAwait(false); + await QdrantCollectionProof + .AssertAsync(client, entry, embedder, mapper, linkNamespace, cancellationToken) + .ConfigureAwait(false); return new QdrantKnowledgeStore( new QdrantSearchChannel(client), @@ -270,12 +151,6 @@ public async ValueTask CreateSearchAsync( Analyzer = analyzer, Mapper = mapper, ScoreFloor = entry.ScoreFloor, - - // Ruling 14(c). One store serves every agent and every agent reads from that one - // fetch, so the store must fetch what the MOST generous agent is allowed to ask - // for. Leaving the store's own default here silently caps an agent that wrote - // limit: 8 -- the schema accepts the 8, the provider trims to 8, and only 5 ever - // arrive. The document's ceiling is the store's floor. Limit = AgentKnowledgeConfiguration.MaximumLimit, }); } @@ -286,169 +161,56 @@ public async ValueTask CreateSearchAsync( } } - /// - /// Reads one point back and proves the payload still carries what the store reads off it. - /// - private static async ValueTask AssertPayloadAsync( - QdrantClient client, - KnowledgeProviderConfiguration entry, - IKnowledgePointMapper? mapper, - Guid linkNamespace, - CancellationToken cancellationToken) + /// Refuses a document whose fields: block cannot feed what the rest of it asks for. + private static void AssertFieldsMapped(KnowledgeProviderConfiguration entry) { - var scrolled = await client - .ScrollAsync(entry.Collection, limit: 1, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - if (scrolled.Result.Count == 0) - { - return; - } - - var point = scrolled.Result[0]; - - if (mapper is not null) - { - // A custom mapper owns the payload shape, so no key list can be asserted — but the - // refuse-to-start property survives: map the one scrolled point and demand text. - var card = mapper.Map(QdrantPointConverter.ToPoint(point.Id, point.Payload, score: null)); - if (card is not { Text.Length: > 0 }) - { - throw new InvalidOperationException( - $"'{entry.Collection}' holds points that mapper '{mapper.Name}' reads as empty: it " - + "returned no card, or a card with no text, for a point scrolled at startup. " - + "AgentCore would then inject blank cards into every turn without failing anything. " - + "Correct the mapper, or point this host at the collection it was written for."); - } - - return; - } - - foreach (var (role, key, numeric) in DeclaredKeys(entry.Fields!)) - { - if (!Carries(point.Payload, key, numeric)) - { - throw new InvalidOperationException( - $"'{entry.Collection}' holds points whose payload has no {(numeric ? "numeric" : "non-empty")} " - + $"'{key}', which providers.knowledge.fields.{role} names. AgentCore reads every field " - + "that block maps off every point and treats a missing key as absent, so this role " - + "would be silently empty on every card. Map the path this collection really uses, " - + "declare the role with an explicit null if the collection does not carry it, or " - + "point this host at the collection whose payload matches."); - } - } - - if (entry.Links is { } links && links.Lookup != KnowledgeLinkLookup.Filter) - { - AssertPointKey(point, entry, links, linkNamespace); - } - } - - /// - /// Every payload key the document actually mapped, with the role that named it and whether that - /// role holds a number rather than text. - /// - /// - /// All six roles, not the two the built-in mapping cannot do without. A wrong path under - /// source, locator or authority throws nothing and returns nothing: the - /// citation is simply blank on every card, on every turn, for the life of the deployment. That is - /// exactly the failure a startup proof exists to convert into a refusal to start. - /// - private static IEnumerable<(string Role, string Key, bool Numeric)> DeclaredKeys( - KnowledgeFieldsConfiguration fields) - { - if (fields.Body is { Length: > 0 } body) - { - yield return ("body", body, false); - } - - if (fields.Id is { Length: > 0 } id) - { - yield return ("id", id, false); - } - - if (fields.Lexical is { Length: > 0 } lexical) - { - yield return ("lexical", lexical, false); - } - - if (fields.Source is { Length: > 0 } source) + if (entry.Mapper is null && entry.Fields?.Body is not { Length: > 0 }) { - yield return ("source", source, false); + throw Fail( + "/providers/knowledge/fields/body", + "providers.knowledge names no mapper, so the built-in fields: mapping reads every " + + "card, and it maps no body. AgentCore has no default field names, so every card " + + "would reach the model empty. Map providers.knowledge.fields.body, or name an " + + "IKnowledgePointMapper with mapper:."); } - if (fields.Locator is { Length: > 0 } locator) + if (entry.Links is not null && entry.Fields?.Id is not { Length: > 0 }) { - yield return ("locator", locator, false); + throw Fail( + "/providers/knowledge/fields/id", + "providers.knowledge.links is configured, and every links.lookup mode resolves a " + + "linked id through providers.knowledge.fields.id, which this document does not map. " + + "Map the id field, or remove the links block."); } - // Authority ranks trust, so a collection writes it as an integer. Demanding a string here - // would refuse every correctly built collection there is. - if (fields.Authority is { Length: > 0 } authority) + if (entry.Links is { } declaredLinks && declaredLinks.Field is not { Length: > 0 }) { - yield return ("authority", authority, true); + throw Fail( + "/providers/knowledge/links/field", + "providers.knowledge.links is configured and names no field. AgentCore has no default " + + "link field: it cannot guess which payload key holds this collection's outbound ids. " + + "Write links.field, or remove the links block."); } } - /// Whether one point really carries the role a mapped key claims. - private static bool Carries(MapField payload, string key, bool numeric) - => QdrantPayload.Read(payload, key) switch - { - { KindCase: Value.KindOneofCase.StringValue } value => !numeric && value.StringValue.Length > 0, - { KindCase: Value.KindOneofCase.IntegerValue } => numeric, - { KindCase: Value.KindOneofCase.DoubleValue } => numeric, - _ => false, - }; - - /// Proves a linked id resolves back to the point that holds it. - private static void AssertPointKey( - RetrievedPoint point, - KnowledgeProviderConfiguration entry, - KnowledgeLinksConfiguration links, - Guid linkNamespace) + /// The UUID5 namespace the links block names, or when links do not use one. + private static Guid LinkNamespace(KnowledgeProviderConfiguration entry) { - if (QdrantPayload.Read(point.Payload, links.Field!) is null) - { - return; - } - - var cardId = QdrantPayload.Read(point.Payload, entry.Fields!.Id!)!.StringValue; - - if (point.Id.PointIdOptionsCase != PointId.PointIdOptionsOneofCase.Uuid) + if (entry.Links is not { Lookup: KnowledgeLinkLookup.Uuid5 } uuid5Links) { - throw new InvalidOperationException( - $"'{entry.Collection}' holds points keyed by number, and providers.knowledge.links.lookup " - + $"is {links.Lookup.ToString().ToLowerInvariant()}, which builds a UUID key. Every " - + "link expansion would silently return nothing. Set links.lookup: filter to match on " - + $"'{entry.Fields.Id}' instead."); + return Guid.Empty; } - Guid expected; - if (links.Lookup == KnowledgeLinkLookup.Direct) - { - if (!Guid.TryParse(cardId, out expected)) - { - throw new InvalidOperationException( - $"'{entry.Collection}' holds a point whose '{entry.Fields.Id}' is '{cardId}', which is " - + "not a GUID, but providers.knowledge.links.lookup is direct. Qdrant's point key is a " - + "GUID or an unsigned integer, so a free-form id cannot be one. Set links.lookup: " - + $"filter to match on '{entry.Fields.Id}' instead."); - } - } - else + try { - expected = Uuid5PointId.For(cardId, linkNamespace, links.Prefix); + return Uuid5PointId.Namespace(uuid5Links.Namespace); } - - if (Guid.Parse(point.Id.Uuid) != expected) + catch (FormatException) { - throw new InvalidOperationException( - $"'{entry.Collection}' holds a point whose '{entry.Fields.Id}' is '{cardId}' and whose " - + $"point key is {point.Id.Uuid}, but providers.knowledge.links.lookup is " - + $"{links.Lookup.ToString().ToLowerInvariant()} with namespace " - + $"'{links.Namespace}' and prefix '{links.Prefix}', which derives {expected}. " - + $"Every '{links.Field}' expansion would silently return nothing. Correct the " - + $"namespace or prefix, or set links.lookup: filter to match on '{entry.Fields.Id}'."); + throw Fail( + "/providers/knowledge/links/namespace", + $"providers.knowledge.links.namespace is '{uuid5Links.Namespace}', which is neither a " + + "known name (url, dns, oid, x500) nor a GUID."); } } @@ -518,4 +280,4 @@ private static ConfigurationLoadException Fail(string pointer, string message) Message = message, Check = ConfigurationCheck.ReferenceResolution, }); -} +} \ No newline at end of file From c360c9da3543acff558458e930f4b679e3490c7d Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 01:45:39 -0600 Subject: [PATCH 25/35] feat(schema-validation): refactor ConfigurationSchemaValidator and add SchemaFailureWording for improved error messaging --- .../Parsing/ConfigurationSchemaValidator.cs | 245 +----------------- .../Parsing/SchemaFailureWording.cs | 228 ++++++++++++++++ 2 files changed, 234 insertions(+), 239 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Parsing/SchemaFailureWording.cs diff --git a/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs b/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs index bd134d32..1094c861 100644 --- a/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs +++ b/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs @@ -1,9 +1,6 @@ -using System.Globalization; using System.Reflection; -using System.Text.RegularExpressions; using System.Text.Json; using System.Text.Json.Nodes; -using Json.Pointer; using Json.Schema; namespace AgentCore.Application.Configuration.Parsing; @@ -15,46 +12,22 @@ namespace AgentCore.Application.Configuration.Parsing; /// The schema ships as an embedded resource of this assembly. Checks 2 to 8 run after this one, on /// the bound records. /// -public static partial class ConfigurationSchemaValidator +public static class ConfigurationSchemaValidator { private const string ResourceName = "AgentCore.Application.Configuration.Schema.agentcore-v1.schema.json"; private static readonly Lazy LazySchemaJson = new(ReadResource); + private static readonly Lazy LazySchema = new(() => JsonSchema.FromText(LazySchemaJson.Value)); - private static readonly Lazy LazySchemaTree = new(() => JsonNode.Parse(LazySchemaJson.Value)!); private static readonly EvaluationOptions Options = new() { - // The list format walks the whole tree once and hands back every node flat, each with its own - // Details cleared. So Details is the answer, and nothing below it needs walking again. OutputFormat = OutputFormat.List, }; - /// - /// The keywords that only relay a child failure upwards. - /// - /// - /// Each of these says "something under here failed", and the thing that failed reports itself at - /// its own pointer. Repeating the parent gives the author a stack of sentences that name no - /// mistake. additionalProperties is not in the list because it has two meanings, and one - /// of them is the author's mistake — see . - /// - private static readonly HashSet RelayKeywords = new(StringComparer.Ordinal) - { - "properties", "patternProperties", "items", "prefixItems", "contains", - "allOf", "then", "else", "dependentSchemas", "dependentRequired", - }; - /// /// The schema keywords whose subschemas are asked a question rather than imposed as a rule. /// - /// - /// A failure inside one of these is how the keyword works, not a mistake in the document. An - /// if that does not match selects another branch; a oneOf branch that does not - /// match is the wrong branch; the subschema of a not is *supposed* to fail. Reporting - /// them told the author of a writer: tool slot that its writer should have been - /// counter, which is the opposite of help. The keyword itself still reports. - /// private static readonly HashSet SpeculativeKeywords = new(StringComparer.Ordinal) { "if", "not", "oneOf", "anyOf", "propertyNames", @@ -90,7 +63,7 @@ public static IReadOnlyList Evaluate(JsonNode document) var pointer = node.InstanceLocation.ToString(); foreach (var error in node.Errors) { - if (Describe(node, error.Key, error.Value) is not { } message) + if (SchemaFailureWording.Describe(node, error.Key, error.Value) is not { } message) { continue; } @@ -150,221 +123,15 @@ private static bool Speculative(EvaluationResults node) return false; } - /// Writes one failure as a sentence about the document, or drops it. - /// The evaluation node the failure came from. - /// The schema keyword that failed, or the empty string for a false schema. - /// The text the library wrote. - /// The message the author reads, or to drop the failure. - /// - /// The library writes for whoever wrote the schema: "All values fail against the false schema" - /// is exact and tells the author of a configuration document nothing. Each sentence here names - /// the rule the document broke. It deliberately does not quote the value that broke it — the - /// pointer already leads to it, and the value may be a whole block. - /// - private static string? Describe(EvaluationResults node, string keyword, string message) - { - if (RelayKeywords.Contains(keyword)) - { - return null; - } - - return keyword switch - { - // A `false` schema. The instance pointer ends in the key that is not allowed to be there. - "" => Name(node) is { Length: > 0 } name - ? $"the key '{name}' is not allowed here" - : "the schema allows nothing here", - - "required" => Names(message) is { Count: 1 } one - ? $"the required property '{one[0]}' is missing" - : $"the required properties {Quote(Names(message))} are missing", - - "additionalProperties" => DescribeAdditionalProperties(node, message), - - "type" => WrongTypePattern().Match(message) is { Success: true } wrong - ? $"the value is {wrong.Groups[1].Value}, and this key takes {wrong.Groups[2].Value}" - : $"the value has the wrong type. {message}", - - "enum" => Accepted(node, "enum") is { Count: > 0 } members - ? $"this key accepts only: {string.Join(", ", members)}" - : "the value is not one this key accepts", - - "const" => Accepted(node, "const") is { Count: 1 } only - ? $"this key is written exactly '{only[0]}', and nothing else" - : "the value is not the one this key holds", - - "pattern" => Keyword(node, "pattern")?.GetValue() switch - { - null => "the value is not written in the form this key requires", - @"\S" => "the text holds no words, and this key needs some", - var form => $"the text is not written in the form this key requires: {form}", - }, - - "minLength" or "maxLength" => Bound(message) is { } length - ? $"the text holds too {length.Way} characters, and this key takes at {length.Limit}" - : $"the text is the wrong length. {message}", - - "minItems" or "maxItems" => Bound(message) is { } count - ? $"the list holds too {count.Way} entries, and this key takes at {count.Limit}" - : $"the list is the wrong length. {message}", - - "uniqueItems" => "the list repeats a value, and every entry here must differ", - - "minimum" or "exclusiveMinimum" or "maximum" or "exclusiveMaximum" or "multipleOf" - => $"the number is outside the range this key accepts: {message}", - - // A composite the document has to satisfy exactly one way. The schema documents each way. - "oneOf" => Alternatives(node) is { Count: > 0 } shapes - ? $"this block matches none of the shapes allowed here: {string.Join("; ", shapes)}" - : "this block matches none of the shapes allowed here", - - // The rule this states is written on the schema node itself, because no keyword can say it. - "not" or "dependentRequired" => Documentation(node) ?? message, - - "propertyNames" => $"these key names are not names the schema accepts: {Quote(Names(message))}", - - // Anything the schema grows later still reports, with the keyword named. - _ => string.Create(CultureInfo.InvariantCulture, $"{message} [{keyword}]"), - }; - } - - /// Writes an additionalProperties failure, or drops it. - /// The evaluation node. - /// The text the library wrote. - /// The message the author reads, or to drop the failure. - /// - /// The keyword carries two different meanings. Against false it is the document's own - /// mistake — a key the schema does not know — and the parent pointer is where the author should - /// look. Against a schema, as state: and guards: use it, it only relays that one of - /// the values under the key failed, and that value reports itself. - /// - private static string? DescribeAdditionalProperties(EvaluationResults node, string message) - => Keyword(node, "additionalProperties") is JsonValue value && value.GetValueKind() == JsonValueKind.False - ? $"the schema does not know these keys here: {Quote(Names(message))}" - : null; - - /// Reads the last segment of the instance pointer, unescaped. - private static string Name(EvaluationResults node) - { - var location = node.InstanceLocation; - return location.SegmentCount == 0 ? string.Empty : location[location.SegmentCount - 1].ToString(); - } - - /// Reads the JSON array of names out of a library message. - private static List Names(string message) - { - var open = message.IndexOf('[', StringComparison.Ordinal); - var close = message.LastIndexOf(']'); - if (open < 0 || close <= open) - { - return []; - } - - try - { - return JsonNode.Parse(message[open..(close + 1)]) is JsonArray array - ? [.. array.Select(item => item?.GetValue() ?? string.Empty)] - : []; - } - catch (JsonException) - { - return []; - } - } - - private static string Quote(List names) - => names.Count == 0 ? "(none)" : string.Join(", ", names.Select(name => $"'{name}'")); - - /// Reads one keyword off the schema node the failure came from. - /// The evaluation node. - /// The keyword to read. - /// The keyword's value, or when the node cannot be resolved. - /// - /// The library reports where in the schema a failure happened, so the schema itself can answer - /// what the document should have written. A location it cannot resolve — the library indexes - /// some composite keywords in a form the document does not hold — falls back to a message that - /// needs no lookup. - /// - private static JsonNode? Keyword(EvaluationResults node, string keyword) - => Schema(node) is JsonObject schema && schema.TryGetPropertyValue(keyword, out var value) ? value : null; - - private static JsonObject? Schema(EvaluationResults node) - { - var fragment = node.SchemaLocation.Fragment; - if (fragment.Length == 0 || fragment[0] != '#' || !JsonPointer.TryParse(fragment[1..], out var pointer)) - { - return null; - } - - // The library indexes some keywords under a name of its own, so the location it reports may - // hold a segment the schema document does not. Walking up finds the nearest node that does - // exist; a walk that lands somewhere unhelpful simply holds no keyword to read, and the - // caller falls back to a sentence that needs no lookup. - for (var levels = 0; levels <= pointer.SegmentCount; levels++) - { - var candidate = levels == 0 ? pointer : pointer.GetParent(levels); - if (candidate is { } at && at.TryEvaluate(LazySchemaTree.Value, out var found) && found is JsonObject schema) - { - return schema; - } - } - - return null; - } - - /// Lists the values one key accepts, as the schema wrote them. - private static List Accepted(EvaluationResults node, string keyword) - => Keyword(node, keyword) switch - { - JsonArray array => [.. array.Select(Written)], - { } single => [Written(single)], - _ => [], - }; - - private static string Written(JsonNode? value) - => value is JsonValue text && text.GetValueKind() == JsonValueKind.String - ? text.GetValue() - : value?.ToJsonString() ?? "null"; - - /// Lists what each branch of a oneOf says about itself. - private static List Alternatives(EvaluationResults node) - => Keyword(node, "oneOf") is JsonArray branches - ? [.. branches - .Select(branch => (branch as JsonObject)?["description"]?.GetValue()) - .Where(description => !string.IsNullOrEmpty(description)) - .Select(description => description!)] - : []; - - /// Reads what the schema says about the rule this node carries. - private static string? Documentation(EvaluationResults node) - => Keyword(node, "description")?.GetValue() ?? Keyword(node, "$comment")?.GetValue(); - - /// Reads "at least 1 items" or "at most 3 items" out of a library message. - /// The text the library wrote. - /// Which way the bound runs and what it is, or when the message does not carry one. - private static (string Way, string Limit)? Bound(string message) - { - if (BoundPattern().Match(message) is not { Success: true } bound) - { - return null; - } - - var way = bound.Groups[1].Value == "least" ? "few" : "many"; - return (way, $"{bound.Groups[1].Value} {bound.Groups[2].Value}"); - } - private static string ReadResource() { var assembly = typeof(ConfigurationSchemaValidator).GetTypeInfo().Assembly; + using var stream = assembly.GetManifestResourceStream(ResourceName) ?? throw new InvalidOperationException($"The embedded resource '{ResourceName}' is missing from the assembly."); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); } - - [GeneratedRegex(@"^Value is ""([^""]+)"" but should be ""([^""]+)""$")] - private static partial Regex WrongTypePattern(); - - [GeneratedRegex(@"at (least|most) (\d+)")] - private static partial Regex BoundPattern(); } diff --git a/src/AgentCore.Application/Configuration/Parsing/SchemaFailureWording.cs b/src/AgentCore.Application/Configuration/Parsing/SchemaFailureWording.cs new file mode 100644 index 00000000..a43201e8 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Parsing/SchemaFailureWording.cs @@ -0,0 +1,228 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using Json.Pointer; +using Json.Schema; + +namespace AgentCore.Application.Configuration.Parsing; + +/// Writes one schema failure as a sentence about the document. +internal static partial class SchemaFailureWording +{ + private static readonly Lazy LazySchemaTree = new(() => JsonNode.Parse(ConfigurationSchemaValidator.SchemaJson)!); + + /// + /// The keywords that only relay a child failure upwards. + /// + private static readonly HashSet RelayKeywords = new(StringComparer.Ordinal) + { + "properties", "patternProperties", "items", "prefixItems", "contains", + "allOf", "then", "else", "dependentSchemas", "dependentRequired", + }; + + /// Writes one failure as a sentence about the document, or drops it. + /// The evaluation node the failure came from. + /// The schema keyword that failed, or the empty string for a false schema. + /// The text the library wrote. + /// The message the author reads, or to drop the failure. + public static string? Describe(EvaluationResults node, string keyword, string message) + { + if (RelayKeywords.Contains(keyword)) + { + return null; + } + + return keyword switch + { + "" => FalseSchema(node), + "required" => Required(message), + "additionalProperties" => AdditionalProperties(node, message), + "type" => WrongType(message), + "enum" => Enumerated(node), + "const" => Constant(node), + "pattern" => Pattern(node), + "minLength" or "maxLength" => Length(message, "text", "characters"), + "minItems" or "maxItems" => Length(message, "list", "entries"), + "uniqueItems" => "the list repeats a value, and every entry here must differ", + + "minimum" or "exclusiveMinimum" or "maximum" or "exclusiveMaximum" or "multipleOf" + => $"the number is outside the range this key accepts: {message}", + + "oneOf" => OneOf(node), + + // The rule this states is written on the schema node itself, because no keyword can say it. + "not" or "dependentRequired" => Documentation(node) ?? message, + + "propertyNames" => $"these key names are not names the schema accepts: {Quote(Names(message))}", + + // Anything the schema grows later still reports, with the keyword named. + _ => string.Create(CultureInfo.InvariantCulture, $"{message} [{keyword}]"), + }; + } + + /// A false schema. The instance pointer ends in the key that is not allowed to be there. + private static string FalseSchema(EvaluationResults node) + => Name(node) is { Length: > 0 } name + ? $"the key '{name}' is not allowed here" + : "the schema allows nothing here"; + + private static string Required(string message) + => Names(message) is { Count: 1 } one + ? $"the required property '{one[0]}' is missing" + : $"the required properties {Quote(Names(message))} are missing"; + + /// Writes an additionalProperties failure, or drops it. + /// The evaluation node. + /// The text the library wrote. + /// The message the author reads, or to drop the failure. + private static string? AdditionalProperties(EvaluationResults node, string message) + => Keyword(node, "additionalProperties") is JsonValue value && value.GetValueKind() == JsonValueKind.False + ? $"the schema does not know these keys here: {Quote(Names(message))}" + : null; + + private static string WrongType(string message) + => WrongTypePattern().Match(message) is { Success: true } wrong + ? $"the value is {wrong.Groups[1].Value}, and this key takes {wrong.Groups[2].Value}" + : $"the value has the wrong type. {message}"; + + private static string Enumerated(EvaluationResults node) + => Accepted(node, "enum") is { Count: > 0 } members + ? $"this key accepts only: {string.Join(", ", members)}" + : "the value is not one this key accepts"; + + private static string Constant(EvaluationResults node) + => Accepted(node, "const") is { Count: 1 } only + ? $"this key is written exactly '{only[0]}', and nothing else" + : "the value is not the one this key holds"; + + private static string Pattern(EvaluationResults node) + => Keyword(node, "pattern")?.GetValue() switch + { + null => "the value is not written in the form this key requires", + @"\S" => "the text holds no words, and this key needs some", + var form => $"the text is not written in the form this key requires: {form}", + }; + + /// Writes a length failure over , counted in . + private static string Length(string message, string what, string unit) + => Bound(message) is { } bound + ? $"the {what} holds too {bound.Way} {unit}, and this key takes at {bound.Limit}" + : $"the {what} is the wrong length. {message}"; + + /// A composite the document has to satisfy exactly one way. The schema documents each way. + private static string OneOf(EvaluationResults node) + => Alternatives(node) is { Count: > 0 } shapes + ? $"this block matches none of the shapes allowed here: {string.Join("; ", shapes)}" + : "this block matches none of the shapes allowed here"; + + /// Reads the last segment of the instance pointer, unescaped. + private static string Name(EvaluationResults node) + { + var location = node.InstanceLocation; + return location.SegmentCount == 0 ? string.Empty : location[location.SegmentCount - 1].ToString(); + } + + /// Reads the JSON array of names out of a library message. + private static List Names(string message) + { + var open = message.IndexOf('[', StringComparison.Ordinal); + var close = message.LastIndexOf(']'); + if (open < 0 || close <= open) + { + return []; + } + + try + { + return JsonNode.Parse(message[open..(close + 1)]) is JsonArray array + ? [.. array.Select(item => item?.GetValue() ?? string.Empty)] + : []; + } + catch (JsonException) + { + return []; + } + } + + private static string Quote(List names) + => names.Count == 0 ? "(none)" : string.Join(", ", names.Select(name => $"'{name}'")); + + /// Reads one keyword off the schema node the failure came from. + /// The evaluation node. + /// The keyword to read. + /// The keyword's value, or when the node cannot be resolved. + private static JsonNode? Keyword(EvaluationResults node, string keyword) + => Schema(node) is JsonObject schema && schema.TryGetPropertyValue(keyword, out var value) ? value : null; + + private static JsonObject? Schema(EvaluationResults node) + { + var fragment = node.SchemaLocation.Fragment; + if (fragment.Length == 0 || fragment[0] != '#' || !JsonPointer.TryParse(fragment[1..], out var pointer)) + { + return null; + } + + // The library indexes some keywords under a name of its own, so the location it reports may + // hold a segment the schema document does not. Walking up finds the nearest node that does + // exist; a walk that lands somewhere unhelpful simply holds no keyword to read, and the + // caller falls back to a sentence that needs no lookup. + for (var levels = 0; levels <= pointer.SegmentCount; levels++) + { + var candidate = levels == 0 ? pointer : pointer.GetParent(levels); + if (candidate is { } at && at.TryEvaluate(LazySchemaTree.Value, out var found) && found is JsonObject schema) + { + return schema; + } + } + + return null; + } + + /// Lists the values one key accepts, as the schema wrote them. + private static List Accepted(EvaluationResults node, string keyword) + => Keyword(node, keyword) switch + { + JsonArray array => [.. array.Select(Written)], + { } single => [Written(single)], + _ => [], + }; + + private static string Written(JsonNode? value) + => value is JsonValue text && text.GetValueKind() == JsonValueKind.String + ? text.GetValue() + : value?.ToJsonString() ?? "null"; + + /// Lists what each branch of a oneOf says about itself. + private static List Alternatives(EvaluationResults node) + => Keyword(node, "oneOf") is JsonArray branches + ? [.. branches + .Select(branch => (branch as JsonObject)?["description"]?.GetValue()) + .Where(description => !string.IsNullOrEmpty(description)) + .Select(description => description!)] + : []; + + /// Reads what the schema says about the rule this node carries. + private static string? Documentation(EvaluationResults node) + => Keyword(node, "description")?.GetValue() ?? Keyword(node, "$comment")?.GetValue(); + + /// Reads "at least 1 items" or "at most 3 items" out of a library message. + /// The text the library wrote. + /// Which way the bound runs and what it is, or when the message does not carry one. + private static (string Way, string Limit)? Bound(string message) + { + if (BoundPattern().Match(message) is not { Success: true } bound) + { + return null; + } + + var way = bound.Groups[1].Value == "least" ? "few" : "many"; + return (way, $"{bound.Groups[1].Value} {bound.Groups[2].Value}"); + } + + [GeneratedRegex(@"^Value is ""([^""]+)"" but should be ""([^""]+)""$")] + private static partial Regex WrongTypePattern(); + + [GeneratedRegex(@"at (least|most) (\d+)")] + private static partial Regex BoundPattern(); +} From abd43ee0230a9f2d52c50794817be02622efc240 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 01:59:27 -0600 Subject: [PATCH 26/35] feat(graph): enhance ExplicitGraphRow with improved node binding and edge handling --- .../Compilation/ExplicitGraphRow.cs | 182 ++++++++++-------- 1 file changed, 104 insertions(+), 78 deletions(-) diff --git a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs index 1044751f..c0e102c1 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs @@ -1,5 +1,6 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Workflows; @@ -26,40 +27,49 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( { var graph = entry.Graph!; var graphPointer = ConfigurationError.AppendPointer(entryPointer, "graph"); - var nodesPointer = ConfigurationError.AppendPointer(graphPointer, "nodes"); - var edgesPointer = ConfigurationError.AppendPointer(graphPointer, "edges"); + var (nodes, start, outputs) = BindNodes(graph, ConfigurationError.AppendPointer(graphPointer, "nodes"), agents); + var stateEntry = ExecutorBindingExtensions.BindExecutor(new GraphStateEntry()); + + WorkflowBuilder builder = new(stateEntry); + builder = builder.AddEdge(stateEntry, nodes[start]); + var (built, guarded) = AddEdges(builder, graph, ConfigurationError.AppendPointer(graphPointer, "edges"), nodes, context); + + if (outputs.Count > 0) + { + built = built.WithOutputFrom([.. outputs]); + } + + var compiled = built.WithName(entryName) + .Build() + .AsAIAgent(name: entryName); + + AIAgent withOutputCheck = new RequireOutputAgent(compiled, entryName); + + return ( + guarded ? new GraphStateAgent(withOutputCheck, entryName) : withOutputCheck, + NoStages()); + } + + /// Binds every node to its agent, and finds the one start node. + private static (Dictionary Nodes, string Start, List Outputs) BindNodes( + GraphConfiguration graph, + string nodesPointer, + Dictionary agents) + { Dictionary nodes = new(StringComparer.Ordinal); - List starts = []; + List starts = []; List outputs = []; for (var index = 0; index < graph.Nodes.Count; index++) { var node = graph.Nodes[index]; - var pointer = ConfigurationError.AppendPointer(nodesPointer, index); - - if (node.Agent is not { } agentId || !agents.TryGetValue(agentId, out var agent)) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "agent"), - $"the node '{node.Id}' names no declared agent, so nothing binds as its executor."); - } - - if (nodes.ContainsKey(node.Id)) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "id"), - $"the node id '{node.Id}' is declared twice."); - } - - // The measured shape: an agent binds as an executor, and the host emits update events so - // the wrapper can stream. Section 8.6. - var binding = new AIAgentBinding(agent, new AIAgentHostOptions { EmitAgentUpdateEvents = true }); + var binding = BindNode(node, ConfigurationError.AppendPointer(nodesPointer, index), agents, nodes); nodes[node.Id] = binding; if (node.Start) { - starts.Add(node); + starts.Add(node.Id); } if (node.Output) @@ -75,31 +85,51 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( $"the graph declares {starts.Count} start nodes. Check 7 of section 8.5 needs exactly one."); } - var stateEntry = ExecutorBindingExtensions.BindExecutor(new GraphStateEntry()); + return (nodes, starts[0], outputs); + } - WorkflowBuilder builder = new(stateEntry); - builder = builder.AddEdge(stateEntry, nodes[starts[0].Id]); + private static AIAgentBinding BindNode( + GraphNodeConfiguration node, + string pointer, + Dictionary agents, + Dictionary nodes) + { + if (node.Agent is not { } agentId || !agents.TryGetValue(agentId, out var agent)) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "agent"), + $"the node '{node.Id}' names no declared agent, so nothing binds as its executor."); + } + + if (nodes.ContainsKey(node.Id)) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "id"), + $"the node id '{node.Id}' is declared twice."); + } + + // The measured shape: an agent binds as an executor, and the host emits update events so + // the wrapper can stream. Section 8.6. + return new AIAgentBinding(agent, new AIAgentHostOptions { EmitAgentUpdateEvents = true }); + } + /// Adds every edge, with a gate in front of each guarded one. + /// The builder, and whether any edge carries a guard. + private static (WorkflowBuilder Builder, bool Guarded) AddEdges( + WorkflowBuilder builder, + GraphConfiguration graph, + string edgesPointer, + Dictionary nodes, + AgentCompilationContext context) + { var guarded = false; for (var index = 0; index < graph.Edges.Count; index++) { var edge = graph.Edges[index]; var pointer = ConfigurationError.AppendPointer(edgesPointer, index); - - if (!nodes.TryGetValue(edge.From, out var from)) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "from"), - $"the node '{edge.From}' is not declared."); - } - - if (!nodes.TryGetValue(edge.To, out var to)) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "to"), - $"the node '{edge.To}' is not declared."); - } + var from = Endpoint(nodes, edge.From, pointer, "from"); + var to = Endpoint(nodes, edge.To, pointer, "to"); if (edge.When is not { } guard) { @@ -107,51 +137,47 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( continue; } - if (context.Guards is not { } evaluator) - { - throw ConfigurationCompiler.Fail( - ConfigurationError.AppendPointer(pointer, "when"), - "the edge carries a guard, and the compilation context binds no guard evaluator. Bind " - + "AgentCompilationContext.Guards, which runs the rule. AddAgentCore binds it to " - + "GuardEvaluator. A guarded edge that silently became unconditional is exactly " - + "the silent graph failure section 8.2 refuses to ship."); - } - - // One gate per guarded edge, holding the run until its guard is true. The gate is a - // workflow executor rather than an edge predicate because the predicate only ever sees - // the edge message: per-call state reaches the gate through the run, filed by the - // graph-state entry. object, not List: the guard reads state, so every - // message on the edge takes the same answer and the turn token is not filtered out. - var gate = new FunctionExecutor( - $"agentcore-gate-{index}", - (message, gateContext, gateToken) => GraphGuardGate.RouteAsync( - message, gateContext, guard, evaluator, gateToken), - null, - [typeof(object)], - null, - true); - + var gate = Gate(index, guard, Evaluator(context, pointer)); builder = builder.AddEdge(from, gate); builder = builder.AddEdge(gate, to); guarded = true; } - if (outputs.Count > 0) - { - builder = builder.WithOutputFrom([.. outputs]); - } - - var compiled = builder.WithName(entryName) - .Build() - .AsAIAgent(name: entryName); - - AIAgent withOutputCheck = new RequireOutputAgent(compiled, entryName); - - return ( - guarded ? new GraphStateAgent(withOutputCheck, entryName) : withOutputCheck, - NoStages()); + return (builder, guarded); } + private static ExecutorBinding Endpoint(Dictionary nodes, string id, string pointer, string key) + => nodes.TryGetValue(id, out var node) + ? node + : throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, key), + $"the node '{id}' is not declared."); + + private static IGuardEvaluator Evaluator(AgentCompilationContext context, string pointer) + => context.Guards ?? throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "when"), + "the edge carries a guard, and the compilation context binds no guard evaluator. Bind " + + "AgentCompilationContext.Guards, which runs the rule. AddAgentCore binds it to " + + "GuardEvaluator. A guarded edge that silently became unconditional is exactly " + + "the silent graph failure section 8.2 refuses to ship."); + + /// + /// One gate per guarded edge, holding the run until its guard is true. The gate is a + /// workflow executor rather than an edge predicate because the predicate only ever sees + /// the edge message: per-call state reaches the gate through the run, filed by the + /// graph-state entry. object, not List<ChatMessage>: the guard reads state, so every + /// message on the edge takes the same answer and the turn token is not filtered out. + /// + private static FunctionExecutor Gate(int index, GuardReference guard, IGuardEvaluator evaluator) + => new( + $"agentcore-gate-{index}", + (message, gateContext, gateToken) => GraphGuardGate.RouteAsync( + message, gateContext, guard, evaluator, gateToken), + null, + [typeof(object)], + null, + true); + /// An explicit graph answers from its output: true nodes. internal override HashSet? SpokenAuthors(AgentCoreConfiguration configuration, EntryConfiguration entry) { From 7cd63ed6852cf0782d4140a573059a40e9cf3b80 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 02:05:09 -0600 Subject: [PATCH 27/35] feat(validation): refactor RecordComparison method for improved operand handling and introduce SplitOperands utility --- .../Validation/GuardRuleFacts.cs | 89 ++++++++++--------- 1 file changed, 46 insertions(+), 43 deletions(-) diff --git a/src/AgentCore.Application/Configuration/Validation/GuardRuleFacts.cs b/src/AgentCore.Application/Configuration/Validation/GuardRuleFacts.cs index b10f2df6..48af15c6 100644 --- a/src/AgentCore.Application/Configuration/Validation/GuardRuleFacts.cs +++ b/src/AgentCore.Application/Configuration/Validation/GuardRuleFacts.cs @@ -120,70 +120,73 @@ private void WalkOperator(string name, JsonNode? argument) private void RecordComparison(string name, List operands) { - var isComparison = GuardOperators.IsNumericComparison(name) - || string.Equals(name, "===", StringComparison.Ordinal) - || string.Equals(name, "!==", StringComparison.Ordinal) - || string.Equals(name, "in", StringComparison.Ordinal); - - if (!isComparison) + if (!IsComparison(name)) { return; } - var slots = new List(); - var literals = new List(); + var (slots, literals) = SplitOperands(operands); + var numeric = GuardOperators.IsNumericComparison(name); - foreach (var operand in operands) + foreach (var slot in slots) { - var slot = TryReadVariable(operand); - if (slot is not null) + if (numeric) { - slots.Add(slot); - continue; + NumericComparisons.Add(new KeyValuePair(name, slot)); } - switch (operand) + if (literals.Count > 0) { - case JsonValue value: - literals.Add(value); - break; - - case JsonArray members: - foreach (var member in members) - { - if (member is JsonValue memberValue) - { - literals.Add(memberValue); - } - } - - break; - - default: - break; + Bucket(slot).AddRange(literals); } } + } - foreach (var slot in slots) + private static bool IsComparison(string name) + => GuardOperators.IsNumericComparison(name) + || string.Equals(name, "===", StringComparison.Ordinal) + || string.Equals(name, "!==", StringComparison.Ordinal) + || string.Equals(name, "in", StringComparison.Ordinal); + + /// Sorts the operands of one comparison into the slots it reads and the literals it compares them with. + private static (List Slots, List Literals) SplitOperands(List operands) + { + var slots = new List(); + var literals = new List(); + + foreach (var operand in operands) { - if (GuardOperators.IsNumericComparison(name)) + if (TryReadVariable(operand) is { } slot) { - NumericComparisons.Add(new KeyValuePair(name, slot)); + slots.Add(slot); } - - if (literals.Count == 0) + else { - continue; + literals.AddRange(ScalarsOf(operand)); } + } - if (!Literals.TryGetValue(slot, out var bucket)) - { - bucket = []; - Literals[slot] = bucket; - } + return (slots, literals); + } + + /// Reads the scalars an operand holds: the value itself, or the scalar members of a list. + private static IEnumerable ScalarsOf(JsonNode? operand) + => operand switch + { + JsonValue value => [value], + JsonArray members => members.OfType(), + _ => [], + }; - bucket.AddRange(literals); + private List Bucket(string slot) + { + if (!Literals.TryGetValue(slot, out var bucket)) + { + bucket = []; + Literals[slot] = bucket; } + + return bucket; } private void AddVariable(string? name) From ede3ea5cb7e42c776ee6c490fc79c0fda7014ced Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 02:16:39 -0600 Subject: [PATCH 28/35] feat(compiler): refactor tool resolution logic to streamline undeclared and declared handling --- .../Compilation/AgentToolCompiler.cs | 82 ++++++++++++------- 1 file changed, 51 insertions(+), 31 deletions(-) diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs index ba866f98..64b172f8 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs @@ -1,6 +1,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Diagnostics; +using AgentCore.Application.Tools.Registry; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; using Microsoft.Extensions.Logging; @@ -26,47 +27,66 @@ internal static class AgentToolCompiler for (var index = 0; index < item.Tools.Count; index++) { var id = item.Tools[index]; - var toolPointer = ConfigurationError.AppendPointer( ConfigurationError.AppendPointer(pointer, "tools"), index); - if (!declared.TryGetValue(id, out var tool)) + if (Resolve(id, declared, context.Tools, resolveAgent, toolPointer) is { } tool) { - if (context.Tools is { } discovered && discovered.Contains(id)) - { - Add(tools, discovered.Resolve(id), item.Id, id, model, context); - continue; - } - - if (context.Tools is null) - { - // No factory, so nothing this loop could have built anyway. - continue; - } - - throw ConfigurationCompiler.Fail(toolPointer, $"the tool id '{id}' is not declared in tools:, and no tool source serves it."); + Add(tools, tool, item.Id, id, model, context); } + } - if (tool.Kind == ToolKind.Agent) - { - // A kind: agent tool needs no tool factory. Section 7 says section 8 adds no port, - // and this kind adds none either: the inner agent is already in the document. - Add(tools, AgentDelegationTool.Create(tool, ResolveInner(tool, resolveAgent, toolPointer)), item.Id, id, model, context); - continue; - } + return tools.Count == 0 ? null : tools; + } - if (context.Tools is { } registry) - { - if (!registry.Contains(id)) - { - throw ConfigurationCompiler.Fail(toolPointer, $"the tool id '{id}' is declared, and no tool source serves it."); - } + /// Finds the tool one id names, or when no source can build it. + private static AITool? Resolve( + string id, + Dictionary declared, + ToolRegistry? registry, + Func resolveAgent, + string pointer) + { + if (!declared.TryGetValue(id, out var tool)) + { + return Undeclared(id, registry, pointer); + } - Add(tools, registry.Resolve(id), item.Id, id, model, context); - } + if (tool.Kind == ToolKind.Agent) + { + // A kind: agent tool needs no tool factory. Section 7 says section 8 adds no port, + // and this kind adds none either: the inner agent is already in the document. + return AgentDelegationTool.Create(tool, ResolveInner(tool, resolveAgent, pointer)); } - return tools.Count == 0 ? null : tools; + return Declared(id, registry, pointer); + } + + /// An id that tools: does not declare. Only a registry that serves it can build it. + private static AITool? Undeclared(string id, ToolRegistry? registry, string pointer) + { + if (registry is null) + { + // No factory, so nothing could have been built anyway. + return null; + } + + return registry.Contains(id) + ? registry.Resolve(id) + : throw ConfigurationCompiler.Fail(pointer, $"the tool id '{id}' is not declared in tools:, and no tool source serves it."); + } + + /// An id that tools: declares. The registry, when there is one, has to serve it. + private static AITool? Declared(string id, ToolRegistry? registry, string pointer) + { + if (registry is null) + { + return null; + } + + return registry.Contains(id) + ? registry.Resolve(id) + : throw ConfigurationCompiler.Fail(pointer, $"the tool id '{id}' is declared, and no tool source serves it."); } /// Adds one tool, unless it is a hosted marker its agent's model cannot run. From 994bf65993d3abfdf55959225cac25b6757aa51c Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 02:20:50 -0600 Subject: [PATCH 29/35] feat(auditing): enhance tool result handling by adding Attach method and TakeFor functionality --- .../AuditingFunctionInvokingChatClient.cs | 57 ++++++++++--------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index 4d222801..3d1e437a 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -42,7 +42,14 @@ private sealed record Drain( TurnSources? Sources, TurnFiles? Files, Action? OnToolFailure, - bool Nested); + bool Nested) + { + /// Takes what one call drew, cited, and published, in that order. + public IEnumerable TakeFor(string callId) + => (Renders?.TakeFor(callId) ?? []) + .Concat(Sources?.TakeFor(callId) ?? []) + .Concat(Files?.TakeFor(callId) ?? []); + } /// Creates the client. /// The model this loop sends its rounds to. @@ -194,37 +201,33 @@ protected override IList CreateResponseMessages(ReadOnlySpan message.Contents)) + foreach (var message in messages) { - // Materialised before the loop below adds to the very list this reads: Contents is a - // List underneath, and its enumerator throws on the next MoveNext once - // anything has been appended, even where nothing further was left to enumerate. - foreach (var callId in contents.OfType().Select(r => r.CallId).ToList()) + Attach(message.Contents); + } + + return messages; + } + + /// Appends what each tool result in one message drew, cited, or published. + private void Attach(IList contents) + { + // Materialised before the loop below adds to the very list this reads: Contents is a + // List underneath, and its enumerator throws on the next MoveNext once + // anything has been appended, even where nothing further was left to enumerate. + foreach (var callId in contents.OfType().Select(r => r.CallId).ToList()) + { + // A nested loop's calls drain nothing: their ids were registered under the + // stripped copy, so removing the entry without draining keeps the outer drain + // from attaching a nested drawing to a message that never reaches the caller. + // Only the outermost loop's own calls attach what they drew or cited. + if (_drains.TryRemove(callId, out var drain) && !drain.Nested) { - // A nested loop's calls drain nothing: their ids were registered under the - // stripped copy, so removing the entry without draining keeps the outer drain - // from attaching a nested drawing to a message that never reaches the caller. - // Only the outermost loop's own calls attach what they drew or cited. - if (_drains.TryRemove(callId, out var drain) && !drain.Nested) + foreach (var attached in drain.TakeFor(callId)) { - foreach (var drawn in drain.Renders?.TakeFor(callId) ?? []) - { - contents.Add(drawn); - } - - foreach (var cited in drain.Sources?.TakeFor(callId) ?? []) - { - contents.Add(cited); - } - - foreach (var published in drain.Files?.TakeFor(callId) ?? []) - { - contents.Add(published); - } + contents.Add(attached); } } } - - return messages; } } From 3092cdf8e76aa2a4625e86788d2ad3ac9932e116 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 02:23:26 -0600 Subject: [PATCH 30/35] feat(compiler): refactor graph and agent selection logic into dedicated methods for improved clarity --- .../Compilation/ConfigurationCompiler.cs | 66 +++++++++++-------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index 17a4eb7c..a58147a4 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -75,27 +75,7 @@ internal static CompileTableRow SelectEntryRow(EntryConfiguration entry, string if (hasGraph) { - var graph = entry.Graph!; - var graphPointer = ConfigurationError.AppendPointer(entryPointer, "graph"); - var hasPattern = graph.Pattern is not null; - var hasNodes = graph.Nodes.Count > 0 || graph.Edges.Count > 0; - - if (hasPattern && hasNodes) - { - throw Fail(graphPointer, "the graph holds both pattern: and nodes:. It holds one or the other."); - } - - if (hasPattern) - { - return PatternGraphRow.Instance; - } - - if (hasNodes) - { - return ExplicitGraphRow.Instance; - } - - throw Fail(graphPointer, "the graph declares neither pattern: nor nodes: and edges:."); + return SelectGraphRow(entry.Graph!, ConfigurationError.AppendPointer(entryPointer, "graph")); } if (hasPolicy) @@ -105,14 +85,7 @@ internal static CompileTableRow SelectEntryRow(EntryConfiguration entry, string if (hasAgent) { - if (entry.Agent!.Length == 0) - { - throw Fail( - ConfigurationError.AppendPointer(entryPointer, "agent"), - "the entry holds an empty agent:. It names one agents.items id."); - } - - return SingleAgentRow.Instance; + return SelectSingleAgentRow(entry.Agent!, ConfigurationError.AppendPointer(entryPointer, "agent")); } throw Fail( @@ -120,6 +93,41 @@ internal static CompileTableRow SelectEntryRow(EntryConfiguration entry, string "the entry holds none of agent:, policy:, and graph:, so it compiles to nothing."); } + /// Picks the graph row: pattern: or nodes: and edges:, never both, never neither. + private static CompileTableRow SelectGraphRow(GraphConfiguration graph, string graphPointer) + { + var hasPattern = graph.Pattern is not null; + var hasNodes = graph.Nodes.Count > 0 || graph.Edges.Count > 0; + + if (hasPattern && hasNodes) + { + throw Fail(graphPointer, "the graph holds both pattern: and nodes:. It holds one or the other."); + } + + if (hasPattern) + { + return PatternGraphRow.Instance; + } + + if (hasNodes) + { + return ExplicitGraphRow.Instance; + } + + throw Fail(graphPointer, "the graph declares neither pattern: nor nodes: and edges:."); + } + + /// Picks the single-agent row, once agent: names an id. + private static SingleAgentRow SelectSingleAgentRow(string agentId, string agentPointer) + { + if (agentId.Length == 0) + { + throw Fail(agentPointer, "the entry holds an empty agent:. It names one agents.items id."); + } + + return SingleAgentRow.Instance; + } + /// Compiles one document into one agent per entry. /// The loaded document. /// The seams the document names. From e19b21e7b82b401c71ab614ea67926a20cca6783 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 02:30:06 -0600 Subject: [PATCH 31/35] feat(compiler): introduce new compilation structures and refactor BuildEntry method for improved clarity and functionality --- .../Compilation/CompileTableRow.cs | 2 +- .../Compilation/CompiledAgent.cs | 58 +++++++-------- .../Compilation/CompiledAgentSet.cs | 14 ++++ .../Compilation/CompiledDocument.cs | 14 ++++ .../Compilation/ConfigurationCompiler.cs | 72 +++++-------------- .../Configuration/Compilation/EntryBuild.cs | 8 +++ .../Compilation/ExplicitGraphRow.cs | 4 +- .../Compilation/PatternGraphRow.cs | 4 +- .../Configuration/Compilation/PolicyRow.cs | 4 +- .../Compilation/SingleAgentRow.cs | 4 +- .../Configuration/Compilation/TurnLayers.cs | 29 ++++++++ 11 files changed, 117 insertions(+), 96 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/CompiledAgentSet.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/CompiledDocument.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/EntryBuild.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/TurnLayers.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs b/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs index c318e4cd..5f6186b4 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs @@ -26,7 +26,7 @@ internal abstract class CompileTableRow /// The seams the document names. /// The agent a turn runs, and the agent id each policy.stages entry names. /// The entry does not compile through this row. - internal abstract (AIAgent Entry, Dictionary Stages) BuildEntry( + internal abstract EntryBuild BuildEntry( AgentCoreConfiguration configuration, string entryName, EntryConfiguration entry, diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs index 8661c426..1001d5a6 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs @@ -18,53 +18,49 @@ public sealed class CompiledAgent private readonly Dictionary _turnByAgentId; -#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. + /// Compiles one entry: its row's build, with the turn layers on every agent a turn runs. + /// What every entry of the document shares. + /// The entry key. It is the agent's name. + /// The entry's stage machine, or when it holds none. + /// The row of the compile table the entry selected. + /// What the row built for the entry. + /// The agents.items entries the row built on. + /// The turn layers of the entry. internal CompiledAgent( - AgentCoreConfiguration configuration, + CompiledDocument document, string entryName, PolicyConfiguration? policy, - string fallbackReply, - string refusalReply, CompileTableRow row, - IConversationStore conversations, - AIAgent entry, - Dictionary byAgentId, - Dictionary agentIdByStage, - IReadOnlySet? spokenBy, - AgentCoreChatHistoryProvider history, - IReadOnlySet harnessStateKeys, - IReadOnlyList backgroundProviders, - Func turnLayers) + EntryBuild build, + CompiledAgentSet agents, + TurnLayers layers) { ArgumentException.ThrowIfNullOrEmpty(entryName); - ArgumentNullException.ThrowIfNull(fallbackReply); - ArgumentNullException.ThrowIfNull(refusalReply); - Configuration = configuration; + Configuration = document.Configuration; EntryName = entryName; Policy = policy; - FallbackReply = fallbackReply; - RefusalReply = refusalReply; + FallbackReply = layers.FallbackReply; + RefusalReply = layers.RefusalReply; Shape = row.Shape; SessionCarriesHistory = row.SessionCarriesHistory; - Agent = entry; - ConversationStore = conversations; - SpokenBy = spokenBy; - History = history; - HarnessStateKeys = harnessStateKeys; - BackgroundProviders = backgroundProviders; - _byAgentId = byAgentId; - _agentIdByStage = agentIdByStage; - - TurnAgent = turnLayers(entry); + Agent = build.Agent; + ConversationStore = document.Conversations; + SpokenBy = layers.SpokenBy; + History = document.History; + HarnessStateKeys = agents.HarnessStateKeys; + BackgroundProviders = agents.BackgroundProviders; + _byAgentId = agents.Agents; + _agentIdByStage = build.Stages; + + TurnAgent = layers.Apply(build.Agent); _turnByAgentId = new Dictionary(StringComparer.Ordinal); - foreach (var (id, agent) in byAgentId) + foreach (var (id, agent) in agents.Agents) { - _turnByAgentId[id] = turnLayers(agent); + _turnByAgentId[id] = layers.Apply(agent); } } -#pragma warning restore MAAI001 /// /// Gets whether the row answers its runs out of store 1 on its own session, rather than the diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentSet.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentSet.cs new file mode 100644 index 00000000..0c108f2c --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentSet.cs @@ -0,0 +1,14 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. +/// The agents.items entries one build produced, and what every one of them declared. +/// The compiled agents, keyed by id. +/// The union of every harness provider's state keys. Never the history provider's key. +/// Every background provider, for the conversation-end release. +internal sealed record CompiledAgentSet( + Dictionary Agents, + IReadOnlySet HarnessStateKeys, + IReadOnlyList BackgroundProviders); +#pragma warning restore MAAI001 diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledDocument.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledDocument.cs new file mode 100644 index 00000000..87fb4370 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledDocument.cs @@ -0,0 +1,14 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; + +namespace AgentCore.Application.Configuration.Compilation; + +/// What every entry of one document shares once compiled. +/// The loaded document. +/// The store every conversation and every word of it is kept in. +/// Store 1, over . +internal sealed record CompiledDocument( + AgentCoreConfiguration Configuration, + IConversationStore Conversations, + AgentCoreChatHistoryProvider History); diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index a58147a4..f3aab4ec 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -1,7 +1,6 @@ using AgentCore.Application.Conversation.Memory; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Evaluation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.Application.Transcript; @@ -133,7 +132,6 @@ private static SingleAgentRow SelectSingleAgentRow(string agentId, string agentP /// The seams the document names. /// The compiled agents, keyed by entry name. Each is a process singleton: see T44. /// An entry does not compile. -#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. public static IReadOnlyDictionary CompileAll( AgentCoreConfiguration configuration, AgentCompilationContext context) @@ -142,11 +140,9 @@ public static IReadOnlyDictionary CompileAll( ArgumentNullException.ThrowIfNull(context); IConversationStore conversations = context.ConversationStore ?? new InMemoryConversationStore(); + CompiledDocument document = new(configuration, conversations, new AgentCoreChatHistoryProvider(conversations)); - AgentCoreChatHistoryProvider history = new(conversations); - - Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders)> built = new(StringComparer.Ordinal); - + Dictionary built = new(StringComparer.Ordinal); Dictionary compiled = new(StringComparer.Ordinal); foreach (var (entryName, entry) in configuration.Entries) @@ -158,58 +154,22 @@ public static IReadOnlyDictionary CompileAll( var key = shape == CompiledAgentShape.SingleAgent || shape == CompiledAgentShape.Policy ? "session" : shape.ToString(); if (!built.TryGetValue(key, out var shared)) { - shared = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null); + shared = BuildAgents(configuration, context, row.SessionCarriesHistory ? document.History : null); built[key] = shared; } - var (entryAgent, stages) = row.BuildEntry(configuration, entryName, entry, entryPointer, shared.Agents, context); - - var spokenBy = row.SpokenAuthors(configuration, entry); - - var fallbackReply = entry.FallbackReply ?? configuration.FallbackReply; - var refusalReply = entry.RefusalReply ?? configuration.RefusalReply; - - compiled[entryName] = new CompiledAgent( - configuration, - entryName, - entry.Policy, - fallbackReply, - refusalReply, - row, - conversations, - entryAgent, - shared.Agents, - stages, - spokenBy, - history, - shared.HarnessStateKeys, - shared.BackgroundProviders, - inner => WithTurnDisposition(inner, fallbackReply, refusalReply, context.Moderation, spokenBy)); - } + var build = row.BuildEntry(configuration, entryName, entry, entryPointer, shared.Agents, context); - return compiled; - } -#pragma warning restore MAAI001 + TurnLayers layers = new( + entry.FallbackReply ?? configuration.FallbackReply, + entry.RefusalReply ?? configuration.RefusalReply, + context.Moderation, + row.SpokenAuthors(configuration, entry)); - /// Puts the two turn-disposition layers on one agent a turn runs. - /// The compiled agent of one entry, or of one policy: stage. - /// The resolved line the caller hears when a turn fails. - /// The resolved line the caller hears when the agent refuses to answer. - /// The endpoint seam, or to moderate nothing. - /// The agents whose reply the caller hears, or for all. - /// The agent the turn loop runs. - private static AIAgent WithTurnDisposition( - AIAgent agent, - string fallbackReply, - string refusalReply, - PromptModerator? moderation, - IReadOnlySet? spokenBy) - { - AIAgent layered = new FallbackAgent(agent, fallbackReply, spokenBy); + compiled[entryName] = new CompiledAgent(document, entryName, entry.Policy, row, build, shared, layers); + } - return moderation is null - ? layered - : new ModerationAgent(layered, moderation, refusalReply, ModerationAgent.DefaultTimeout); + return compiled; } #pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. @@ -217,8 +177,8 @@ private static AIAgent WithTurnDisposition( /// The loaded document. /// The seams the document names. /// Store 1, or to leave the framework default in place. - /// The agents keyed by id, the union of every harness provider's state keys, and every background provider for the conversation-end release. - private static (Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders) BuildAgents( + /// The agents keyed by id, with what every one of them declared. + private static CompiledAgentSet BuildAgents( AgentCoreConfiguration configuration, AgentCompilationContext context, AgentCoreChatHistoryProvider? history) @@ -228,7 +188,7 @@ private static (Dictionary Agents, IReadOnlySet Harness List backgroundProviders = []; if (configuration.Agents is not { } section) { - return (agents, harnessStateKeys, backgroundProviders); + return new CompiledAgentSet(agents, harnessStateKeys, backgroundProviders); } var clarification = ResolvedClarification.From(configuration); @@ -261,7 +221,7 @@ private static (Dictionary Agents, IReadOnlySet Harness Resolve(item.Id); } - return (agents, harnessStateKeys, backgroundProviders); + return new CompiledAgentSet(agents, harnessStateKeys, backgroundProviders); AIAgent? Resolve(string id) { diff --git a/src/AgentCore.Application/Configuration/Compilation/EntryBuild.cs b/src/AgentCore.Application/Configuration/Compilation/EntryBuild.cs new file mode 100644 index 00000000..6a8187db --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/EntryBuild.cs @@ -0,0 +1,8 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +/// What one compile-table row built for one entry. +/// The agent a turn runs. +/// The agent id each policy.stages entry names. Empty for a row with no stages. +internal sealed record EntryBuild(AIAgent Agent, Dictionary Stages); diff --git a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs index c0e102c1..bc951a19 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs @@ -17,7 +17,7 @@ internal sealed class ExplicitGraphRow : CompileTableRow internal override CompiledAgentShape Shape => CompiledAgentShape.ExplicitGraph; - internal override (AIAgent Entry, Dictionary Stages) BuildEntry( + internal override EntryBuild BuildEntry( AgentCoreConfiguration configuration, string entryName, EntryConfiguration entry, @@ -46,7 +46,7 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( AIAgent withOutputCheck = new RequireOutputAgent(compiled, entryName); - return ( + return new EntryBuild( guarded ? new GraphStateAgent(withOutputCheck, entryName) : withOutputCheck, NoStages()); } diff --git a/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs b/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs index 5b4ee85e..41bb2735 100644 --- a/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs @@ -16,7 +16,7 @@ internal sealed class PatternGraphRow : CompileTableRow internal override CompiledAgentShape Shape => CompiledAgentShape.PatternGraph; - internal override (AIAgent Entry, Dictionary Stages) BuildEntry( + internal override EntryBuild BuildEntry( AgentCoreConfiguration configuration, string entryName, EntryConfiguration entry, @@ -55,7 +55,7 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( _ => BuildGroupChat(entryName, participants), }; - return (workflow.AsAIAgent(name: entryName), NoStages()); + return new EntryBuild(workflow.AsAIAgent(name: entryName), NoStages()); } /// diff --git a/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs b/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs index 3cbda430..422d6932 100644 --- a/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs @@ -19,7 +19,7 @@ internal sealed class PolicyRow : CompileTableRow internal override bool SessionCarriesHistory => true; - internal override (AIAgent Entry, Dictionary Stages) BuildEntry( + internal override EntryBuild BuildEntry( AgentCoreConfiguration configuration, string entryName, EntryConfiguration entry, @@ -67,6 +67,6 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( $"the initial stage '{policy.Initial}' names no agent, so no turn can run."); } - return (agents[initialAgent], stages); + return new EntryBuild(agents[initialAgent], stages); } } diff --git a/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs b/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs index 02e26d52..da1b7041 100644 --- a/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs @@ -16,7 +16,7 @@ internal sealed class SingleAgentRow : CompileTableRow internal override bool SessionCarriesHistory => true; - internal override (AIAgent Entry, Dictionary Stages) BuildEntry( + internal override EntryBuild BuildEntry( AgentCoreConfiguration configuration, string entryName, EntryConfiguration entry, @@ -40,6 +40,6 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( $"the entry '{entryName}' names the agent '{agentId}', which agents.items does not declare."); } - return (agent, NoStages()); + return new EntryBuild(agent, NoStages()); } } diff --git a/src/AgentCore.Application/Configuration/Compilation/TurnLayers.cs b/src/AgentCore.Application/Configuration/Compilation/TurnLayers.cs new file mode 100644 index 00000000..d844953e --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/TurnLayers.cs @@ -0,0 +1,29 @@ +using AgentCore.Application.Evaluation; +using AgentCore.Application.Runtime; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +/// The two turn-disposition layers one entry puts on every agent a turn runs. +/// The resolved line the caller hears when a turn fails. +/// The resolved line the caller hears when the agent refuses to answer. +/// The endpoint seam, or to moderate nothing. +/// The agents whose reply the caller hears, or for all. +internal sealed record TurnLayers( + string FallbackReply, + string RefusalReply, + PromptModerator? Moderation, + IReadOnlySet? SpokenBy) +{ + /// Puts the layers on one agent. + /// The compiled agent of one entry, or of one policy: stage. + /// The agent the turn loop runs. + public AIAgent Apply(AIAgent agent) + { + AIAgent layered = new FallbackAgent(agent, FallbackReply, SpokenBy); + + return Moderation is null + ? layered + : new ModerationAgent(layered, Moderation, RefusalReply, ModerationAgent.DefaultTimeout); + } +} From 2f3cf0d40ee988c5388835a66015ef89de6d6c11 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 15:17:46 -0600 Subject: [PATCH 32/35] Refactor Turn Invocation Handling and Introduce ITurnAttachments Interface --- .../AgentContextProviderCompiler.cs | 28 ++-- .../Compilation/AgentDelegationTool.cs | 4 +- .../Configuration/Compilation/AgentsWalk.cs | 17 +++ .../Compilation/ConfigurationCompiler.cs | 18 +-- .../Validation/ExitExclusivityCheck.cs | 18 +-- .../Validation/GuardExclusivityCheck.cs | 17 +-- .../Configuration/Validation/SiblingGroup.cs | 14 ++ .../Knowledge/ClaimedProbe.cs | 9 ++ .../Knowledge/FacetFilteredSearch.cs | 4 +- .../Knowledge/KnowledgeAuditRecord.cs | 6 +- .../Knowledge/KnowledgeBinding.cs | 18 +++ .../Knowledge/KnowledgeProbe.cs | 129 ++++++++---------- .../Knowledge/KnowledgeProviderFactory.cs | 2 +- .../Knowledge/KnowledgeSearch.cs | 28 ++-- .../Knowledge/KnowledgeSearchRecord.cs | 1 - .../Knowledge/ProbeWiring.cs | 32 +++++ .../AuditingFunctionInvokingChatClient.cs | 36 ++--- .../Runtime/ConversationEventChain.cs | 28 ++-- .../Runtime/ConversationSession.cs | 12 +- .../ConversationTurnCommit.cs | 10 +- .../Runtime/ConversationSessionFactory.cs | 24 +--- .../Runtime/ConversationSessionSeams.cs | 19 +++ .../Runtime/Turn/ITurnAttachments.cs | 24 ++++ .../Runtime/Turn/OuterCall.cs | 24 ++++ .../Runtime/Turn/TurnAttachments.cs | 9 +- .../Runtime/TurnInvocation.cs | 34 ++++- .../Tools/Binding/ToolParameterBindings.cs | 6 +- .../DependencyInjection/AgentCoreBoot.cs | 33 +++-- .../Startup/CompilationStartup.cs | 65 ++------- .../Startup/ToolRegistryStartup.cs | 23 ++-- .../ClarificationWiringBindingTests.cs | 5 +- .../Knowledge/FacetFilterTests.cs | 17 +-- .../Knowledge/KnowledgeAuditRecordTests.cs | 22 +-- .../Knowledge/KnowledgeProbeTests.cs | 5 +- .../KnowledgeProviderFactoryTests.cs | 5 +- ...nctionInvokingChatClientCallRecordTests.cs | 51 +++++++ .../Tools/FilePublishToolDefinitionTests.cs | 8 +- .../Tools/TypedBindingToolTests.cs | 20 ++- .../ToolRegistryStartupTests.cs | 9 +- 39 files changed, 465 insertions(+), 369 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentsWalk.cs create mode 100644 src/AgentCore.Application/Configuration/Validation/SiblingGroup.cs create mode 100644 src/AgentCore.Application/Knowledge/ClaimedProbe.cs create mode 100644 src/AgentCore.Application/Knowledge/KnowledgeBinding.cs create mode 100644 src/AgentCore.Application/Knowledge/ProbeWiring.cs create mode 100644 src/AgentCore.Application/Runtime/ConversationSessionSeams.cs create mode 100644 src/AgentCore.Application/Runtime/Turn/ITurnAttachments.cs create mode 100644 src/AgentCore.Application/Runtime/Turn/OuterCall.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientCallRecordTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index 374edb47..e1247b8e 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -7,7 +7,6 @@ using AgentCore.Application.Skills; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Compaction; -using Microsoft.Extensions.AI; namespace AgentCore.Application.Configuration.Compilation; internal static class AgentContextProviderCompiler @@ -18,22 +17,20 @@ internal static class AgentContextProviderCompiler /// private static readonly SourceLocatorCitationFormatter DefaultCitations = new(); - /// - /// Builds the context providers of one agent. is the document's - /// ambiguity wiring (§8), the same for every agent — built once by the caller rather than - /// re-derived per agent. - /// -#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. + /// Builds the context providers of one agent. + /// What every agent of this walk shares. + /// The agent being compiled. + /// The compile-time seams. + /// This agent's JSON pointer. + /// Resolves an agents.items id to its compiled agent, or when undeclared. public static List Build( - AgentDefaults? defaults, + AgentsWalk walk, AgentConfiguration item, AgentCompilationContext context, string pointer, - ResolvedClarification clarification, - KnowledgeScopeConfiguration? scope, - Func resolve, - ICollection? background = null) + Func resolve) { + var defaults = walk.Defaults; List providers = []; if (item.Pinned.Count > 0) @@ -71,7 +68,7 @@ public static List Build( #pragma warning restore MAAI001 } - AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background); + AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, walk.Background); if (AgentKnowledge.Compose(defaults, item) is not { } composed) { @@ -90,7 +87,7 @@ public static List Build( // The document-level wiring, carried onto this agent's own resolved knowledge so the search // side does not have to re-derive it. - var knowledge = composed with { Clarification = clarification }; + var knowledge = composed with { Clarification = walk.Clarification }; providers.Add(KnowledgeProviderFactory.Create( port, @@ -98,11 +95,10 @@ public static List Build( item.Id, context.Citations ?? DefaultCitations, context.Loggers, - scope)); + walk.Scope)); return providers; } -#pragma warning restore MAAI001 private static SkillCatalog RequireCatalog(AgentConfiguration item, AgentCompilationContext context, string pointer, string key) { diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs index 19c7b12a..a6140b1f 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs @@ -82,9 +82,7 @@ public override JsonElement JsonSchema { ArgumentNullException.ThrowIfNull(arguments); - var parent = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var turn) && turn is TurnInvocation p - ? p - : null; + var parent = TurnInvocation.FiledIn(arguments); // Schemaless the donor advertises one query string; declared, the payload the // document shaped. Either way the nested agent reads words, not arguments. diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentsWalk.cs b/src/AgentCore.Application/Configuration/Compilation/AgentsWalk.cs new file mode 100644 index 00000000..cf2b78c1 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentsWalk.cs @@ -0,0 +1,17 @@ +using AgentCore.Application.Configuration.Schema; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. +/// What one walk over agents.items shares between every agent it compiles. +/// The agents.defaults section, or . +/// The document's ambiguity wiring (§8), built once rather than re-derived per agent. +/// The providers.knowledge.scope block, or . +/// Collects the built background providers, so the conversation can release their sessions when it ends. +internal sealed record AgentsWalk( + AgentDefaults? Defaults, + ResolvedClarification Clarification, + KnowledgeScopeConfiguration? Scope, + ICollection Background); +#pragma warning restore MAAI001 diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index f3aab4ec..d046fcd2 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -191,8 +191,6 @@ private static CompiledAgentSet BuildAgents( return new CompiledAgentSet(agents, harnessStateKeys, backgroundProviders); } - var clarification = ResolvedClarification.From(configuration); - Dictionary tools = new(StringComparer.Ordinal); foreach (var tool in configuration.Tools) { @@ -216,6 +214,12 @@ private static CompiledAgentSet BuildAgents( // compile error rather than a stack overflow. List path = []; + AgentsWalk walk = new( + section.Defaults, + ResolvedClarification.From(configuration), + configuration.Providers?.Knowledge?.Scope, + backgroundProviders); + foreach (var item in section.Items) { Resolve(item.Id); @@ -254,15 +258,7 @@ private static CompiledAgentSet BuildAgents( var compiledTools = AgentToolCompiler.Build( item, item.Model ?? section.Defaults?.Model, tools, context, pointer, Resolve); - var providers = AgentContextProviderCompiler.Build( - section.Defaults, - item, - context, - pointer, - clarification, - configuration.Providers?.Knowledge?.Scope, - Resolve, - backgroundProviders); + var providers = AgentContextProviderCompiler.Build(walk, item, context, pointer, Resolve); harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); harnessStateKeys.UnionWith(AgentApproval.StateKeysFor(section.Defaults, item, compiledTools)); diff --git a/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs b/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs index 6db5853a..06ff8545 100644 --- a/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/ExitExclusivityCheck.cs @@ -53,12 +53,13 @@ private static void CheckStages( }; GuardExclusivityCheck.Run( - exits, - ConfigurationError.AppendPointer(ValidationPointer.Stage(name, index), "to"), - $"the stage '{stage.Id}'", + new SiblingGroup( + exits, + ConfigurationError.AppendPointer(ValidationPointer.Stage(name, index), "to"), + $"the stage '{stage.Id}'", + pinned), evaluator, configuration.State, - pinned, errors, warnings); } @@ -83,12 +84,13 @@ private static void CheckNodes( .ToList(); GuardExclusivityCheck.Run( - exits, - ValidationPointer.GraphEdges(name), - $"the node '{group.Key}'", + new SiblingGroup( + exits, + ValidationPointer.GraphEdges(name), + $"the node '{group.Key}'", + new Dictionary(StringComparer.Ordinal)), evaluator, configuration.State, - new Dictionary(StringComparer.Ordinal), errors, warnings); } diff --git a/src/AgentCore.Application/Configuration/Validation/GuardExclusivityCheck.cs b/src/AgentCore.Application/Configuration/Validation/GuardExclusivityCheck.cs index c0ba4250..1c0c614d 100644 --- a/src/AgentCore.Application/Configuration/Validation/GuardExclusivityCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/GuardExclusivityCheck.cs @@ -23,24 +23,19 @@ internal sealed record SiblingExit(string Description, string Pointer, GuardRefe internal static class GuardExclusivityCheck { /// Runs check 5 over one group of siblings. - /// The siblings, in document order. - /// The JSON Pointer to the group, used by the coverage warning. - /// How the warning names the group. + /// The siblings, and what the group already fixes. /// The evaluator that resolves and runs a rule. /// The declared state slots. - /// Slots whose value the group already fixes, such as stage. /// Receives an overlap error. /// Receives a partial-coverage warning. public static void Run( - IReadOnlyList exits, - string groupPointer, - string groupDescription, + SiblingGroup group, GuardEvaluator evaluator, IReadOnlyDictionary slots, - IReadOnlyDictionary pinned, List errors, List warnings) { + var exits = group.Exits; if (exits.Count < 2) { // One exit cannot overlap a sibling, and no exit is check 6's concern. @@ -55,7 +50,7 @@ public static void Run( facts.Collect(rules[index]); } - var domains = StateDomain.Build(facts, slots, pinned); + var domains = StateDomain.Build(facts, slots, group.Pinned); var total = StateDomain.CountPoints(domains); IEnumerable> points; @@ -64,10 +59,10 @@ public static void Run( points = StateDomain.Sample(domains, StateDomain.MaximumPoints); warnings.Add(new ConfigurationError { - Pointer = groupPointer, + Pointer = group.Pointer, Message = string.Create( CultureInfo.InvariantCulture, - $"the state domain of {groupDescription} passes {StateDomain.MaximumPoints} points, so check 5 sampled {StateDomain.MaximumPoints} points at random and its coverage is partial"), + $"the state domain of {group.Description} passes {StateDomain.MaximumPoints} points, so check 5 sampled {StateDomain.MaximumPoints} points at random and its coverage is partial"), Check = ConfigurationCheck.GuardExclusivity, }); } diff --git a/src/AgentCore.Application/Configuration/Validation/SiblingGroup.cs b/src/AgentCore.Application/Configuration/Validation/SiblingGroup.cs new file mode 100644 index 00000000..28888180 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/SiblingGroup.cs @@ -0,0 +1,14 @@ +using System.Text.Json.Nodes; + +namespace AgentCore.Application.Configuration.Validation; + +/// One group of siblings check 5 reads together: the exits of one stage, or the edges out of one node. +/// The siblings, in document order. +/// The JSON Pointer to the group, used by the coverage warning. +/// How the warning names the group. +/// Slots whose value the group already fixes, such as stage. +internal sealed record SiblingGroup( + IReadOnlyList Exits, + string Pointer, + string Description, + IReadOnlyDictionary Pinned); diff --git a/src/AgentCore.Application/Knowledge/ClaimedProbe.cs b/src/AgentCore.Application/Knowledge/ClaimedProbe.cs new file mode 100644 index 00000000..f30888b8 --- /dev/null +++ b/src/AgentCore.Application/Knowledge/ClaimedProbe.cs @@ -0,0 +1,9 @@ +using AgentCore.Application.Runtime; + +namespace AgentCore.Application.Knowledge; + +/// The one probe this turn won, and the facet it is about to drop. +/// The conversation's ambiguity holder. +/// The latch this caller won. Every way out publishes or fails it. +/// The facet the probe drops, and charges. +internal sealed record ClaimedProbe(Clarifications Clarifications, Clarifications.Probe Probe, string Facet); diff --git a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs index 70917f98..637a001e 100644 --- a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs +++ b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs @@ -53,9 +53,7 @@ internal FacetFilteredSearch( ? FacetFilterReader.Read(arguments, _facets) : null; - var turn = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var filed) && filed is TurnInvocation invocation - ? invocation - : null; + var turn = TurnInvocation.FiledIn(arguments); // The donor's own declaration names the question: the model was built against it. var question = FirstQueryArgument(InnerFunction.JsonSchema) is { } name diff --git a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs index b727e429..d9c09437 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs @@ -42,8 +42,11 @@ internal sealed record KnowledgeAuditRecord public string? Failure { get; init; } /// Builds the record of one retrieval. + /// + /// stays empty: the provider that writes this record can reach no conversation + /// id and no turn index, and a synthesised one would read as real to whoever greps for it. + /// public static KnowledgeAuditRecord For( - string? turnId, string agent, KnowledgeMode mode, string query, @@ -58,7 +61,6 @@ public static KnowledgeAuditRecord For( return new KnowledgeAuditRecord { - TurnId = turnId, Agent = agent, Mode = mode, Query = query, diff --git a/src/AgentCore.Application/Knowledge/KnowledgeBinding.cs b/src/AgentCore.Application/Knowledge/KnowledgeBinding.cs new file mode 100644 index 00000000..5d5a151a --- /dev/null +++ b/src/AgentCore.Application/Knowledge/KnowledgeBinding.cs @@ -0,0 +1,18 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Ports; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Knowledge; + +/// What one agent's knowledge search is bound to, once, at compile time. +/// The store every search reads. +/// The agent's resolved knowledge: block. +/// The id of the agent that asks, for the log line. +/// The wording providers.knowledge.citation named. +/// Where the search's own log events go. +internal sealed record KnowledgeBinding( + IKnowledgeRetrievalPort Port, + ResolvedKnowledge Knowledge, + string Agent, + IKnowledgeCitationFormatter Citations, + ILogger Logger); diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs index 41fd0ef6..ece8a724 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs @@ -18,44 +18,25 @@ namespace AgentCore.Application.Knowledge; internal static class KnowledgeProbe { /// Runs the probe. - /// The store the probe's own second search reads. - /// The agent's resolved knowledge: block. + /// The agent's port, wiring and logger. The probe's own second search reads the same port. /// The live scope the main search just ran under. - /// The id of the agent that asked, for the log line. /// The search text the framework composed. /// The conversation's ambiguity holder, or inside a nested tool call. /// Whether this row's session carries the caller's own history. - /// Where the probe's own log events go. /// The caller's own token — cancelling this is the caller hanging up, not a timeout. /// What the probe found: its note, or the "holds nothing" notice. internal static async Task> RunAsync( - IKnowledgeRetrievalPort port, - ResolvedKnowledge knowledge, + KnowledgeBinding binding, KnowledgeScope scope, - string agent, string query, Clarifications? clarifications, bool carriesHistory, - ILogger logger, CancellationToken cancellationToken) { // K42: a nested tool call runs with the holder stripped from its invocation, so a delegated // run's own search cannot latch, count or record — but a scoped run still owes the caller // the notice. - if (clarifications is null) - { - return [KnowledgeNotices.Of(KnowledgeNotices.Empty)]; - } - - var wiring = knowledge.Clarification; - - // K19: with no ambiguity: configured (and so no wildcard, since the validator requires one - // alongside the other) there is nothing for the probe to drop, and behaviour stays - // byte-identical to the wildcard plan's own "holds nothing" notice. - if (wiring.Ambiguity is not { } ambiguity - || wiring.WildcardValue is not { } wildcardValue - || wiring.WildcardFacets is not { Count: > 0 } wildcardFacets - || wiring.Template is not { } template) + if (clarifications is null || ProbeWiring.From(binding.Knowledge.Clarification) is not { } wiring) { return [KnowledgeNotices.Of(KnowledgeNotices.Empty)]; } @@ -64,8 +45,7 @@ internal static class KnowledgeProbe // turn's probe has already run — so it must stay cheap, deterministic and repeatable rather // than mutate anything. Nothing is latched by this exit: a second call that also finds no // droppable facet simply reaches this same conclusion again. - if (DroppableFacet(wiring.FromState, wildcardValue, wildcardFacets, scope, ambiguity, clarifications) - is not { } facet) + if (DroppableFacet(wiring, scope, clarifications) is not { } facet) { return [KnowledgeNotices.Of(KnowledgeNotices.Empty)]; } @@ -73,9 +53,11 @@ internal static class KnowledgeProbe var probe = clarifications.ClaimProbe(); if (!probe.Won) { - return await ReplayAsync(probe, ambiguity, cancellationToken).ConfigureAwait(false); + return await ReplayAsync(probe, wiring.Ambiguity, cancellationToken).ConfigureAwait(false); } + ClaimedProbe claimed = new(clarifications, probe, facet); + // Every way out of the winner's path has to resolve the latch. Fail() is the catch-all: it // does nothing once an outcome has been published, and where nothing was published it wakes // the turn's other callers instead of leaving them to wait out the full margin for an answer @@ -88,7 +70,7 @@ internal static class KnowledgeProbe // in the same turn would re-run the search and advance probeAsks a second time. clarifications.Update(facet, s => s.ProbeAsks++); - using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(ambiguity.ProbeDeadlineSeconds)); + using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(wiring.Ambiguity.ProbeDeadlineSeconds)); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); @@ -96,24 +78,7 @@ internal static class KnowledgeProbe try { - var narrowedScope = WithoutFacet(scope, facet); - var started = Stopwatch.GetTimestamp(); - - probeCards = await port.SearchAsync(query, narrowedScope, deadline.Token).ConfigureAwait(false); - - if (logger.IsEnabled(LogLevel.Debug)) - { - var record = KnowledgeSearchRecord.Of( - agent, - knowledge, - query, - narrowedScope, - probeCards, - Stopwatch.GetElapsedTime(started).TotalMilliseconds, - failure: null).ForLog(); - - Log.KnowledgeRetrieved(logger, agent, probeCards.Count, record); - } + probeCards = await SearchAsync(binding, WithoutFacet(scope, facet), query, deadline.Token).ConfigureAwait(false); } catch (Exception failure) when (KnowledgeCancellation.ByCaller(failure, timeout, cancellationToken)) { @@ -129,12 +94,12 @@ internal static class KnowledgeProbe { // A throw or a timeout that is not caller cancellation: the main search already // answered for reachability, so this says "holds nothing", never "unreachable". - Log.KnowledgeProbeFailed(logger, agent, facet, failure); + Log.KnowledgeProbeFailed(binding.Logger, binding.Agent, facet, failure); return Publish(probe, KnowledgeNotices.Empty); } - return Name(probeCards, template, ambiguity, wiring, wildcardValue, facet, agent, logger, clarifications, carriesHistory, probe); + return Name(binding, wiring, claimed, probeCards, carriesHistory); } finally { @@ -142,6 +107,34 @@ internal static class KnowledgeProbe } } + /// §8 step 4: the probe's own second search, under the narrowed scope, logged like the main one. + private static async Task> SearchAsync( + KnowledgeBinding binding, + KnowledgeScope narrowedScope, + string query, + CancellationToken deadline) + { + var started = Stopwatch.GetTimestamp(); + + var probeCards = await binding.Port.SearchAsync(query, narrowedScope, deadline).ConfigureAwait(false); + + if (binding.Logger.IsEnabled(LogLevel.Debug)) + { + var record = KnowledgeSearchRecord.Of( + binding.Agent, + binding.Knowledge, + query, + narrowedScope, + probeCards, + Stopwatch.GetElapsedTime(started).TotalMilliseconds, + failure: null).ForLog(); + + Log.KnowledgeRetrieved(binding.Logger, binding.Agent, probeCards.Count, record); + } + + return probeCards; + } + /// K43: replays the outcome of the one probe this turn already claimed. private static async Task> ReplayAsync( Clarifications.Probe probe, @@ -165,29 +158,25 @@ internal static class KnowledgeProbe /// §8 steps 5-6: reads the candidates out of the probe's cards and decides what to say. private static IReadOnlyList Name( + KnowledgeBinding binding, + ProbeWiring wiring, + ClaimedProbe claimed, IReadOnlyList probeCards, - ScopeTemplate template, - KnowledgeAmbiguityConfiguration ambiguity, - ResolvedClarification wiring, - string wildcardValue, - string facet, - string agent, - ILogger logger, - Clarifications clarifications, - bool carriesHistory, - Clarifications.Probe probe) + bool carriesHistory) { + var (clarifications, probe, facet) = claimed; + // §8 step 5: the value at the facet's payload path is a string or a list of strings alike — // the real corpus stores arrays, and a cast straight to string would silently return null for // every card on a multi-model collection. - var path = template.Resolve(facet); + var path = wiring.Template.Resolve(facet); SortedSet union = new(StringComparer.Ordinal); union.UnionWith(probeCards .SelectMany(card => FacetValues(card, path)) - .Where(value => !string.Equals(value, wildcardValue, StringComparison.Ordinal))); + .Where(value => !string.Equals(value, wiring.WildcardValue, StringComparison.Ordinal))); - Log.KnowledgeProbeRan(logger, agent, facet, union.Count); + Log.KnowledgeProbeRan(binding.Logger, binding.Agent, facet, union.Count); if (union.Count == 0) { @@ -196,9 +185,9 @@ internal static class KnowledgeProbe // §8 step 6. probeAsks was already advanced in step 4; nothing below chooses anything but the // message. - var wouldName = Clarifications.LastNamed.For(union, ambiguity.MaxCandidates); + var wouldName = Clarifications.LastNamed.For(union, wiring.Ambiguity.MaxCandidates); var candidates = union.ToList(); - + // K39, drawn for the record rather than for the message: on a graph row AgentCore cannot know // whether the participant's own tool result ever reached the caller, so the note still goes // out, but the record of what was named — which arms K21's tie-break — does not. The flag @@ -227,7 +216,7 @@ internal static class KnowledgeProbe var description = ClarificationText.DescriptionOf(facet, wiring.SlotDescriptions); - return Publish(probe, ClarificationText.Note(description, candidates, ambiguity.MaxCandidates)); + return Publish(probe, ClarificationText.Note(description, candidates, wiring.Ambiguity.MaxCandidates)); } /// Hands one notice to this caller and to every other search in the turn alike. @@ -243,13 +232,7 @@ internal static class KnowledgeProbe /// §8 step 3: the first facet, in fromState declaration order, the wildcard filled and that /// dropping would not empty the scope or skip a slot at its ask cap. /// - private static string? DroppableFacet( - IReadOnlyList fromState, - string wildcardValue, - IReadOnlyList wildcardFacets, - KnowledgeScope scope, - KnowledgeAmbiguityConfiguration ambiguity, - Clarifications clarifications) + private static string? DroppableFacet(ProbeWiring wiring, KnowledgeScope scope, Clarifications clarifications) { // K33: the scope's only facet is undroppable — opening it empty is what a scoped store // refuses. This holds for every candidate alike, so no candidate can be droppable at all. @@ -258,7 +241,7 @@ internal static class KnowledgeProbe return null; } - foreach (var name in fromState) + foreach (var name in wiring.FromState) { // K14: the wildcard filled it — its value is the wildcard's own, and the facet is named // among the ones the wildcard is allowed to widen. Origins overrules the value where it @@ -266,9 +249,9 @@ internal static class KnowledgeProbe // it", and widening that facet would overrule an instruction rather than recover a lost // one. A scope composed without origins carries none, so an absent entry falls back to // the value alone. - if (!wildcardFacets.Contains(name, StringComparer.Ordinal) + if (!wiring.WildcardFacets.Contains(name, StringComparer.Ordinal) || !scope.Facets.TryGetValue(name, out var value) - || !string.Equals(value, wildcardValue, StringComparison.Ordinal) + || !string.Equals(value, wiring.WildcardValue, StringComparison.Ordinal) || (scope.Origins.TryGetValue(name, out var origin) && origin != KnowledgeFacetOrigin.Wildcard)) { @@ -276,7 +259,7 @@ internal static class KnowledgeProbe } // K22: the probe's own counter is monotone and capped at maxAsks. - if (clarifications.Read(name).ProbeAsks >= ambiguity.MaxAsks) + if (clarifications.Read(name).ProbeAsks >= wiring.Ambiguity.MaxAsks) { continue; } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs index 083b6727..70b66529 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs @@ -55,7 +55,7 @@ internal static AIContextProvider Create( RecentMessageMemoryLimit = 4, }; - KnowledgeSearch.Core core = KnowledgeSearch.Bind(port, knowledge, agent, citations, logger); + KnowledgeSearch.Core core = KnowledgeSearch.Bind(new KnowledgeBinding(port, knowledge, agent, citations, logger)); // The template's own delegate never runs: tool-mode searches go through the // invocation-bound wrapper, prefetch through per-invocation providers. It fails diff --git a/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs b/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs index 4d4f66a5..9aeb80b6 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs @@ -30,34 +30,22 @@ internal static class KnowledgeSearch new() { Facets = new Dictionary(StringComparer.Ordinal) }; /// Binds the core to one agent's port, wiring and loggers. - internal static Core Bind( - IKnowledgeRetrievalPort port, - ResolvedKnowledge knowledge, - string agent, - IKnowledgeCitationFormatter citations, - ILogger logger) + internal static Core Bind(KnowledgeBinding binding) { - ArgumentNullException.ThrowIfNull(port); - ArgumentNullException.ThrowIfNull(knowledge); - ArgumentNullException.ThrowIfNull(agent); - ArgumentNullException.ThrowIfNull(citations); - ArgumentNullException.ThrowIfNull(logger); - - return (query, facets, turn, cancellationToken) => RunAsync( - port, knowledge, agent, query, facets, turn, citations, logger, cancellationToken); + ArgumentNullException.ThrowIfNull(binding); + + return (query, facets, turn, cancellationToken) => RunAsync(binding, query, facets, turn, cancellationToken); } private static async Task> RunAsync( - IKnowledgeRetrievalPort port, - ResolvedKnowledge knowledge, - string agent, + KnowledgeBinding binding, string query, IReadOnlyDictionary? facets, TurnInvocation? turn, - IKnowledgeCitationFormatter citations, - ILogger logger, CancellationToken cancellationToken) { + var (port, knowledge, agent, citations, logger) = binding; + // No scope filters nothing, so it is the absent scope in disguise. The shared store // can only fail closed when EVERY agent is scoped, so in a mixed deployment this is // the only check standing between a scoped agent and every customer's cards. A null @@ -96,7 +84,7 @@ internal static Core Bind( && under.Facets.Count > 0) { return await KnowledgeProbe - .RunAsync(port, knowledge, under, agent, query, turn?.Clarifications, turn?.CarriesHistory ?? false, logger, cancellationToken) + .RunAsync(binding, under, query, turn?.Clarifications, turn?.CarriesHistory ?? false, cancellationToken) .ConfigureAwait(false); } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs index 14b177ed..512f0663 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs @@ -26,7 +26,6 @@ internal static KnowledgeAuditRecord Of( double latencyMs, Exception? failure) => KnowledgeAuditRecord.For( - turnId: null, agent, knowledge.Mode, query, diff --git a/src/AgentCore.Application/Knowledge/ProbeWiring.cs b/src/AgentCore.Application/Knowledge/ProbeWiring.cs new file mode 100644 index 00000000..096ecdd4 --- /dev/null +++ b/src/AgentCore.Application/Knowledge/ProbeWiring.cs @@ -0,0 +1,32 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Knowledge; + +/// The ambiguity wiring the probe runs on, with every part it needs present. +/// How the search asks the caller which value they meant. +/// The payload value that satisfies any scope on a wildcard facet. +/// The facet keys widens. +/// The payload path each facet key becomes. +/// The fromState slots, in declaration order. +/// Each slot's description, keyed by slot name. +internal sealed record ProbeWiring( + KnowledgeAmbiguityConfiguration Ambiguity, + string WildcardValue, + IReadOnlyList WildcardFacets, + ScopeTemplate Template, + IReadOnlyList FromState, + IReadOnlyDictionary SlotDescriptions) +{ + /// Reads the probe's wiring off the document's, or answers when the probe cannot run. + /// + /// K19: with no ambiguity: configured (and so no wildcard, since the validator requires one + /// alongside the other) there is nothing for the probe to drop, and behaviour stays byte-identical + /// to the wildcard plan's own "holds nothing" notice. + /// + public static ProbeWiring? From(ResolvedClarification wiring) + => wiring is { Ambiguity: { } ambiguity, WildcardValue: { } wildcardValue, WildcardFacets: { Count: > 0 } wildcardFacets, Template: { } template } + ? new(ambiguity, wildcardValue, wildcardFacets, template, wiring.FromState, wiring.SlotDescriptions) + : null; +} diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index 3d1e437a..0b162e3d 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -38,17 +38,13 @@ internal sealed class AuditingFunctionInvokingChatClient : FunctionInvokingChatC private readonly ConcurrentDictionary _drains = new(StringComparer.Ordinal); private sealed record Drain( - TurnRenders? Renders, - TurnSources? Sources, - TurnFiles? Files, + IReadOnlyList Attachments, Action? OnToolFailure, bool Nested) { - /// Takes what one call drew, cited, and published, in that order. + /// Takes what one call produced, kind by kind, in the turn's own order. public IEnumerable TakeFor(string callId) - => (Renders?.TakeFor(callId) ?? []) - .Concat(Sources?.TakeFor(callId) ?? []) - .Concat(Files?.TakeFor(callId) ?? []); + => Attachments.SelectMany(kind => kind.TakeFor(callId)); } /// Creates the client. @@ -99,24 +95,15 @@ internal void Release(IReadOnlyList callIds) if (invocation is not null) { - // Snapshot the turn once per tool call and file it in the call's arguments, so tools + // Snapshot the turn once per tool call and file it beside the call's arguments, so tools // declare what they need as parameters. - context.Arguments[TurnInvocation.ArgumentsKey] = invocation; - _drains[callId] = new Drain( - invocation.Renders, invocation.Sources, invocation.Files, invocation.OnToolFailure, nested); + invocation.FileIn(context.Arguments); + _drains[callId] = new Drain(invocation.Attachments(), invocation.OnToolFailure, nested); invocation.Results?.NoteCall(callId, Release); } - using var outerCall = invocation?.Renders is { } renders && !nested - ? renders.BeginOuterCall(invocation.OuterCallId ?? callId) - : null; - - using var outerSources = invocation?.Sources is { } sources && !nested - ? sources.BeginOuterCall(invocation.OuterCallId ?? callId) - : null; - - using var outerFiles = invocation?.Files is { } files && !nested - ? files.BeginOuterCall(invocation.OuterCallId ?? callId) + using var outerCall = invocation is not null && !nested + ? OuterCall.Open(_drains[callId].Attachments, invocation.OuterCallId ?? callId) : null; try @@ -147,13 +134,6 @@ internal void Release(IReadOnlyList callIds) throw; } - finally - { - // Filed for the tool alone: the workflow checkpoint persists arguments at turn end, - // and a live turn does not survive JSON. The tool already ran, and nothing downstream - // reads the key back. - context.Arguments.Remove(TurnInvocation.ArgumentsKey); - } } /// Reports whether a fault is one the model cannot possibly answer. diff --git a/src/AgentCore.Application/Runtime/ConversationEventChain.cs b/src/AgentCore.Application/Runtime/ConversationEventChain.cs index 7edcded2..49d22574 100644 --- a/src/AgentCore.Application/Runtime/ConversationEventChain.cs +++ b/src/AgentCore.Application/Runtime/ConversationEventChain.cs @@ -1,4 +1,5 @@ using System.Globalization; +using AgentCore.Domain; using AgentCore.Domain.Audit; namespace AgentCore.Application.Runtime; @@ -85,28 +86,17 @@ internal bool EndConversation(ConversationEndReason reason, DateTimeOffset ended } /// Raises the durable facts of one finished turn, in the order they happened. - /// The turn that just spoke. - /// The moment the turn ended. - /// The stage the turn spoke in. - /// The stage the machine holds after the turn. - /// The text the caller heard. + /// The turn that just spoke: its index, stages, the text the caller heard, when it ended, and how far it played. /// The whole reply the model produced. /// The message of the fault, or . - /// The played duration, or . /// /// The identity of the turn.completed fact, so a barge-in that arrives after this turn /// already ended can name it through . /// - internal Guid WriteTurnEvents( - int turnIndex, - DateTimeOffset endedAt, - string stageBefore, - string stageAfter, - string reply, - string spokenReply, - string? toolFault, - TimeSpan? interruptedAfter) + internal Guid WriteTurnEvents(TurnResult result, string spokenReply, string? toolFault) { + var (turnIndex, endedAt) = (result.TurnIndex, result.EndedAt); + if (toolFault is not null) { _ = Raise( @@ -126,13 +116,13 @@ internal Guid WriteTurnEvents( payload: new Dictionary(StringComparer.Ordinal) { [AuditPayloadKeys.ReplyTextSha256] = AuditHash.OfText(spokenReply).Value, - [AuditPayloadKeys.StageBefore] = stageBefore, - [AuditPayloadKeys.StageAfter] = stageAfter, + [AuditPayloadKeys.StageBefore] = result.StageBefore, + [AuditPayloadKeys.StageAfter] = result.StageAfter, }); - if (interruptedAfter is { } played) + if (result.InterruptedAfter is { } played) { - RaiseReplyInterrupted(turnIndex, endedAt, completed, reply, played); + RaiseReplyInterrupted(turnIndex, endedAt, completed, result.ReplyText, played); } return completed; diff --git a/src/AgentCore.Application/Runtime/ConversationSession.cs b/src/AgentCore.Application/Runtime/ConversationSession.cs index 1b4da065..c2c09531 100644 --- a/src/AgentCore.Application/Runtime/ConversationSession.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession.cs @@ -159,18 +159,14 @@ public sealed class ConversationSession : IConversationPort, IAsyncDisposable /// internal ConversationSession( string conversationId, - CompiledAgent compiled, - IGuardEvaluator guards, - StateExtractor? extractor, - TimeProvider timeProvider, + ConversationSessionSeams seams, ConversationObserverDispatcher? observers = null, - ILogger? logger = null, ConversationWorkspace? workspace = null) { ArgumentException.ThrowIfNullOrEmpty(conversationId); - ArgumentNullException.ThrowIfNull(compiled); - ArgumentNullException.ThrowIfNull(guards); - ArgumentNullException.ThrowIfNull(timeProvider); + ArgumentNullException.ThrowIfNull(seams); + + var (compiled, guards, extractor, timeProvider, logger) = seams; ConversationId = conversationId; diff --git a/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs index d10a0be7..a1b68b47 100644 --- a/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs +++ b/src/AgentCore.Application/Runtime/ConversationSession/ConversationTurnCommit.cs @@ -41,15 +41,7 @@ internal TurnResult Publish(ConversationTurn turn, ReplyOutcome outcome, Transcr // Only now. The chain stores a hash of the spoken text and store 1 stores the text, so a // reply.interrupted raised before the append would name a hash of words nothing holds. - var completedEventId = _session.Events.WriteTurnEvents( - turn.Index, - result.EndedAt, - turn.StageBefore, - result.StageAfter, - outcome.Reply, - outcome.SpokenReply, - outcome.ToolFault, - outcome.InterruptedAfter); + var completedEventId = _session.Events.WriteTurnEvents(result, outcome.SpokenReply, outcome.ToolFault); // A turn one barge-in already cut is not amendable again, so it is not published here. _session.AmendableEventId = outcome.InterruptedAfter is null ? completedEventId : null; diff --git a/src/AgentCore.Application/Runtime/ConversationSessionFactory.cs b/src/AgentCore.Application/Runtime/ConversationSessionFactory.cs index ed41786f..3e2f4080 100644 --- a/src/AgentCore.Application/Runtime/ConversationSessionFactory.cs +++ b/src/AgentCore.Application/Runtime/ConversationSessionFactory.cs @@ -13,18 +13,10 @@ namespace AgentCore.Application.Runtime; /// public sealed class ConversationSessionFactory : IConversationSessionFactory { - private readonly CompiledAgent _compiled; - - private readonly IGuardEvaluator _guards; - - private readonly StateExtractor? _extractor; - - private readonly TimeProvider _time; + private readonly ConversationSessionSeams _seams; private readonly IConversationObserver[] _observers; - private readonly ILogger? _logger; - private readonly string? _workspaceRoot; /// @@ -43,11 +35,7 @@ public ConversationSessionFactory( ArgumentNullException.ThrowIfNull(compiled); ArgumentNullException.ThrowIfNull(guards); - _compiled = compiled; - _guards = guards; - _extractor = extractor; - _time = timeProvider ?? TimeProvider.System; - _logger = logger; + _seams = new ConversationSessionSeams(compiled, guards, extractor, timeProvider ?? TimeProvider.System, logger); _workspaceRoot = workspaceRoot; // Copied, not held: the list is the caller's, and a caller that keeps adding to it after this @@ -85,12 +73,8 @@ public ConversationSession Create(string? conversationId = null, ConversationSes ConversationSession session = new( resolvedConversationId, - _compiled, - _guards, - _extractor, - _time, - new ConversationObserverDispatcher(_observers, _logger), - _logger, + _seams, + new ConversationObserverDispatcher(_observers, _seams.Logger), workspace); // Named, not applied. The session resumes on its first turn, where store 0's own copy diff --git a/src/AgentCore.Application/Runtime/ConversationSessionSeams.cs b/src/AgentCore.Application/Runtime/ConversationSessionSeams.cs new file mode 100644 index 00000000..0d211e64 --- /dev/null +++ b/src/AgentCore.Application/Runtime/ConversationSessionSeams.cs @@ -0,0 +1,19 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.State; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Runtime; + +/// What every session one factory builds shares: the entry, and the seams it runs on. +/// The compiled entry every conversation runs. +/// The evaluator that runs each exit guard. +/// The state extractor the document declares, or . +/// The clock every turn reads. +/// Where the session's own log events go, or for none. +internal sealed record ConversationSessionSeams( + CompiledAgent Compiled, + IGuardEvaluator Guards, + StateExtractor? Extractor, + TimeProvider Time, + ILogger? Logger); diff --git a/src/AgentCore.Application/Runtime/Turn/ITurnAttachments.cs b/src/AgentCore.Application/Runtime/Turn/ITurnAttachments.cs new file mode 100644 index 00000000..5bde579d --- /dev/null +++ b/src/AgentCore.Application/Runtime/Turn/ITurnAttachments.cs @@ -0,0 +1,24 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime.Turn; + +/// +/// One kind of thing a turn's tools produce for the caller, as the invoking client handles every +/// kind alike: opened around the outermost tool call, drained onto that call's result message. +/// +/// +/// A new kind implements this once and joins TurnInvocation.Attachments(). The invoking client +/// never names a kind. +/// +internal interface ITurnAttachments +{ + /// Opens one outermost tool call as the key publishes file under. + /// The id of the outermost tool call now running. + /// The scope. Disposing it puts back the key that was open before. + IDisposable BeginOuterCall(string callId); + + /// Takes what was filed under one outer tool call, in publish order. + /// The call whose content to take. + /// What that call filed, or empty. + IReadOnlyList TakeFor(string callId); +} diff --git a/src/AgentCore.Application/Runtime/Turn/OuterCall.cs b/src/AgentCore.Application/Runtime/Turn/OuterCall.cs new file mode 100644 index 00000000..448363ff --- /dev/null +++ b/src/AgentCore.Application/Runtime/Turn/OuterCall.cs @@ -0,0 +1,24 @@ +namespace AgentCore.Application.Runtime.Turn; + +/// One outermost tool call, open on every kind of attachment at once. +internal sealed class OuterCall : IDisposable +{ + private readonly IDisposable[] _opened; + + private OuterCall(IDisposable[] opened) => _opened = opened; + + /// Opens the call on every kind, in list order. + /// Every kind the turn carries. + /// The id of the outermost tool call now running. + /// The scope. Disposing it closes every kind, last opened first. + public static OuterCall Open(IReadOnlyList attachments, string callId) + => new([.. attachments.Select(kind => kind.BeginOuterCall(callId))]); + + public void Dispose() + { + for (var index = _opened.Length - 1; index >= 0; index--) + { + _opened[index].Dispose(); + } + } +} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs b/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs index 952b256f..899c67f9 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnAttachments.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.AI; + namespace AgentCore.Application.Runtime.Turn; /// @@ -10,7 +12,8 @@ namespace AgentCore.Application.Runtime.Turn; /// outside any turn there is none, and a publish is discarded. /// /// The content one publish files. -internal abstract class TurnAttachments +internal abstract class TurnAttachments : ITurnAttachments + where TContent : AIContent { private readonly Lock _gate = new(); @@ -24,7 +27,7 @@ internal abstract class TurnAttachments /// Opens one outermost tool call as the key publishes file under. /// The id of the outermost tool call now running. /// The scope. Disposing it puts back the key that was open before. - internal IDisposable BeginOuterCall(string callId) + public IDisposable BeginOuterCall(string callId) { ArgumentNullException.ThrowIfNull(callId); @@ -51,6 +54,8 @@ internal IReadOnlyList TakeFor(string callId) } } + IReadOnlyList ITurnAttachments.TakeFor(string callId) => TakeFor(callId); + /// Files one content under a call. A later publish of the same thing wins, in the place the earlier one took, so publish order is kept. /// The outer call to file under. /// What to file. diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs index 8dd675e7..c19281e6 100644 --- a/src/AgentCore.Application/Runtime/TurnInvocation.cs +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -9,13 +9,13 @@ namespace AgentCore.Application.Runtime; // Everything one turn hands its tools, as one explicit value. The loop builds one per turn; -// the invoking client snapshots it into every tool call's arguments, so a tool declares what +// the invoking client files it beside every tool call's arguments, so a tool declares what // it needs as a parameter instead of reading the flow. Nested runs see the same turn with the // clarifications stripped and the outermost call id stamped, via `with` copies the client makes. internal sealed record TurnInvocation { - /// The argument name the invoking client files the turn under. Namespaced: a model - /// argument will never be called this, and the binder intercepts the type before JSON binding. + /// The options key the loop files the turn under, for the invoking client to read. + /// Namespaced: no vendor field will ever be called this. internal const string ArgumentsKey = "urn:agentcore:turn"; /// Gets the id of the conversation the turn belongs to. @@ -63,6 +63,13 @@ internal sealed record TurnInvocation /// Gets what the turn publishes files into. Never on a loop-built turn. public TurnFiles? Files { get; init; } + /// + /// Lists every kind of thing this turn's tools produce for the caller, in the order they attach to + /// a tool-result message. A new kind is one new property and one name here. + /// + internal IReadOnlyList Attachments() + => [.. new ITurnAttachments?[] { Renders, Sources, Files }.OfType()]; + /// Gets the tools a delegated run of this conversation is offered, or for none. public IReadOnlyList? Tools { get; init; } @@ -87,7 +94,6 @@ internal sealed record TurnInvocation /// public StateDocument? State { get; init; } - /// Builds the per-run options carrying this turn to the invoking client. /// Reads the turn filed on a run's options by , or null when there is none. internal static TurnInvocation? From(AgentRunOptions? options) => options is ChatClientAgentRunOptions run @@ -95,6 +101,26 @@ internal sealed record TurnInvocation ? filed as TurnInvocation : null; + /// Reads the turn filed beside one tool call's arguments by , or null outside a turn. + internal static TurnInvocation? FiledIn(AIFunctionArguments? arguments) + => arguments?.Context?.TryGetValue(typeof(TurnInvocation), out var filed) == true + ? filed as TurnInvocation + : null; + + /// + /// Files this turn beside one tool call's arguments, where the runtime-bound parameters read it. + /// Beside, never among: the arguments dictionary is the model's own call record, and a checkpoint + /// persists it, while lives only as long as the call. + /// + /// The same arguments, for a caller that builds them inline. + internal AIFunctionArguments FileIn(AIFunctionArguments arguments) + { + arguments.Context ??= new Dictionary(); + arguments.Context[typeof(TurnInvocation)] = this; + return arguments; + } + + /// Builds the per-run options carrying this turn to the invoking client. internal ChatClientAgentRunOptions RunOptions() { ChatOptions chat = new() diff --git a/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs b/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs index 9241a91e..d8c66790 100644 --- a/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs +++ b/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs @@ -5,7 +5,7 @@ namespace AgentCore.Application.Tools.Binding; // The runtime-filled parameters a bound tool declares. The model never sees them: they bind -// from the turn the invoking client filed in the conversation's arguments. +// from the turn the invoking client filed beside the call's arguments. internal static class ToolParameterBindings { /// Binds one runtime-filled parameter, or answers for the model's own. @@ -21,9 +21,7 @@ internal static AIFunctionFactoryOptions.ParameterBindingOptions For(ParameterIn private static object? Bind(Type type, AIFunctionArguments? args) { - var invocation = args is not null && args.TryGetValue(TurnInvocation.ArgumentsKey, out var filed) - ? filed as TurnInvocation - : null; + var invocation = TurnInvocation.FiledIn(args); if (type == typeof(TurnInvocation)) { diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index dd59ada7..ce18be43 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -9,6 +9,7 @@ using AgentCore.Application.Ports; using AgentCore.Application.Secrets; using AgentCore.Application.Tools.Binding; +using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Registry; using AgentCore.AspNetCore.DependencyInjection.Startup; using Microsoft.AspNetCore.Http; @@ -202,7 +203,12 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) .ConfigureAwait(false)); var tools = await ToolRegistryStartup - .BuildAsync(this, _options, startup, chatClients, blobs, _loggers, configuration, cancellationToken) + .BuildAsync( + this, + _options, + startup, + new BuiltinToolPorts(chatClients, blobs, WorkspaceRoot: _options.WorkspaceRoot, Loggers: _loggers), + cancellationToken) .ConfigureAwait(false); ConfigurationValidator.ValidateToolReferences(configuration, tools.ServedIds); @@ -232,17 +238,20 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) var graph = await CompilationStartup .CompileAsync( configuration, - chatClients, - tools.Registry, - conversations, - evaluators, - knowledge, - skills, - KnowledgeCitationFormatterFactory.Resolve(configuration, _options.KnowledgeCitations), - _loggers, - _options.WorkspaceRoot, - _options.TimeProvider, - secrets) + new AgentCompilationContext(chatClients) + { + Tools = tools.Registry, + Guards = new GuardEvaluator(configuration.Guards, _loggers.CreateLogger()), + Moderation = PromptModerator.FromRegistry(evaluators), + ConversationStore = conversations, + Knowledge = knowledge, + Skills = skills, + Citations = KnowledgeCitationFormatterFactory.Resolve(configuration, _options.KnowledgeCitations), + Loggers = _loggers, + WorkspaceRoot = _options.WorkspaceRoot, + Clock = _options.TimeProvider, + Secrets = secrets, + }) .ConfigureAwait(false); var seams = ConversationSeamStartup.Build(configuration, _options); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs index 4e4f0186..f7a576f2 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -2,13 +2,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Evaluation; -using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; -using AgentCore.Application.Secrets; -using AgentCore.Application.Skills; -using AgentCore.Application.Tools.Registry; -using Microsoft.Extensions.Logging; namespace AgentCore.AspNetCore.DependencyInjection; @@ -19,65 +13,30 @@ namespace AgentCore.AspNetCore.DependencyInjection; /// The compiled entries, keyed by entry name. Every conversation shares them. internal readonly record struct CompiledGraph( IChatClientFactory ChatClients, - GuardEvaluator Guards, + IGuardEvaluator Guards, CompiledAgentRegistry Registry, IReadOnlyDictionary Entries); /// Step 5: compile the document once, so every conversation shares the result. internal static class CompilationStartup { - /// Compiles every entry of the document against the tools and the chat clients already built. + /// Compiles every entry of the document against the seams the earlier steps built. /// The loaded document. - /// The factory step 3c built, which the compile table asks for every agent and for the extractor. - /// The registry step 4 built. - /// The store every conversation's row and every word of it is kept in. - /// - /// The registry the moderator comes out of. R3 puts moderation in the chat pipeline of every - /// compiled agent, so it is bound here rather than on the session factory. + /// + /// The seams the compile table needs. is set: R3 puts + /// moderation and the guards in the chat pipeline of every compiled agent, so both are bound + /// here rather than on the session factory. /// - /// The port step 3b opened, or when the host bound no knowledge vendor. - /// The catalog step "skills" opened, or when the host bound no skills folder. - /// The wording providers.knowledge.citation named. - /// The factory the guard evaluator and the knowledge provider take their loggers from. - /// The root options.UseWorkspace(...) bound, or . - /// The clock the host bound, or for the system clock. - /// The set a shell: block's env: resolves its ${secret:name} references against. /// The compiled entries, and the seams that made them. /// An entry does not compile. - internal static ValueTask CompileAsync( - AgentCoreConfiguration configuration, - IChatClientFactory chatClients, - ToolRegistry tools, - IConversationStore conversations, - EvaluatorRegistry evaluators, - IKnowledgeRetrievalPort? knowledge, - SkillCatalog? skills, - IKnowledgeCitationFormatter citations, - ILoggerFactory loggers, - string? workspaceRoot = null, - TimeProvider? clock = null, - ResolvedSecrets? secrets = null) + internal static ValueTask CompileAsync(AgentCoreConfiguration configuration, AgentCompilationContext context) { - GuardEvaluator guards = new(configuration.Guards, loggers.CreateLogger()); - CompiledAgentRegistry registry = new(); + var guards = context.Guards + ?? throw new InvalidOperationException("Step 5 compiles against a guard evaluator, and the context names none."); - var entries = registry.EnsureAll( - configuration, - new AgentCompilationContext(chatClients) - { - Tools = tools, - Guards = guards, - Moderation = PromptModerator.FromRegistry(evaluators), - ConversationStore = conversations, - Knowledge = knowledge, - Skills = skills, - Citations = citations, - Loggers = loggers, - WorkspaceRoot = workspaceRoot, - Clock = clock, - Secrets = secrets, - }); + CompiledAgentRegistry registry = new(); + var entries = registry.EnsureAll(configuration, context); - return ValueTask.FromResult(new CompiledGraph(chatClients, guards, registry, entries)); + return ValueTask.FromResult(new CompiledGraph(context.ChatClients, guards, registry, entries)); } } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs index 93c97a05..4661503a 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs @@ -3,7 +3,6 @@ using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Registry; -using Microsoft.Extensions.Logging; namespace AgentCore.AspNetCore.DependencyInjection.Startup; @@ -27,10 +26,11 @@ internal static class ToolRegistryStartup /// The owner every source is tracked against, the moment it is built. /// The options the host filled. /// The loaded document and the resolved secrets. - /// The factory a shipped agent runs on. Step 3c fails the boot rather than returning none. - /// The store step 4d opened, or when the document names none. - /// The factory a built-in takes its logger from. - /// The loaded document. + /// + /// What a shipped built-in runs on: the chat client factory step 3c built (it fails the boot rather + /// than returning none), the blob store step 4d opened or , the workspace + /// root, and the logger factory. + /// /// Cancels the discovery. /// The registry, and the served-ids union decision 15's reference pass reads. /// @@ -42,19 +42,14 @@ internal static async ValueTask BuildAsync( AgentCoreBoot boot, AgentCoreOptions options, AgentCoreStartup startup, - IChatClientFactory chatClients, - IBlobStore? blobs, - ILoggerFactory loggers, - AgentCoreConfiguration configuration, + BuiltinToolPorts ports, CancellationToken cancellationToken) { + var configuration = startup.Configuration; + List sources = [ - new BuiltinToolSource(new BuiltinToolPorts( - chatClients, - blobs, - WorkspaceRoot: options.WorkspaceRoot, - Loggers: loggers)), + new BuiltinToolSource(ports), new BindingToolSource(options.Bindings), ]; diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs index 6c7828ab..bce285de 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs @@ -139,11 +139,10 @@ private static async Task SearchAsync(AIContextProvider provider, string Invoking("hello", session), TestContext.Current.CancellationToken).ConfigureAwait(false); var search = Assert.Single(context.Tools!, tool => tool.Name == "Search"); var results = await ((AIFunction)search).InvokeAsync( - new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) + turn.FileIn(new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) { ["userQuestion"] = query, - [TurnInvocation.ArgumentsKey] = turn, - }), + })), TestContext.Current.CancellationToken).ConfigureAwait(false) as IReadOnlyList; return Assert.Single(results!).Text; diff --git a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs index a90de5f8..bcaf431c 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs @@ -278,17 +278,18 @@ private static async Task CallAsync( ["key"] = filter.Key, ["value"] = filter.Value, })), - [TurnInvocation.ArgumentsKey] = new TurnInvocation - { - ConversationId = "conversation", - TurnIndex = 0, - Stage = "", - Knowledge = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) }, - }, + }; + + TurnInvocation turn = new() + { + ConversationId = "conversation", + TurnIndex = 0, + Stage = "", + Knowledge = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) }, }; var results = await tool.InvokeAsync( - new AIFunctionArguments(arguments), TestContext.Current.CancellationToken) + turn.FileIn(new AIFunctionArguments(arguments)), TestContext.Current.CancellationToken) as IReadOnlyList; return results is null ? string.Empty : string.Join("\n", results.Select(result => result.Text)); diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs index 141478d1..0a43254b 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs @@ -15,7 +15,7 @@ public void Cards_DistinguishRankedFromLinked() { // `via` is the mechanism the probes proved is required for correctness, three times over. // It is therefore the thing that will need debugging. - var record = KnowledgeAuditRecord.For("turn", "resolver", KnowledgeMode.Prefetch, "e33", Scope(), + var record = KnowledgeAuditRecord.For("resolver", KnowledgeMode.Prefetch, "e33", Scope(), [Ranked("a", 0.87), Linked("b")], latencyMs: 106, failure: null); Assert.Equal("ranked", record.Cards[0].Via); @@ -32,7 +32,7 @@ public void For_ReadsTheWholeRetrievalLatencyAsOneNumber() { // Ruling 19: IKnowledgeRetrievalPort is one atomic method, so embed time and search time // are not separately observable above it. There is one field, not two. - var record = KnowledgeAuditRecord.For("turn", "resolver", KnowledgeMode.Prefetch, "e33", Scope(), + var record = KnowledgeAuditRecord.For("resolver", KnowledgeMode.Prefetch, "e33", Scope(), [], latencyMs: 106, failure: null); Assert.Equal(106, record.LatencyMs); @@ -42,7 +42,7 @@ public void For_ReadsTheWholeRetrievalLatencyAsOneNumber() public void For_AFailedRetrieval_KeepsTheRealCause() { // In tool mode the framework discards the exception message. This is the only place it survives. - var record = KnowledgeAuditRecord.For("turn", "resolver", KnowledgeMode.Tool, "e33", Scope(), + var record = KnowledgeAuditRecord.For("resolver", KnowledgeMode.Tool, "e33", Scope(), [], latencyMs: 92, failure: new InvalidOperationException("qdrant is down")); Assert.Contains("qdrant is down", record.Failure, StringComparison.Ordinal); @@ -54,7 +54,7 @@ public void CardEntry_CarriesEveryFieldTheCitationIsRebuiltFrom() // Only Via and Score were checked before, so a mapping mistake in the other four would // survive: an engineer reading the record would be shown the wrong manual, at the wrong page, // for the wrong card, with nothing looking broken. - var record = KnowledgeAuditRecord.For("turn", "resolver", KnowledgeMode.Prefetch, "e33", Scope(), + var record = KnowledgeAuditRecord.For("resolver", KnowledgeMode.Prefetch, "e33", Scope(), [Ranked("ct900-e33-incline-err", 0.87)], latencyMs: 106, failure: null); var card = Assert.Single(record.Cards); @@ -68,8 +68,8 @@ public void CardEntry_CarriesEveryFieldTheCitationIsRebuiltFrom() [Fact] public void For_CarriesEveryFieldTheOutageIsDiagnosedFrom() { - var record = KnowledgeAuditRecord.For("turn-7", "analyst", KnowledgeMode.Tool, "belt slipping", Scope(), - [], latencyMs: 106, failure: null); + var record = KnowledgeAuditRecord.For("analyst", KnowledgeMode.Tool, "belt slipping", Scope(), + [], latencyMs: 106, failure: null) with { TurnId = "turn-7" }; Assert.Equal("turn-7", record.TurnId); Assert.Equal("analyst", record.Agent); @@ -83,7 +83,7 @@ public void For_NoTurnIdIsReachable_LeavesTheFieldEmptyRatherThanInventingOne() { // Ruling 19, then Ruling 21. The provider that writes this record can reach no conversation id and no // turn index, so it passes null. A synthesised id would read as real to whoever greps for it. - var record = KnowledgeAuditRecord.For(turnId: null, "analyst", KnowledgeMode.Tool, "e33", scope: null, + var record = KnowledgeAuditRecord.For("analyst", KnowledgeMode.Tool, "e33", scope: null, [], latencyMs: 106, failure: null); Assert.Null(record.TurnId); @@ -117,7 +117,7 @@ public void For_CarriesTheScopeOrigins() }; var record = KnowledgeAuditRecord.For( - null, "agent", KnowledgeMode.Tool, "q", scope, [], 1.0, null); + "agent", KnowledgeMode.Tool, "q", scope, [], 1.0, null); Assert.Equal(KnowledgeFacetOrigin.Wildcard, record.ScopeOrigins["brand"]); } @@ -142,7 +142,7 @@ public void ForLog_WritesEachFacetWithItsOriginAsText() }, }; - var view = KnowledgeAuditRecord.For(null, "agent", KnowledgeMode.Tool, "q", scope, [], 1.0, null) + var view = KnowledgeAuditRecord.For("agent", KnowledgeMode.Tool, "q", scope, [], 1.0, null) .ForLog(); Assert.Equal("code=* (Wildcard), model=f85-2019 (Tool)", view.Scope); @@ -151,7 +151,7 @@ public void ForLog_WritesEachFacetWithItsOriginAsText() [Fact] public void ForLog_FacetWithNoRecordedOrigin_WritesTheValueAlone() { - var view = KnowledgeAuditRecord.For(null, "agent", KnowledgeMode.Tool, "q", Scope(), [], 1.0, null) + var view = KnowledgeAuditRecord.For("agent", KnowledgeMode.Tool, "q", Scope(), [], 1.0, null) .ForLog(); Assert.Equal("model=ct900", view.Scope); @@ -160,7 +160,7 @@ public void ForLog_FacetWithNoRecordedOrigin_WritesTheValueAlone() [Fact] public void ForLog_NoScopeWasOpen_WritesAnEmptyString() { - var view = KnowledgeAuditRecord.For(null, "agent", KnowledgeMode.Tool, "q", scope: null, [], 1.0, null) + var view = KnowledgeAuditRecord.For("agent", KnowledgeMode.Tool, "q", scope: null, [], 1.0, null) .ForLog(); Assert.Equal(string.Empty, view.Scope); diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs index 8e558a18..232e8aa7 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs @@ -1122,11 +1122,10 @@ private static KnowledgeCard CardWithFacetList(string id, string facetKey, IRead Invoking("hello", session), TestContext.Current.CancellationToken).ConfigureAwait(false); var search = Assert.Single(context.Tools!, tool => tool.Name == "Search"); var results = await ((AIFunction)search).InvokeAsync( - new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) + turn.FileIn(new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) { ["userQuestion"] = query, - [TurnInvocation.ArgumentsKey] = turn, - }), + })), callerToken).ConfigureAwait(false) as IReadOnlyList; return results!; diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs index 0dbd61bc..0782417d 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs @@ -723,11 +723,10 @@ private static AIContextProvider Provider(IKnowledgeRetrievalPort port, Resolved Invoking("hello", session), TestContext.Current.CancellationToken).ConfigureAwait(false); var search = Assert.Single(context.Tools!, tool => tool.Name == "Search"); var results = await ((AIFunction)search).InvokeAsync( - new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) + turn.FileIn(new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) { ["userQuestion"] = query, - [TurnInvocation.ArgumentsKey] = turn, - }), + })), TestContext.Current.CancellationToken).ConfigureAwait(false) as IReadOnlyList; return results!; diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientCallRecordTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientCallRecordTests.cs new file mode 100644 index 00000000..b42b7d3e --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientCallRecordTests.cs @@ -0,0 +1,51 @@ +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools.Binding; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// The call record the model wrote is the model's alone. The turn a tool reads arrives beside it, +/// through , never among its keys — so what a checkpoint +/// persists is exactly what the model said, and a live turn is never asked to survive JSON. +/// +public sealed class AuditingFunctionInvokingChatClientCallRecordTests +{ + [Fact] + public async Task TheTurnReachesTheTool_AndTheModelsCallRecordKeepsOnlyItsOwnKeys() + { + TurnInvocation? seen = null; + + var tool = AIFunctionFactory.Create( + (string city, TurnInvocation? turn) => + { + seen = turn; + return $"sunny in {city}"; + }, + new AIFunctionFactoryOptions + { + Name = "weather", + ConfigureParameterBinding = ToolParameterBindings.For, + }); + + TurnInvocation invocation = new() { ConversationId = "conversation", TurnIndex = 0, Stage = "" }; + + ToolCallingChatClient inner = new( + "the loop continues.", + new Dictionary(StringComparer.Ordinal) { ["city"] = "Taipei" }); + using AuditingFunctionInvokingChatClient client = new(inner); + + var response = await client.GetResponseAsync( + [new ChatMessage(ChatRole.User, "weather")], + new ChatOptions { Tools = [tool], AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = invocation } }, + TestContext.Current.CancellationToken); + + Assert.Equal("conversation", seen?.ConversationId); + + var call = response.Messages.SelectMany(message => message.Contents).OfType().Single(); + Assert.Equal(["city"], call.Arguments!.Keys); + Assert.Equal("Taipei", call.Arguments["city"]); + } +} diff --git a/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs b/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs index ffea2d7c..e225595e 100644 --- a/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/FilePublishToolDefinitionTests.cs @@ -181,21 +181,21 @@ private async Task PublishAsync( { var function = (AIFunction)Build(policy); - Dictionary arguments = new(StringComparer.Ordinal) { ["path"] = path, ["title"] = title }; + AIFunctionArguments arguments = new(new Dictionary(StringComparer.Ordinal) { ["path"] = path, ["title"] = title }); if (turn) { - arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation + new TurnInvocation { ConversationId = "conversation-1", TurnIndex = 0, Stage = string.Empty, Workspace = Path.Combine(_root, "conversation-1"), Files = files, - }; + }.FileIn(arguments); } - var result = await function.InvokeAsync(new AIFunctionArguments(arguments), TestContext.Current.CancellationToken); + var result = await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); return Assert.IsType(ToolResultJson.ToNode(result)); } diff --git a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs index 718276d8..1c94d601 100644 --- a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs @@ -217,18 +217,16 @@ public async Task AToolCallScopeParameterWithTheTurnFiled_BindsWithoutAFlow() return reason; }); + TurnInvocation turn = new() + { + ConversationId = "conversation-9", + TurnIndex = 4, + Stage = "handling", + Workspace = "ws", + }; + var result = await tool.InvokeAsync( - new AIFunctionArguments - { - ["reason"] = "the caller wants a person", - [TurnInvocation.ArgumentsKey] = new TurnInvocation - { - ConversationId = "conversation-9", - TurnIndex = 4, - Stage = "handling", - Workspace = "ws", - }, - }, + turn.FileIn(new AIFunctionArguments { ["reason"] = "the caller wants a person" }), TestContext.Current.CancellationToken); Assert.Equal("the caller wants a person", $"{result}"); diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs index 273a32bd..01267c9b 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/ToolRegistryStartupTests.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using AgentCore.Application.Secrets; +using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Registry; using AgentCore.Application.Tools; using AgentCore.AspNetCore.DependencyInjection; @@ -146,10 +147,10 @@ private static ValueTask BuildAsync( boot ?? Boot(), options, startup, - new RoutingChatClientFactory(new FragmentingChatClient("hello")), - blobs: null, - NullLoggerFactory.Instance, - configuration, + new BuiltinToolPorts( + new RoutingChatClientFactory(new FragmentingChatClient("hello")), + Blobs: null, + Loggers: NullLoggerFactory.Instance), TestContext.Current.CancellationToken); } From 950befe37aa79f03e7b210e682927dc7bfad2a16 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 15:45:39 -0600 Subject: [PATCH 33/35] feat(cache): add PassThroughHybridCache implementation and integrate into AgentCoreOptions --- Directory.Packages.props | 1 + .../AgentCore.Application.csproj | 1 + .../Cache/PassThroughHybridCache.cs | 44 +++++++++++++++++++ .../DependencyInjection/.gitkeep | 0 .../PublicAPI.Unshipped.txt | 6 +++ .../DependencyInjection/AgentCoreOptions.cs | 6 +++ .../AgentCoreServiceCollectionExtensions.cs | 5 +++ .../PublicAPI.Unshipped.txt | 2 + 8 files changed, 65 insertions(+) create mode 100644 src/AgentCore.Application/Cache/PassThroughHybridCache.cs delete mode 100644 src/AgentCore.Application/DependencyInjection/.gitkeep diff --git a/Directory.Packages.props b/Directory.Packages.props index dcb78ddb..d0489767 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,6 +8,7 @@ + diff --git a/src/AgentCore.Application/AgentCore.Application.csproj b/src/AgentCore.Application/AgentCore.Application.csproj index 50e08bb8..e838bfc5 100644 --- a/src/AgentCore.Application/AgentCore.Application.csproj +++ b/src/AgentCore.Application/AgentCore.Application.csproj @@ -12,6 +12,7 @@ + diff --git a/src/AgentCore.Application/Cache/PassThroughHybridCache.cs b/src/AgentCore.Application/Cache/PassThroughHybridCache.cs new file mode 100644 index 00000000..a4be9864 --- /dev/null +++ b/src/AgentCore.Application/Cache/PassThroughHybridCache.cs @@ -0,0 +1,44 @@ +using Microsoft.Extensions.Caching.Hybrid; + +namespace AgentCore.Application.Cache; + +/// +/// The cache a container runs on when the host set none: it stores nothing, so every read runs +/// its factory and every write and removal is a no-op. +/// +public sealed class PassThroughHybridCache : HybridCache +{ + /// Gets the one instance; it holds no state, so one is enough. + public static PassThroughHybridCache Instance { get; } = new(); + + private PassThroughHybridCache() + { + } + + /// + public override ValueTask GetOrCreateAsync( + string key, + TState state, + Func> factory, + HybridCacheEntryOptions? options = null, + IEnumerable? tags = null, + CancellationToken cancellationToken = default) + => factory(state, cancellationToken); + + /// + public override ValueTask SetAsync( + string key, + T value, + HybridCacheEntryOptions? options = null, + IEnumerable? tags = null, + CancellationToken cancellationToken = default) + => default; + + /// + public override ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default) + => default; + + /// + public override ValueTask RemoveByTagAsync(string tag, CancellationToken cancellationToken = default) + => default; +} diff --git a/src/AgentCore.Application/DependencyInjection/.gitkeep b/src/AgentCore.Application/DependencyInjection/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index d389d455..6a5a7171 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2328,3 +2328,9 @@ override AgentCore.Application.Conversation.StoredConversation.GetHashCode() -> override AgentCore.Application.Conversation.StoredConversation.ToString() -> string! static AgentCore.Application.Conversation.StoredConversation.operator ==(AgentCore.Application.Conversation.StoredConversation? left, AgentCore.Application.Conversation.StoredConversation? right) -> bool static AgentCore.Application.Conversation.StoredConversation.operator !=(AgentCore.Application.Conversation.StoredConversation? left, AgentCore.Application.Conversation.StoredConversation? right) -> bool +AgentCore.Application.Cache.PassThroughHybridCache +static AgentCore.Application.Cache.PassThroughHybridCache.Instance.get -> AgentCore.Application.Cache.PassThroughHybridCache! +override AgentCore.Application.Cache.PassThroughHybridCache.GetOrCreateAsync(string! key, TState state, System.Func>! factory, Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions? options = null, System.Collections.Generic.IEnumerable? tags = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +override AgentCore.Application.Cache.PassThroughHybridCache.SetAsync(string! key, T value, Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions? options = null, System.Collections.Generic.IEnumerable? tags = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +override AgentCore.Application.Cache.PassThroughHybridCache.RemoveAsync(string! key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +override AgentCore.Application.Cache.PassThroughHybridCache.RemoveByTagAsync(string! tag, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index b5ea3e26..620a43a2 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Tools; using AgentCore.Application.Tools.Binding; using Microsoft.Agents.AI; +using Microsoft.Extensions.Caching.Hybrid; using Microsoft.Extensions.Logging; namespace AgentCore.AspNetCore.DependencyInjection; @@ -33,6 +34,11 @@ public sealed class AgentCoreOptions /// Gets or sets the factory the library takes its loggers from. public ILoggerFactory? LoggerFactory { get; set; } + /// + /// Gets or sets the cache this container reads through, or for none. + /// + public HybridCache? Cache { get; set; } + /// Gets the map from a binds: name to the host delegate behind it. public ToolBindingRegistry Bindings { get; } = new(); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs index f5df141b..ef05948c 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs @@ -1,3 +1,4 @@ +using AgentCore.Application.Cache; using AgentCore.Application.Audit; using AgentCore.Application.Conversation; using AgentCore.Application.Configuration.Schema; @@ -71,6 +72,10 @@ public static IServiceCollection AddAgentCore( provider.GetRequiredService>().Value.TimeProvider ?? TimeProvider.System); + services.TryAddSingleton(provider => + provider.GetRequiredService>().Value.Cache + ?? PassThroughHybridCache.Instance); + services.AddHostedService(provider => new ConversationSessionSweeper( provider, provider.GetRequiredService(), diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 18309e78..23db8b54 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -23,6 +23,8 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.SecretResolver.get -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.SecretResolver.set -> void AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.TimeProvider.get -> System.TimeProvider? AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.TimeProvider.set -> void +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.Cache.get -> Microsoft.Extensions.Caching.Hybrid.HybridCache? +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.Cache.set -> void AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseAuditSinks(params AgentCore.Application.Ports.IAuditSinkAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseConversation(params AgentCore.Application.Ports.IConversationAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseConversationSessions(System.Func! open) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! From ce0fd428674c8c61bf6b70d409e2f9cafb3d3df5 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 16:19:31 -0600 Subject: [PATCH 34/35] feat(embeddings): implement HybridCachingEmbeddingGenerator and related tests --- Directory.Packages.props | 2 + .../HybridCachingEmbeddingGenerator.cs | 66 +++++++++++++++ .../PublicAPI.Unshipped.txt | 3 + .../Startup/EmbeddingStartup.cs | 20 +++-- .../AgentCore.Application.Tests.csproj | 2 + .../Fakes/CountingEmbeddingGenerator.cs | 32 ++++++++ .../HybridCachingEmbeddingGeneratorTests.cs | 80 +++++++++++++++++++ 7 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 src/AgentCore.Application/Embeddings/HybridCachingEmbeddingGenerator.cs create mode 100644 tests/AgentCore.Application.Tests/Embeddings/Fakes/CountingEmbeddingGenerator.cs create mode 100644 tests/AgentCore.Application.Tests/Embeddings/HybridCachingEmbeddingGeneratorTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index d0489767..6a31555c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,8 @@ + + diff --git a/src/AgentCore.Application/Embeddings/HybridCachingEmbeddingGenerator.cs b/src/AgentCore.Application/Embeddings/HybridCachingEmbeddingGenerator.cs new file mode 100644 index 00000000..02403b81 --- /dev/null +++ b/src/AgentCore.Application/Embeddings/HybridCachingEmbeddingGenerator.cs @@ -0,0 +1,66 @@ +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Caching.Hybrid; + +namespace AgentCore.Application.Embeddings; + +/// +/// Remembers each text's embedding in the host's cache, so a repeat of the same text under the same +/// model skips the vendor call. The framework's base class wants a plain read and a plain write; +/// has no plain read, so the read is a create that is told not to create. +/// +public sealed class HybridCachingEmbeddingGenerator : CachingEmbeddingGenerator> +{ + /// How long an entry lives when the host names no lifetime. + public static readonly TimeSpan DefaultLifetime = TimeSpan.FromDays(1); + + private const string KeyPrefix = "agentcore:embedding:"; + + private static readonly HybridCacheEntryOptions ReadOnly = new() + { + Flags = HybridCacheEntryFlags.DisableUnderlyingData, + }; + + private readonly HybridCache _cache; + + private readonly HybridCacheEntryOptions _write; + + private readonly string? _defaultModel; + + /// Wraps one generator in the cache. + /// The generator that talks to the vendor. + /// The host's cache. + /// How long one embedding stays cached, or for . + public HybridCachingEmbeddingGenerator( + IEmbeddingGenerator> inner, + HybridCache cache, + TimeSpan? lifetime = null) + : base(inner) + { + ArgumentNullException.ThrowIfNull(cache); + + _cache = cache; + _write = new HybridCacheEntryOptions { Expiration = lifetime ?? DefaultLifetime }; + _defaultModel = inner.GetService()?.DefaultModelId; + } + + /// + /// + /// The base hands in the text and the call's options. The options may name no model, in which + /// case the vendor falls back to the generator's default, so that default joins the key. + /// + protected override string GetCacheKey(params ReadOnlySpan values) + { + object?[] parts = [.. values, _defaultModel]; + return KeyPrefix + AIJsonUtilities.HashDataToString(parts, AIJsonUtilities.DefaultOptions); + } + + /// + protected override async Task?> ReadCacheAsync(string key, CancellationToken cancellationToken) + => await _cache + .GetOrCreateAsync(key, static _ => ValueTask.FromResult?>(null), ReadOnly, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + /// + protected override Task WriteCacheAsync(string key, Embedding value, CancellationToken cancellationToken) + => _cache.SetAsync(key, value, _write, cancellationToken: cancellationToken).AsTask(); +} diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 6a5a7171..b74efc61 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -2334,3 +2334,6 @@ override AgentCore.Application.Cache.PassThroughHybridCache.GetOrCreateAsync(string! key, T value, Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions? options = null, System.Collections.Generic.IEnumerable? tags = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask override AgentCore.Application.Cache.PassThroughHybridCache.RemoveAsync(string! key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask override AgentCore.Application.Cache.PassThroughHybridCache.RemoveByTagAsync(string! tag, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Embeddings.HybridCachingEmbeddingGenerator +AgentCore.Application.Embeddings.HybridCachingEmbeddingGenerator.HybridCachingEmbeddingGenerator(Microsoft.Extensions.AI.IEmbeddingGenerator!>! inner, Microsoft.Extensions.Caching.Hybrid.HybridCache! cache, System.TimeSpan? lifetime = null) -> void +static readonly AgentCore.Application.Embeddings.HybridCachingEmbeddingGenerator.DefaultLifetime -> System.TimeSpan diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/EmbeddingStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/EmbeddingStartup.cs index 04cffd64..953dc01a 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/EmbeddingStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/EmbeddingStartup.cs @@ -11,12 +11,22 @@ internal static class EmbeddingStartup /// The loaded document. It carries providers.embeddings. /// The options the host filled. It carries the registered vendors. /// Cancels the adapter build. - internal static ValueTask>?> OpenAsync( + internal static async ValueTask>?> OpenAsync( AgentCoreConfiguration configuration, AgentCoreOptions options, CancellationToken cancellationToken) - => options.Embeddings is { } adapters - ? CompositeEmbeddingGeneratorFactory.CreateAsync( - configuration, options.SecretResolver, adapters, cancellationToken) - : ValueTask.FromResult>?>(null); + { + if (options.Embeddings is not { } adapters) + { + return null; + } + + var generator = await CompositeEmbeddingGeneratorFactory + .CreateAsync(configuration, options.SecretResolver, adapters, cancellationToken) + .ConfigureAwait(false); + + return generator is null || options.Cache is not { } cache + ? generator + : new HybridCachingEmbeddingGenerator(generator, cache); + } } diff --git a/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj b/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj index 52210c94..a993c820 100644 --- a/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj +++ b/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj @@ -11,6 +11,8 @@ + + diff --git a/tests/AgentCore.Application.Tests/Embeddings/Fakes/CountingEmbeddingGenerator.cs b/tests/AgentCore.Application.Tests/Embeddings/Fakes/CountingEmbeddingGenerator.cs new file mode 100644 index 00000000..e1e972fa --- /dev/null +++ b/tests/AgentCore.Application.Tests/Embeddings/Fakes/CountingEmbeddingGenerator.cs @@ -0,0 +1,32 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Tests.Embeddings.Fakes; + +/// +/// A vendor that counts how many texts it was asked to embed and answers each with its length. +/// +internal sealed class CountingEmbeddingGenerator(string defaultModel) : IEmbeddingGenerator> +{ + private readonly EmbeddingGeneratorMetadata _metadata = new(defaultModelId: defaultModel); + + /// Gets how many texts reached the vendor, across every call. + public int TextsEmbedded { get; private set; } + + public Task>> GenerateAsync( + IEnumerable values, + EmbeddingGenerationOptions? options = null, + CancellationToken cancellationToken = default) + { + var texts = values.ToList(); + TextsEmbedded += texts.Count; + return Task.FromResult(new GeneratedEmbeddings>( + texts.Select(text => new Embedding(new float[] { text.Length })))); + } + + public object? GetService(Type serviceType, object? serviceKey = null) + => serviceType == typeof(EmbeddingGeneratorMetadata) ? _metadata : null; + + public void Dispose() + { + } +} diff --git a/tests/AgentCore.Application.Tests/Embeddings/HybridCachingEmbeddingGeneratorTests.cs b/tests/AgentCore.Application.Tests/Embeddings/HybridCachingEmbeddingGeneratorTests.cs new file mode 100644 index 00000000..50eb6d54 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Embeddings/HybridCachingEmbeddingGeneratorTests.cs @@ -0,0 +1,80 @@ +using AgentCore.Application.Embeddings; +using AgentCore.Application.Tests.Embeddings.Fakes; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace AgentCore.Application.Tests.Embeddings; + +/// +/// The cache in front of the embedding vendor. A repeat of one text under one model must not +/// reach the vendor again; a different model must. +/// +public sealed class HybridCachingEmbeddingGeneratorTests +{ + private static HybridCache NewCache() + { + ServiceCollection services = new(); + services.AddHybridCache(); + return services.BuildServiceProvider().GetRequiredService(); + } + + [Fact] + public async Task Repeat_of_one_text_skips_the_vendor() + { + CountingEmbeddingGenerator vendor = new("model-a"); + using HybridCachingEmbeddingGenerator generator = new(vendor, NewCache()); + + var first = await generator.GenerateAsync(["hello"], cancellationToken: TestContext.Current.CancellationToken); + var second = await generator.GenerateAsync(["hello"], cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(1, vendor.TextsEmbedded); + Assert.Equal(first[0].Vector.ToArray(), second[0].Vector.ToArray()); + } + + [Fact] + public async Task Only_the_new_text_in_a_batch_reaches_the_vendor() + { + CountingEmbeddingGenerator vendor = new("model-a"); + using HybridCachingEmbeddingGenerator generator = new(vendor, NewCache()); + + await generator.GenerateAsync(["hello"], cancellationToken: TestContext.Current.CancellationToken); + var batch = await generator.GenerateAsync(["hello", "world!"], cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(2, vendor.TextsEmbedded); + Assert.Equal([5f], batch[0].Vector.ToArray()); + Assert.Equal([6f], batch[1].Vector.ToArray()); + } + + [Fact] + public async Task A_different_model_gets_its_own_entry() + { + CountingEmbeddingGenerator vendor = new("model-a"); + using HybridCachingEmbeddingGenerator generator = new(vendor, NewCache()); + + await generator.GenerateAsync(["hello"], cancellationToken: TestContext.Current.CancellationToken); + await generator.GenerateAsync( + ["hello"], + new EmbeddingGenerationOptions { ModelId = "model-b" }, + TestContext.Current.CancellationToken); + + Assert.Equal(2, vendor.TextsEmbedded); + } + + [Fact] + public async Task Two_vendors_with_different_default_models_do_not_share_entries() + { + var cache = NewCache(); + CountingEmbeddingGenerator vendorA = new("model-a"); + CountingEmbeddingGenerator vendorB = new("model-b"); + using HybridCachingEmbeddingGenerator generatorA = new(vendorA, cache); + using HybridCachingEmbeddingGenerator generatorB = new(vendorB, cache); + + await generatorA.GenerateAsync(["hello"], cancellationToken: TestContext.Current.CancellationToken); + await generatorB.GenerateAsync(["hello"], cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(1, vendorA.TextsEmbedded); + Assert.Equal(1, vendorB.TextsEmbedded); + } +} From f666d320c1cf2c518d547f126797da61d4ebf369 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 19 Sep 2026 16:45:43 -0600 Subject: [PATCH 35/35] feat(compiler): refactor CompiledAgent construction using CompiledAgentBuilder for improved clarity and maintainability --- .../Compilation/CompiledAgent.cs | 92 ++++++++----------- .../Compilation/CompiledAgentBuilder.cs | 41 +++++++++ .../Compilation/ConfigurationCompiler.cs | 11 ++- .../PublicAPI.Unshipped.txt | 3 - 4 files changed, 89 insertions(+), 58 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/CompiledAgentBuilder.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs index 1001d5a6..dfd5e469 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs @@ -12,53 +12,36 @@ namespace AgentCore.Application.Configuration.Compilation; /// public sealed class CompiledAgent { - private readonly Dictionary _byAgentId; + private readonly CompiledDocument _document; - private readonly Dictionary _agentIdByStage; + private readonly CompileTableRow _row; + + private readonly EntryBuild _build; + + private readonly CompiledAgentSet _agents; + + private readonly TurnLayers _layers; private readonly Dictionary _turnByAgentId; /// Compiles one entry: its row's build, with the turn layers on every agent a turn runs. - /// What every entry of the document shares. - /// The entry key. It is the agent's name. - /// The entry's stage machine, or when it holds none. - /// The row of the compile table the entry selected. - /// What the row built for the entry. - /// The agents.items entries the row built on. - /// The turn layers of the entry. - internal CompiledAgent( - CompiledDocument document, - string entryName, - PolicyConfiguration? policy, - CompileTableRow row, - EntryBuild build, - CompiledAgentSet agents, - TurnLayers layers) + /// Every part of the entry, complete. + internal CompiledAgent(CompiledAgentBuilder builder) { - ArgumentException.ThrowIfNullOrEmpty(entryName); - - Configuration = document.Configuration; - EntryName = entryName; - Policy = policy; - FallbackReply = layers.FallbackReply; - RefusalReply = layers.RefusalReply; - Shape = row.Shape; - SessionCarriesHistory = row.SessionCarriesHistory; - Agent = build.Agent; - ConversationStore = document.Conversations; - SpokenBy = layers.SpokenBy; - History = document.History; - HarnessStateKeys = agents.HarnessStateKeys; - BackgroundProviders = agents.BackgroundProviders; - _byAgentId = agents.Agents; - _agentIdByStage = build.Stages; - - TurnAgent = layers.Apply(build.Agent); + _document = builder.Document; + EntryName = builder.EntryName; + Policy = builder.Policy; + _row = builder.Row; + _build = builder.Entry; + _agents = builder.Agents; + _layers = builder.Layers; + + TurnAgent = _layers.Apply(_build.Agent); _turnByAgentId = new Dictionary(StringComparer.Ordinal); - foreach (var (id, agent) in agents.Agents) + foreach (var (id, agent) in _agents.Agents) { - _turnByAgentId[id] = layers.Apply(agent); + _turnByAgentId[id] = _layers.Apply(agent); } } @@ -66,25 +49,25 @@ internal CompiledAgent( /// Gets whether the row answers its runs out of store 1 on its own session, rather than the /// request messages. /// - internal bool SessionCarriesHistory { get; } + internal bool SessionCarriesHistory => _row.SessionCarriesHistory; /// Gets the document this agent was compiled from. - public AgentCoreConfiguration Configuration { get; } + public AgentCoreConfiguration Configuration => _document.Configuration; /// Gets the entry key this agent was compiled from. It is the agent's name. - public string EntryName { get; } + internal string EntryName { get; } /// Gets this entry's stage machine, or when the entry holds none. public PolicyConfiguration? Policy { get; } /// Gets the resolved line the caller hears when a turn fails. - public string FallbackReply { get; } + public string FallbackReply => _layers.FallbackReply; /// Gets the resolved line the caller hears when the agent refuses to answer. - public string RefusalReply { get; } + internal string RefusalReply => _layers.RefusalReply; /// Gets the row of the compile table this entry selected. - public CompiledAgentShape Shape { get; } + internal CompiledAgentShape Shape => _row.Shape; /// Gets the name of the entry. public string Name => EntryName; @@ -92,33 +75,34 @@ internal CompiledAgent( /// /// Gets the agent a turn runs. /// - public AIAgent Agent { get; } + public AIAgent Agent => _build.Agent; /// /// Gets the agents whose reply the caller hears, or for all of them. /// - internal IReadOnlySet? SpokenBy { get; } + internal IReadOnlySet? SpokenBy => _layers.SpokenBy; /// /// Gets store 1 of every conversation this agent answers. /// - internal AgentCoreChatHistoryProvider History { get; } + internal AgentCoreChatHistoryProvider History => _document.History; /// Gets the store this agent's conversations and every word of them are kept in. - internal IConversationStore ConversationStore { get; } + internal IConversationStore ConversationStore => _document.Conversations; + /// /// Gets the union of every harness provider's state keys, over every agent this document /// compiled — never the history provider's key. Empty when the document names no harness /// switch. This is what a conversation's Providers keeps beside its stage and its slots. /// - internal IReadOnlySet HarnessStateKeys { get; } + internal IReadOnlySet HarnessStateKeys => _agents.HarnessStateKeys; #pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. /// /// Gets every background provider this document compiled, over every agent. The conversation releases /// each one's session when it ends, so children still running cannot outlive it. /// - internal IReadOnlyList BackgroundProviders { get; } + internal IReadOnlyList BackgroundProviders => _agents.BackgroundProviders; #pragma warning restore MAAI001 /// @@ -129,7 +113,7 @@ internal CompiledAgent( /// /// Gets every compiled agent, keyed by the agents.items id. /// - public IReadOnlyDictionary Agents => _byAgentId; + public IReadOnlyDictionary Agents => _agents.Agents; /// Gets the agent one stage names. /// The stage id. @@ -139,12 +123,12 @@ internal CompiledAgent( { ArgumentNullException.ThrowIfNull(stageId); - if (!_agentIdByStage.TryGetValue(stageId, out var agentId)) + if (!_build.Stages.TryGetValue(stageId, out var agentId)) { throw new KeyNotFoundException($"The stage '{stageId}' is not declared in policy.stages."); } - return agentId.Length == 0 ? null : _byAgentId[agentId]; + return agentId.Length == 0 ? null : _agents.Agents[agentId]; } /// Gets the agent one stage names, with the turn-disposition layers on it. @@ -155,7 +139,7 @@ internal CompiledAgent( { ArgumentNullException.ThrowIfNull(stageId); - if (!_agentIdByStage.TryGetValue(stageId, out var agentId)) + if (!_build.Stages.TryGetValue(stageId, out var agentId)) { throw new KeyNotFoundException($"The stage '{stageId}' is not declared in policy.stages."); } diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentBuilder.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentBuilder.cs new file mode 100644 index 00000000..cc64474b --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentBuilder.cs @@ -0,0 +1,41 @@ +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Configuration.Compilation; + +/// +/// Collects what one entry compiles from, then builds the once every +/// part is present. required makes the compiler enforce completeness, so a new part is one +/// property here and one on the record that owns it; the constructor never grows. +/// +internal sealed class CompiledAgentBuilder +{ + /// Gets what every entry of the document shares. + public required CompiledDocument Document { get; init; } + + /// Gets the entry key. It is the agent's name. + public required string EntryName { get; init; } + + /// Gets the entry's stage machine, or when it holds none. + public PolicyConfiguration? Policy { get; init; } + + /// Gets the row of the compile table the entry selected. + public required CompileTableRow Row { get; init; } + + /// Gets what the row built for the entry. + public required EntryBuild Entry { get; init; } + + /// Gets the agents.items entries the row built on. + public required CompiledAgentSet Agents { get; init; } + + /// Gets the turn layers of the entry. + public required TurnLayers Layers { get; init; } + + /// Builds the agent, putting the turn layers on every agent a turn runs. + /// The compiled entry. + public CompiledAgent Build() + { + ArgumentException.ThrowIfNullOrEmpty(EntryName); + + return new CompiledAgent(this); + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index d046fcd2..c528aedc 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -166,7 +166,16 @@ public static IReadOnlyDictionary CompileAll( context.Moderation, row.SpokenAuthors(configuration, entry)); - compiled[entryName] = new CompiledAgent(document, entryName, entry.Policy, row, build, shared, layers); + compiled[entryName] = new CompiledAgentBuilder + { + Document = document, + EntryName = entryName, + Policy = entry.Policy, + Row = row, + Entry = build, + Agents = shared, + Layers = layers, + }.Build(); } return compiled; diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index b74efc61..45e5b98a 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -177,13 +177,10 @@ AgentCore.Application.Configuration.Compilation.CompiledAgent.Agent.get -> Micro AgentCore.Application.Configuration.Compilation.CompiledAgent.Agents.get -> System.Collections.Generic.IReadOnlyDictionary! AgentCore.Application.Configuration.Compilation.CompiledAgent.Configuration.get -> AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! AgentCore.Application.Configuration.Compilation.CompiledAgent.CreatePolicy(AgentCore.Application.Configuration.Validation.IGuardEvaluator! guards) -> AgentCore.Application.Policy.StagePolicy! -AgentCore.Application.Configuration.Compilation.CompiledAgent.EntryName.get -> string! AgentCore.Application.Configuration.Compilation.CompiledAgent.FallbackReply.get -> string! AgentCore.Application.Configuration.Compilation.CompiledAgent.ForStage(string! stageId) -> Microsoft.Agents.AI.AIAgent? AgentCore.Application.Configuration.Compilation.CompiledAgent.Name.get -> string! AgentCore.Application.Configuration.Compilation.CompiledAgent.Policy.get -> AgentCore.Application.Configuration.Schema.PolicyConfiguration? -AgentCore.Application.Configuration.Compilation.CompiledAgent.RefusalReply.get -> string! -AgentCore.Application.Configuration.Compilation.CompiledAgent.Shape.get -> AgentCore.Application.Configuration.Compilation.CompiledAgentShape AgentCore.Application.Configuration.Compilation.CompiledAgentRegistry AgentCore.Application.Configuration.Compilation.CompiledAgentRegistry.CompileCount.get -> int AgentCore.Application.Configuration.Compilation.CompiledAgentRegistry.CompiledAgentRegistry() -> void