From 85d511f9a22b32bb08df24a8fb9f4e7d83886937 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Fri, 11 Sep 2026 17:59:41 -0600 Subject: [PATCH 01/32] feat!: Let a host append to a call from outside any turn The store now numbers every message from a counter it owns, so a human-handoff row written from another machine cannot collide with the session's own rows. Every AgentCore table moves into the `agentcore` schema. - Add `call.next_ordinal`. `AppendAsync` takes drafts and returns the rows with their ordinals, numbered in one atomic statement. - Add `ICallStore.AppendMessageAsync(callId, message)` for a host to write one row outside any turn. - `RewriteAsync` finds a row by message id, not by ordinal. - Move `NextOrdinal` from `CallSessionState` to `CallRecord`. - At every turn after the first, the session drains, reads the counter, and re-reads the words only when the counter moved. A failed read raises `CallEventKind.TranscriptResyncFailed` (13) and the turn runs on the words it holds. - Name the `agentcore` schema in every statement. The ledger is now `agentcore.schema_migration`. - Split `PostgresCallStore` into `PostgresCallRows` and `PostgresCallVerification`. Split the three largest test files. BREAKING CHANGE: `ICallStore.AppendAsync` takes a call id and `CallMessageDraft` rows and returns the written rows. `RewriteAsync` takes a message id. `CallSessionState.NextOrdinal` is gone. Every table lives in the `agentcore` schema, so a consumer's `principalSchema` is now `"agentcore"`. --- src/AgentCore.Application/Calls/CallRecord.cs | 8 +- .../Calls/CallSessionState.cs | 3 - .../Calls/Memory/InMemoryCallStore.cs | 78 ++- src/AgentCore.Application/Diagnostics/Log.cs | 13 + src/AgentCore.Application/Ports/ICallStore.cs | 45 +- .../PublicAPI.Unshipped.txt | 36 +- .../Runtime/CallEventChain.cs | 11 + .../Runtime/CallEventKind.cs | 6 + .../Runtime/CallEventKinds.cs | 1 + .../Runtime/CallSession.cs | 50 +- .../AgentCoreChatHistoryProvider.cs | 74 ++- .../Transcript/CallMessageDraft.cs | 12 + .../Transcript/CallMessageIds.cs | 8 + .../Transcript/CallTranscript.cs | 19 +- .../Audit/Postgres/PostgresAuditSink.cs | 41 +- .../Calls/Postgres/PostgresCallRows.cs | 66 +++ .../Calls/Postgres/PostgresCallStore.cs | 151 ++--- .../Calls/Postgres/PostgresCallStoreSql.cs | 83 +-- .../Postgres/PostgresCallVerification.cs | 44 ++ .../Postgres/Migrations/001_agentcore.sql | 100 ++-- .../Database/Postgres/PostgresSchema.cs | 23 +- .../Audit/AuditCallObserverTests.cs | 1 + .../Calls/ChatCallTitlerTests.cs | 3 +- .../Calls/DelegatingCallStoreTests.cs | 10 +- .../Calls/InMemoryCallStoreTests.cs | 8 +- .../Calls/InMemoryCallStoreTranscriptTests.cs | 63 ++- .../Memory/InMemoryCallStoreAppendTests.cs | 185 +++++++ .../Fakes/RecordingCallStore.cs | 51 +- .../Fakes/ThrowingCallStore.cs | 7 +- .../Runtime/AgentCoreAgentSessionTests.cs | 364 +++++++++++++ .../Runtime/AgentCoreAgentTestSupport.cs | 88 +++ .../Runtime/AgentCoreAgentTests.cs | 431 +-------------- .../Runtime/CallEventKindsTests.cs | 3 +- ...AgentCoreChatHistoryProviderTestSupport.cs | 149 +++++ .../AgentCoreChatHistoryProviderTests.cs | 315 +---------- ...entCoreChatHistoryProviderTruncateTests.cs | 181 ++++++ .../CallSessionOutsideAppendTests.cs | 208 +++++++ .../CallSessionResumeTestSupport.cs | 147 +++++ .../Transcript/CallSessionResumeTests.cs | 515 +----------------- .../CallSessionStateRestoreTests.cs | 334 ++++++++++++ .../CallSessionStoreFailureTests.cs | 24 + .../DependencyInjection/AddAgentCoreTests.cs | 11 +- .../Postgres/PostgresAuditSinkAdapterTests.cs | 4 +- .../Audit/Postgres/PostgresAuditSinkTests.cs | 16 +- .../Calls/Postgres/CallThreadSchemaTests.cs | 38 +- .../Calls/Postgres/PostgresCallListTests.cs | 4 +- .../Postgres/PostgresCallPrincipalTests.cs | 12 +- .../Postgres/PostgresCallStoreAppendTests.cs | 214 ++++++++ .../Postgres/PostgresCallStoreSweepTests.cs | 36 +- .../Calls/Postgres/PostgresCallStoreTests.cs | 10 +- .../PostgresCallStoreTruncateTests.cs | 32 +- .../Postgres/PostgresCallStoreWordsTests.cs | 135 ++--- .../Database/Postgres/PostgresSchemaTests.cs | 73 ++- .../DelegatingCallStore.cs | 11 +- .../AgentCore.TestSupport/ParkingCallStore.cs | 9 +- 55 files changed, 2788 insertions(+), 1776 deletions(-) create mode 100644 src/AgentCore.Application/Transcript/CallMessageDraft.cs create mode 100644 src/AgentCore.Application/Transcript/CallMessageIds.cs create mode 100644 src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs create mode 100644 src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs create mode 100644 tests/AgentCore.Application.Tests/Calls/Memory/InMemoryCallStoreAppendTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTestSupport.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs create mode 100644 tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs diff --git a/src/AgentCore.Application/Calls/CallRecord.cs b/src/AgentCore.Application/Calls/CallRecord.cs index f8d7ac25..9065706e 100644 --- a/src/AgentCore.Application/Calls/CallRecord.cs +++ b/src/AgentCore.Application/Calls/CallRecord.cs @@ -18,6 +18,11 @@ namespace AgentCore.Application.Calls; /// 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, @@ -26,4 +31,5 @@ public sealed record CallRecord( JsonElement? Custom, DateTimeOffset CreatedAt, DateTimeOffset? LastMessageAt, - CallSessionState? State = null); + CallSessionState? State = null, + int NextOrdinal = 0); diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Calls/CallSessionState.cs index 274d6a73..e7dbb0c0 100644 --- a/src/AgentCore.Application/Calls/CallSessionState.cs +++ b/src/AgentCore.Application/Calls/CallSessionState.cs @@ -20,9 +20,6 @@ public sealed record CallSessionState /// Gets the shape this blob was written in. public int Version { get; init; } = CurrentVersion; - /// Gets the next free ordinal of the call. - public int NextOrdinal { get; init; } - /// Gets the index the call's next turn takes. public int NextTurnIndex { get; init; } diff --git a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs index 05f6550e..3aefe81b 100644 --- a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs +++ b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs @@ -17,6 +17,9 @@ public sealed class InMemoryCallStore : ICallStore /// 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 = []; private readonly TimeProvider _time; @@ -39,7 +42,11 @@ public ValueTask CreateAsync(string callId, CancellationToken cancel _calls[callId] = existing; } - return ValueTask.FromResult(existing with { State = _state.GetValueOrDefault(callId) }); + return ValueTask.FromResult(existing with + { + State = _state.GetValueOrDefault(callId), + NextOrdinal = _nextOrdinal.GetValueOrDefault(callId), + }); } } @@ -51,7 +58,14 @@ public ValueTask CreateAsync(string callId, CancellationToken cancel lock (_lock) { var call = _calls.GetValueOrDefault(callId); - return ValueTask.FromResult(call is null ? null : call with { State = _state.GetValueOrDefault(callId) }); + + return ValueTask.FromResult(call is null + ? null + : call with + { + State = _state.GetValueOrDefault(callId), + NextOrdinal = _nextOrdinal.GetValueOrDefault(callId), + }); } } @@ -137,6 +151,7 @@ public ValueTask DeleteAsync(string callId, CancellationToken cancellationToken _calls.Remove(callId); _claims.RemoveWhere(claim => claim.CallId == callId); _state.Remove(callId); + _nextOrdinal.Remove(callId); RemoveWords(callId); } @@ -170,6 +185,7 @@ public ValueTask SweepAsync( _calls.Remove(callId); _claims.RemoveWhere(claim => claim.CallId == callId); _state.Remove(callId); + _nextOrdinal.Remove(callId); RemoveWords(callId); } @@ -209,48 +225,74 @@ public ValueTask DetachPrincipalAsync( } /// - public ValueTask AppendAsync( - IReadOnlyList messages, + 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) { - var now = _time.GetUtcNow(); + 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); - foreach (var message in messages) + var rows = new List(messages.Count); + for (var index = 0; index < messages.Count; index++) { - _rows.Add((message.CallId, message.Ordinal), message); + var draft = messages[index]; + CallMessage row = new( + callId, first + index, draft.TurnIndex ?? fallbackTurnIndex, draft.Content, draft.MessageId); - if (_calls.TryGetValue(message.CallId, out var call)) - { - _calls[message.CallId] = call with { LastMessageAt = now }; - } + rows.Add(row); + _rows.Add((row.CallId, row.Ordinal), row); } - if (state is not null && messages.Count > 0) + _nextOrdinal[callId] = first + messages.Count; + + var now = _time.GetUtcNow(); + _calls[callId] = call with { LastMessageAt = now }; + + if (state is not null) { - _state[messages[0].CallId] = state; + _state[callId] = state; } - } - return default; + return ValueTask.FromResult>(rows); + } } /// public ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(callId); + ArgumentException.ThrowIfNullOrEmpty(messageId); ArgumentNullException.ThrowIfNull(content); lock (_lock) { - if (_rows.TryGetValue((callId, ordinal), out var row)) + foreach (var pair in _rows) { - _rows[(callId, ordinal)] = row with { Content = content }; + if (pair.Key.CallId != callId || pair.Value.MessageId != messageId) + { + continue; + } + + _rows[pair.Key] = pair.Value with { Content = content }; + break; } } diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index 5645fdc5..db398a39 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -236,4 +236,17 @@ public static partial void KnowledgeScopeComposed( + "added. Point this agent at a model whose vendor runs a hosted web search, or remove " + "the tool from this agent.")] public static partial void HostedWebSearchDropped(ILogger logger, string agentId, string toolId, string model); + + /// 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 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. " + + "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); } diff --git a/src/AgentCore.Application/Ports/ICallStore.cs b/src/AgentCore.Application/Ports/ICallStore.cs index b1da3e1f..f9c63100 100644 --- a/src/AgentCore.Application/Ports/ICallStore.cs +++ b/src/AgentCore.Application/Ports/ICallStore.cs @@ -64,6 +64,7 @@ ValueTask ListAsync( ValueTask DeleteAsync(string callId, 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 rows to write, oldest first. /// /// What the session holds after this turn, or to leave the stored state @@ -73,18 +74,54 @@ ValueTask ListAsync( /// it to ride with, so there is nothing to write it beside. /// /// Cancels the write. - ValueTask AppendAsync( - IReadOnlyList messages, + /// + /// 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 + /// 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. + /// + ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? 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. + /// + /// The call 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, 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 rows = await AppendAsync(callId, [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 message's position within the call. + /// + /// 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. + /// /// What the caller actually heard. /// Cancels the write. ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default); + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default); /// Reads one whole call's words, oldest message first. /// The call to read. diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 62ff50a4..e33ca916 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -78,17 +78,19 @@ 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) -> 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) -> 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 @@ -103,8 +105,6 @@ 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.NextOrdinal.get -> int -AgentCore.Application.Calls.CallSessionState.NextOrdinal.init -> void AgentCore.Application.Calls.CallSessionState.NextTurnIndex.get -> int AgentCore.Application.Calls.CallSessionState.NextTurnIndex.init -> void AgentCore.Application.Calls.CallSessionState.Slots.get -> System.Collections.Generic.IReadOnlyDictionary! @@ -123,7 +123,7 @@ AgentCore.Application.Calls.ChatCallTitler.ChatCallTitler(AgentCore.Application. 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(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.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 @@ -134,7 +134,7 @@ AgentCore.Application.Calls.Memory.InMemoryCallStore.InMemoryCallStore(System.Ti 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, int ordinal, Microsoft.Extensions.AI.ChatMessage! content, 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.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 @@ -989,7 +989,8 @@ AgentCore.Application.Ports.ICallSessions.CloseAsync(string! callId, System.Thre 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(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.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.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 @@ -999,7 +1000,7 @@ AgentCore.Application.Ports.ICallStore.GetAsync(string! callId, System.Threading 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, int ordinal, Microsoft.Extensions.AI.ChatMessage! content, 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.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 @@ -1101,6 +1102,7 @@ AgentCore.Application.Runtime.CallEventKind.ModerationUnavailable = 2 -> AgentCo 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.TranscriptResyncFailed = 13 -> AgentCore.Application.Runtime.CallEventKind AgentCore.Application.Runtime.CallEventKind.ToolFailed = 4 -> AgentCore.Application.Runtime.CallEventKind AgentCore.Application.Runtime.CallEventKind.TranscriptWriteFailed = 10 -> AgentCore.Application.Runtime.CallEventKind AgentCore.Application.Runtime.CallEventKind.TurnCompleted = 7 -> AgentCore.Application.Runtime.CallEventKind @@ -1295,6 +1297,18 @@ 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.RenderContent AgentCore.Application.Transcript.RenderContent.Data.get -> System.Text.Json.JsonElement AgentCore.Application.Transcript.RenderContent.Data.set -> void @@ -1600,6 +1614,9 @@ override AgentCore.Application.Tools.Registry.ToolSourceContext.ToString() -> st 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.Call.CallInput.Barge.Equals(AgentCore.Application.Call.CallInput? other) -> bool override sealed AgentCore.Application.Call.CallInput.Keypress.Equals(AgentCore.Application.Call.CallInput? other) -> bool override sealed AgentCore.Application.Call.CallInput.Utterance.Equals(AgentCore.Application.Call.CallInput? other) -> bool @@ -1835,6 +1852,9 @@ static AgentCore.Application.Tools.ToolErrorResult.IsError(System.Text.Json.Node 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.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! diff --git a/src/AgentCore.Application/Runtime/CallEventChain.cs b/src/AgentCore.Application/Runtime/CallEventChain.cs index dcc7e237..d09c5a36 100644 --- a/src/AgentCore.Application/Runtime/CallEventChain.cs +++ b/src/AgentCore.Application/Runtime/CallEventChain.cs @@ -228,6 +228,17 @@ internal void RaiseDroppedTranscriptWrite(int turnIndex, Exception exception) [CallEventPayloadKeys.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, + _time.GetUtcNow(), + turnIndex, + payload: new Dictionary(StringComparer.Ordinal) + { + [CallEventPayloadKeys.Reason] = $"{exception.GetType().Name}: {exception.Message}", + }); + /// Hands one fact to everything watching the call, and never waits for it. /// What happened. /// When it happened. diff --git a/src/AgentCore.Application/Runtime/CallEventKind.cs b/src/AgentCore.Application/Runtime/CallEventKind.cs index 2d510152..a654d307 100644 --- a/src/AgentCore.Application/Runtime/CallEventKind.cs +++ b/src/AgentCore.Application/Runtime/CallEventKind.cs @@ -43,4 +43,10 @@ public enum CallEventKind /// A resumed call could not restore part of its stored state: the document changed under it. StateRestorePartial = 11, + + /// + /// Store 1 could not be read as a turn opened, so the turn ran on the words the session already + /// held. A message appended outside a turn since the last read is not among them. + /// + TranscriptResyncFailed = 13, } diff --git a/src/AgentCore.Application/Runtime/CallEventKinds.cs b/src/AgentCore.Application/Runtime/CallEventKinds.cs index e1500681..e2d49a12 100644 --- a/src/AgentCore.Application/Runtime/CallEventKinds.cs +++ b/src/AgentCore.Application/Runtime/CallEventKinds.cs @@ -43,6 +43,7 @@ public static string ToToken(CallEventKind kind) 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. diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 33d8bfcc..530fe0df 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -486,7 +486,42 @@ public bool EndCall(CallEndReason reason) } /// - /// Opens the session of this call, once, and hands the same one to every later turn. + /// 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. + /// + /// The session of this call. + /// Cancels the reads. + private async ValueTask ResyncTranscriptAsync(AgentSession opened, CancellationToken cancellationToken) + { + await _history.DrainAsync(opened).ConfigureAwait(false); + + try + { + var refreshed = await _compiled.CallStore.GetAsync(CallId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException( + $"Store 0 holds no call '{CallId}' for its own session to resync against."); + + if (refreshed.NextOrdinal == _history.NextOrdinal(opened)) + { + return; + } + + var rows = await _compiled.CallStore.ReadAsync(CallId, cancellationToken).ConfigureAwait(false); + + _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. + catch (Exception exception) when (exception is not OperationCanceledException) +#pragma warning restore CA1031 + { + Log.TranscriptResyncFailed(_logger, CallId, State.TurnIndex, exception); + _events.RaiseFailedTranscriptResync(State.TurnIndex, exception); + } + } + + /// + /// Opens the session of this call, once, and re-syncs it with store 0 before handing it to every + /// later turn. /// /// Cancels the open. /// The session. @@ -494,6 +529,7 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell { if (Session() is { } opened) { + await ResyncTranscriptAsync(opened, cancellationToken).ConfigureAwait(false); return opened; } @@ -514,7 +550,12 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell _agentSession = session; State.TurnIndex = _history.BeginCall( - session, CallId, spoken, _events.RaiseDroppedTranscriptWrite, record.State ?? _checkpoint); + session, + CallId, + spoken, + _events.RaiseDroppedTranscriptWrite, + new TranscriptMarks( + record.NextOrdinal, (record.State ?? _checkpoint)?.NextTurnIndex ?? 0)); // After the constructor, never inside it. The const writer has already run by now, // so a slot a previous session filled lands on top of the const default rather than @@ -561,11 +602,6 @@ internal CallSessionState Snapshot() // commit reads it. NextTurnIndex = State.TurnIndex, - // Read here so a snapshot taken outside a turn — the serialize seam — carries it. On the - // commit path the provider overwrites it, because the ordinal this turn leaves behind is - // not settled until the turn's rows are cut. - NextOrdinal = Session() is { } session ? _history.NextOrdinal(session) : 0, - Clarifications = _clarifications.Spent(), }; } diff --git a/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs b/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs index 7fc90ff8..6a4c792c 100644 --- a/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs +++ b/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs @@ -49,10 +49,10 @@ public AgentCoreChatHistoryProvider(ICallStore? store = null, ILogger? logger = /// session of one call is handed the first session's words here, and nowhere else. /// /// Where a dropped store 1 write is reported, if anywhere. - /// - /// The state kept beside these words, or for a call that has none because - /// it has never spoken. Its marks say how far the call had got; the words cannot, because an edit - /// deletes the rows that would otherwise answer for it. + /// + /// How far the call had got, from store 0's own counters — or the zero marks of a call 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( @@ -60,16 +60,12 @@ public int BeginCall( string callId, IReadOnlyList spoken, TranscriptWriteDropped? report = null, - CallSessionState? stored = null) + TranscriptMarks marks = default) { ArgumentNullException.ThrowIfNull(session); ArgumentException.ThrowIfNullOrEmpty(callId); ArgumentNullException.ThrowIfNull(spoken); - var marks = stored is null - ? default - : new TranscriptMarks(stored.NextOrdinal, stored.NextTurnIndex); - return UnderLock( session, (transcript, gate) => @@ -80,6 +76,40 @@ public int BeginCall( }); } + /// Reads the ordinal the session expects the call's next row to take. + /// The session this call 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. + /// + public int NextOrdinal(AgentSession session) + { + ArgumentNullException.ThrowIfNull(session); + + return UnderLock(session, static transcript => transcript.NextOrdinal); + } + + /// + /// Replaces the call'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) + { + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(rows); + + UnderLock( + session, + transcript => + { + transcript.Resync(rows, nextOrdinal); + return true; + }); + } + /// /// Stamps the turn the next run belongs to. /// @@ -106,16 +136,6 @@ public IReadOnlyList Read(AgentSession session) return UnderLock(session, static transcript => transcript.Read()); } - /// Reads the next free ordinal of the call on one session. - /// The session this call runs on. - /// The ordinal the call's next row takes. - public int NextOrdinal(AgentSession session) - { - ArgumentNullException.ThrowIfNull(session); - - return UnderLock(session, static transcript => transcript.NextOrdinal); - } - /// Adds one finished turn's messages to the call, and the state that follows them. /// The session this call runs on. /// The messages the turn produced. @@ -154,13 +174,15 @@ public int NextOrdinal(AgentSession session) { var rows = transcript.Append(messages, firstMessageId); - // After the append, never before. The caller reads the state on its own thread and - // hands it in — which is right for everything else it carries — but the ordinal this - // turn leaves behind is not known until the rows are cut, and a state that named the - // ordinal from before them would resume the call one turn short and overwrite them. - var stored = state is null ? null : state with { NextOrdinal = transcript.NextOrdinal }; + var drafts = rows + .Select(row => new CallMessageDraft(row.TurnIndex, row.Content, row.MessageId)) + .ToArray(); - Enqueue(gate, () => _store.AppendAsync(rows, stored, CancellationToken.None), transcript); + Enqueue( + gate, + () => new ValueTask(_store.AppendAsync( + transcript.CallId, drafts, state, CancellationToken.None).AsTask()), + transcript); return rows[^1].MessageId; }); } @@ -262,7 +284,7 @@ public bool TruncateLastReply(AgentSession session, string heard, TimeSpan playe { Enqueue( gate, - () => _store.RewriteAsync(row.CallId, row.Ordinal, row.Content, CancellationToken.None), + () => _store.RewriteAsync(row.CallId, row.MessageId, row.Content, CancellationToken.None), transcript); } diff --git a/src/AgentCore.Application/Transcript/CallMessageDraft.cs b/src/AgentCore.Application/Transcript/CallMessageDraft.cs new file mode 100644 index 00000000..c89e2375 --- /dev/null +++ b/src/AgentCore.Application/Transcript/CallMessageDraft.cs @@ -0,0 +1,12 @@ +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Transcript; + +/// One message to write to a call. 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. +/// +/// The message itself. +/// What the message is called. Unique within the call. Never empty. +public sealed record CallMessageDraft(int? TurnIndex, ChatMessage Content, string MessageId); diff --git a/src/AgentCore.Application/Transcript/CallMessageIds.cs b/src/AgentCore.Application/Transcript/CallMessageIds.cs new file mode 100644 index 00000000..18a63f4d --- /dev/null +++ b/src/AgentCore.Application/Transcript/CallMessageIds.cs @@ -0,0 +1,8 @@ +namespace AgentCore.Application.Transcript; + +/// Mints the name a message takes when nobody names it. +public static class CallMessageIds +{ + /// 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/CallTranscript.cs index 86a34815..5b5ea2f3 100644 --- a/src/AgentCore.Application/Transcript/CallTranscript.cs +++ b/src/AgentCore.Application/Transcript/CallTranscript.cs @@ -28,6 +28,19 @@ internal sealed class CallTranscript /// 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) + { + Resync(rows, marks.NextOrdinal); + + return marks.NextTurnIndex; + } + + /// + /// Replaces the live history with what store 1 now holds, without disturbing + /// 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) { ArgumentNullException.ThrowIfNull(rows); @@ -43,14 +56,12 @@ public int Resume(IReadOnlyList rows, TranscriptMarks marks) Message = row.Content.WithoutHostContent(), })]; - NextOrdinal = marks.NextOrdinal; + NextOrdinal = nextOrdinal; // Without this a caller who barges in on the first reply of a resumed session is not heard: // TruncateLastReply finds no ordinal to cut at and returns nothing, and the provider reports // that as a write it declined rather than as a cut it lost. RestoreLastAssistantOrdinal(); - - return marks.NextTurnIndex; } /// Finds the ordinal a message sits at, by the name a caller knows it under. @@ -190,7 +201,7 @@ public IReadOnlyList TruncateLastReply(string heard) } /// Mints a name for a row the caller had no name for. - private static string NewMessageId() => Guid.CreateVersion7().ToString("n"); + private static string NewMessageId() => CallMessageIds.New(); /// One message of the live history, with the ordinal its stored row carries. internal sealed class StoredMessage diff --git a/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs b/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs index 6a5f9b6e..20c8bd2a 100644 --- a/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs +++ b/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs @@ -2,6 +2,7 @@ using System.Text.Json; using AgentCore.Application.Ports; using AgentCore.Domain.Audit; +using AgentCore.Infrastructure.Database.Postgres; using Npgsql; using NpgsqlTypes; @@ -12,46 +13,18 @@ namespace AgentCore.Infrastructure.Audit.Postgres; /// 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. - /// - /// - /// A transaction-scoped lock, so it is released on commit and on rollback with nothing to - /// remember. hashtext collides across call ids now and then. A collision never costs correctness - /// — two unrelated calls simply take one lock, and one batch waits — but it does weaken the - /// deadlock argument in : that argument orders the locks by - /// call_id, and ordering ids gives a consistent order on LOCKS only while the hash is - /// injective over the ids in play. Two batches whose calls hash into inverted pairs can still - /// take two locks in opposite orders and wait on each other. - /// - /// - /// Accepted rather than fixed, with the price named. Reaching it needs two 32-bit collisions - /// among the ids live at that moment, in two concurrent multi-call batches, positioned the wrong - /// way round; the consequence is that PostgreSQL's deadlock detector aborts one of the two - /// batches, which QueuedAuditSink already logs and drops off the turn. Ordering by the - /// hash itself is what would make it airtight, and rewriting the mechanism the whole chain rests - /// on is worth more than this hazard costs. - /// - /// internal const string LockSql = "SELECT pg_advisory_xact_lock(hashtext($1))"; /// Appends one call's run, numbering only the rows that will actually survive. - /// - /// row_number() runs over the rows unnest produces, so a row it would have discarded on the - /// ON CONFLICT arbiter must never reach the window function — otherwise a partially-replayed - /// batch reserves a number for a row that never lands, and the chain gaps. The NOT EXISTS filter - /// removes those rows before row_number() ever sees them. It is trustworthy only because the - /// advisory lock is held for the whole transaction: no concurrent inserter for this call can land - /// a row between the NOT EXISTS check and this INSERT's commit, so what NOT EXISTS sees here is - /// exactly what ON CONFLICT would have refused anyway. ON CONFLICT stays as the belt: it is what - /// makes a duplicate EventId inside this same batch (which NOT EXISTS cannot see, since those - /// rows are not in the table yet) merely redundant instead of a broken constraint. - /// - internal const string AppendSql = """ - INSERT INTO audit_event ( + internal const string AppendSql = $""" + INSERT INTO {Schema}.audit_event ( call_id, event_id, sequence, kind, occurred_at, turn_index, amends_event_id, payload) SELECT $1, d.event_id, - coalesce((SELECT max(sequence) FROM audit_event WHERE call_id = $1), -1) + coalesce((SELECT max(sequence) FROM {Schema}.audit_event WHERE call_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[], @@ -59,7 +32,7 @@ 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 audit_event e WHERE e.call_id = $1 AND e.event_id = d.event_id) + 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 """; diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs new file mode 100644 index 00000000..98dc83d4 --- /dev/null +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallRows.cs @@ -0,0 +1,66 @@ +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/Calls/Postgres/PostgresCallStore.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs index 050c8e4a..c37d34a7 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.AI; using Npgsql; using NpgsqlTypes; +using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallRows; using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreSql; namespace AgentCore.Infrastructure.Calls.Postgres; @@ -216,47 +217,6 @@ public async ValueTask DetachPrincipalAsync( /// A task that completes when the pool is closed. public ValueTask DisposeAsync() => _dataSource.DisposeAsync(); - /// - /// One call's row from , whose ninth column is the state a resume reads back. - /// - private static CallRecord Read(NpgsqlDataReader reader) => - ReadListing(reader) with { State = reader.IsDBNull(8) ? null : ReadState(reader.GetString(8)) }; - - /// 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. - private 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 column to read, so is left at its default - /// rather than paying to deserialize a blob a listing never shows. - /// - private 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)); - - private static string ToText(CallStatus status) => status == CallStatus.Archived ? Archived : Regular; - - private static CallStatus ToStatus(string text) => - text == Archived ? CallStatus.Archived : CallStatus.Regular; - private async ValueTask AmendAsync( string sql, string callId, NpgsqlParameter value, CancellationToken cancellationToken) { @@ -267,39 +227,48 @@ private async ValueTask AmendAsync( } /// - public async ValueTask AppendAsync( - IReadOnlyList messages, + public async ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? state = null, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(callId); ArgumentNullException.ThrowIfNull(messages); if (messages.Count == 0) { - return; + return []; } await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); await using NpgsqlBatch batch = new(connection); - foreach (CallMessage message in messages) + NpgsqlBatchCommand appendCommand = new(AppendSql); + appendCommand.Parameters.Add(new NpgsqlParameter { Value = callId }); + appendCommand.Parameters.Add(new NpgsqlParameter { - NpgsqlBatchCommand command = new(AppendSql); - command.Parameters.Add(new NpgsqlParameter { Value = message.CallId }); - command.Parameters.Add(new NpgsqlParameter { Value = message.Ordinal }); - command.Parameters.Add(new NpgsqlParameter { Value = message.TurnIndex }); - command.Parameters.Add(new NpgsqlParameter { Value = message.Content.Role.Value }); - command.Parameters.Add( - new NpgsqlParameter { Value = Serialise(message.Content), NpgsqlDbType = NpgsqlDbType.Jsonb }); - command.Parameters.Add(new NpgsqlParameter { Value = message.MessageId }); - - batch.BatchCommands.Add(command); - } + TypedValue = [.. messages.Select(message => message.TurnIndex)], + }); + appendCommand.Parameters.Add(new NpgsqlParameter + { + TypedValue = [.. messages.Select(message => message.Content.Role.Value)], + }); + appendCommand.Parameters.Add(new NpgsqlParameter + { + Value = messages.Select(message => Serialise(message.Content)).ToArray(), + NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Jsonb, + }); + appendCommand.Parameters.Add(new NpgsqlParameter + { + TypedValue = [.. messages.Select(message => message.MessageId)], + }); + batch.BatchCommands.Add(appendCommand); if (state is not null) { NpgsqlBatchCommand stateCommand = new(StateSql); - stateCommand.Parameters.Add(new NpgsqlParameter { Value = messages[0].CallId }); + stateCommand.Parameters.Add(new NpgsqlParameter { Value = callId }); stateCommand.Parameters.Add(new NpgsqlParameter { Value = JsonSerializer.Serialize(state, CallStateJson.Options), @@ -309,19 +278,42 @@ public async ValueTask AppendAsync( batch.BatchCommands.Add(stateCommand); } - await batch.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + // AppendSql is the only command with a RETURNING clause, so its result set is the only one + // this reads. Matched by message_id and not by row order: PostgreSQL makes no promise that a + // multi-row INSERT ... SELECT returns in the order its source rows arrived. + Dictionary written = []; + + await using (var reader = await batch.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false)) + { + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + written[reader.GetString(2)] = (reader.GetInt32(0), reader.GetInt32(1)); + } + } + + if (written.Count == 0) + { + throw new InvalidOperationException($"Store 0 holds no call '{callId}' to append words to."); + } + + return [.. messages.Select(draft => + { + var (ordinal, turnIndex) = written[draft.MessageId]; + return new CallMessage(callId, ordinal, turnIndex, draft.Content, draft.MessageId); + })]; } /// public async ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(callId); + 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 = ordinal }); + command.Parameters.Add(new NpgsqlParameter { Value = messageId }); command.Parameters.Add(new NpgsqlParameter { Value = Serialise(content), NpgsqlDbType = NpgsqlDbType.Jsonb }); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); @@ -384,42 +376,7 @@ public async ValueTask EraseAsync(string callId, CancellationToken cancella /// Cancels the read. /// One row for each spoken turn, oldest turn first. /// The call id is . - public async Task> ReadSpokenTurnsAsync( + public Task> ReadSpokenTurnsAsync( string callId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(callId); - - await using var command = _dataSource.CreateCommand(VerifySql); - command.Parameters.Add(new NpgsqlParameter { Value = callId }); - - List turns = []; - - await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); - while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) - { - turns.Add(new TranscriptTurnDigest( - reader.GetInt32(0), - reader.GetString(1), - reader.IsDBNull(2) ? null : reader.GetString(2))); - } - - return turns; - } - - - private static string Serialise(ChatMessage message) - => JsonSerializer.Serialize(message, TranscriptJson.Options); - - private static ChatMessage Deserialise(string content) - => JsonSerializer.Deserialize(content, TranscriptJson.Options) - ?? throw new InvalidOperationException("A call_message row holds JSON null in content."); - + => PostgresCallVerification.ReadSpokenTurnsAsync(_dataSource, callId, cancellationToken); } - -/// One spoken turn, as store 1 holds it and as store 3 proves it. -/// The turn, which is the join between the two stores. -/// The words store 1 holds. A barge-in cut them down to what the caller heard. -/// -/// The digest the chain holds for the turn, or when its event carried none. -/// -internal sealed record TranscriptTurnDigest(int TurnIndex, string Spoken, string? ReplyTextSha256); diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs index e6b76aae..137a4d33 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs @@ -1,10 +1,13 @@ using AgentCore.Domain.Audit; +using AgentCore.Infrastructure.Database.Postgres; namespace AgentCore.Infrastructure.Calls.Postgres; /// Every statement runs. internal static class PostgresCallStoreSql { + private const string Schema = PostgresSchema.SchemaName; + internal const string Regular = "regular"; internal const string Archived = "archived"; @@ -21,52 +24,52 @@ internal static class PostgresCallStoreSql """; internal const string ActivityJoin = - """ + $""" LEFT JOIN LATERAL ( - SELECT max(updated_at) AS last_message_at FROM call_message x WHERE x.call_id = c.call_id + SELECT max(updated_at) AS last_message_at FROM {Schema}.call_message x WHERE x.call_id = c.call_id ) m ON true """; internal const string CreateSql = - "INSERT INTO call (call_id) VALUES ($1) ON CONFLICT (call_id) DO NOTHING"; + $"INSERT INTO {Schema}.call (call_id) VALUES ($1) ON CONFLICT (call_id) DO NOTHING"; - /// One call's row, with the session state a resume reads back. + /// One call's row, with the session state a resume reads back and its ordinal counter. internal static readonly string GetSql = - $"SELECT {Projection}, c.state FROM call c {ActivityJoin} WHERE c.call_id = $1"; + $"SELECT {Projection}, c.state, c.next_ordinal FROM {Schema}.call c {ActivityJoin} WHERE c.call_id = $1"; internal const string StateSql = - "UPDATE call SET state = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.call SET state = $2, updated_at = now() WHERE call_id = $1"; internal const string RenameSql = - "UPDATE call SET title = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.call SET title = $2, updated_at = now() WHERE call_id = $1"; internal const string StatusSql = - "UPDATE call SET status = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.call SET status = $2, updated_at = now() WHERE call_id = $1"; internal const string CustomSql = - "UPDATE call SET custom = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.call SET custom = $2, updated_at = now() WHERE call_id = $1"; internal const string ExternalIdSql = - "UPDATE call SET external_id = $2, updated_at = now() WHERE call_id = $1"; + $"UPDATE {Schema}.call SET external_id = $2, updated_at = now() WHERE call_id = $1"; - internal const string DeleteSql = "DELETE FROM call WHERE call_id = $1"; + internal const string DeleteSql = $"DELETE FROM {Schema}.call WHERE call_id = $1"; internal const string AttachSql = - """ - INSERT INTO call_principal (call_id, principal_key, role) + $""" + INSERT INTO {Schema}.call_principal (call_id, principal_key, role) VALUES ($1, $2, $3) ON CONFLICT (principal_key, call_id) DO NOTHING """; internal const string DetachSql = - "DELETE FROM call_principal WHERE call_id = $1 AND principal_key = $2"; + $"DELETE FROM {Schema}.call_principal WHERE call_id = $1 AND principal_key = $2"; /// One page of one principal's calls. internal static readonly string ListSql = $""" SELECT {Projection} - FROM call_principal p - JOIN call c USING (call_id) + FROM {Schema}.call_principal p + JOIN {Schema}.call c USING (call_id) {ActivityJoin} WHERE p.principal_key = $1 AND ($2::text IS NULL OR c.status = $2) @@ -76,33 +79,51 @@ JOIN call c USING (call_id) LIMIT $5 """; - internal const string AppendSql = """ - INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id) - VALUES ($1, $2, $3, $4, $5, $6) + /// + /// Numbers and inserts every row of one append in a single statement. $5 (the message ids) + /// 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 + /// of naming one, which is what an append from outside any turn asks for. + /// + internal const string AppendSql = $""" + WITH mark AS ( + UPDATE {Schema}.call + SET next_ordinal = next_ordinal + cardinality($5::text[]), updated_at = now() + WHERE call_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) + 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. internal const string ReadSql = - """ + $""" SELECT ordinal, turn_index, content, message_id - FROM call_message WHERE call_id = $1 ORDER BY ordinal + FROM {Schema}.call_message WHERE call_id = $1 ORDER BY ordinal """; /// Withdraws the tail of a call, from one ordinal onward. internal const string TruncateSql = - "DELETE FROM call_message WHERE call_id = $1 AND ordinal >= $2"; + $"DELETE FROM {Schema}.call_message WHERE call_id = $1 AND ordinal >= $2"; - internal const string RewriteSql = """ - UPDATE call_message SET content = $3, updated_at = now() - WHERE call_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 """; - internal const string EraseSql = "DELETE FROM call_message WHERE call_id = $1"; + internal const string EraseSql = $"DELETE FROM {Schema}.call_message WHERE call_id = $1"; /// /// Reads what store 1 holds for each spoken turn of one call, beside what store 3 proves. /// - internal const string VerifySql = """ + internal const string VerifySql = $$""" WITH spoken AS ( SELECT DISTINCT ON (call_id, turn_index) call_id, turn_index, @@ -110,7 +131,7 @@ SELECT DISTINCT ON (call_id, turn_index) FROM jsonb_array_elements(content -> 'contents') WITH ORDINALITY AS element(part, position) WHERE part ->> '$type' = 'text') AS words - FROM call_message + FROM {{Schema}}.call_message WHERE call_id = $1 AND role = 'assistant' AND content -> 'contents' @> '[{"$type": "text"}]' @@ -118,7 +139,7 @@ FROM call_message ), completed AS ( SELECT DISTINCT ON (call_id, turn_index) call_id, turn_index, payload - FROM audit_event + FROM {{Schema}}.audit_event WHERE call_id = $1 AND kind = 'turn.completed' ORDER BY call_id, turn_index, sequence DESC ) @@ -130,11 +151,11 @@ ORDER BY m.turn_index /// Deletes one batch of calls that have aged out whole. internal static readonly string SweepSql = $""" - DELETE FROM call + DELETE FROM {Schema}.call WHERE call_id IN ( SELECT call_id FROM ( SELECT c.call_id - FROM call c + FROM {Schema}.call c {ActivityJoin} WHERE {SortAt} < now() - $1 LIMIT $2 diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs new file mode 100644 index 00000000..705c13d4 --- /dev/null +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallVerification.cs @@ -0,0 +1,44 @@ +using Npgsql; +using static AgentCore.Infrastructure.Calls.Postgres.PostgresCallStoreSql; + +namespace AgentCore.Infrastructure.Calls.Postgres; + +/// Reads store 1's words beside the hashes store 3 holds for them, for a retroactive check. +internal static class PostgresCallVerification +{ + /// Reads one call's spoken turns beside the hashes the audit chain holds for them. + /// The pool the read runs on. + /// The call to check. + /// Cancels the read. + /// One row for each spoken turn, oldest turn first. + /// The call id is . + public static async Task> ReadSpokenTurnsAsync( + NpgsqlDataSource dataSource, string callId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(callId); + + await using var command = dataSource.CreateCommand(VerifySql); + command.Parameters.Add(new NpgsqlParameter { Value = callId }); + + List turns = []; + + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + turns.Add(new TranscriptTurnDigest( + reader.GetInt32(0), + reader.GetString(1), + reader.IsDBNull(2) ? null : reader.GetString(2))); + } + + return turns; + } +} + +/// One spoken turn, as store 1 holds it and as store 3 proves it. +/// The turn, which is the join between the two stores. +/// The words store 1 holds. A barge-in cut them down to what the caller heard. +/// +/// The digest the chain holds for the turn, or when its event carried none. +/// +internal sealed record TranscriptTurnDigest(int TurnIndex, string Spoken, string? ReplyTextSha256); diff --git a/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql b/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql index 27e0c691..fca2b634 100644 --- a/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql +++ b/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql @@ -1,8 +1,9 @@ -- 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; --- call before call_message, because the words are a child of the call they belong to; audit_event --- last, with the triggers that refuse to let it change. +-- 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; audit_event last, with the triggers that refuse to +-- let it change. -- The role the running system connects as. Store 0, store 1 and store 3 share it. @@ -24,16 +25,18 @@ EXCEPTION RAISE EXCEPTION 'agentcore_writer does not exist and this role may not create it. Either CREATE ROLE agentcore_writer NOLOGIN as a role that may, or grant CREATEROLE to the migrating role.'; END $$; --- The tables land in the first schema of the migrating role's search_path, so the grant follows them --- there rather than naming public. -DO $$ -BEGIN - EXECUTE format('GRANT USAGE ON SCHEMA %I TO agentcore_writer', current_schema()); -END $$; +-- Every AgentCore table lives here, never in whatever schema happens to be first on the migrating +-- role's search_path. Nothing in this file or in the application relies on search_path: every +-- statement below names the schema explicitly. +CREATE SCHEMA IF NOT EXISTS agentcore; + +-- USAGE on the schema is what lets agentcore_writer see into any table below at all; the per-table +-- grants that follow are meaningless without it. +GRANT USAGE ON SCHEMA agentcore TO agentcore_writer; -- The running system starts as this role and asks the ledger what is already applied, so it reads -- the ledger and never writes it. Only a privileged first run migrates. -GRANT SELECT ON agentcore_schema_migration 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. @@ -44,25 +47,34 @@ GRANT SELECT ON agentcore_schema_migration TO agentcore_writer; -- 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 call ( - call_id text PRIMARY KEY, - title text NULL, - status text NOT NULL DEFAULT 'regular', - external_id text NULL, - custom jsonb NULL, +CREATE TABLE agentcore.call ( + call_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 two marks that say how far the call has got. - -- Not the words — those are call_message. Written in the same batch as the turn's words, so a - -- crash cannot land one without the other. + -- 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 + -- turn's words, so a crash cannot land one without the other. -- - -- The marks are here and nowhere else on purpose. An edit deletes the rows it replaces, so the - -- largest ordinal and turn index still in call_message are smaller than the largest ever issued, - -- and a session that recomputed from the surviving rows would hand the next turn a place a - -- deleted row already stood in. - state jsonb NULL, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), + -- The ordinal mark is not here. next_ordinal, below, holds it instead: an append can come from + -- the session or from a host outside any turn, so the shared counter needs a column the store + -- 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 + -- 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, + -- 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')) ); @@ -70,8 +82,8 @@ CREATE TABLE call ( -- 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 call_principal ( - call_id text NOT NULL REFERENCES call(call_id) ON DELETE CASCADE, +CREATE TABLE agentcore.call_principal ( + call_id text NOT NULL REFERENCES agentcore.call(call_id) ON DELETE CASCADE, principal_key text NOT NULL, role text NOT NULL, attached_at timestamptz NOT NULL DEFAULT now(), @@ -81,19 +93,19 @@ CREATE TABLE call_principal ( -- 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 call_principal (call_id); +CREATE INDEX call_principal_call_idx ON agentcore.call_principal (call_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 call, call_principal TO agentcore_writer; +GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.call, agentcore.call_principal TO agentcore_writer; -- Store 1 — the words of a call. One row per message, never one JSON blob per call. -- -- 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 call_message ( - call_id text NOT NULL REFERENCES call(call_id) ON DELETE CASCADE, +CREATE TABLE agentcore.call_message ( + call_id text NOT NULL REFERENCES agentcore.call(call_id) ON DELETE CASCADE, ordinal integer NOT NULL, turn_index integer NOT NULL, role text NOT NULL, @@ -119,15 +131,15 @@ CREATE TABLE call_message ( CONSTRAINT call_message_message_id_unique UNIQUE (call_id, message_id) ); -CREATE INDEX call_message_updated_at_idx ON call_message (updated_at); -CREATE INDEX call_message_turn_idx ON call_message (call_id, turn_index); -CREATE INDEX call_message_retention_idx ON call_message (call_id, updated_at DESC); +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); -- UPDATE amends a reply the caller cut short. DELETE erases one caller, and withdraws the tail of a -- call an edit replaced. Neither is a hole: this table holds words, and words stay erasable. -- Retention deletes the call itself and reaches these rows through the cascade, so it needs no -- privilege of its own here. -GRANT SELECT, INSERT, UPDATE, DELETE ON call_message TO agentcore_writer; +GRANT SELECT, INSERT, UPDATE, DELETE ON agentcore.call_message TO agentcore_writer; -- Store 3 — the append-only record of what happened on a call. @@ -140,7 +152,7 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON call_message TO agentcore_writer; -- -- 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 audit_event ( +CREATE TABLE agentcore.audit_event ( write_position bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, call_id text NOT NULL, event_id uuid NOT NULL, @@ -168,24 +180,24 @@ CREATE TABLE audit_event ( -- -- The PUBLIC revoke is required and its absence was a real hole. A privilege held by PUBLIC is not -- removed by revoking from the role: with a GRANT ALL ... TO PUBLIC present, the other two statements --- ran clean and has_table_privilege('agentcore_writer','audit_event','UPDATE') still returned true. -REVOKE ALL ON audit_event FROM PUBLIC; -REVOKE ALL ON audit_event FROM agentcore_writer; -GRANT INSERT, SELECT ON audit_event TO agentcore_writer; +-- ran clean and has_table_privilege('agentcore_writer','agentcore.audit_event','UPDATE') still returned true. +REVOKE ALL ON agentcore.audit_event FROM PUBLIC; +REVOKE ALL ON agentcore.audit_event FROM agentcore_writer; +GRANT INSERT, SELECT ON agentcore.audit_event TO agentcore_writer; -- Refusals 4, 5 and 6: the table owner is refused as well. -- -- Know what these stop. They stop the writer role and they stop an accident. They do not stop an -- owner who means it: ALTER TABLE ... DISABLE TRIGGER USER leaves no trace, and -- SET session_replication_role = replica bypasses all three in one statement with no DDL. -CREATE FUNCTION agentcore_audit_refuse() RETURNS trigger LANGUAGE plpgsql AS $$ +CREATE FUNCTION agentcore.agentcore_audit_refuse() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'audit_event is append-only. A correction is a new event that names the old one.'; END $$; CREATE TRIGGER audit_event_no_update - BEFORE UPDATE ON audit_event FOR EACH ROW EXECUTE FUNCTION agentcore_audit_refuse(); + BEFORE UPDATE ON agentcore.audit_event FOR EACH ROW EXECUTE FUNCTION agentcore.agentcore_audit_refuse(); CREATE TRIGGER audit_event_no_delete - BEFORE DELETE ON audit_event FOR EACH ROW EXECUTE FUNCTION agentcore_audit_refuse(); + BEFORE DELETE ON agentcore.audit_event FOR EACH ROW EXECUTE FUNCTION agentcore.agentcore_audit_refuse(); CREATE TRIGGER audit_event_no_truncate - BEFORE TRUNCATE ON audit_event FOR EACH STATEMENT EXECUTE FUNCTION agentcore_audit_refuse(); + BEFORE TRUNCATE ON agentcore.audit_event FOR EACH STATEMENT EXECUTE FUNCTION agentcore.agentcore_audit_refuse(); diff --git a/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs b/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs index ad203dd6..f5687599 100644 --- a/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs +++ b/src/AgentCore.Infrastructure/Database/Postgres/PostgresSchema.cs @@ -9,6 +9,9 @@ public static class PostgresSchema { private const string ResourcePrefix = "AgentCore.Infrastructure.Database.Postgres.Migrations."; + /// The schema every AgentCore table lives in. + internal const string SchemaName = "agentcore"; + /// Guards two processes migrating one database at the same moment. /// /// The value is arbitrary. It only has to be the same in every process that migrates, so it is a @@ -16,10 +19,10 @@ public static class PostgresSchema /// private const long ApplyLockKey = 0x41C05CE700000001; - private const string LedgerName = "agentcore_schema_migration"; + private const string LedgerName = $"{SchemaName}.schema_migration"; - private const string LedgerDdl = """ - CREATE TABLE agentcore_schema_migration ( + private const string LedgerDdl = $""" + CREATE TABLE {LedgerName} ( version text NOT NULL PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() ) @@ -44,7 +47,7 @@ private static string Read(string version) } /// Applies every migration the database has not seen yet. - /// A data source whose role may create tables in its search path. + /// 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. /// @@ -68,6 +71,14 @@ public static async Task> ApplyAsync( await serialise.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } + var schemaExists = await ScalarAsync( + connection, transaction, $"SELECT to_regnamespace('{SchemaName}') IS NOT NULL", cancellationToken).ConfigureAwait(false); + + if (!schemaExists) + { + await ExecuteAsync(connection, transaction, $"CREATE SCHEMA {SchemaName}", cancellationToken).ConfigureAwait(false); + } + // Ask whether the ledger is there rather than issuing CREATE TABLE IF NOT EXISTS. The running // system starts as agentcore_writer, which may create nothing; on an already-migrated database // this path then reads twice and writes no DDL, and only the first, privileged run creates. @@ -93,7 +104,7 @@ public static async Task> ApplyAsync( await ExecuteAsync(connection, transaction, Read(version), cancellationToken).ConfigureAwait(false); await using var record = new NpgsqlCommand( - "INSERT INTO agentcore_schema_migration (version) VALUES ($1)", connection, transaction); + $"INSERT INTO {LedgerName} (version) VALUES ($1)", connection, transaction); record.Parameters.AddWithValue(version); await record.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); @@ -111,7 +122,7 @@ private static async Task> ReadAppliedAsync( { HashSet applied = new(StringComparer.Ordinal); - await using var command = new NpgsqlCommand("SELECT version FROM agentcore_schema_migration", connection, transaction); + await using var command = new NpgsqlCommand($"SELECT version FROM {LedgerName}", connection, transaction); await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) diff --git a/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs b/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs index b570b74b..f62f9946 100644 --- a/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs +++ b/tests/AgentCore.Application.Tests/Audit/AuditCallObserverTests.cs @@ -25,6 +25,7 @@ public sealed class AuditCallObserverTests CallEventKind.ExtractionFailed, CallEventKind.TranscriptWriteFailed, CallEventKind.StateRestorePartial, + CallEventKind.TranscriptResyncFailed, ]; /// Every kind, once, across the two tables above. diff --git a/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs b/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs index a0d3d73d..a2e6817d 100644 --- a/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/ChatCallTitlerTests.cs @@ -169,7 +169,8 @@ private static async Task> CollectAsync(IAsyncEnumerable st InMemoryCallStore calls = new(); await calls.CreateAsync("c1", Token); await calls.AppendAsync( - [new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "my belt squeaks"), "m0")], + "c1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "my belt squeaks"), "m0")], cancellationToken: Token); return (new ChatCallTitler(calls, new StubChatClient(pieces)), calls); diff --git a/tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs b/tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs index f0eb894b..5c6db484 100644 --- a/tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/DelegatingCallStoreTests.cs @@ -17,13 +17,14 @@ private sealed class CountingAppends(ICallStore inner) : DelegatingCallStore(inn { public int Appends { get; private set; } - public override ValueTask AppendAsync( - IReadOnlyList messages, + public override ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? state = null, CancellationToken cancellationToken = default) { Appends++; - return base.AppendAsync(messages, state, cancellationToken); + return base.AppendAsync(callId, messages, state, cancellationToken); } } @@ -32,10 +33,11 @@ public async Task AnOverride_CountsItsOwnCalls_AndStillReachesTheInnerStore() { // Arrange CountingAppends store = new(new InMemoryCallStore()); + await store.CreateAsync("c1", Token); // Act await store.AppendAsync( - [new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "hi"), "m0")], cancellationToken: Token); + "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hi"), "m0")], cancellationToken: Token); // Assert Assert.Equal(1, store.Appends); diff --git a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs b/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs index 8c249951..2e9b784b 100644 --- a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTests.cs @@ -236,7 +236,7 @@ public async Task DeleteAsync_ACall_TakesItsResumeStateWithIt() // two backings answering differently is the defect this pins. InMemoryCallStore store = new(); await store.CreateAsync("c1", Token); - await store.AppendAsync([Word("c1")], new CallSessionState { Stage = "collecting" }, Token); + await store.AppendAsync("c1", [Word()], new CallSessionState { Stage = "collecting" }, Token); // Act await store.DeleteAsync("c1", Token); @@ -254,7 +254,7 @@ public async Task SweepAsync_ACallPastRetention_TakesItsResumeStateWithIt() TestTimeProvider clock = new(); InMemoryCallStore store = new(clock); await store.CreateAsync("c1", Token); - await store.AppendAsync([Word("c1")], new CallSessionState { Stage = "collecting" }, Token); + await store.AppendAsync("c1", [Word()], new CallSessionState { Stage = "collecting" }, Token); // Act clock.Advance(TimeSpan.FromDays(2)); @@ -265,6 +265,6 @@ public async Task SweepAsync_ACallPastRetention_TakesItsResumeStateWithIt() Assert.Null((await store.CreateAsync("c1", Token)).State); } - private static CallMessage Word(string callId) - => new(callId, 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0"); + private static CallMessageDraft Word() + => new(0, new ChatMessage(ChatRole.User, "hello"), "m0"); } diff --git a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs b/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs index 1c74c9ac..69122ea5 100644 --- a/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/InMemoryCallStoreTranscriptTests.cs @@ -1,5 +1,4 @@ using AgentCore.Application.Calls.Memory; -using AgentCore.Application.Ports; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; using Xunit; @@ -16,13 +15,15 @@ public async Task ReadAsync_AfterAppend_ReturnsTheRowsOldestFirst() { // Arrange InMemoryCallStore store = new(); + await store.CreateAsync("c1", Token); // Act await store.AppendAsync( - [ - new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0"), - new CallMessage("c1", 1, 0, new ChatMessage(ChatRole.Assistant, "hi"), "m1"), - ], cancellationToken: Token); + "c1", + [ + new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0"), + new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "hi"), "m1"), + ], cancellationToken: Token); // Assert var rows = await store.ReadAsync("c1", Token); @@ -32,15 +33,18 @@ await store.AppendAsync( } [Fact] - public async Task RewriteAsync_AnExistingOrdinal_ReplacesItsContent() + public async Task RewriteAsync_AnExistingMessage_ReplacesItsContent() { // Arrange InMemoryCallStore store = new(); + await store.CreateAsync("c1", Token); await store.AppendAsync( - [new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.Assistant, "long reply"), "m0")], cancellationToken: Token); + "c1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "long reply"), "m0")], + cancellationToken: Token); // Act - await store.RewriteAsync("c1", 0, new ChatMessage(ChatRole.Assistant, "cut"), Token); + await store.RewriteAsync("c1", "m0", new ChatMessage(ChatRole.Assistant, "cut"), Token); // Assert var rows = await store.ReadAsync("c1", Token); @@ -52,11 +56,12 @@ public async Task EraseAsync_ACallWithWords_RemovesThemAndReportsTheCount() { // Arrange InMemoryCallStore 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); await store.AppendAsync( - [ - new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "a"), "m0"), - new CallMessage("c2", 0, 0, new ChatMessage(ChatRole.User, "b"), "m0"), - ], cancellationToken: Token); + "c2", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "b"), "m0")], cancellationToken: Token); // Act var erased = await store.EraseAsync("c1", Token); @@ -76,7 +81,7 @@ public async Task GetAsync_AfterAppend_ReportsWhenTheCallWasLastSpokenOn() // Act await store.AppendAsync( - [new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], cancellationToken: Token); + "c1", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], cancellationToken: Token); // Assert var call = await store.GetAsync("c1", Token); @@ -87,12 +92,15 @@ await store.AppendAsync( [Fact] public async Task ReadAsync_ACallWithMessages_ReturnsThemOldestFirst() { - // Arrange + // 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(); + await store.CreateAsync("c1", Token); await store.AppendAsync( + "c1", [ - new CallMessage("c1", 1, 0, new ChatMessage(ChatRole.User, "second"), "m1"), - new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "first"), "m0"), + new CallMessageDraft(0, new ChatMessage(ChatRole.User, "first"), "m0"), + new CallMessageDraft(0, new ChatMessage(ChatRole.User, "second"), "m1"), ], cancellationToken: Token); @@ -101,6 +109,7 @@ await store.AppendAsync( // Assert Assert.Equal([0, 1], rows.Select(row => row.Ordinal)); + Assert.Equal(["first", "second"], rows.Select(row => row.Content.Text)); } [Fact] @@ -121,8 +130,12 @@ public async Task ReadAsync_AnotherCallsMessages_AreNotReturned() { // Arrange InMemoryCallStore store = new(); - await store.AppendAsync([new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "mine"), "m0")], cancellationToken: Token); - await store.AppendAsync([new CallMessage("c2", 0, 0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); + 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); + await store.AppendAsync( + "c2", [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); // Act var rows = await store.ReadAsync("c1", Token); @@ -136,10 +149,12 @@ public async Task EraseAsync_ACall_TakesEveryRowAndReportsHowMany() { // Arrange InMemoryCallStore store = new(); + await store.CreateAsync("c1", Token); await store.AppendAsync( + "c1", [ - new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "one"), "m0"), - new CallMessage("c1", 1, 0, new ChatMessage(ChatRole.Assistant, "two"), "m1"), + new CallMessageDraft(0, new ChatMessage(ChatRole.User, "one"), "m0"), + new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "two"), "m1"), ], cancellationToken: Token); @@ -156,8 +171,12 @@ public async Task EraseAsync_ACall_LeavesEveryOtherCallAlone() { // Arrange InMemoryCallStore store = new(); - await store.AppendAsync([new CallMessage("c1", 0, 0, new ChatMessage(ChatRole.User, "mine"), "m0")], cancellationToken: Token); - await store.AppendAsync([new CallMessage("c2", 0, 0, new ChatMessage(ChatRole.User, "theirs"), "m0")], cancellationToken: Token); + 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); + await store.AppendAsync( + "c2", [new CallMessageDraft(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/Calls/Memory/InMemoryCallStoreAppendTests.cs new file mode 100644 index 00000000..c1df5f71 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Calls/Memory/InMemoryCallStoreAppendTests.cs @@ -0,0 +1,185 @@ +using System.Text.RegularExpressions; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Calls.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. +/// +#pragma warning disable CA1859 // store is typed as ICallStore throughout: AppendAsync(callId, message, ct) + // is a default interface method, and only resolves through the interface type. +public sealed partial class InMemoryCallStoreAppendTests +{ + private static CancellationToken Token => TestContext.Current.CancellationToken; + + [Fact] + public async Task AppendAsync_OneMessage_OnAFreshCall_IsOrdinalZeroAndTurnZero() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + await store.CreateAsync("c1", Token); + + // Act + var row = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "hello"), Token); + + // Assert + Assert.Equal(0, row.Ordinal); + Assert.Equal(0, row.TurnIndex); + Assert.Matches(HexId(), row.MessageId); + } + + [Fact] + public async Task AppendAsync_OneMessage_WithItsOwnId_KeepsIt() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + await store.CreateAsync("c1", Token); + ChatMessage message = new(ChatRole.User, "hello") { MessageId = "caller-named" }; + + // Act + var row = await store.AppendMessageAsync("c1", message, Token); + + // Assert + Assert.Equal("caller-named", row.MessageId); + } + + [Fact] + public async Task AppendAsync_TwoOutsideAppends_AreNumberedZeroThenOne() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + await store.CreateAsync("c1", Token); + + // Act + var first = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "one"), Token); + var second = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "two"), Token); + + // Assert + Assert.Equal(0, first.Ordinal); + Assert.Equal(1, second.Ordinal); + var call = await store.GetAsync("c1", Token); + Assert.Equal(2, call?.NextOrdinal); + } + + [Fact] + public async Task AppendAsync_ABatchWithAnExplicitTurnIndex_NumbersThreeConsecutiveRowsInDraftOrder() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + await store.CreateAsync("c1", Token); + await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "outside"), Token); + + CallMessageDraft[] drafts = + [ + new(4, new ChatMessage(ChatRole.User, "a"), "m-a"), + new(4, new ChatMessage(ChatRole.Assistant, "b"), "m-b"), + new(4, new ChatMessage(ChatRole.User, "c"), "m-c"), + ]; + + // Act + var rows = await store.AppendAsync("c1", drafts, cancellationToken: Token); + + // Assert + Assert.Equal([1, 2, 3], rows.Select(row => row.Ordinal)); + Assert.All(rows, row => Assert.Equal(4, row.TurnIndex)); + Assert.Equal(["m-a", "m-b", "m-c"], rows.Select(row => row.MessageId)); + } + + [Fact] + public async Task AppendAsync_OutsideAppend_AfterABatchThatWroteState_IsStampedWithTheStoredNextTurnIndex() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + await store.CreateAsync("c1", Token); + await store.AppendAsync( + "c1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new CallSessionState { NextTurnIndex = 7 }, + Token); + + // Act + var row = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "outside"), Token); + + // Assert + Assert.Equal(7, row.TurnIndex); + } + + [Fact] + public async Task AppendAsync_ACallThatDoesNotExist_ThrowsNamingIt() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + + // Act + var failure = await Record.ExceptionAsync( + () => store.AppendMessageAsync("missing", new ChatMessage(ChatRole.User, "hello"), Token).AsTask()); + + // Assert + var invalid = Assert.IsType(failure); + Assert.Contains("missing", invalid.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task RewriteAsync_OneRow_ChangesOnlyThatRowsContent() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + 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); + + // Act + await store.RewriteAsync("c1", "m0", new ChatMessage(ChatRole.User, "corrected"), Token); + + // Assert + var rows = await store.ReadAsync("c1", Token); + Assert.Equal(["corrected", "second"], rows.Select(row => row.Content.Text)); + } + + [Fact] + public async Task AppendAsync_AfterATruncate_NeverReusesTheOrdinalsItTook() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + 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); + await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "two"), Token); + await store.TruncateAsync("c1", 1, Token); + + // Act + var row = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "three"), Token); + + // Assert + Assert.Equal(3, row.Ordinal); + } + + [Fact] + public async Task ReadAsync_ARowWithAdditionalProperties_KeepsThemAcrossTheRoundTrip() + { + // Arrange + ICallStore store = new InMemoryCallStore(); + await store.CreateAsync("c1", Token); + ChatMessage message = new(ChatRole.User, "hello") + { + AdditionalProperties = new() { ["speaker"] = "human" }, + }; + + // Act + await store.AppendMessageAsync("c1", message, Token); + + // Assert + var rows = await store.ReadAsync("c1", Token); + Assert.Equal("human", Assert.Single(rows).Content.AdditionalProperties?["speaker"]?.ToString()); + } + + [GeneratedRegex("^[0-9a-f]{32}$")] + private static partial Regex HexId(); +} +#pragma warning restore CA1859 diff --git a/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs b/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs index 235a694e..79dfb4b9 100644 --- a/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs +++ b/tests/AgentCore.Application.Tests/Fakes/RecordingCallStore.cs @@ -18,9 +18,12 @@ internal sealed class RecordingCallStore() : DelegatingCallStore(new InMemoryCal /// 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. TurnIndex is not carried. + /// 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) @@ -32,46 +35,60 @@ public IReadOnlyList Live(string callId) } /// - public override ValueTask AppendAsync( - IReadOnlyList messages, + public override async ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? state = null, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(messages); + var rows = await base.AppendAsync(callId, messages, state, cancellationToken).ConfigureAwait(false); lock (_lock) { - Rows.AddRange(messages); - foreach (var message in messages) + Rows.AddRange(rows); + foreach (var row in rows) { - _rows.Add((message.CallId, message.Ordinal), message); + _rows[(row.CallId, row.Ordinal)] = row; } } - return default; + return rows; } /// - public override ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) + 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) { - Rewrites.Add(new CallMessage(callId, ordinal, TurnIndex: -1, content, $"m{ordinal}")); - - if (_rows.TryGetValue((callId, ordinal), out var row)) + foreach (var pair in _rows) { - _rows[(callId, ordinal)] = row with { Content = content }; + 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; } } - - return default; } /// public override ValueTask> ReadAsync( string callId, CancellationToken cancellationToken = default) - => ValueTask.FromResult(Live(callId)); + { + lock (_lock) + { + Reads++; + } + + return ValueTask.FromResult(Live(callId)); + } /// public override ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) diff --git a/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs b/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs index b06e8d7e..81c825f7 100644 --- a/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs +++ b/tests/AgentCore.Application.Tests/Fakes/ThrowingCallStore.cs @@ -9,14 +9,15 @@ 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( - IReadOnlyList messages, + 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, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) => throw new InvalidOperationException("the call store is down."); public override ValueTask> ReadAsync( diff --git a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs new file mode 100644 index 00000000..7a7150ce --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentSessionTests.cs @@ -0,0 +1,364 @@ +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using System.Text.Json; +using System.Text.Json.Nodes; +using Xunit; +using static AgentCore.Application.Tests.Runtime.AgentCoreAgentTestSupport; + +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. +/// +public sealed class AgentCoreAgentSessionTests +{ + [Fact] + public async Task SerializeSessionAsync_WritesTheStateTheCallHolds() + { + 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 serialized = await agent.SerializeSessionAsync( + session, cancellationToken: TestContext.Current.CancellationToken); + + var read = serialized.GetProperty("state").Deserialize(CallStateJson.Options); + + Assert.NotNull(read); + Assert.Equal(CallSessionState.CurrentVersion, read.Version); + Assert.Equal(call.Stage, read.Stage); + Assert.True(read.Slots["escalate"]!.GetValue()); + } + + [Fact] + public async Task SerializeSessionAsync_NamesTheCallTheStateBelongsTo() + { + var agent = BuildAgent(new SequencedChatClient("a reply"), out _); + var session = await agent.CreateSessionAsync("call-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 + // that has no words behind it, which is the one failure this envelope exists to prevent. + Assert.Equal("call-42", serialized.GetProperty("callId").GetString()); + } + + [Fact] + public async Task SerializeSessionAsync_NoSession_IsRefusedRatherThanAnsweredWithAFreshCall() + { + 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 + // 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. + await Assert.ThrowsAsync(async () => + await agent.SerializeSessionAsync(null!, cancellationToken: TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task ARoundTrip_ComesBackOnTheSameCall() + { + var agent = BuildAgent(new SequencedChatClient("a reply", "another reply"), out _); + var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); + _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); + + var serialized = await agent.SerializeSessionAsync( + session, cancellationToken: TestContext.Current.CancellationToken); + var revived = await agent.DeserializeSessionAsync( + serialized, cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal("call-42", revived.GetService()?.CallId); + } + + [Fact] + public async Task DeserializeSessionAsync_BringsBackACallThatCarriesThatState() + { + var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); + + CallSessionState stored = new() + { + Stage = string.Empty, + Slots = new Dictionary(StringComparer.Ordinal) + { + ["escalate"] = JsonValue.Create(true), + }, + }; + + var revived = await agent.DeserializeSessionAsync( + Envelope("call-42", stored), cancellationToken: TestContext.Current.CancellationToken); + + // The turn is what opens the session, and the session is the one place a call resumes from, + // whichever of the two sources it resumes out of. + _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); + + var call = revived.GetService(); + + Assert.NotNull(call); + Assert.False(call.IsComplete); + Assert.True(call.State.Read("escalate")!.GetValue()); + } + + [Fact] + public async Task ARoundTripBeforeTheFirstTurn_LosesNothing() + { + var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); + + CallSessionState checkpoint = new() + { + Slots = new Dictionary(StringComparer.Ordinal) + { + ["escalate"] = JsonValue.Create(true), + ["note"] = JsonValue.Create("carried"), + }, + }; + + var revived = await agent.DeserializeSessionAsync( + Envelope("call-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 + // the checkpoint it just handed in. The seam has to read back what it was given. + var serialized = await agent.SerializeSessionAsync( + revived, cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal("call-42", serialized.GetProperty("callId").GetString()); + + var read = serialized.GetProperty("state").Deserialize(CallStateJson.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 + // 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. + _ = 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 again = await agent.SerializeSessionAsync( + revived, cancellationToken: TestContext.Current.CancellationToken); + var after = again.GetProperty("state").Deserialize(CallStateJson.Options); + + Assert.NotNull(after); + Assert.True(after.Slots["escalate"]!.GetValue()); + Assert.Equal("learned after the turn", after.Slots["note"]!.GetValue()); + } + + [Fact] + public async Task DeserializeSessionAsync_WithStateTheDocumentRefuses_StillRunsTheTurn() + { + var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); + + // 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() + { + Stage = "a stage this document never declared", + IsComplete = true, + Slots = new Dictionary(StringComparer.Ordinal) + { + [ReservedStateSlots.Stage] = JsonValue.Create("reserved"), + ["a slot this document never declared"] = JsonValue.Create(1), + }, + }; + + var revived = await agent.DeserializeSessionAsync( + Envelope("call-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 + // turn away, which is the outcome the best-effort restore exists to avoid. + Assert.False(revived.GetService()?.IsComplete); + } + + [Fact] + public async Task SerializeSessionAsync_CarriesNoWords() + { + var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); + var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); + _ = 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 serialized = await agent.SerializeSessionAsync( + session, cancellationToken: TestContext.Current.CancellationToken); + var raw = serialized.GetRawText(); + + // Something to lose first. On a document with no slots the whole blob is a handful of short + // scalars, and an implementation that wrote {} would pass the two assertions below. + Assert.Contains("escalate", raw, StringComparison.Ordinal); + + // Store 1 is durable already. A checkpoint that carried the words would give one conversation + // two records and one chance to disagree. + Assert.DoesNotContain("remember this sentence", raw, StringComparison.Ordinal); + Assert.DoesNotContain("a reply", raw, StringComparison.Ordinal); + } + + [Fact] + public async Task DeserializeSessionAsync_WhenStore0KnowsTheCall_Store0Wins() + { + InMemoryCallStore store = new(); + await store.CreateAsync("call-42", TestContext.Current.CancellationToken); + + // Store 0's own copy of this call: 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 + { + Slots = new Dictionary(StringComparer.Ordinal) + { + ["escalate"] = JsonValue.Create(false), + }, + }, + TestContext.Current.CancellationToken); + + var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml, store); + + // 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() + { + Slots = new Dictionary(StringComparer.Ordinal) + { + ["escalate"] = JsonValue.Create(true), + ["note"] = JsonValue.Create("from the checkpoint"), + }, + }; + + var revived = await agent.DeserializeSessionAsync( + Envelope("call-42", checkpoint), cancellationToken: TestContext.Current.CancellationToken); + + _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); + + var call = revived.GetService(); + Assert.NotNull(call); + + // 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()); + + // 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")); + } + + [Fact] + 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. + var bare = JsonSerializer.SerializeToElement( + new CallSessionState { Stage = string.Empty }, CallStateJson.Options); + + var failure = await Assert.ThrowsAsync( + async () => await agent.DeserializeSessionAsync( + bare, cancellationToken: TestContext.Current.CancellationToken)); + + Assert.Contains("{ callId, state }", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task DeserializeSessionAsync_WithStateButNoCallId_StartsANewCall() + { + 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. + var named = JsonSerializer.SerializeToElement( + new Dictionary(StringComparer.Ordinal) + { + ["state"] = JsonSerializer.SerializeToNode( + new CallSessionState + { + Slots = new Dictionary(StringComparer.Ordinal) + { + ["escalate"] = JsonValue.Create(true), + }, + }, + CallStateJson.Options), + }, + CallStateJson.Options); + + var revived = await agent.DeserializeSessionAsync( + named, cancellationToken: TestContext.Current.CancellationToken); + + var call = revived.GetService(); + + Assert.NotNull(call); + Assert.NotEmpty(call.CallId); + + _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); + + Assert.True(call.State.Read("escalate")!.GetValue()); + } + + [Fact] + public async Task ARoundTripOfATerminalCall_ComesBackTerminalAndRefusesItsTurn() + { + var agent = BuildAgent(new SequencedChatClient("a reply"), out _, TerminalAgentYaml); + var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); + + _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); + 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. + 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); + } + + [Fact] + public async Task Resume_AfterTheCallHasOpened_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); + + // 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())); + + 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 new file mode 100644 index 00000000..66dbd2fe --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTestSupport.cs @@ -0,0 +1,88 @@ +using AgentCore.Application.Calls; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace AgentCore.Application.Tests.Runtime; + +/// The documents and the shim-building helper the tests share. +internal static class AgentCoreAgentTestSupport +{ + internal const string SingleAgentYaml = + """ + apiVersion: agentcore/v1 + name: shim-test + agents: + defaults: + model: { ref: reply } + items: + - { id: solo, instructions: "answer the caller" } + """; + + // The same row with one declared slot, so the round trip has something of its own to carry. + // SingleAgentYaml declares none, and a document with no slots proves nothing about slots. + internal const string SlottedAgentYaml = + """ + apiVersion: agentcore/v1 + name: shim-test-slots + state: + escalate: { type: boolean, writer: extractor, default: false } + note: { type: string, writer: extractor, default: "" } + agents: + defaults: + model: { ref: reply } + items: + - { id: solo, instructions: "answer the caller" } + """; + + // A policy that ends itself after one turn, so a call 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 = + """ + apiVersion: agentcore/v1 + name: shim-test-terminal + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + defaults: + model: { ref: reply } + items: + - { id: solo, instructions: "answer the caller" } + policy: + initial: talking + stages: + - { id: talking, agent: solo, to: [ { stage: done, when: always } ] } + - { id: done, agent: solo, terminal: true } + """; + + internal static AgentCoreAgent BuildAgent( + IChatClient reply, + out CompiledAgent compiled, + string yaml = SingleAgentYaml, + ICallStore? store = null) + { + var document = ConfigurationLoader.LoadYaml(yaml); + compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new RoutingChatClientFactory(reply)) { CallStore = store }); + + CallSessionFactory sessions = new(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + return new AgentCoreAgent(sessions, compiled.Name); + } + + /// Writes what a host hands to DeserializeSessionAsync: a call id and its state. + internal static JsonElement Envelope(string callId, CallSessionState state) + => JsonSerializer.SerializeToElement( + new Dictionary(StringComparer.Ordinal) + { + ["callId"] = JsonValue.Create(callId), + ["state"] = JsonSerializer.SerializeToNode(state, CallStateJson.Options), + }, + CallStateJson.Options); +} diff --git a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs index ee86c7c1..c3c576c0 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AgentCoreAgentTests.cs @@ -1,19 +1,8 @@ -using AgentCore.TestSupport; -using AgentCore.Application.Calls; -using AgentCore.Application.Calls.Memory; -using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Transcript; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; -using System.Text.Json; -using System.Text.Json.Nodes; using Xunit; +using static AgentCore.Application.Tests.Runtime.AgentCoreAgentTestSupport; namespace AgentCore.Application.Tests.Runtime; @@ -23,53 +12,6 @@ namespace AgentCore.Application.Tests.Runtime; /// public sealed class AgentCoreAgentTests { - private const string SingleAgentYaml = - """ - apiVersion: agentcore/v1 - name: shim-test - agents: - defaults: - model: { ref: reply } - items: - - { id: solo, instructions: "answer the caller" } - """; - - // The same row with one declared slot, so the round trip has something of its own to carry. - // SingleAgentYaml declares none, and a document with no slots proves nothing about slots. - private const string SlottedAgentYaml = - """ - apiVersion: agentcore/v1 - name: shim-test-slots - state: - escalate: { type: boolean, writer: extractor, default: false } - note: { type: string, writer: extractor, default: "" } - agents: - defaults: - model: { ref: reply } - items: - - { id: solo, instructions: "answer the caller" } - """; - - // A policy that ends itself after one turn, so a call can be driven terminal and then round - // tripped. The guard reads the reserved turnIndex slot, so no extractor and no tool is needed. - private const string TerminalAgentYaml = - """ - apiVersion: agentcore/v1 - name: shim-test-terminal - guards: - always: { ">=": [ { var: turnIndex }, 0 ] } - agents: - defaults: - model: { ref: reply } - items: - - { id: solo, instructions: "answer the caller" } - policy: - initial: talking - stages: - - { id: talking, agent: solo, to: [ { stage: done, when: always } ] } - - { id: done, agent: solo, terminal: true } - """; - [Fact] public async Task RunAsync_WithOneSession_RunsTurnsOfOneCall() { @@ -200,349 +142,6 @@ public async Task GetService_OnTheSession_AnswersTheCallSession() Assert.Same(call, session.GetService()); } - [Fact] - public async Task SerializeSessionAsync_WritesTheStateTheCallHolds() - { - 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 serialized = await agent.SerializeSessionAsync( - session, cancellationToken: TestContext.Current.CancellationToken); - - var read = serialized.GetProperty("state").Deserialize(CallStateJson.Options); - - Assert.NotNull(read); - Assert.Equal(CallSessionState.CurrentVersion, read.Version); - Assert.Equal(call.Stage, read.Stage); - Assert.True(read.Slots["escalate"]!.GetValue()); - } - - [Fact] - public async Task SerializeSessionAsync_NamesTheCallTheStateBelongsTo() - { - var agent = BuildAgent(new SequencedChatClient("a reply"), out _); - var session = await agent.CreateSessionAsync("call-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 - // that has no words behind it, which is the one failure this envelope exists to prevent. - Assert.Equal("call-42", serialized.GetProperty("callId").GetString()); - } - - [Fact] - public async Task SerializeSessionAsync_NoSession_IsRefusedRatherThanAnsweredWithAFreshCall() - { - 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 - // 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. - await Assert.ThrowsAsync(async () => - await agent.SerializeSessionAsync(null!, cancellationToken: TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task ARoundTrip_ComesBackOnTheSameCall() - { - var agent = BuildAgent(new SequencedChatClient("a reply", "another reply"), out _); - var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); - _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); - - var serialized = await agent.SerializeSessionAsync( - session, cancellationToken: TestContext.Current.CancellationToken); - var revived = await agent.DeserializeSessionAsync( - serialized, cancellationToken: TestContext.Current.CancellationToken); - - Assert.Equal("call-42", revived.GetService()?.CallId); - } - - [Fact] - public async Task DeserializeSessionAsync_BringsBackACallThatCarriesThatState() - { - var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); - - CallSessionState stored = new() - { - Stage = string.Empty, - Slots = new Dictionary(StringComparer.Ordinal) - { - ["escalate"] = JsonValue.Create(true), - }, - }; - - var revived = await agent.DeserializeSessionAsync( - Envelope("call-42", stored), cancellationToken: TestContext.Current.CancellationToken); - - // The turn is what opens the session, and the session is the one place a call resumes from, - // whichever of the two sources it resumes out of. - _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - - var call = revived.GetService(); - - Assert.NotNull(call); - Assert.False(call.IsComplete); - Assert.True(call.State.Read("escalate")!.GetValue()); - } - - [Fact] - public async Task ARoundTripBeforeTheFirstTurn_LosesNothing() - { - var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); - - CallSessionState checkpoint = new() - { - Slots = new Dictionary(StringComparer.Ordinal) - { - ["escalate"] = JsonValue.Create(true), - ["note"] = JsonValue.Create("carried"), - }, - }; - - var revived = await agent.DeserializeSessionAsync( - Envelope("call-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 - // the checkpoint it just handed in. The seam has to read back what it was given. - var serialized = await agent.SerializeSessionAsync( - revived, cancellationToken: TestContext.Current.CancellationToken); - - Assert.Equal("call-42", serialized.GetProperty("callId").GetString()); - - var read = serialized.GetProperty("state").Deserialize(CallStateJson.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 - // 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. - _ = 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 again = await agent.SerializeSessionAsync( - revived, cancellationToken: TestContext.Current.CancellationToken); - var after = again.GetProperty("state").Deserialize(CallStateJson.Options); - - Assert.NotNull(after); - Assert.True(after.Slots["escalate"]!.GetValue()); - Assert.Equal("learned after the turn", after.Slots["note"]!.GetValue()); - } - - [Fact] - public async Task DeserializeSessionAsync_WithStateTheDocumentRefuses_StillRunsTheTurn() - { - var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); - - // 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() - { - Stage = "a stage this document never declared", - IsComplete = true, - Slots = new Dictionary(StringComparer.Ordinal) - { - [ReservedStateSlots.Stage] = JsonValue.Create("reserved"), - ["a slot this document never declared"] = JsonValue.Create(1), - }, - }; - - var revived = await agent.DeserializeSessionAsync( - Envelope("call-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 - // turn away, which is the outcome the best-effort restore exists to avoid. - Assert.False(revived.GetService()?.IsComplete); - } - - [Fact] - public async Task SerializeSessionAsync_CarriesNoWords() - { - var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml); - var session = await agent.CreateSessionAsync(TestContext.Current.CancellationToken); - _ = 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 serialized = await agent.SerializeSessionAsync( - session, cancellationToken: TestContext.Current.CancellationToken); - var raw = serialized.GetRawText(); - - // Something to lose first. On a document with no slots the whole blob is a handful of short - // scalars, and an implementation that wrote {} would pass the two assertions below. - Assert.Contains("escalate", raw, StringComparison.Ordinal); - - // Store 1 is durable already. A checkpoint that carried the words would give one conversation - // two records and one chance to disagree. - Assert.DoesNotContain("remember this sentence", raw, StringComparison.Ordinal); - Assert.DoesNotContain("a reply", raw, StringComparison.Ordinal); - } - - [Fact] - public async Task DeserializeSessionAsync_WhenStore0KnowsTheCall_Store0Wins() - { - InMemoryCallStore store = new(); - await store.CreateAsync("call-42", TestContext.Current.CancellationToken); - - // Store 0's own copy of this call: one word, and the state written in the same batch. - await store.AppendAsync( - [new CallMessage("call-42", 0, 0, new ChatMessage(ChatRole.User, "an earlier turn"), "m0")], - new CallSessionState - { - Slots = new Dictionary(StringComparer.Ordinal) - { - ["escalate"] = JsonValue.Create(false), - }, - }, - TestContext.Current.CancellationToken); - - var agent = BuildAgent(new SequencedChatClient("a reply"), out _, SlottedAgentYaml, store); - - // 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() - { - Slots = new Dictionary(StringComparer.Ordinal) - { - ["escalate"] = JsonValue.Create(true), - ["note"] = JsonValue.Create("from the checkpoint"), - }, - }; - - var revived = await agent.DeserializeSessionAsync( - Envelope("call-42", checkpoint), cancellationToken: TestContext.Current.CancellationToken); - - _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - - var call = revived.GetService(); - Assert.NotNull(call); - - // 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()); - - // 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")); - } - - [Fact] - 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. - var bare = JsonSerializer.SerializeToElement( - new CallSessionState { Stage = string.Empty }, CallStateJson.Options); - - var failure = await Assert.ThrowsAsync( - async () => await agent.DeserializeSessionAsync( - bare, cancellationToken: TestContext.Current.CancellationToken)); - - Assert.Contains("{ callId, state }", failure.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task DeserializeSessionAsync_WithStateButNoCallId_StartsANewCall() - { - 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. - var named = JsonSerializer.SerializeToElement( - new Dictionary(StringComparer.Ordinal) - { - ["state"] = JsonSerializer.SerializeToNode( - new CallSessionState - { - Slots = new Dictionary(StringComparer.Ordinal) - { - ["escalate"] = JsonValue.Create(true), - }, - }, - CallStateJson.Options), - }, - CallStateJson.Options); - - var revived = await agent.DeserializeSessionAsync( - named, cancellationToken: TestContext.Current.CancellationToken); - - var call = revived.GetService(); - - Assert.NotNull(call); - Assert.NotEmpty(call.CallId); - - _ = await agent.RunAsync("hello", revived, cancellationToken: TestContext.Current.CancellationToken); - - Assert.True(call.State.Read("escalate")!.GetValue()); - } - - [Fact] - public async Task ARoundTripOfATerminalCall_ComesBackTerminalAndRefusesItsTurn() - { - var agent = BuildAgent(new SequencedChatClient("a reply"), out _, TerminalAgentYaml); - var session = await agent.CreateSessionAsync("call-42", TestContext.Current.CancellationToken); - - _ = await agent.RunAsync("hello", session, cancellationToken: TestContext.Current.CancellationToken); - 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. - 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); - } - - [Fact] - public async Task Resume_AfterTheCallHasOpened_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); - - // 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())); - - Assert.Contains("already run a turn", failure.Message, StringComparison.Ordinal); - } - [Fact] public void Name_ReportsWhatTheHostNamedIt() { @@ -550,32 +149,4 @@ public void Name_ReportsWhatTheHostNamedIt() Assert.Equal(compiled.Name, agent.Name); } - - // ------------------------------------------------------------------------------------------- - // Helpers. - // ------------------------------------------------------------------------------------------- - private static AgentCoreAgent BuildAgent( - IChatClient reply, - out CompiledAgent compiled, - string yaml = SingleAgentYaml, - ICallStore? store = null) - { - var document = ConfigurationLoader.LoadYaml(yaml); - compiled = ConfigurationCompiler.Compile( - document, - new AgentCompilationContext(new RoutingChatClientFactory(reply)) { CallStore = store }); - - CallSessionFactory sessions = new(compiled, new GuardEvaluator(compiled.Configuration.Guards)); - return new AgentCoreAgent(sessions, compiled.Name); - } - - /// Writes what a host hands to DeserializeSessionAsync: a call id and its state. - private static JsonElement Envelope(string callId, CallSessionState state) - => JsonSerializer.SerializeToElement( - new Dictionary(StringComparer.Ordinal) - { - ["callId"] = JsonValue.Create(callId), - ["state"] = JsonSerializer.SerializeToNode(state, CallStateJson.Options), - }, - CallStateJson.Options); } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs index 2d0e7e09..83336987 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CallEventKindsTests.cs @@ -32,6 +32,7 @@ public sealed class CallEventKindsTests { CallEventKind.ExtractionFailed, "extraction.failed" }, { CallEventKind.TranscriptWriteFailed, "transcript.write.failed" }, { CallEventKind.StateRestorePartial, "state.restore.partial" }, + { CallEventKind.TranscriptResyncFailed, "transcript.resync.failed" }, }; [Theory] @@ -62,7 +63,7 @@ public void EveryKind_IsEitherStoredOrDiagnostic_AndEveryOneIsCovered() var stored = Enum.GetValues() .Count(kind => CallEventKinds.TryGetAuditKind(kind, out _)); - Assert.Equal(13, Enum.GetValues().Length); + Assert.Equal(14, Enum.GetValues().Length); Assert.Equal(7, stored); } diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs new file mode 100644 index 00000000..6c6df84d --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs @@ -0,0 +1,149 @@ +using System.Text.Json; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Transcript; +using AgentCore.TestSupport; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +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. +internal static class AgentCoreChatHistoryProviderTestSupport +{ + internal const string CallId = "call-1"; + + /// + /// The key the call's transcript is filed under in . Changing + /// it orphans the state of any session already persisted under the old one. + /// + internal const string StateKey = "AgentCoreChatHistoryProvider"; + + /// The converters the provider files the transcript with. + internal static JsonSerializerOptions StateOptions => AIJsonUtilities.DefaultOptions; + + /// + /// 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 + /// makes it before it ever reaches this provider. + /// + internal static async Task<(AgentCoreChatHistoryProvider Provider, RecordingCallStore Store, StubSession Session)> NewCall() + { + var store = new RecordingCallStore(); + await store.CreateAsync(CallId, TestContext.Current.CancellationToken); + var provider = new AgentCoreChatHistoryProvider(store); + var session = new StubSession(); + provider.BeginCall(session, CallId, []); + return (provider, store, session); + } + + /// Writes one turn the way CallSession does: name the turn, then append it. + internal static void AppendTurn( + AgentCoreChatHistoryProvider provider, + AgentSession session, + int turnIndex, + string said, + string replied) + { + provider.BeginTurn(session, turnIndex); + provider.AppendTurn( + session, + [new ChatMessage(ChatRole.User, said), new ChatMessage(ChatRole.Assistant, replied)]); + } + + /// Reads one session's transcript straight out of its state bag, past the provider. + internal static CallTranscript TranscriptIn(AgentSession session) + { + Assert.True(session.StateBag.TryGetValue(StateKey, out var transcript, StateOptions)); + Assert.NotNull(transcript); + return transcript; + } + + internal static async Task> ProvideAsync( + AgentCoreChatHistoryProvider provider, AgentSession session) + { +#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. + var context = new ChatHistoryProvider.InvokingContext(StubAgent.Instance, session, []); +#pragma warning restore MAAI001 + var messages = await provider.InvokingAsync(context, TestContext.Current.CancellationToken); + return [.. messages]; + } +} + +/// +/// 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()) +{ + private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + private bool _block; + + public Task Entered => _entered.Task; + + public void BlockNextAppend() => _block = true; + + public void Release() => _release.TrySetResult(); + + public override async ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, + CallSessionState? state = null, + CancellationToken cancellationToken = default) + { + if (_block) + { + _block = false; + _entered.TrySetResult(); + await _release.Task.WaitAsync(cancellationToken); + } + + return await Inner.AppendAsync(callId, messages, state, cancellationToken); + } + + public override ValueTask RewriteAsync( + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => Inner.RewriteAsync(callId, messageId, content, cancellationToken); +} + +internal sealed class StubSession : AgentSession; + +/// Stands in for the agent the framework names on a context. Nothing here runs it. +internal sealed class StubAgent : AIAgent +{ + public static StubAgent Instance { get; } = new(); + + protected override ValueTask CreateSessionCoreAsync( + CancellationToken cancellationToken = default) + => new(new StubSession()); + + protected override ValueTask SerializeSessionCoreAsync( + AgentSession session, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override ValueTask DeserializeSessionCoreAsync( + JsonElement serializedState, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); +} diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs index 3fb2c32a..eb641c26 100644 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs @@ -1,14 +1,9 @@ -using AgentCore.Application.Calls; -using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Calls.Memory; using AgentCore.Application.Transcript; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; -using System.Text.Json; -using AgentCore.TestSupport; using Xunit; +using static AgentCore.Application.Tests.Transcript.AgentCoreChatHistoryProviderTestSupport; namespace AgentCore.Application.Tests.Transcript; @@ -18,19 +13,11 @@ namespace AgentCore.Application.Tests.Transcript; /// public sealed class AgentCoreChatHistoryProviderTests { - private const string CallId = "call-1"; - - /// - /// The key the call's transcript is filed under in . Changing - /// it orphans the state of any session already persisted under the old one. - /// - private const string StateKey = "AgentCoreChatHistoryProvider"; - [Fact] public async Task ProvideChatHistory_AfterAppend_ReturnsMessagesInOrder() { // Arrange - var (provider, _, session) = NewCall(); + var (provider, _, session) = await NewCall(); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday"); @@ -47,7 +34,7 @@ public async Task ProvideChatHistory_AfterAppend_ReturnsMessagesInOrder() public async Task AppendTurn_MultipleTurns_OrdinalsAreDenseAndUnique() { // Arrange - var (provider, store, session) = NewCall(); + var (provider, store, session) = await NewCall(); AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); // Act @@ -64,7 +51,7 @@ public async Task AppendTurn_MultipleTurns_OrdinalsAreDenseAndUnique() public async Task AppendTurn_RefusedTurn_IsStored() { // Arrange - var (provider, store, session) = NewCall(); + var (provider, store, session) = await NewCall(); // Act AppendTurn(provider, session, turnIndex: 0, "something flagged", "I can't help with that."); @@ -80,7 +67,7 @@ public async Task AppendTurn_RefusedTurn_IsStored() public async Task AppendTurn_FailedTurn_IsStored() { // Arrange - var (provider, store, session) = NewCall(); + var (provider, store, session) = await NewCall(); // Act AppendTurn(provider, session, turnIndex: 0, "check my order", "Sorry, I had trouble with that."); @@ -102,7 +89,7 @@ public async Task AppendTurn_FailedTurn_IsStored() public async Task StoreChatHistory_FinishedRun_StoresNothing() { // Arrange - var (provider, store, session) = NewCall(); + var (provider, store, session) = await NewCall(); provider.BeginTurn(session, turnIndex: 0); // Act @@ -122,156 +109,11 @@ [new ChatMessage(ChatRole.Assistant, "it ships Friday")]), Assert.Empty(await ProvideAsync(provider, session)); } - [Fact] - public async Task TruncateLastReply_LastAssistantMessage_RewritesOnlyThatMessage() - { - // Arrange - var (provider, store, session) = NewCall(); - AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); - AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday from the depot"); - - // Act - var cut = provider.TruncateLastReply(session, "it ships", TimeSpan.FromMilliseconds(420)); - - // Assert - Assert.True(cut); - var history = await ProvideAsync(provider, session); - Assert.Equal( - ["hello", "hi there", "order 41?", "it ships"], - history.Select(message => message.Text)); - await provider.DrainAsync(session); - Assert.Equal([3], store.Rewrites.Select(rewrite => rewrite.Ordinal)); - } - - [Fact] - public async Task ProvideChatHistory_AfterTruncate_ReturnsHeardTextNotProducedText() - { - // Arrange - var (provider, _, session) = NewCall(); - AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday from the depot"); - - // Act - _ = provider.TruncateLastReply(session, "it ships Fri", TimeSpan.FromMilliseconds(300)); - - // Assert - var history = await ProvideAsync(provider, session); - Assert.Equal(["order 41?", "it ships Fri"], history.Select(message => message.Text)); - } - - /// - /// The barge-in lands while the turn it belongs to is still inside its own write. The write - /// chain is what orders the two: a rewrite that overtook the insert it targets would find no row - /// and leave the record holding words the caller never heard. - /// - [Fact] - public async Task TruncateLastReply_WhileTheAppendIsStillWriting_ReachesTheStoreAfterIt() - { - // Arrange - var store = new BlockingCallStore(); - var provider = new AgentCoreChatHistoryProvider(store); - var session = new StubSession(); - provider.BeginCall(session, CallId, []); - AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); - await provider.DrainAsync(session); - store.BlockNextAppend(); - AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday from the depot"); - await store.Entered; - - // Act - var cut = provider.TruncateLastReply(session, "it ships", TimeSpan.FromMilliseconds(90)); - store.Release(); - await provider.DrainAsync(session); - - // Assert - Assert.True(cut); - Assert.Equal( - ["hello", "hi there", "order 41?", "it ships"], - (await store.ReadAsync(CallId, 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 - /// 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) = NewCall(); - AppendTurn(provider, session, turnIndex: 0, "hello", "hi there caller"); - provider.BeginTurn(session, turnIndex: 1); - - // Act - var cut = provider.TruncateLastReply(session, "hi there", TimeSpan.FromMilliseconds(300)); - - // Assert - Assert.True(cut); - var history = await ProvideAsync(provider, session); - Assert.Equal(["hello", "hi there"], history.Select(message => message.Text)); - } - - /// - /// A model routinely writes a line and puts the tool call it announces on the same message, and a - /// graph row writes one reply for each node. The caller heard as much of the turn as the vendor - /// played and nothing else, so no earlier word of that turn may survive the cut as text the - /// caller is recorded as having heard. - /// - [Fact] - public async Task TruncateLastReply_TurnWithProseBesideAToolCall_DropsEveryWordButTheHeardOnes() - { - // Arrange - var (provider, store, session) = NewCall(); - provider.BeginTurn(session, turnIndex: 0); - ChatMessage announced = new( - ChatRole.Assistant, - [new TextContent("Let me check that for you"), new FunctionCallContent("call-1", "lookup")]); - provider.AppendTurn( - session, - [ - new ChatMessage(ChatRole.User, "how much?"), - announced, - new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", "50")]), - new ChatMessage(ChatRole.Assistant, "the price is fifty"), - ]); - - // Act - var cut = provider.TruncateLastReply(session, "the price", TimeSpan.FromMilliseconds(400)); - - // Assert - Assert.True(cut); - var history = await ProvideAsync(provider, session); - Assert.Equal(["how much?", string.Empty, string.Empty, "the price"], history.Select(m => m.Text)); - - // The side effect ran, so the pair stays. That is the rule the cut must not break. - Assert.Contains(history, m => m.Contents.OfType().Any()); - Assert.Contains(history, m => m.Contents.OfType().Any()); - - await provider.DrainAsync(session); - Assert.Equal([1, 3], store.Rewrites.Select(rewrite => rewrite.Ordinal)); - } - - [Fact] - public async Task TruncateLastReply_BeforeAnyReplyExists_NoOps() - { - // Arrange - var (provider, store, session) = NewCall(); - provider.BeginTurn(session, turnIndex: 0); - - // Act - var cut = provider.TruncateLastReply(session, "nothing was said", TimeSpan.Zero); - - // Assert - Assert.False(cut); - Assert.Empty(store.Rewrites); - Assert.Empty(await ProvideAsync(provider, session)); - } - [Fact] public async Task AppendTurn_ConcurrentAppends_LosesNoMessage() { // Arrange - var (provider, store, session) = NewCall(); + var (provider, store, session) = await NewCall(); provider.BeginTurn(session, turnIndex: 0); var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var turns = Enumerable.Range(0, 20) @@ -334,10 +176,10 @@ public void StateKeys_IsTheSingleKeyTheTranscriptIsFiledUnder() } [Fact] - public void AppendTurn_PutsTheTranscriptInTheSessionStateBagUnderTheProviderKey() + public async Task AppendTurn_PutsTheTranscriptInTheSessionStateBagUnderTheProviderKey() { // Arrange - var (provider, _, session) = NewCall(); + var (provider, _, session) = await NewCall(); // Act AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday"); @@ -404,143 +246,4 @@ public async Task BeginCall_BackingStoreThrows_TellsTheReporterWhichTurnWasLost( await provider.DrainAsync(session); Assert.Equal([3], dropped); } - - [Fact] - public async Task InMemoryStore_AfterTurnAndBargeIn_HoldsTheHeardTextInOrder() - { - // Arrange - var store = new InMemoryCallStore(); - var provider = new AgentCoreChatHistoryProvider(store); - var session = new StubSession(); - provider.BeginCall(session, CallId, []); - AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday from the depot"); - - // Act - _ = provider.TruncateLastReply(session, "it ships", TimeSpan.FromMilliseconds(200)); - - // Assert - await provider.DrainAsync(session); - Assert.Equal( - ["order 41?", "it ships"], - (await store.ReadAsync(CallId, TestContext.Current.CancellationToken)).Select(row => row.Content.Text)); - } - - /// Opens one call on a fresh session, the way CallSession does at call start. - private static (AgentCoreChatHistoryProvider Provider, RecordingCallStore Store, StubSession Session) NewCall() - { - var store = new RecordingCallStore(); - var provider = new AgentCoreChatHistoryProvider(store); - var session = new StubSession(); - provider.BeginCall(session, CallId, []); - return (provider, store, session); - } - - /// Writes one turn the way CallSession does: name the turn, then append it. - private static void AppendTurn( - AgentCoreChatHistoryProvider provider, - AgentSession session, - int turnIndex, - string said, - string replied) - { - provider.BeginTurn(session, turnIndex); - provider.AppendTurn( - session, - [new ChatMessage(ChatRole.User, said), new ChatMessage(ChatRole.Assistant, replied)]); - } - - /// The converters the provider files the transcript with. - private static JsonSerializerOptions StateOptions => AIJsonUtilities.DefaultOptions; - - /// Reads one session's transcript straight out of its state bag, past the provider. - private static CallTranscript TranscriptIn(AgentSession session) - { - Assert.True(session.StateBag.TryGetValue(StateKey, out var transcript, StateOptions)); - Assert.NotNull(transcript); - return transcript; - } - - private static async Task> ProvideAsync( - AgentCoreChatHistoryProvider provider, AgentSession session) - { -#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. - var context = new ChatHistoryProvider.InvokingContext(StubAgent.Instance, session, []); -#pragma warning restore MAAI001 - var messages = await provider.InvokingAsync(context, TestContext.Current.CancellationToken); - return [.. messages]; - } - - /// - /// 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. - /// - private sealed class BlockingCallStore() : DelegatingCallStore(new InMemoryCallStore()) - { - private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); - private bool _block; - - public Task Entered => _entered.Task; - - public void BlockNextAppend() => _block = true; - - public void Release() => _release.TrySetResult(); - - public override async ValueTask AppendAsync( - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - { - if (_block) - { - _block = false; - _entered.TrySetResult(); - await _release.Task.WaitAsync(cancellationToken); - } - - await Inner.AppendAsync(messages, state, cancellationToken); - } - - public override ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) - => Inner.RewriteAsync(callId, ordinal, content, cancellationToken); - } - - private sealed class StubSession : AgentSession; - - /// Stands in for the agent the framework names on a context. Nothing here runs it. - private sealed class StubAgent : AIAgent - { - public static StubAgent Instance { get; } = new(); - - protected override ValueTask CreateSessionCoreAsync( - CancellationToken cancellationToken = default) - => new(new StubSession()); - - protected override ValueTask SerializeSessionCoreAsync( - AgentSession session, - JsonSerializerOptions? jsonSerializerOptions = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - protected override ValueTask DeserializeSessionCoreAsync( - JsonElement serializedState, - JsonSerializerOptions? jsonSerializerOptions = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - protected override Task RunCoreAsync( - IEnumerable messages, - AgentSession? session = null, - AgentRunOptions? options = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - protected override IAsyncEnumerable RunCoreStreamingAsync( - IEnumerable messages, - AgentSession? session = null, - AgentRunOptions? options = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - } } diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs new file mode 100644 index 00000000..99d84c78 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTruncateTests.cs @@ -0,0 +1,181 @@ +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; +using static AgentCore.Application.Tests.Transcript.AgentCoreChatHistoryProviderTestSupport; + +namespace AgentCore.Application.Tests.Transcript; + +/// +/// Pins what a barge-in does to the words the provider already wrote: which row it rewrites, and +/// when the rewrite is guaranteed to land after the append it corrects. +/// +public sealed class AgentCoreChatHistoryProviderTruncateTests +{ + [Fact] + public async Task TruncateLastReply_LastAssistantMessage_RewritesOnlyThatMessage() + { + // Arrange + var (provider, store, session) = await NewCall(); + AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); + AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday from the depot"); + + // Act + var cut = provider.TruncateLastReply(session, "it ships", TimeSpan.FromMilliseconds(420)); + + // Assert + Assert.True(cut); + var history = await ProvideAsync(provider, session); + Assert.Equal( + ["hello", "hi there", "order 41?", "it ships"], + history.Select(message => message.Text)); + await provider.DrainAsync(session); + Assert.Equal([3], store.Rewrites.Select(rewrite => rewrite.Ordinal)); + } + + [Fact] + public async Task ProvideChatHistory_AfterTruncate_ReturnsHeardTextNotProducedText() + { + // Arrange + var (provider, _, session) = await NewCall(); + AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday from the depot"); + + // Act + _ = provider.TruncateLastReply(session, "it ships Fri", TimeSpan.FromMilliseconds(300)); + + // Assert + var history = await ProvideAsync(provider, session); + Assert.Equal(["order 41?", "it ships Fri"], history.Select(message => message.Text)); + } + + /// + /// The barge-in lands while the turn it belongs to is still inside its own write. The write + /// chain is what orders the two: a rewrite that overtook the insert it targets would find no row + /// and leave the record holding words the caller never heard. + /// + [Fact] + public async Task TruncateLastReply_WhileTheAppendIsStillWriting_ReachesTheStoreAfterIt() + { + // Arrange + var store = new BlockingCallStore(); + await store.CreateAsync(CallId, TestContext.Current.CancellationToken); + var provider = new AgentCoreChatHistoryProvider(store); + var session = new StubSession(); + provider.BeginCall(session, CallId, []); + AppendTurn(provider, session, turnIndex: 0, "hello", "hi there"); + await provider.DrainAsync(session); + store.BlockNextAppend(); + AppendTurn(provider, session, turnIndex: 1, "order 41?", "it ships Friday from the depot"); + await store.Entered; + + // Act + var cut = provider.TruncateLastReply(session, "it ships", TimeSpan.FromMilliseconds(90)); + store.Release(); + await provider.DrainAsync(session); + + // Assert + Assert.True(cut); + Assert.Equal( + ["hello", "hi there", "order 41?", "it ships"], + (await store.ReadAsync(CallId, 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 + /// 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(); + AppendTurn(provider, session, turnIndex: 0, "hello", "hi there caller"); + provider.BeginTurn(session, turnIndex: 1); + + // Act + var cut = provider.TruncateLastReply(session, "hi there", TimeSpan.FromMilliseconds(300)); + + // Assert + Assert.True(cut); + var history = await ProvideAsync(provider, session); + Assert.Equal(["hello", "hi there"], history.Select(message => message.Text)); + } + + /// + /// A model routinely writes a line and puts the tool call it announces on the same message, and a + /// graph row writes one reply for each node. The caller heard as much of the turn as the vendor + /// played and nothing else, so no earlier word of that turn may survive the cut as text the + /// caller is recorded as having heard. + /// + [Fact] + public async Task TruncateLastReply_TurnWithProseBesideAToolCall_DropsEveryWordButTheHeardOnes() + { + // Arrange + var (provider, store, session) = await NewCall(); + provider.BeginTurn(session, turnIndex: 0); + ChatMessage announced = new( + ChatRole.Assistant, + [new TextContent("Let me check that for you"), new FunctionCallContent("call-1", "lookup")]); + provider.AppendTurn( + session, + [ + new ChatMessage(ChatRole.User, "how much?"), + announced, + new ChatMessage(ChatRole.Tool, [new FunctionResultContent("call-1", "50")]), + new ChatMessage(ChatRole.Assistant, "the price is fifty"), + ]); + + // Act + var cut = provider.TruncateLastReply(session, "the price", TimeSpan.FromMilliseconds(400)); + + // Assert + Assert.True(cut); + var history = await ProvideAsync(provider, session); + Assert.Equal(["how much?", string.Empty, string.Empty, "the price"], history.Select(m => m.Text)); + + // The side effect ran, so the pair stays. That is the rule the cut must not break. + Assert.Contains(history, m => m.Contents.OfType().Any()); + Assert.Contains(history, m => m.Contents.OfType().Any()); + + await provider.DrainAsync(session); + Assert.Equal([1, 3], store.Rewrites.Select(rewrite => rewrite.Ordinal)); + } + + [Fact] + public async Task TruncateLastReply_BeforeAnyReplyExists_NoOps() + { + // Arrange + var (provider, store, session) = await NewCall(); + provider.BeginTurn(session, turnIndex: 0); + + // Act + var cut = provider.TruncateLastReply(session, "nothing was said", TimeSpan.Zero); + + // Assert + Assert.False(cut); + Assert.Empty(store.Rewrites); + Assert.Empty(await ProvideAsync(provider, session)); + } + + [Fact] + public async Task InMemoryStore_AfterTurnAndBargeIn_HoldsTheHeardTextInOrder() + { + // Arrange + var store = new InMemoryCallStore(); + await store.CreateAsync(CallId, TestContext.Current.CancellationToken); + var provider = new AgentCoreChatHistoryProvider(store); + var session = new StubSession(); + provider.BeginCall(session, CallId, []); + AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday from the depot"); + + // Act + _ = provider.TruncateLastReply(session, "it ships", TimeSpan.FromMilliseconds(200)); + + // Assert + await provider.DrainAsync(session); + Assert.Equal( + ["order 41?", "it ships"], + (await store.ReadAsync(CallId, TestContext.Current.CancellationToken)).Select(row => row.Content.Text)); + } +} diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs new file mode 100644 index 00000000..6968cd27 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionOutsideAppendTests.cs @@ -0,0 +1,208 @@ +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Transcript; +using Microsoft.Extensions.AI; +using Xunit; +using static AgentCore.Application.Tests.Transcript.CallSessionResumeTestSupport; + +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) + // is a default interface method, and only resolves through the interface type. +public sealed class CallSessionOutsideAppendTests +{ + [Fact] + public async Task SecondTurn_SeesTheOutsideMessagesBetweenTheTurns_AndKeepsTheirProperties() + { + ICallStore store = new InMemoryCallStore(); + var (_, client) = await RunTwoTurnsWithAnOutsideHandoffAsync(store); + + var secondRequest = client.Requests[1]; + + // Both outside rows land between turn 1's words and turn 2's own question, in the order the + // host wrote them. + Assert.Equal( + ["my name is Dana", "hi Dana", "Dana joined", "human phase", "are you still there?"], + secondRequest.Select(message => message.Text)); + + var joined = Assert.Single(secondRequest, message => message.Text == "Dana joined"); + Assert.Equal("human-agent", joined.AdditionalProperties?["speaker"]?.ToString()); + } + + [Fact] + public async Task AfterTheSecondTurn_TheStoresOrdinalsAreDenseAndUnique() + { + ICallStore store = new InMemoryCallStore(); + var (session, _) = await RunTwoTurnsWithAnOutsideHandoffAsync(store); + + var rows = await store.ReadAsync(session.CallId, TestContext.Current.CancellationToken); + var ordinals = rows.Select(row => row.Ordinal).ToArray(); + + for (var index = 1; index < ordinals.Length; index++) + { + Assert.True(ordinals[index] > ordinals[index - 1]); + } + + // 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); + 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 + // passes between them. + ICallStore store = new InMemoryCallStore(); + + SequencedChatClient clientA = new("hi Dana"); + var sessionA = CreateSession(OneAgentYaml, clientA, store); + await sessionA.RunTurnAsync("my name is Dana", TestContext.Current.CancellationToken); + await sessionA.FlushTranscriptAsync(); + + await store.AppendMessageAsync( + sessionA.CallId, + new ChatMessage(ChatRole.Assistant, "Dana joined") + { + AdditionalProperties = new() { ["speaker"] = "human-agent" }, + }, + TestContext.Current.CancellationToken); + + SequencedChatClient clientB = new("welcome back"); + var sessionB = CreateSession(OneAgentYaml, clientB, store, sessionA.CallId); + + await sessionB.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + await sessionB.FlushTranscriptAsync(); + + Assert.Equal( + ["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); + Assert.Equal([0, 1, 2, 3, 4], rows.Select(row => row.Ordinal)); + + var record = await store.GetAsync(sessionA.CallId, TestContext.Current.CancellationToken); + Assert.Equal(rows.Count, record?.NextOrdinal); + } + + [Fact] + public async Task AnEditAfterAnOutsideAppend_CutsTheOutsideRowWithTheReplyItReplaces() + { + ICallStore store = new InMemoryCallStore(); + SequencedChatClient client = new("first reply", "second reply"); + var session = CreateSession(OneAgentYaml, client, store); + + await session.RunTurnAtOriginAsync( + "first question", + new CallTurnOrigin("m1", null) { NamesParent = true }, + TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + + await store.AppendMessageAsync( + session.CallId, + new ChatMessage(ChatRole.Assistant, "Dana joined") + { + AdditionalProperties = new() { ["speaker"] = "human-agent" }, + }, + TestContext.Current.CancellationToken); + + // Names m1 as the parent, so the edit must see the outside row that now sits after it in + // order to cut it along with the reply it replaces. + await session.RunTurnAtOriginAsync( + "first question, rewritten", + new CallTurnOrigin("m2", "m1") { NamesParent = true }, + TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + + var rows = await store.ReadAsync(session.CallId, TestContext.Current.CancellationToken); + + Assert.Equal(3, rows.Count); + Assert.Equal("m1", rows[0].MessageId); + Assert.Equal("m2", rows[1].MessageId); + Assert.Equal( + ["first question", "first question, rewritten", "second reply"], + rows.Select(row => row.Content.Text)); + } + + [Fact] + public async Task AfterOneTurn_TheStoredBlobCarriesTheTurnIndexAndTheCounterLivesOnTheRecord() + { + ICallStore store = new InMemoryCallStore(); + 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); + + // 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. + Assert.Equal(1, record?.State?.NextTurnIndex); + Assert.Equal(2, record?.NextOrdinal); + } + + [Fact] + public async Task SecondTurn_WithNoOutsideAppend_DoesNotReadTheWordsBack() + { + RecordingCallStore store = new(); + SequencedChatClient client = new("hi Dana", "welcome back"); + var session = CreateSession(OneAgentYaml, client, store); + + await session.RunTurnAsync("my name is Dana", TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + await session.RunTurnAsync("are you still there?", TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + + // The counter store 0 hands back matches the one the session holds, so nobody wrote from + // outside and there is nothing to read. + Assert.Equal(0, store.Reads); + Assert.Equal( + ["my name is Dana", "hi Dana", "are you still there?"], + client.Requests[1].Select(message => message.Text)); + } + + [Fact] + public async Task SecondTurn_AfterAnOutsideAppend_ReadsTheWordsBackOnce() + { + RecordingCallStore store = new(); + await RunTwoTurnsWithAnOutsideHandoffAsync(store); + + Assert.Equal(1, store.Reads); + } + + private static async Task<(CallSession Session, SequencedChatClient Client)> RunTwoTurnsWithAnOutsideHandoffAsync( + ICallStore store) + { + SequencedChatClient client = new("hi Dana", "welcome back"); + var session = CreateSession(OneAgentYaml, client, store); + + await session.RunTurnAsync("my name is Dana", TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + + await store.AppendMessageAsync( + session.CallId, + new ChatMessage(ChatRole.Assistant, "Dana joined") + { + AdditionalProperties = new() { ["speaker"] = "human-agent" }, + }, + TestContext.Current.CancellationToken); + await store.AppendMessageAsync( + session.CallId, + new ChatMessage(ChatRole.User, "human phase"), + TestContext.Current.CancellationToken); + + await session.RunTurnAsync("are you still there?", TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + + return (session, client); + } +} +#pragma warning restore CA1859 diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs new file mode 100644 index 00000000..eedc1c28 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTestSupport.cs @@ -0,0 +1,147 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Transcript; + +/// The documents and session-building helpers a call's resume tests share. +internal static class CallSessionResumeTestSupport +{ + internal const string OneAgentYaml = """ + apiVersion: agentcore/v1 + name: resume-check + agents: + items: + - { id: only, instructions: "greet the caller" } + """; + + /// + /// A document with something to forget: one slot a writer fills, and a stage that moves. + /// + internal const string StagedYaml = """ + apiVersion: agentcore/v1 + name: resume-state-check + state: + turnsTaken: + type: integer + default: 0 + writer: counter + increment: { ">=": [ { var: turnIndex }, 0 ] } + guards: + pastFirstTurn: { ">": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: intake, instructions: "ask the caller for the model" } + - { id: help, instructions: "help the caller" } + policy: + initial: intake + stages: + - { id: intake, agent: intake, to: [ { stage: help, when: pastFirstTurn } ] } + - { id: help, agent: help } + """; + + /// + /// A document whose stages run three deep, so a machine left in the first one is visible. + /// + internal const string ThreeStageYaml = """ + apiVersion: agentcore/v1 + name: resume-machine-check + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: first, instructions: "greet the caller" } + - { id: second, instructions: "ask the caller for the model" } + - { id: third, instructions: "help the caller" } + policy: + initial: one + stages: + - { id: one, agent: first, to: [ { stage: two, when: always } ] } + - { id: two, agent: second, to: [ { stage: three, when: always } ] } + - { id: three, agent: third } + """; + + internal static async Task FirstTurnAsync( + ICallStore store, string said, string heard) + { + using ScriptedChatClient reply = new(heard); + var session = CreateSession(OneAgentYaml, reply, store); + + await session.RunTurnAsync(said, TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + + return session.CallId; + } + + internal static async Task SecondTurnAsync( + ICallStore store, string callId, string said, string heard) + { + using ScriptedChatClient reply = new(heard); + var session = CreateSession(OneAgentYaml, reply, store, callId); + + await session.RunTurnAsync(said, TestContext.Current.CancellationToken); + await session.FlushTranscriptAsync(); + } + + internal static CallSession CreateSession( + string yaml, + IChatClient reply, + ICallStore store, + string? callId = null, + ICallObserver? observer = null) + { + var document = ConfigurationLoader.LoadYaml(yaml); + var chatClients = new FakeChatClientFactory(reply); + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) + { + CallStore = store, + Tools = TestToolRegistry.From(document, null, TestContext.Current.CancellationToken), + }); + + var factory = new CallSessionFactory( + compiled, + new GuardEvaluator(compiled.Configuration.Guards), + extractor: null, + observers: observer is null ? null : [observer]); + + return factory.Create(callId); + } +} + +/// Keeps every fact of the call, in the order the turn loop raised them. +internal sealed class RecordingObserver : ICallObserver +{ + private readonly Lock _gate = new(); + private readonly List _events = []; + + /// Gets what the call raised, oldest first. + public IReadOnlyList Events + { + get + { + lock (_gate) + { + return [.. _events]; + } + } + } + + public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) + { + lock (_gate) + { + _events.Add(callEvent); + } + + return ValueTask.CompletedTask; + } +} diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs index dbf635a8..82d07a77 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionResumeTests.cs @@ -1,17 +1,11 @@ -using System.Text.Json.Nodes; -using AgentCore.Application.Calls; using AgentCore.Application.Calls.Memory; -using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Tests.Runtime; 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; @@ -20,60 +14,6 @@ namespace AgentCore.Application.Tests.Transcript; /// public sealed class CallSessionResumeTests { - private const string OneAgentYaml = """ - apiVersion: agentcore/v1 - name: resume-check - agents: - items: - - { id: only, instructions: "greet the caller" } - """; - - /// - /// A document with something to forget: one slot a writer fills, and a stage that moves. - /// - private const string StagedYaml = """ - apiVersion: agentcore/v1 - name: resume-state-check - state: - turnsTaken: - type: integer - default: 0 - writer: counter - increment: { ">=": [ { var: turnIndex }, 0 ] } - guards: - pastFirstTurn: { ">": [ { var: turnIndex }, 0 ] } - agents: - items: - - { id: intake, instructions: "ask the caller for the model" } - - { id: help, instructions: "help the caller" } - policy: - initial: intake - stages: - - { id: intake, agent: intake, to: [ { stage: help, when: pastFirstTurn } ] } - - { id: help, agent: help } - """; - - /// - /// A document whose stages run three deep, so a machine left in the first one is visible. - /// - private const string ThreeStageYaml = """ - apiVersion: agentcore/v1 - name: resume-machine-check - guards: - always: { ">=": [ { var: turnIndex }, 0 ] } - agents: - items: - - { id: first, instructions: "greet the caller" } - - { id: second, instructions: "ask the caller for the model" } - - { id: third, instructions: "help the caller" } - policy: - initial: one - stages: - - { id: one, agent: first, to: [ { stage: two, when: always } ] } - - { id: two, agent: second, to: [ { stage: three, when: always } ] } - - { id: three, agent: third } - """; - [Fact] public async Task ASecondSessionOfOneCall_SendsTheFirstTurnToTheModel() { @@ -153,382 +93,6 @@ await Assert.ThrowsAsync( () => resumed.RunTurnAsync("what is my name?", TestContext.Current.CancellationToken)); } - [Fact] - public async Task ASecondSessionOfOneCall_KeepsTheStageTheFirstOneReached() - { - InMemoryCallStore store = new(); - - using ScriptedChatClient first = new("what model is it?"); - var opened = CreateSession(StagedYaml, first, store); - await opened.RunTurnAsync("hello", TestContext.Current.CancellationToken); - await opened.FlushTranscriptAsync(); - - Assert.Equal("help", opened.Stage); - - using ScriptedChatClient second = new("sure"); - var resumed = CreateSession(StagedYaml, second, store, opened.CallId); - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - // StageBefore, and not Stage. The stage is restored when the session OPENS and the session - // opens on the first turn, so the restored stage is the one that turn spoke in, and 'intake' - // is what a session that forgot would report. Reading Stage after the turn would prove - // nothing: this document's only guard reads the reserved turnIndex slot, which store 1 - // restores off the words on its own, so even a session that remembered nothing would land in - // 'help' by the end of the turn. - Assert.Equal("help", resumed.LastTurn!.StageBefore); - } - - [Fact] - public async Task ASecondSessionOfOneCall_MovesTheStageMachineAndNotOnlyItsLabel() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-machine", TestContext.Current.CancellationToken); - - await store.AppendAsync( - [new CallMessage("C-machine", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "two" }, - TestContext.Current.CancellationToken); - - using ScriptedChatClient reply = new("sure"); - var resumed = CreateSession(ThreeStageYaml, reply, store, "C-machine"); - - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - // 'three', because the turn ran in 'two' and moved on from there. A session that restored - // the reserved stage slot and left the machine where the document starts would report 'two' - // twice over: 'two' as the stage the turn spoke in, because the slot says so, and 'two' - // again afterwards, because the machine only just walked to it — while the turn itself was - // answered by the agent of 'one'. - Assert.Equal("two", resumed.LastTurn!.StageBefore); - Assert.Equal("three", resumed.Stage); - } - - [Fact] - public async Task ASecondSessionOfOneCall_KeepsTheSlotsTheFirstOneFilled() - { - InMemoryCallStore store = new(); - - using ScriptedChatClient first = new("what model is it?"); - var opened = CreateSession(StagedYaml, first, store); - await opened.RunTurnAsync("hello", TestContext.Current.CancellationToken); - await opened.FlushTranscriptAsync(); - - Assert.Equal(1L, opened.State.Read("turnsTaken")!.GetValue()); - - using ScriptedChatClient second = new("sure"); - var resumed = CreateSession(StagedYaml, second, store, opened.CallId); - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - // Two, not one. A session that forgot would count its own turn from zero. - Assert.Equal(2L, resumed.State.Read("turnsTaken")!.GetValue()); - } - - [Fact] - public async Task ASecondSessionOfOneCall_DropsASlotTheDocumentNoLongerDeclares() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-drift", TestContext.Current.CancellationToken); - - // Written as though a build that declared 'retired' had run this call. - await store.AppendAsync( - [new CallMessage("C-drift", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState - { - Stage = "intake", - Slots = new Dictionary(StringComparer.Ordinal) - { - ["turnsTaken"] = JsonValue.Create(4L), - ["retired"] = JsonValue.Create("gone"), - }, - }, - TestContext.Current.CancellationToken); - - using ScriptedChatClient reply = new("sure"); - RecordingObserver observer = new(); - var resumed = CreateSession(StagedYaml, reply, store, "C-drift", observer); - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - 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 - // 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); - Assert.Equal( - "the document no longer declares the slot 'retired'.", - dropped.Payload[CallEventPayloadKeys.Reason]); - } - - [Fact] - public async Task ASecondSessionOfOneCall_DropsASlotWhoseDeclaredTypeNoLongerTakesTheStoredValue() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-retyped", TestContext.Current.CancellationToken); - - // Written as though 'turnsTaken' had been declared a string when this call ran. - await store.AppendAsync( - [new CallMessage("C-retyped", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState - { - Stage = "intake", - Slots = new Dictionary(StringComparer.Ordinal) - { - ["turnsTaken"] = JsonValue.Create("four"), - }, - }, - TestContext.Current.CancellationToken); - - using ScriptedChatClient reply = new("sure"); - RecordingObserver observer = new(); - var resumed = CreateSession(StagedYaml, reply, store, "C-retyped", observer); - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - // Back to the declared default, and then this turn's own increment. - Assert.Equal(1L, resumed.State.Read("turnsTaken")!.GetValue()); - - // 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); - Assert.Equal( - "the slot 'turnsTaken' no longer takes the value it was stored with.", - dropped.Payload[CallEventPayloadKeys.Reason]); - } - - [Fact] - public async Task ASecondSessionOfOneCall_DropsAReservedSlotRatherThanRefusingTheCall() - { - InMemoryCallStore 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. - await store.AppendAsync( - [new CallMessage("C-reserved", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState - { - Stage = "intake", - Slots = new Dictionary(StringComparer.Ordinal) - { - ["turnsTaken"] = JsonValue.Create(4L), - ["stage"] = JsonValue.Create("help"), - }, - }, - TestContext.Current.CancellationToken); - - using ScriptedChatClient reply = new("sure"); - RecordingObserver observer = new(); - var resumed = CreateSession(StagedYaml, reply, store, "C-reserved", observer); - - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - // It ran, and the declared slot beside the reserved one still landed. - Assert.NotNull(resumed.LastTurn); - Assert.Equal(5L, resumed.State.Read("turnsTaken")!.GetValue()); - - var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); - Assert.Equal( - "the slot 'stage' is reserved, and a reserved slot is never restored.", - dropped.Payload[CallEventPayloadKeys.Reason]); - } - - [Fact] - public async Task ASecondSessionOfOneCall_IgnoresAStateBlobWrittenInAShapeThisBuildDoesNotKnow() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-future", TestContext.Current.CancellationToken); - - await store.AppendAsync( - [new CallMessage("C-future", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState - { - Version = CallSessionState.CurrentVersion + 1, - Stage = "help", - Slots = new Dictionary(StringComparer.Ordinal) - { - ["turnsTaken"] = JsonValue.Create(4L), - }, - }, - TestContext.Current.CancellationToken); - - using ScriptedChatClient reply = new("sure"); - RecordingObserver observer = new(); - var resumed = CreateSession(StagedYaml, reply, store, "C-future", observer); - - 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. - 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); - Assert.Equal( - $"the stored state is version {CallSessionState.CurrentVersion + 1} " - + $"and this build writes {CallSessionState.CurrentVersion}.", - dropped.Payload[CallEventPayloadKeys.Reason]); - } - - [Fact] - public async Task ASecondSessionOfACallWhoseDocumentLostItsPolicy_DropsTheStoredStage() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-nopolicy", TestContext.Current.CancellationToken); - - await store.AppendAsync( - [new CallMessage("C-nopolicy", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { 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. - var resumed = CreateSession(OneAgentYaml, reply, store, "C-nopolicy", observer); - - await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); - - // Empty, not 'intake'. There is no machine to hold that stage, and writing it into the - // 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); - Assert.Equal( - "the document declares no policy, so the stage 'intake' has nowhere to go.", - dropped.Payload[CallEventPayloadKeys.Reason]); - } - - [Fact] - public async Task ASecondSessionOfACallThatAlreadyFinished_RefusesTheTurn() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-finished", TestContext.Current.CancellationToken); - - await store.AppendAsync( - [new CallMessage("C-finished", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { 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 - // 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. - await Assert.ThrowsAsync( - () => resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task ASecondSessionOfOneCall_FallsBackWhenTheStageIsGone() - { - InMemoryCallStore store = new(); - await store.CreateAsync("C-nostage", TestContext.Current.CancellationToken); - - await store.AppendAsync( - [new CallMessage("C-nostage", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], - new CallSessionState { Stage = "a-stage-nobody-declares" }, - TestContext.Current.CancellationToken); - - using ScriptedChatClient reply = new("sure"); - RecordingObserver observer = new(); - var resumed = CreateSession(StagedYaml, reply, store, "C-nostage", observer); - - 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 - // 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); - Assert.Contains( - "a-stage-nobody-declares", dropped.Payload[CallEventPayloadKeys.Reason], StringComparison.Ordinal); - } - - [Fact] - public async Task ACallWithNoStoredState_StartsWhereTheDocumentSays() - { - InMemoryCallStore store = new(); - - using ScriptedChatClient reply = new("what model is it?"); - var session = CreateSession(StagedYaml, reply, store); - - await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); - - Assert.NotNull(session.LastTurn); - Assert.Equal("intake", session.LastTurn!.StageBefore); - } - - [Fact] - public async Task ATurnWhoseWriteQueuesBehindASlowOne_StoresItsOwnStateAndNotALaterTurns() - { - ParkingRecordingCallStore store = new(new InMemoryCallStore()); - - using ScriptedChatClient reply = new("sure"); - var session = CreateSession(StagedYaml, reply, store); - - // Three turns and no drain between them. The first write parks, so the second and the third - // queue behind it exactly as they would behind a database that is still thinking. - await session.RunTurnAsync("one", TestContext.Current.CancellationToken); - await session.RunTurnAsync("two", TestContext.Current.CancellationToken); - await session.RunTurnAsync("three", TestContext.Current.CancellationToken); - - store.Release(); - await session.FlushTranscriptAsync(); - - var counted = store.States.Select(state => state!.Slots["turnsTaken"]!.GetValue()).ToArray(); - - // One, two, three: each write carries the state of the turn that queued it. A snapshot read - // when the write finally ran would instead read whatever the call had reached by then, and - // stamp the third turn's count on the two rows before it. - Assert.Equal([1L, 2L, 3L], counted); - } - - /// A store 1 that holds its first write open, and remembers the state each write carried. - private sealed class ParkingRecordingCallStore(ICallStore inner) : DelegatingCallStore(inner) - { - private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly Lock _gate = new(); - private readonly List _states = []; - private int _appends; - - /// Gets the state each append carried, in the order the store took them. - public IReadOnlyList States - { - get - { - lock (_gate) - { - return [.. _states]; - } - } - } - - /// Lets the parked first write finish, and everything queued behind it with it. - public void Release() => _release.TrySetResult(); - - public override async ValueTask AppendAsync( - IReadOnlyList messages, - CallSessionState? state = null, - CancellationToken cancellationToken = default) - { - if (Interlocked.Increment(ref _appends) == 1) - { - await _release.Task.WaitAsync(cancellationToken).ConfigureAwait(false); - } - - lock (_gate) - { - _states.Add(state); - } - - await base.AppendAsync(messages, state, cancellationToken).ConfigureAwait(false); - } - } - /// A store 1 that takes words and will not give them back. private sealed class UnreadableCallStore(ICallStore inner) : DelegatingCallStore(inner) { @@ -536,81 +100,4 @@ public override ValueTask> ReadAsync( string callId, CancellationToken cancellationToken = default) => throw new InvalidOperationException("store 1 will not answer a read."); } - - private static async Task FirstTurnAsync( - ICallStore store, string said, string heard) - { - using ScriptedChatClient reply = new(heard); - var session = CreateSession(OneAgentYaml, reply, store); - - await session.RunTurnAsync(said, TestContext.Current.CancellationToken); - await session.FlushTranscriptAsync(); - - return session.CallId; - } - - private static async Task SecondTurnAsync( - ICallStore store, string callId, string said, string heard) - { - using ScriptedChatClient reply = new(heard); - var session = CreateSession(OneAgentYaml, reply, store, callId); - - await session.RunTurnAsync(said, TestContext.Current.CancellationToken); - await session.FlushTranscriptAsync(); - } - - private static CallSession CreateSession( - string yaml, - IChatClient reply, - ICallStore store, - string? callId = null, - ICallObserver? observer = null) - { - var document = ConfigurationLoader.LoadYaml(yaml); - var chatClients = new FakeChatClientFactory(reply); - var compiled = ConfigurationCompiler.Compile( - document, - new AgentCompilationContext(chatClients) - { - CallStore = store, - Tools = TestToolRegistry.From(document, null, TestContext.Current.CancellationToken), - }); - - var factory = new CallSessionFactory( - compiled, - new GuardEvaluator(compiled.Configuration.Guards), - extractor: null, - observers: observer is null ? null : [observer]); - - return factory.Create(callId); - } - - /// Keeps every fact of the call, in the order the turn loop raised them. - private sealed class RecordingObserver : ICallObserver - { - private readonly Lock _gate = new(); - private readonly List _events = []; - - /// Gets what the call raised, oldest first. - public IReadOnlyList Events - { - get - { - lock (_gate) - { - return [.. _events]; - } - } - } - - public ValueTask OnCallEventAsync(CallEvent callEvent, CancellationToken cancellationToken) - { - lock (_gate) - { - _events.Add(callEvent); - } - - return ValueTask.CompletedTask; - } - } } diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs new file mode 100644 index 00000000..ee5a5209 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionStateRestoreTests.cs @@ -0,0 +1,334 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.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; + +namespace AgentCore.Application.Tests.Transcript; + +/// +/// What a second session of one call restores from the state a first one left behind. +/// +public sealed class CallSessionStateRestoreTests +{ + [Fact] + public async Task ASecondSessionOfOneCall_KeepsTheStageTheFirstOneReached() + { + InMemoryCallStore store = new(); + + using ScriptedChatClient first = new("what model is it?"); + var opened = CreateSession(StagedYaml, first, store); + await opened.RunTurnAsync("hello", TestContext.Current.CancellationToken); + await opened.FlushTranscriptAsync(); + + Assert.Equal("help", opened.Stage); + + using ScriptedChatClient second = new("sure"); + var resumed = CreateSession(StagedYaml, second, store, opened.CallId); + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + // StageBefore, and not Stage. The stage is restored when the session OPENS and the session + // opens on the first turn, so the restored stage is the one that turn spoke in, and 'intake' + // is what a session that forgot would report. Reading Stage after the turn would prove + // nothing: this document's only guard reads the reserved turnIndex slot, which store 1 + // restores off the words on its own, so even a session that remembered nothing would land in + // 'help' by the end of the turn. + Assert.Equal("help", resumed.LastTurn!.StageBefore); + } + + [Fact] + public async Task ASecondSessionOfOneCall_MovesTheStageMachineAndNotOnlyItsLabel() + { + InMemoryCallStore 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" }, + TestContext.Current.CancellationToken); + + using ScriptedChatClient reply = new("sure"); + var resumed = CreateSession(ThreeStageYaml, reply, store, "C-machine"); + + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + // 'three', because the turn ran in 'two' and moved on from there. A session that restored + // the reserved stage slot and left the machine where the document starts would report 'two' + // twice over: 'two' as the stage the turn spoke in, because the slot says so, and 'two' + // again afterwards, because the machine only just walked to it — while the turn itself was + // answered by the agent of 'one'. + Assert.Equal("two", resumed.LastTurn!.StageBefore); + Assert.Equal("three", resumed.Stage); + } + + [Fact] + public async Task ASecondSessionOfOneCall_KeepsTheSlotsTheFirstOneFilled() + { + InMemoryCallStore store = new(); + + using ScriptedChatClient first = new("what model is it?"); + var opened = CreateSession(StagedYaml, first, store); + await opened.RunTurnAsync("hello", TestContext.Current.CancellationToken); + await opened.FlushTranscriptAsync(); + + Assert.Equal(1L, opened.State.Read("turnsTaken")!.GetValue()); + + using ScriptedChatClient second = new("sure"); + var resumed = CreateSession(StagedYaml, second, store, opened.CallId); + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + // Two, not one. A session that forgot would count its own turn from zero. + Assert.Equal(2L, resumed.State.Read("turnsTaken")!.GetValue()); + } + + [Fact] + public async Task ASecondSessionOfOneCall_DropsASlotTheDocumentNoLongerDeclares() + { + InMemoryCallStore store = new(); + await store.CreateAsync("C-drift", TestContext.Current.CancellationToken); + + // Written as though a build that declared 'retired' had run this call. + await store.AppendAsync( + "C-drift", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new CallSessionState + { + Stage = "intake", + Slots = new Dictionary(StringComparer.Ordinal) + { + ["turnsTaken"] = JsonValue.Create(4L), + ["retired"] = JsonValue.Create("gone"), + }, + }, + TestContext.Current.CancellationToken); + + using ScriptedChatClient reply = new("sure"); + RecordingObserver observer = new(); + var resumed = CreateSession(StagedYaml, reply, store, "C-drift", observer); + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + 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 + // 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); + Assert.Equal( + "the document no longer declares the slot 'retired'.", + dropped.Payload[CallEventPayloadKeys.Reason]); + } + + [Fact] + public async Task ASecondSessionOfOneCall_DropsASlotWhoseDeclaredTypeNoLongerTakesTheStoredValue() + { + InMemoryCallStore store = new(); + await store.CreateAsync("C-retyped", TestContext.Current.CancellationToken); + + // Written as though 'turnsTaken' had been declared a string when this call ran. + await store.AppendAsync( + "C-retyped", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new CallSessionState + { + Stage = "intake", + Slots = new Dictionary(StringComparer.Ordinal) + { + ["turnsTaken"] = JsonValue.Create("four"), + }, + }, + TestContext.Current.CancellationToken); + + using ScriptedChatClient reply = new("sure"); + RecordingObserver observer = new(); + var resumed = CreateSession(StagedYaml, reply, store, "C-retyped", observer); + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + // Back to the declared default, and then this turn's own increment. + Assert.Equal(1L, resumed.State.Read("turnsTaken")!.GetValue()); + + // 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); + Assert.Equal( + "the slot 'turnsTaken' no longer takes the value it was stored with.", + dropped.Payload[CallEventPayloadKeys.Reason]); + } + + [Fact] + public async Task ASecondSessionOfOneCall_DropsAReservedSlotRatherThanRefusingTheCall() + { + InMemoryCallStore 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. + await store.AppendAsync( + "C-reserved", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new CallSessionState + { + Stage = "intake", + Slots = new Dictionary(StringComparer.Ordinal) + { + ["turnsTaken"] = JsonValue.Create(4L), + ["stage"] = JsonValue.Create("help"), + }, + }, + TestContext.Current.CancellationToken); + + using ScriptedChatClient reply = new("sure"); + RecordingObserver observer = new(); + var resumed = CreateSession(StagedYaml, reply, store, "C-reserved", observer); + + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + // It ran, and the declared slot beside the reserved one still landed. + Assert.NotNull(resumed.LastTurn); + Assert.Equal(5L, resumed.State.Read("turnsTaken")!.GetValue()); + + var dropped = Assert.Single(observer.Events, fact => fact.Kind == CallEventKind.StateRestorePartial); + Assert.Equal( + "the slot 'stage' is reserved, and a reserved slot is never restored.", + dropped.Payload[CallEventPayloadKeys.Reason]); + } + + [Fact] + public async Task ASecondSessionOfOneCall_IgnoresAStateBlobWrittenInAShapeThisBuildDoesNotKnow() + { + InMemoryCallStore 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 + { + Version = CallSessionState.CurrentVersion + 1, + Stage = "help", + Slots = new Dictionary(StringComparer.Ordinal) + { + ["turnsTaken"] = JsonValue.Create(4L), + }, + }, + TestContext.Current.CancellationToken); + + using ScriptedChatClient reply = new("sure"); + RecordingObserver observer = new(); + var resumed = CreateSession(StagedYaml, reply, store, "C-future", observer); + + 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. + 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); + Assert.Equal( + $"the stored state is version {CallSessionState.CurrentVersion + 1} " + + $"and this build writes {CallSessionState.CurrentVersion}.", + dropped.Payload[CallEventPayloadKeys.Reason]); + } + + [Fact] + public async Task ASecondSessionOfACallWhoseDocumentLostItsPolicy_DropsTheStoredStage() + { + InMemoryCallStore 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" }, + 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. + var resumed = CreateSession(OneAgentYaml, reply, store, "C-nopolicy", observer); + + await resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken); + + // Empty, not 'intake'. There is no machine to hold that stage, and writing it into the + // 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); + Assert.Equal( + "the document declares no policy, so the stage 'intake' has nowhere to go.", + dropped.Payload[CallEventPayloadKeys.Reason]); + } + + [Fact] + public async Task ASecondSessionOfACallThatAlreadyFinished_RefusesTheTurn() + { + InMemoryCallStore 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 }, + 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 + // 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. + await Assert.ThrowsAsync( + () => resumed.RunTurnAsync("still there?", TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task ASecondSessionOfOneCall_FallsBackWhenTheStageIsGone() + { + InMemoryCallStore 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" }, + TestContext.Current.CancellationToken); + + using ScriptedChatClient reply = new("sure"); + RecordingObserver observer = new(); + var resumed = CreateSession(StagedYaml, reply, store, "C-nostage", observer); + + 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 + // 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); + Assert.Contains( + "a-stage-nobody-declares", dropped.Payload[CallEventPayloadKeys.Reason], StringComparison.Ordinal); + } + + [Fact] + public async Task ACallWithNoStoredState_StartsWhereTheDocumentSays() + { + InMemoryCallStore store = new(); + + using ScriptedChatClient reply = new("what model is it?"); + var session = CreateSession(StagedYaml, reply, store); + + await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); + + Assert.NotNull(session.LastTurn); + Assert.Equal("intake", session.LastTurn!.StageBefore); + } +} diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs index 6683ccad..184eeecb 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionStoreFailureTests.cs @@ -77,6 +77,30 @@ public async Task Append_StoreThrows_CallContinues() reply.Requests[1]); } + /// + /// A turn that cannot re-read store 1 as it opens says so, and runs on the words it holds. + /// + [Fact] + 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); + _ = await session.RunTurnAsync("hello", TestContext.Current.CancellationToken); + + // Act + var second = await session.RunTurnAsync("order 41?", TestContext.Current.CancellationToken); + + // Assert + Assert.Equal("it ships Friday", second.ReplyText); + var failed = Assert.Single( + observer.Events, + callEvent => callEvent.Kind == CallEventKind.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 /// logged and stored nowhere. diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index d3ae4360..5459f036 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -1327,8 +1327,9 @@ public IReadOnlyList Roles } } - public override ValueTask AppendAsync( - IReadOnlyList messages, + public override ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? state = null, CancellationToken cancellationToken = default) { @@ -1337,11 +1338,13 @@ public override ValueTask AppendAsync( _roles.AddRange(messages.Select(message => message.Content.Role.Value)); } - return ValueTask.CompletedTask; + IReadOnlyList rows = [.. messages.Select( + (message, index) => new CallMessage(callId, index, message.TurnIndex ?? 0, message.Content, message.MessageId))]; + return ValueTask.FromResult(rows); } public override ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) => ValueTask.CompletedTask; public override ValueTask> ReadAsync( diff --git a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs index 93375587..a939abbb 100644 --- a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkAdapterTests.cs @@ -59,7 +59,7 @@ public async Task OpenAsync_UnmigratedDatabase_AppliesTheSchema() await using var sink = (PostgresAuditSink)await adapter.OpenAsync(Entry, secrets, Token); // Assert - Assert.True(await ScalarAsync("SELECT to_regclass('audit_event') IS NOT NULL")); + Assert.True(await ScalarAsync("SELECT to_regclass('agentcore.audit_event') IS NOT NULL")); } [PostgresFact] @@ -81,7 +81,7 @@ await sink.AppendAsync( Token); // Assert - Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } private MapSecretResolver Resolver() => diff --git a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs index 4fffae02..15575229 100644 --- a/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Audit/Postgres/PostgresAuditSinkTests.cs @@ -28,7 +28,7 @@ public async Task AppendAsync_OneEvent_WritesOneRow() await sink.AppendAsync(Started("C1"), Token); // Assert - Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } [PostgresFact] @@ -57,7 +57,7 @@ public async Task AppendAsync_EventWithNoTurnOrAmendment_StoresBothAsNull() await sink.AppendAsync(Started("C1"), Token); // Assert - var nulls = await ScalarAsync("SELECT turn_index IS NULL AND amends_event_id IS NULL FROM audit_event"); + var nulls = await ScalarAsync("SELECT turn_index IS NULL AND amends_event_id IS NULL FROM agentcore.audit_event"); Assert.True(nulls); } @@ -71,7 +71,7 @@ public async Task AppendAsync_EventWithPayload_StoresItAsAJsonObject() await sink.AppendAsync(TurnCompleted("C1", 0), Token); // Assert - var reply = await ScalarAsync($"SELECT payload ->> '{AuditPayloadKeys.ReplyTextSha256}' FROM audit_event"); + var reply = await ScalarAsync($"SELECT payload ->> '{AuditPayloadKeys.ReplyTextSha256}' FROM agentcore.audit_event"); Assert.Equal(AuditHash.OfText("the belt ships Friday").Value, reply); } @@ -88,7 +88,7 @@ public async Task AppendManyAsync_RunHoldingAMalformedEvent_WritesNoneOfIt() await Assert.ThrowsAsync(() => sink.AppendManyAsync(run, Token).AsTask()); // Assert - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } [PostgresFact] @@ -115,7 +115,7 @@ public async Task AppendAsync_ConcurrentWritersOnSeparateCalls_WriteEveryRow() await Task.WhenAll(writers); // Assert - Assert.Equal(20L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(20L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } [PostgresFact] @@ -298,7 +298,7 @@ private async Task> ReadSequencesAsync() List sequences = []; await using NpgsqlCommand command = DataSource.CreateCommand( - "SELECT sequence FROM audit_event ORDER BY write_position"); + "SELECT sequence FROM agentcore.audit_event ORDER BY write_position"); await using var reader = await command.ExecuteReaderAsync(Token); while (await reader.ReadAsync(Token)) @@ -312,7 +312,7 @@ private async Task> ReadSequencesAsync() private async Task SequencesOfAsync(string callId) { await using var command = DataSource.CreateCommand( - "SELECT sequence FROM audit_event WHERE call_id = $1 ORDER BY sequence"); + "SELECT sequence FROM agentcore.audit_event WHERE call_id = $1 ORDER BY sequence"); command.Parameters.Add(new NpgsqlParameter { Value = callId }); List sequences = []; @@ -329,7 +329,7 @@ private async Task SequencesOfAsync(string callId) private async Task KindsOfAsync(string callId) { await using var command = DataSource.CreateCommand( - "SELECT kind FROM audit_event WHERE call_id = $1 ORDER BY sequence"); + "SELECT kind FROM agentcore.audit_event WHERE call_id = $1 ORDER BY sequence"); command.Parameters.Add(new NpgsqlParameter { Value = callId }); List kinds = []; diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs index 748caa60..e51f0e4e 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/CallThreadSchemaTests.cs @@ -25,7 +25,7 @@ public async Task Migration_Applied_MakesBothTables() var tables = await ScalarAsync( """ SELECT count(*) FROM information_schema.tables - WHERE table_schema = current_schema() AND table_name IN ('call', 'call_principal') + WHERE table_schema = 'agentcore' AND table_name IN ('call', 'call_principal') """); // Assert @@ -37,7 +37,7 @@ public async Task Call_AStatusOutsideTheTwo_IsRefused() { // Act var refusal = await Record.ExceptionAsync( - () => ExecuteAsync("INSERT INTO call (call_id, status) VALUES ('c1', 'nonsense')")); + () => ExecuteAsync("INSERT INTO agentcore.call (call_id, status) VALUES ('c1', 'nonsense')")); // Assert Assert.Equal("23514", Assert.IsType(refusal).SqlState); @@ -47,26 +47,26 @@ public async Task Call_AStatusOutsideTheTwo_IsRefused() public async Task CallPrincipal_ItsCallDeleted_GoesWithIt() { // Arrange - await ExecuteAsync("INSERT INTO call (call_id) VALUES ('c1')"); - await ExecuteAsync("INSERT INTO call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'caller')"); + 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')"); // Act - await ExecuteAsync("DELETE FROM call WHERE call_id = 'c1'"); + await ExecuteAsync("DELETE FROM agentcore.call WHERE call_id = 'c1'"); // Assert - Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM call_principal")); + Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); } [PostgresFact] public async Task CallPrincipal_TheSamePairTwice_IsRefusedByThePrimaryKey() { // Arrange - await ExecuteAsync("INSERT INTO call (call_id) VALUES ('c1')"); - await ExecuteAsync("INSERT INTO call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'caller')"); + 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')"); // Act var refusal = await Record.ExceptionAsync( - () => ExecuteAsync("INSERT INTO call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'agent')")); + () => ExecuteAsync("INSERT INTO agentcore.call_principal (call_id, principal_key, role) VALUES ('c1', 'p1', 'agent')")); // Assert Assert.Equal("23505", Assert.IsType(refusal).SqlState); @@ -82,7 +82,7 @@ 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 = 'call_principal'::regclass AND i.indisprimary + WHERE i.indrelid = 'agentcore.call_principal'::regclass AND i.indisprimary """); // Assert @@ -96,7 +96,7 @@ public async Task CallPrincipal_TheOtherDirection_HasItsOwnIndex() var indexes = await ScalarAsync( """ SELECT count(*) FROM pg_indexes - WHERE schemaname = current_schema() + WHERE schemaname = 'agentcore' AND tablename = 'call_principal' AND indexname = 'call_principal_call_idx' """); @@ -106,14 +106,14 @@ SELECT count(*) FROM pg_indexes } [PostgresTheory] - [InlineData("call", "SELECT")] - [InlineData("call", "INSERT")] - [InlineData("call", "UPDATE")] - [InlineData("call", "DELETE")] - [InlineData("call_principal", "SELECT")] - [InlineData("call_principal", "INSERT")] - [InlineData("call_principal", "UPDATE")] - [InlineData("call_principal", "DELETE")] + [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")] 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/Calls/Postgres/PostgresCallListTests.cs index 7e729e7e..57d216a0 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallListTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallListTests.cs @@ -161,7 +161,7 @@ public async Task ListAsync_CallsSharingOneTimestamp_AreStillPagedWithoutLoss() await Claim(store, $"c{i}", "person-a"); } - await ExecuteAsync("UPDATE call SET created_at = timestamptz '2026-01-01 00:00:00+00'"); + await ExecuteAsync("UPDATE agentcore.call SET created_at = timestamptz '2026-01-01 00:00:00+00'"); // Act List seen = []; @@ -220,7 +220,7 @@ private static async Task Claim(PostgresCallStore store, string callId, string p private Task Spoke(string callId, string ago) => ExecuteAsync( $$""" - INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) + 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}}') """); } diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs index c6627656..14c9638a 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallPrincipalTests.cs @@ -21,7 +21,7 @@ public async Task AttachPrincipalAsync_AKey_WritesOneRow() await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); // Assert - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM call_principal")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); } [PostgresFact] @@ -38,7 +38,7 @@ public async Task AttachPrincipalAsync_TheSamePairTwice_IsNotAThrowAndStaysOneRo // Assert Assert.Null(thrown); - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM call_principal")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); } [PostgresFact] @@ -48,13 +48,13 @@ public async Task AttachPrincipalAsync_TheSamePairTwice_KeepsTheFirstAttachedAt( PostgresCallStore store = new(DataSource); await store.CreateAsync("c1", Token); await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); - var first = await ScalarAsync("SELECT attached_at FROM call_principal"); + var first = await ScalarAsync("SELECT attached_at FROM agentcore.call_principal"); // Act await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); // Assert - Assert.Equal(first, await ScalarAsync("SELECT attached_at FROM call_principal")); + Assert.Equal(first, await ScalarAsync("SELECT attached_at FROM agentcore.call_principal")); } [PostgresFact] @@ -69,7 +69,7 @@ public async Task AttachPrincipalAsync_TwoKeysOnOneCall_BothStay() await store.AttachPrincipalAsync("c1", "person-a", "caller", Token); // Assert - Assert.Equal(2, await ScalarAsync("SELECT count(*) FROM call_principal")); + Assert.Equal(2, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); } [PostgresFact] @@ -85,7 +85,7 @@ public async Task DetachPrincipalAsync_OneOfTwoKeys_LeavesTheOther() await store.DetachPrincipalAsync("c1", "person-a", Token); // Assert - Assert.Equal("tenant-a", await ScalarAsync("SELECT principal_key FROM call_principal")); + Assert.Equal("tenant-a", await ScalarAsync("SELECT principal_key FROM agentcore.call_principal")); } [PostgresFact] diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs new file mode 100644 index 00000000..34573360 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreAppendTests.cs @@ -0,0 +1,214 @@ +using System.Text.RegularExpressions; +using AgentCore.Application.Calls; +using AgentCore.Application.Ports; +using AgentCore.Application.Transcript; +using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Tests.Database.Postgres; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Calls.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 +/// live session. +/// +#pragma warning disable CA1859 // store is typed as ICallStore throughout: AppendAsync(callId, message, ct) + // is a default interface method, and only resolves through the interface type. +public sealed partial class PostgresCallStoreAppendTests : PostgresDatabaseTest +{ + /// + protected override bool Migrated => true; + + [PostgresFact] + public async Task AppendAsync_OneMessage_OnAFreshCall_IsOrdinalZeroAndTurnZero() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + await store.CreateAsync("c1", Token); + + // Act + var row = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "hello"), Token); + + // Assert + Assert.Equal(0, row.Ordinal); + Assert.Equal(0, row.TurnIndex); + Assert.Matches(HexId(), row.MessageId); + } + + [PostgresFact] + public async Task AppendAsync_OneMessage_WithItsOwnId_KeepsIt() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + await store.CreateAsync("c1", Token); + ChatMessage message = new(ChatRole.User, "hello") { MessageId = "caller-named" }; + + // Act + var row = await store.AppendMessageAsync("c1", message, Token); + + // Assert + Assert.Equal("caller-named", row.MessageId); + } + + [PostgresFact] + public async Task AppendAsync_TwoOutsideAppends_AreNumberedZeroThenOne() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + await store.CreateAsync("c1", Token); + + // Act + var first = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "one"), Token); + var second = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "two"), Token); + + // Assert + Assert.Equal(0, first.Ordinal); + Assert.Equal(1, second.Ordinal); + var call = await store.GetAsync("c1", Token); + Assert.Equal(2, call?.NextOrdinal); + } + + [PostgresFact] + public async Task AppendAsync_ABatchWithAnExplicitTurnIndex_NumbersThreeConsecutiveRowsInDraftOrder() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + await store.CreateAsync("c1", Token); + await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "outside"), Token); + + CallMessageDraft[] drafts = + [ + new(4, new ChatMessage(ChatRole.User, "a"), "m-a"), + new(4, new ChatMessage(ChatRole.Assistant, "b"), "m-b"), + new(4, new ChatMessage(ChatRole.User, "c"), "m-c"), + ]; + + // Act + var rows = await store.AppendAsync("c1", drafts, cancellationToken: Token); + + // Assert + Assert.Equal([1, 2, 3], rows.Select(row => row.Ordinal)); + Assert.All(rows, row => Assert.Equal(4, row.TurnIndex)); + Assert.Equal(["m-a", "m-b", "m-c"], rows.Select(row => row.MessageId)); + } + + [PostgresFact] + public async Task AppendAsync_OutsideAppend_AfterABatchThatWroteState_IsStampedWithTheStoredNextTurnIndex() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + await store.CreateAsync("c1", Token); + await store.AppendAsync( + "c1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], + new CallSessionState { NextTurnIndex = 7 }, + Token); + + // Act + var row = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "outside"), Token); + + // Assert + Assert.Equal(7, row.TurnIndex); + } + + [PostgresFact] + public async Task AppendAsync_TwoWritersFiftyEach_LandsOneHundredRowsWithNoCollision() + { + // 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); + await store.CreateAsync("c1", Token); + + async Task WriteFiftyAsync(string label) + { + for (var i = 0; i < 50; i++) + { + await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, $"{label}-{i}"), Token); + } + } + + // Act + await Task.WhenAll(WriteFiftyAsync("a"), WriteFiftyAsync("b")); + + // Assert + var rows = await store.ReadAsync("c1", Token); + Assert.Equal(100, rows.Count); + Assert.Equal(Enumerable.Range(0, 100), rows.Select(row => row.Ordinal).Order()); + } + + [PostgresFact] + public async Task AppendAsync_ACallThatDoesNotExist_ThrowsNamingIt() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + + // Act + var failure = await Record.ExceptionAsync( + () => store.AppendMessageAsync("missing", new ChatMessage(ChatRole.User, "hello"), Token).AsTask()); + + // Assert + var invalid = Assert.IsType(failure); + Assert.Contains("missing", invalid.Message, StringComparison.Ordinal); + } + + [PostgresFact] + public async Task RewriteAsync_OneRow_ChangesOnlyThatRowsContent() + { + // Arrange + ICallStore store = new PostgresCallStore(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); + + // Act + await store.RewriteAsync("c1", "m0", new ChatMessage(ChatRole.User, "corrected"), Token); + + // Assert + var rows = await store.ReadAsync("c1", Token); + Assert.Equal(["corrected", "second"], rows.Select(row => row.Content.Text)); + } + + [PostgresFact] + public async Task AppendAsync_AfterATruncate_NeverReusesTheOrdinalsItTook() + { + // Arrange + ICallStore store = new PostgresCallStore(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); + await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "two"), Token); + await store.TruncateAsync("c1", 1, Token); + + // Act + var row = await store.AppendMessageAsync("c1", new ChatMessage(ChatRole.User, "three"), Token); + + // Assert + Assert.Equal(3, row.Ordinal); + } + + [PostgresFact] + public async Task ReadAsync_ARowWithAdditionalProperties_KeepsThemAcrossTheRoundTrip() + { + // Arrange + ICallStore store = new PostgresCallStore(DataSource); + await store.CreateAsync("c1", Token); + ChatMessage message = new(ChatRole.User, "hello") + { + AdditionalProperties = new() { ["speaker"] = "human" }, + }; + + // Act + await store.AppendMessageAsync("c1", message, Token); + + // Assert + var rows = await store.ReadAsync("c1", Token); + Assert.Equal("human", Assert.Single(rows).Content.AdditionalProperties?["speaker"]?.ToString()); + } + + [GeneratedRegex("^[0-9a-f]{32}$")] + private static partial Regex HexId(); +} +#pragma warning restore CA1859 diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs index cefb7db3..f86c52a3 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreSweepTests.cs @@ -16,8 +16,8 @@ public sealed class PostgresCallStoreSweepTests : PostgresDatabaseTest /// protected override bool Migrated => true; - private static CallMessage Word(string callId) => - new(callId, 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0"); + private static CallMessageDraft Word() => + new(0, new ChatMessage(ChatRole.User, "hello"), "m0"); [PostgresFact] public async Task SweepAsync_ACallWhoseLastMessageIsOld_TakesTheCallAndItsWords() @@ -25,16 +25,16 @@ public async Task SweepAsync_ACallWhoseLastMessageIsOld_TakesTheCallAndItsWords( // Arrange PostgresCallStore store = new(DataSource); await store.CreateAsync("old", Token); - await store.AppendAsync([Word("old")], cancellationToken: Token); - await ExecuteAsync("UPDATE call_message SET updated_at = now() - interval '90 days'"); + await store.AppendAsync("old", [Word()], cancellationToken: Token); + await ExecuteAsync("UPDATE agentcore.call_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 call")); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM call_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); } [PostgresFact] @@ -43,14 +43,14 @@ public async Task SweepAsync_ACallWithNoWordsAtAll_TakesItOnCreatedAt() // Arrange PostgresCallStore store = new(DataSource); await store.CreateAsync("empty", Token); - await ExecuteAsync("UPDATE call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.call 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 call")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); } /// @@ -63,15 +63,15 @@ public async Task SweepAsync_ACallSpokenOnInsideTheWindow_LeavesIt() // Arrange PostgresCallStore store = new(DataSource); await store.CreateAsync("fresh", Token); - await store.AppendAsync([Word("fresh")], cancellationToken: Token); - await ExecuteAsync("UPDATE call SET created_at = now() - interval '90 days'"); + await store.AppendAsync("fresh", [Word()], cancellationToken: Token); + await ExecuteAsync("UPDATE agentcore.call 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 call")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); } [PostgresFact] @@ -80,10 +80,10 @@ public async Task SweepAsync_ASweptCall_LeavesItsAuditEvents() // Arrange PostgresCallStore store = new(DataSource); await store.CreateAsync("old", Token); - await ExecuteAsync("UPDATE call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.call SET created_at = now() - interval '90 days'"); await ExecuteAsync( """ - INSERT INTO audit_event (call_id, event_id, sequence, kind, occurred_at) + INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) VALUES ('old', gen_random_uuid(), 0, 'call.started', now()) """); @@ -91,7 +91,7 @@ INSERT INTO audit_event (call_id, event_id, sequence, kind, occurred_at) await store.SweepAsync(Window, cancellationToken: Token); // Assert - Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } [PostgresFact] @@ -104,14 +104,14 @@ public async Task SweepAsync_MoreExpiredCallsThanOneBatch_LoopsUntilNoneAreLeft( await store.CreateAsync($"c{i}", Token); } - await ExecuteAsync("UPDATE call SET created_at = now() - interval '90 days'"); + await ExecuteAsync("UPDATE agentcore.call 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 call")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call")); } [PostgresFact] @@ -120,14 +120,14 @@ public async Task EraseAsync_ACallsWords_LeavesTheCallItselfListed() // Arrange PostgresCallStore store = new(DataSource); await store.CreateAsync("c1", Token); - await store.AppendAsync([Word("c1")], cancellationToken: Token); + await store.AppendAsync("c1", [Word()], cancellationToken: Token); // Act var erased = await store.EraseAsync("c1", Token); // 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 call_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); Assert.NotNull(await store.GetAsync("c1", Token)); } } diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs index 45638850..6cf19dc8 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTests.cs @@ -26,7 +26,7 @@ public async Task CreateAsync_ANewCall_WritesOneRow() Assert.Equal("c1", call.CallId); Assert.Null(call.Title); Assert.Equal(CallStatus.Regular, call.Status); - Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM call")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call")); } [PostgresFact] @@ -43,7 +43,7 @@ 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 call")); + Assert.Equal(1, await ScalarAsync("SELECT count(*) FROM agentcore.call")); } [PostgresFact] @@ -81,7 +81,7 @@ public async Task GetAsync_ACallWithMessages_ReportsTheNewestMessageTime() await store.CreateAsync("c1", Token); await ExecuteAsync( """ - INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) + INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id, created_at, updated_at) VALUES ('c1', 1, 0, 'user', '{}'::jsonb, 'm1', now(), now() + interval '1 hour') """); @@ -195,8 +195,8 @@ public async Task DeleteAsync_ACall_LeavesNoRowAndNoClaim() await store.DeleteAsync("c1", Token); // Assert - Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM call")); - Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM call_principal")); + Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.call")); + Assert.Equal(0, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); } [PostgresFact] diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs index 7bcc1225..d3af79fd 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreTruncateTests.cs @@ -29,11 +29,12 @@ public async Task Truncate_TakesTheNamedOrdinalAndEverythingAfterIt() { var store = await OpenAsync(); await store.AppendAsync( + "C1", [ - new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "q1"), "m0"), - new CallMessage("C1", 1, 0, new ChatMessage(ChatRole.Assistant, "a1"), "m1"), - new CallMessage("C1", 2, 1, new ChatMessage(ChatRole.User, "q2"), "m2"), - new CallMessage("C1", 3, 1, new ChatMessage(ChatRole.Assistant, "a2"), "m3"), + 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"), ], state: null, Token); @@ -53,17 +54,19 @@ public async Task Truncate_LeavesTheNextAppendFreeToClimbPastTheGap() // the gap, and reissuing a number would put two turns in one place in the chain. var store = await OpenAsync(); await store.AppendAsync( + "C1", [ - new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "q1"), "m0"), - new CallMessage("C1", 1, 0, new ChatMessage(ChatRole.Assistant, "a1"), "m1"), - new CallMessage("C1", 2, 1, new ChatMessage(ChatRole.User, "q2"), "m2"), + 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"), ], state: null, Token); await store.TruncateAsync("C1", 2, Token); await store.AppendAsync( - [new CallMessage("C1", 3, 2, new ChatMessage(ChatRole.User, "q2 again"), "m3")], + "C1", + [new CallMessageDraft(2, new ChatMessage(ChatRole.User, "q2 again"), "m3")], state: null, Token); @@ -77,7 +80,8 @@ public async Task AMessageName_RoundTripsAndIsUniqueWithinTheCall() { var store = await OpenAsync(); await store.AppendAsync( - [new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "q1"), "m0")], + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0")], state: null, Token); @@ -85,7 +89,8 @@ await store.AppendAsync( var clash = await Record.ExceptionAsync( () => store.AppendAsync( - [new CallMessage("C1", 1, 0, new ChatMessage(ChatRole.User, "q2"), "m0")], + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q2"), "m0")], state: null, Token).AsTask()); @@ -99,15 +104,16 @@ public async Task Truncate_LeavesTheStateAndTheCallRowAlone() // state are what stop the next turn standing where a deleted row stood. var store = await OpenAsync(); await store.AppendAsync( - [new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "q1"), "m0")], - new CallSessionState { Stage = "collecting", NextOrdinal = 1, NextTurnIndex = 1 }, + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "q1"), "m0")], + new CallSessionState { Stage = "collecting", NextTurnIndex = 1 }, Token); await store.TruncateAsync("C1", 0, Token); var record = await store.GetAsync("C1", Token); Assert.Equal("collecting", record?.State?.Stage); - Assert.Equal(1, record?.State?.NextOrdinal); + Assert.Equal(1, record?.NextOrdinal); Assert.Equal(1, record?.State?.NextTurnIndex); Assert.Empty(await store.ReadAsync("C1", Token)); } diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs index e5ec08ef..da6b3f5e 100644 --- a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/PostgresCallStoreWordsTests.cs @@ -41,10 +41,10 @@ public async Task AppendAsync_ATurn_WritesOneRowForEachMessage() var store = await OpenAsync(); // Act - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // Assert - Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM call_message")); + Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); } [PostgresFact] @@ -54,12 +54,12 @@ public async Task AppendAsync_ATurn_LiftsTheRoleOutOfTheContent() var store = await OpenAsync(); // Act - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // 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 call_message")); + await ScalarAsync("SELECT string_agg(role, ',' ORDER BY ordinal) FROM agentcore.call_message")); } [PostgresFact] @@ -75,9 +75,10 @@ public async Task AppendAsync_AToolCallingTurn_RoundTripsEveryContentPart() // Act await store.AppendAsync( + "C1", [ - new CallMessage("C1", 0, 0, announced, "m0"), - new CallMessage("C1", 1, 0, result, "m1"), + new CallMessageDraft(0, announced, "m0"), + new CallMessageDraft(0, result, "m1"), ], cancellationToken: Token); @@ -99,26 +100,10 @@ public async Task AppendAsync_NoMessages_TouchesNothing() var store = await OpenAsync(); // Act - await store.AppendAsync([], cancellationToken: Token); + await store.AppendAsync("C1", [], cancellationToken: Token); // Assert - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM call_message")); - } - - [PostgresFact] - public async Task AppendAsync_AnOrdinalTheCallAlreadyUsed_IsRefused() - { - // Arrange — an ordinal is permanent, so a repeat is a defect and never a silent overwrite. - // AgentCoreChatHistoryProvider is what catches this and lets the call continue. - var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); - - // Act - var failure = await Record.ExceptionAsync( - () => store.AppendAsync(Turn("C1", turnIndex: 1, ordinal: 0), cancellationToken: Token).AsTask()); - - // Assert - Assert.NotNull(failure); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); } [PostgresFact] @@ -136,7 +121,8 @@ public async Task ItWritesTheStateBesideTheWords() }; await store.AppendAsync( - [new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], state, Token); @@ -163,11 +149,13 @@ public async Task AnAppendWithNoStateLeavesTheStoredStateAlone() var store = await OpenAsync(); await store.AppendAsync( - [new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], new CallSessionState { Stage = "collecting" }, Token); await store.AppendAsync( - [new CallMessage("C1", 1, 0, new ChatMessage(ChatRole.Assistant, "hi"), "m1")], + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.Assistant, "hi"), "m1")], state: null, Token); @@ -187,25 +175,28 @@ public async Task AnAppendThatFails_LandsNeitherTheWordsNorTheState() // is worth a test that fails the day a version of Npgsql splits the batch. var store = await OpenAsync(); await store.AppendAsync( - [new CallMessage("C1", 0, 0, new ChatMessage(ChatRole.User, "hello"), "m0")], + "C1", + [new CallMessageDraft(0, new ChatMessage(ChatRole.User, "hello"), "m0")], new CallSessionState { Stage = "a" }, Token); - // Act — a batch whose FIRST row is fine and whose second repeats ordinal 0. Ordinal 2 has to - // succeed and then be taken back for the implicit transaction to have shown itself; failing - // the only row would prove nothing, because every command behind it never runs. + // Act — a batch whose FIRST row is new and whose second repeats a message id the call + // 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, + // and "m2" landing would be what a batch that was never one transaction looks like. var failure = await Record.ExceptionAsync( () => store.AppendAsync( + "C1", [ - new CallMessage("C1", 2, 1, new ChatMessage(ChatRole.User, "lands first"), "m2"), - new CallMessage("C1", 0, 1, new ChatMessage(ChatRole.User, "again"), "m0-again"), + new CallMessageDraft(1, new ChatMessage(ChatRole.User, "lands first"), "m2"), + new CallMessageDraft(1, new ChatMessage(ChatRole.User, "again"), "m0"), ], new CallSessionState { 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 - // moved on without its words; a surviving ordinal 2 would be a batch that was never one + // moved on without its words; a surviving "m2" would be a batch that was never one // transaction. Assert.NotNull(failure); var record = await store.GetAsync("C1", Token); @@ -213,7 +204,7 @@ await store.AppendAsync( var rows = await store.ReadAsync("C1", Token); Assert.Single(rows); - Assert.Equal(0, rows[0].Ordinal); + Assert.Equal("m0", rows[0].MessageId); } [PostgresFact] @@ -223,7 +214,7 @@ public async Task AStateBlobThatWillNotParse_ReadsAsNoBlobRatherThanClosingTheCa // 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 call SET state = '[1, 2, 3]'::jsonb WHERE call_id = 'C1'"); + await ExecuteAsync("UPDATE agentcore.call SET state = '[1, 2, 3]'::jsonb WHERE call_id = 'C1'"); // Act var record = await store.GetAsync("C1", Token); @@ -243,8 +234,8 @@ public async Task ReadAsync_AWrittenCall_ReturnsEveryRowInOrdinalOrder() { // Arrange var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); - await store.AppendAsync(Turn("C1", turnIndex: 1, ordinal: 2), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 1, idSeed: 2), cancellationToken: Token); // Act var rows = await store.ReadAsync("C1", Token); @@ -253,27 +244,12 @@ public async Task ReadAsync_AWrittenCall_ReturnsEveryRowInOrdinalOrder() Assert.Equal([0, 1, 2, 3], rows.Select(row => row.Ordinal).ToArray()); } - [PostgresFact] - public async Task ReadAsync_AWrittenCall_ReturnsTheOrdinalsAResumeGoesOnFrom() - { - // Arrange — a read that answered with the messages alone would restart ordinals at zero and - // collide with the rows already there, on a primary key the provider never sees. - var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 3, ordinal: 6), cancellationToken: Token); - - // Act - var rows = await store.ReadAsync("C1", Token); - - // Assert - Assert.Equal([(6, 3), (7, 3)], rows.Select(row => (row.Ordinal, row.TurnIndex)).ToArray()); - } - [PostgresFact] public async Task ReadAsync_AnotherCall_ReturnsNothing() { // Arrange var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // Act var rows = await store.ReadAsync("C2", Token); @@ -290,10 +266,10 @@ public async Task RewriteAsync_ARow_ReplacesTheWordsOfThatRowOnly() { // Arrange var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // Act - await store.RewriteAsync("C1", 1, new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); + await store.RewriteAsync("C1", "m1", new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); // Assert var rows = await store.ReadAsync("C1", Token); @@ -306,30 +282,30 @@ public async Task RewriteAsync_ARow_MovesUpdatedAtAndLeavesCreatedAt() // Arrange — the retention sweep reads updated_at, so a corrected turn ages from its // correction. var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); - await ExecuteAsync("UPDATE call_message SET created_at = now() - interval '1 hour', updated_at = created_at"); + 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"); // Act - await store.RewriteAsync("C1", 1, new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); + await store.RewriteAsync("C1", "m1", new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); // Assert Assert.True(await ScalarAsync( - "SELECT updated_at > created_at FROM call_message WHERE call_id = 'C1' AND ordinal = 1")); + "SELECT updated_at > created_at FROM agentcore.call_message WHERE call_id = 'C1' AND message_id = 'm1'")); } [PostgresFact] - public async Task RewriteAsync_AnOrdinalThatIsNotThere_WritesNothing() + public async Task RewriteAsync_AMessageIdThatIsNotThere_WritesNothing() { // Arrange — a barge-in that raced the append it corrects. The append carries the corrected // words, so there is nothing to report and nothing to guess at. var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // Act - await store.RewriteAsync("C1", 9, new ChatMessage(ChatRole.Assistant, "never spoken"), Token); + await store.RewriteAsync("C1", "does-not-exist", new ChatMessage(ChatRole.Assistant, "never spoken"), Token); // Assert - Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM call_message")); + Assert.Equal(2L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); } // --------------------------------------------------------------------------------------------- @@ -340,8 +316,8 @@ public async Task EraseAsync_OneCall_DeletesItsRowsAndLeavesTheOthers() { // Arrange var store = await OpenAsync(); - await store.AppendAsync(Turn("C1", turnIndex: 0, ordinal: 0), cancellationToken: Token); - await store.AppendAsync(Turn("C2", turnIndex: 0, ordinal: 0), cancellationToken: Token); + await store.AppendAsync("C1", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); + await store.AppendAsync("C2", Turn(turnIndex: 0, idSeed: 0), cancellationToken: Token); // Act var erased = await store.EraseAsync("C1", Token); @@ -421,7 +397,7 @@ public async Task ReadSpokenTurnsAsync_ATurnWhoseWordsWereErased_ReturnsNoRowFor // Assert Assert.Empty(turns); - Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } [PostgresFact] @@ -431,7 +407,7 @@ public async Task ReadSpokenTurnsAsync_ATurnAmendedInTheChain_ReturnsOneRowHoldi // Without the guard on the chain side the join multiplies and one turn answers twice. var store = await OpenAsync(); var firstEventId = await WriteToolCallingTurnAsync(store, "C1", turnIndex: 0, spoken: "Order 41 ships Friday."); - await store.RewriteAsync("C1", 3, new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); + await store.RewriteAsync("C1", "m3", new ChatMessage(ChatRole.Assistant, "Order 41 sh"), Token); await AmendTurnAsync("C1", turnIndex: 0, amends: firstEventId, spoken: "Order 41 sh"); // Act @@ -442,11 +418,15 @@ public async Task ReadSpokenTurnsAsync_ATurnAmendedInTheChain_ReturnsOneRowHoldi Assert.Equal(AuditHash.OfText("Order 41 sh").Value, turn.ReplyTextSha256); } - /// One ordinary turn: what the caller said, and what the caller heard. - private static CallMessage[] Turn(string callId, int turnIndex, int ordinal) => + /// + /// 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 + /// ordinal, so it no longer says where the turn lands. + /// + private static CallMessageDraft[] Turn(int turnIndex, int idSeed) => [ - new CallMessage(callId, ordinal, turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), $"m{ordinal}"), - new CallMessage(callId, ordinal + 1, turnIndex, new ChatMessage(ChatRole.Assistant, "Order 41 ships Friday."), $"m{ordinal + 1}"), + 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}"), ]; /// Writes a tool-calling turn to store 1 and its turn.completed row to store 3. @@ -465,12 +445,13 @@ private async Task WriteToolCallingTurnAsync( } await store.AppendAsync( + callId, [ - new CallMessage(callId, 0, turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), "m0"), - new CallMessage(callId, 1, turnIndex, new ChatMessage( + new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.User, "what about order 41"), "m0"), + new CallMessageDraft(turnIndex, new ChatMessage( ChatRole.Assistant, [new FunctionCallContent("id1", "lookup", null)]), "m1"), - new CallMessage(callId, 2, turnIndex, new ChatMessage(ChatRole.Tool, toolResultContents), "m2"), - new CallMessage(callId, 3, turnIndex, new ChatMessage(ChatRole.Assistant, spoken), "m3"), + new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.Tool, toolResultContents), "m2"), + new CallMessageDraft(turnIndex, new ChatMessage(ChatRole.Assistant, spoken), "m3"), ], cancellationToken: Token); @@ -519,5 +500,5 @@ await chain.AppendAsync( /// 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 call_message SET updated_at = now() - interval '{age.TotalDays} days' WHERE call_id = '{callId}'"); + $"UPDATE agentcore.call_message SET updated_at = now() - interval '{age.TotalDays} days' WHERE call_id = '{callId}'"); } diff --git a/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs b/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs index e13959f1..380287a6 100644 --- a/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Database/Postgres/PostgresSchemaTests.cs @@ -13,10 +13,11 @@ public sealed class PostgresSchemaTests : PostgresDatabaseTest protected override bool Migrated => false; [PostgresTheory] - [InlineData("call")] - [InlineData("call_principal")] - [InlineData("call_message")] - [InlineData("audit_event")] + [InlineData("agentcore.call")] + [InlineData("agentcore.call_principal")] + [InlineData("agentcore.call_message")] + [InlineData("agentcore.audit_event")] + [InlineData("agentcore.schema_migration")] public async Task ApplyAsync_FreshDatabase_CreatesTheTable(string table) { // Arrange @@ -29,6 +30,24 @@ public async Task ApplyAsync_FreshDatabase_CreatesTheTable(string table) Assert.True(exists); } + [PostgresFact] + public async Task ApplyAsync_FreshDatabase_GivesCallANextOrdinalColumn() + { + // Arrange + await PostgresSchema.ApplyAsync(DataSource, Token); + + // Act + var column = await ScalarAsync( + """ + SELECT is_nullable || ',' || column_default + FROM information_schema.columns + WHERE table_schema = 'agentcore' AND table_name = 'call' AND column_name = 'next_ordinal' + """); + + // Assert + Assert.Equal("NO,0", column); + } + [PostgresFact] public async Task ApplyAsync_FreshDatabase_AppliesEveryMigration() { @@ -80,7 +99,7 @@ public async Task ApplyAsync_FreshDatabase_LeavesTheWriterInsertAndSelectOnly(st await PostgresSchema.ApplyAsync(DataSource, Token); // Act - var held = await ScalarAsync($"SELECT has_table_privilege('agentcore_writer', 'audit_event', '{privilege}')"); + var held = await ScalarAsync($"SELECT has_table_privilege('agentcore_writer', 'agentcore.audit_event', '{privilege}')"); // Assert Assert.Equal(expected, held); @@ -98,16 +117,16 @@ public async Task ApplyAsync_PublicHoldsGrantAll_StillLeavesTheWriterWithoutTheP await PostgresSchema.ApplyAsync(DataSource, Token); // Act - var held = await ScalarAsync($"SELECT has_table_privilege('agentcore_writer', 'audit_event', '{privilege}')"); + var held = await ScalarAsync($"SELECT has_table_privilege('agentcore_writer', 'agentcore.audit_event', '{privilege}')"); // Assert Assert.False(held); } [PostgresTheory] - [InlineData("UPDATE audit_event SET kind = 'tampered'")] - [InlineData("DELETE FROM audit_event")] - [InlineData("TRUNCATE audit_event")] + [InlineData("UPDATE agentcore.audit_event SET kind = 'tampered'")] + [InlineData("DELETE FROM agentcore.audit_event")] + [InlineData("TRUNCATE agentcore.audit_event")] public async Task AuditEvent_OwnerWritesOverAnExistingRow_IsRefusedByTrigger(string statement) { // Arrange @@ -130,7 +149,7 @@ public async Task AuditEvent_SuppliedWritePosition_IsRefused() // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( """ - INSERT INTO audit_event (write_position, call_id, event_id, sequence, kind, occurred_at) + 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()) """)); @@ -149,7 +168,7 @@ public async Task AuditEvent_SecondRowOnTheSameCallAndSequence_IsRefused() // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( """ - INSERT INTO audit_event (call_id, event_id, sequence, kind, occurred_at) + INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) VALUES ('C1', gen_random_uuid(), 1, 'call.ended', now()) """)); @@ -165,7 +184,7 @@ public async Task AuditEvent_SessionReplicationRoleIsReplica_BypassesEveryTrigge await PostgresSchema.ApplyAsync(DataSource, Token); await ExecuteAsync( """ - INSERT INTO audit_event (call_id, event_id, sequence, kind, occurred_at) + INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) VALUES ('C1', gen_random_uuid(), 0, 'call.started', now()) """); @@ -173,12 +192,12 @@ INSERT INTO audit_event (call_id, event_id, sequence, kind, occurred_at) await ExecuteAsync( """ SET session_replication_role = replica; - UPDATE audit_event SET kind = 'call.ended' WHERE sequence = 0; + UPDATE agentcore.audit_event SET kind = 'call.ended' WHERE sequence = 0; SET session_replication_role = origin; """); // Assert - Assert.Equal("call.ended", await ScalarAsync("SELECT kind FROM audit_event WHERE sequence = 0")); + Assert.Equal("call.ended", await ScalarAsync("SELECT kind FROM agentcore.audit_event WHERE sequence = 0")); } [PostgresFact] @@ -186,13 +205,13 @@ public async Task CallMessage_SecondMessageOnTheSameOrdinal_IsRefused() { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); - await ExecuteAsync("INSERT INTO call (call_id) VALUES ('C1')"); + await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('C1')"); await ExecuteAsync( - "INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); + "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( - "INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'assistant', '{}', 'm1')")); + "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'assistant', '{}', 'm1')")); // Assert Assert.Equal("23505", Assert.IsType(refusal).SqlState); @@ -207,11 +226,11 @@ public async Task CallMessage_WithNoCallRow_IsRefused() { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); - await ExecuteAsync("INSERT INTO call (call_id) VALUES ('present')"); + await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('present')"); // Act var refusal = await Record.ExceptionAsync(() => ExecuteAsync( - "INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('absent', 0, 0, 'user', '{}', 'm0')")); + "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('absent', 0, 0, 'user', '{}', 'm0')")); // Assert Assert.Equal("23503", Assert.IsType(refusal).SqlState); @@ -227,25 +246,25 @@ public async Task DeletingACall_TakesItsMessagesAndPrincipals_AndLeavesItsAuditE { // Arrange await PostgresSchema.ApplyAsync(DataSource, Token); - await ExecuteAsync("INSERT INTO call (call_id) VALUES ('C1')"); + await ExecuteAsync("INSERT INTO agentcore.call (call_id) VALUES ('C1')"); await ExecuteAsync( - "INSERT INTO call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); + "INSERT INTO agentcore.call_message (call_id, ordinal, turn_index, role, content, message_id) VALUES ('C1', 0, 0, 'user', '{}', 'm0')"); await ExecuteAsync( - "INSERT INTO call_principal (call_id, principal_key, role) VALUES ('C1', 'p1', 'owner')"); + "INSERT INTO agentcore.call_principal (call_id, principal_key, role) VALUES ('C1', 'p1', 'owner')"); await InsertOneEventAsync(); // Act - await ExecuteAsync("DELETE FROM call WHERE call_id = 'C1'"); + await ExecuteAsync("DELETE FROM agentcore.call WHERE call_id = 'C1'"); // Assert - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM call_message")); - Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM call_principal")); - Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM audit_event")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_message")); + Assert.Equal(0L, await ScalarAsync("SELECT count(*) FROM agentcore.call_principal")); + Assert.Equal(1L, await ScalarAsync("SELECT count(*) FROM agentcore.audit_event")); } private Task InsertOneEventAsync() => ExecuteAsync( """ - INSERT INTO audit_event (call_id, event_id, sequence, kind, occurred_at) + INSERT INTO agentcore.audit_event (call_id, event_id, sequence, kind, occurred_at) VALUES ('C1', gen_random_uuid(), 1, 'call.started', now()) """); diff --git a/tests/AgentCore.TestSupport/DelegatingCallStore.cs b/tests/AgentCore.TestSupport/DelegatingCallStore.cs index f1bbbf89..6d98a71f 100644 --- a/tests/AgentCore.TestSupport/DelegatingCallStore.cs +++ b/tests/AgentCore.TestSupport/DelegatingCallStore.cs @@ -59,16 +59,17 @@ public virtual ValueTask DeleteAsync(string callId, CancellationToken cancellati => Inner.DeleteAsync(callId, cancellationToken); /// - public virtual ValueTask AppendAsync( - IReadOnlyList messages, + public virtual ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? state = null, CancellationToken cancellationToken = default) - => Inner.AppendAsync(messages, state, cancellationToken); + => Inner.AppendAsync(callId, messages, state, cancellationToken); /// public virtual ValueTask RewriteAsync( - string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default) - => Inner.RewriteAsync(callId, ordinal, content, cancellationToken); + string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default) + => Inner.RewriteAsync(callId, messageId, content, cancellationToken); /// public virtual ValueTask> ReadAsync( diff --git a/tests/AgentCore.TestSupport/ParkingCallStore.cs b/tests/AgentCore.TestSupport/ParkingCallStore.cs index b839d095..81ac1da0 100644 --- a/tests/AgentCore.TestSupport/ParkingCallStore.cs +++ b/tests/AgentCore.TestSupport/ParkingCallStore.cs @@ -29,16 +29,15 @@ public sealed class ParkingCallStore() : DelegatingCallStore(new InMemoryCallSto public void Release() => _release.TrySetResult(); /// - public override async ValueTask AppendAsync( - IReadOnlyList messages, + public override async ValueTask> AppendAsync( + string callId, + IReadOnlyList messages, CallSessionState? state = null, CancellationToken cancellationToken = default) { _entered.TrySetResult(); await _release.Task.WaitAsync(cancellationToken); _landed = true; + return await base.AppendAsync(callId, messages, state, cancellationToken); } - - - } \ No newline at end of file From b34531fc85960f0b649e2e77fbda5f48acb37418 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 01:05:38 -0600 Subject: [PATCH 02/32] feat: Introduce ToolCallScope and enhance CallSession with call tracking --- .../PublicAPI.Unshipped.txt | 16 ++ .../Runtime/CallSession.cs | 1 + .../Runtime/ToolCallScopes.cs | 32 ++++ .../Runtime/TurnAmbients.cs | 7 + .../Tools/Binding/ToolBindingRegistry.cs | 4 +- .../Tools/Binding/TypedBindingTool.cs | 10 +- .../Tools/ToolCallScope.cs | 7 + .../DependencyInjection/AgentCoreOptions.cs | 5 +- .../Tools/ToolCallScopeTests.cs | 151 ++++++++++++++++++ .../Tools/TypedBindingToolTests.cs | 31 ++++ 10 files changed, 261 insertions(+), 3 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/ToolCallScopes.cs create mode 100644 src/AgentCore.Application/Tools/ToolCallScope.cs create mode 100644 tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index e33ca916..5f17d04f 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -1280,6 +1280,17 @@ AgentCore.Application.Tools.ToolCallNames AgentCore.Application.Tools.ToolCallNames.Called(Microsoft.Extensions.AI.FunctionCallContent! call) -> void AgentCore.Application.Tools.ToolCallNames.Of(Microsoft.Extensions.AI.FunctionResultContent! result) -> string? 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) -> 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) -> void +AgentCore.Application.Tools.ToolCallScope.TurnIndex.get -> int +AgentCore.Application.Tools.ToolCallScope.TurnIndex.init -> void AgentCore.Application.Tools.ToolErrorResult AgentCore.Application.Tools.ToolResultJson AgentCore.Application.Transcript.CallMessage @@ -1611,6 +1622,9 @@ override AgentCore.Application.Tools.Registry.ToolRegistration.ToString() -> str override AgentCore.Application.Tools.Registry.ToolSourceContext.Equals(object? obj) -> bool override AgentCore.Application.Tools.Registry.ToolSourceContext.GetHashCode() -> int override AgentCore.Application.Tools.Registry.ToolSourceContext.ToString() -> string! +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! @@ -1847,6 +1861,8 @@ static AgentCore.Application.Tools.Registry.ToolSourceContext.operator !=(AgentC static AgentCore.Application.Tools.Registry.ToolSourceContext.operator ==(AgentCore.Application.Tools.Registry.ToolSourceContext? left, AgentCore.Application.Tools.Registry.ToolSourceContext? right) -> bool static AgentCore.Application.Tools.Registry.ToolSourceError.Fail(string! message) -> AgentCore.Application.Configuration.Parsing.ConfigurationLoadException! static AgentCore.Application.Tools.ToolArgumentJson.ToJsonObject(System.Collections.Generic.IEnumerable>! arguments) -> System.Text.Json.Nodes.JsonObject! +static AgentCore.Application.Tools.ToolCallScope.operator !=(AgentCore.Application.Tools.ToolCallScope? left, AgentCore.Application.Tools.ToolCallScope? right) -> bool +static AgentCore.Application.Tools.ToolCallScope.operator ==(AgentCore.Application.Tools.ToolCallScope? left, AgentCore.Application.Tools.ToolCallScope? right) -> bool 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? diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 530fe0df..2b9efed0 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -734,6 +734,7 @@ private async ValueTask RunSessionAsync(Turn turn, CancellationTok /// The scope. Disposing it closes every ambient it opened. private IDisposable EnterAmbients(Turn turn) => TurnAmbients.Enter( + CallId, State, turn.Renders, turn.Sources, diff --git a/src/AgentCore.Application/Runtime/ToolCallScopes.cs b/src/AgentCore.Application/Runtime/ToolCallScopes.cs new file mode 100644 index 00000000..578e041e --- /dev/null +++ b/src/AgentCore.Application/Runtime/ToolCallScopes.cs @@ -0,0 +1,32 @@ +using AgentCore.Application.Tools; + +namespace AgentCore.Application.Runtime; + +/// +/// The of the turn running on this flow of execution. +/// +internal static class ToolCallScopes +{ + /// The message throws with when no turn is open. + 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."; + + /// Builds the scope of the call and turn running on this flow. + /// The scope. + /// + /// No turn is open on this flow of execution. The message names the fault and says what opens one. + /// + internal static ToolCallScope Current() + { + var ambients = TurnAmbients.Current; + + if (ambients?.CallId is not { } callId || ambients.State is not { } state) + { + throw new InvalidOperationException(NoTurnMessage); + } + + return new ToolCallScope(callId, state.TurnIndex, state.Stage); + } +} diff --git a/src/AgentCore.Application/Runtime/TurnAmbients.cs b/src/AgentCore.Application/Runtime/TurnAmbients.cs index 1e7f81e6..1d3c20d8 100644 --- a/src/AgentCore.Application/Runtime/TurnAmbients.cs +++ b/src/AgentCore.Application/Runtime/TurnAmbients.cs @@ -16,6 +16,9 @@ internal sealed record TurnAmbients /// Gets what is ambient on this flow, or when nothing is open. internal static TurnAmbients? Current => Ambient.Value; + /// Gets the id of the call the turn belongs to. + public string? CallId { get; init; } + /// Gets the state document the call reads and writes. public StateDocument? State { get; init; } @@ -44,6 +47,7 @@ internal sealed record TurnAmbients public Clarifications? Clarifications { get; init; } /// Opens what a turn owns, and carries every other ambient through unchanged. + /// The id of the call the turn belongs to. /// The state document the call reads and writes. /// What this turn draws into, or when it has no screen. /// What this turn cites into. Never null: a call with no screen still has sources. @@ -52,6 +56,7 @@ internal sealed record TurnAmbients /// What this turn may see of the knowledge base, or when the document composes none. /// The call's ambiguity holder. internal static IDisposable Enter( + string callId, StateDocument state, TurnRenders? renders, TurnSources sources, @@ -60,6 +65,7 @@ internal static IDisposable Enter( KnowledgeScope? knowledge, Clarifications clarifications) { + ArgumentNullException.ThrowIfNull(callId); ArgumentNullException.ThrowIfNull(state); ArgumentNullException.ThrowIfNull(sources); ArgumentNullException.ThrowIfNull(onToolFailure); @@ -70,6 +76,7 @@ internal static IDisposable Enter( return Push(current with { + CallId = callId, State = state, Screen = renders, Renders = renders, diff --git a/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs b/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs index 1228d5f5..7c673e1e 100644 --- a/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs +++ b/src/AgentCore.Application/Tools/Binding/ToolBindingRegistry.cs @@ -41,7 +41,9 @@ 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. + /// on a parameter reaches the model. A + /// parameter of type is filled by the runtime with the call the turn + /// belongs to, and is not exposed to the model. /// /// This registry, so a host chains its registrations. /// The name is already registered. diff --git a/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs b/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs index f584f2f8..39571483 100644 --- a/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs +++ b/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs @@ -1,5 +1,6 @@ using System.Text.Json; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; using Microsoft.Extensions.AI; namespace AgentCore.Application.Tools.Binding; @@ -13,7 +14,14 @@ internal sealed class TypedBindingTool : DeclaredTool internal TypedBindingTool(ToolConfiguration tool, Delegate method) : base(tool) - => _inner = AIFunctionFactory.Create(method, tool.Id, tool.Description); + => _inner = AIFunctionFactory.Create(method, new AIFunctionFactoryOptions + { + Name = tool.Id, + Description = tool.Description, + ConfigureParameterBinding = parameter => parameter.ParameterType == typeof(ToolCallScope) + ? new() { ExcludeFromSchema = true, BindParameter = static (_, _) => ToolCallScopes.Current() } + : default, + }); /// /// Gets the schema the host method's parameters describe. It replaces the base schema, which diff --git a/src/AgentCore.Application/Tools/ToolCallScope.cs b/src/AgentCore.Application/Tools/ToolCallScope.cs new file mode 100644 index 00000000..022da574 --- /dev/null +++ b/src/AgentCore.Application/Tools/ToolCallScope.cs @@ -0,0 +1,7 @@ +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 zero-based index of the turn now running. +/// The stage the call's state machine holds. Empty when the document declares no policy. +public sealed record ToolCallScope(string CallId, int TurnIndex, string Stage); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index 1fa28c7e..6ad46b5c 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Llm; using AgentCore.Application.Ports; +using AgentCore.Application.Tools; using AgentCore.Application.Tools.Binding; using Microsoft.Agents.AI; using Microsoft.Extensions.Logging; @@ -294,7 +295,9 @@ public AgentCoreOptions Bind(string name, ToolBinding binding) /// The name a binds: field writes, such as CreateCase. /// /// The method the tool calls. Its parameters are the arguments the model fills, and their JSON - /// Schema, so the declaration writes no parameters:. + /// 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 not exposed to the model. /// /// These options, so a host chains its calls. /// The name is already registered. diff --git a/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs b/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs new file mode 100644 index 00000000..f741ecff --- /dev/null +++ b/tests/AgentCore.Application.Tests/Tools/ToolCallScopeTests.cs @@ -0,0 +1,151 @@ +using System.Runtime.CompilerServices; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools; +using AgentCore.Application.Tools.Binding; +using AgentCore.Application.Tools.Registry; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Tools; + +/// +/// 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 +{ + private const string Yaml = """ + apiVersion: agentcore/v1 + name: scope-check + tools: + - { id: request_human, kind: binding, binds: RequestHuman, description: "Ask a human to take the call." } + policy: + initial: handling + stages: + - { id: handling, agent: only, to: [ { stage: waiting } ] } + - { id: waiting, agent: only, to: [ { stage: handling } ] } + agents: + items: + - { id: only, instructions: "help the caller", tools: [ request_human ] } + """; + + [Fact] + public async Task ABoundTool_ReceivesTheRunningCallsScope() + { + List captured = []; + ToolBindingRegistry bindings = new(); + bindings.Register("RequestHuman", (string reason, ToolCallScope scope) => captured.Add(scope)); + + var document = ConfigurationLoader.LoadYaml(Yaml); + var chatClients = new FakeChatClientFactory(new PerTurnToolCallingChatClient("connecting you now.")); + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) + { + Tools = await ToolRegistryBuilder.BuildAsync( + [new BindingToolSource(bindings)], + new ToolSourceContext(document), + TestContext.Current.CancellationToken), + }); + + var factory = new CallSessionFactory( + compiled, new GuardEvaluator(compiled.Configuration.Guards)); + var session = factory.Create("call-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(0, first.TurnIndex); + Assert.Equal("handling", first.Stage); + + captured.Clear(); + await session.RunTurnAsync("still need a person", TestContext.Current.CancellationToken); + + var second = Assert.Single(captured); + Assert.Equal(session.CallId, second.CallId); + Assert.Equal(1, second.TurnIndex); + } + + /// + /// Calls the one offered tool once per turn, rather than once per call: 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. + /// + private sealed class PerTurnToolCallingChatClient : IChatClient + { + private readonly string _reply; + private int _nextCallId; + + public PerTurnToolCallingChatClient(string reply) => _reply = reply; + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + await Task.Yield(); + + var transcript = messages.ToList(); + var lastUserIndex = transcript.FindLastIndex(message => message.Role == ChatRole.User); + var answeredThisTurn = transcript + .Skip(lastUserIndex + 1) + .Any(message => message.Contents.OfType().Any()); + + var responseId = Guid.NewGuid().ToString("N"); + + if (!answeredThisTurn && options?.Tools?.OfType().FirstOrDefault() is { } tool) + { + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [ + new FunctionCallContent( + $"call_{_nextCallId++}", + tool.Name, + new Dictionary(StringComparer.Ordinal) + { + ["reason"] = "the caller wants a person", + }), + ]) + { + ResponseId = responseId, + MessageId = responseId, + }; + + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, _reply) + { + ResponseId = responseId, + MessageId = responseId, + }; + } + + 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) => null; + + public void Dispose() + { + } + } +} diff --git a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs index 2c5346d0..cf2d61ac 100644 --- a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs @@ -3,6 +3,7 @@ using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; using AgentCore.Application.Tools; using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tools.Registry; @@ -106,6 +107,18 @@ 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. + [Fact] + public async Task AToolCallScopeParameter_IsLeftOutOfTheSchema() + { + var tool = await CreateAsync((string reason, ToolCallScope scope, CancellationToken ct) => reason); + + 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); + } + // --------------------------------------------------------------------------------------------- // Calling. // --------------------------------------------------------------------------------------------- @@ -175,6 +188,24 @@ await Assert.ThrowsAnyAsync(async () => await tool.InvokeAsync(new AIFunctionArguments { ["summary"] = "anything" }, cancelled.Token)); } + /// + /// A binding declares a parameter to read the call it runs in, but a + /// call to the tool with no turn open on this flow has no call to report. + /// + [Fact] + public async Task AToolCallScopeParameterWithNoTurnOpen_Throws() + { + var tool = await CreateAsync((string reason, ToolCallScope scope) => reason); + + var thrown = await Assert.ThrowsAsync(async () => + await tool.InvokeAsync( + new AIFunctionArguments { ["reason"] = "the caller wants a person" }, + TestContext.Current.CancellationToken)); + + Assert.Contains("ToolCallScope", thrown.Message, StringComparison.Ordinal); + Assert.Equal(ToolCallScopes.NoTurnMessage, thrown.Message); + } + /// The error policy of section 8.7 keys off , not off the delegate. [Fact] public async Task ATypedBinding_IsStillADeclaredTool() From a4b99854bb5b33213ec3b25a077c196627f2d6b3 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 03:05:03 -0600 Subject: [PATCH 03/32] feat: integrate Jint for script execution in drawing tools --- Directory.Packages.props | 3 + .../KnowledgeRetrievalPortExtensions.cs | 4 +- .../Ports/IScriptRunnerPort.cs | 15 ++ .../PublicAPI.Unshipped.txt | 43 ++++- .../AuditingFunctionInvokingChatClient.cs | 9 +- .../Runtime/CallSession.cs | 7 + .../Runtime/TurnAmbients.cs | 7 + .../Runtime/TurnResults.cs | 127 ++++++++++++++ .../Scripting/ScriptRequest.cs | 21 +++ .../Scripting/ScriptResult.cs | 23 +++ .../Tools/Builtin/IBuiltinToolDefinition.cs | 3 +- .../Tools/Drawing/DrawingAgentDefinition.cs | 23 ++- .../Tools/Drawing/DrawingData.cs | 132 +++++++++++++++ .../Tools/Drawing/DrawingVocabulary.cs | 4 +- .../Tools/Drawing/PresentTool.cs | 47 ++++-- .../Tools/Drawing/vocabulary.md | 28 +++- .../Tools/Shipped/IShippedAgentDefinition.cs | 5 + .../Tools/Shipped/ShippedAgentBuilder.cs | 57 ++++++- .../DependencyInjection/AgentCoreOptions.cs | 13 ++ .../Startup/ToolRegistryStartup.cs | 2 +- .../PublicAPI.Unshipped.txt | 1 + .../AgentCoreHostBuilderExtensions.cs | 4 + .../AgentCore.Infrastructure.csproj | 1 + .../PublicAPI.Unshipped.txt | 3 + .../Scripting/Jint/JintScriptRunner.cs | 140 ++++++++++++++++ .../Fakes/FakeScriptRunner.cs | 38 +++++ ...ngFunctionInvokingChatClientRenderTests.cs | 2 +- .../Runtime/RuntimeFakes.cs | 15 +- .../Runtime/TurnResultsTests.cs | 139 +++++++++++++++ .../Tools/BuiltinToolTests.cs | 8 +- .../Tools/DrawingAgentTests.cs | 60 ++++++- .../Tools/DrawingDataTests.cs | 95 +++++++++++ .../Tools/PresentToolTests.cs | 94 +++++++++-- .../Tools/ShippedAgentBuilderTests.cs | 2 + .../DependencyInjection/AddAgentCoreTests.cs | 1 + .../VectorData/Qdrant/FacetReadTests.cs | 1 + .../Scripting/Jint/JintScriptRunnerTests.cs | 158 ++++++++++++++++++ 37 files changed, 1276 insertions(+), 59 deletions(-) rename src/AgentCore.Application/{Ports => Knowledge}/KnowledgeRetrievalPortExtensions.cs (92%) create mode 100644 src/AgentCore.Application/Ports/IScriptRunnerPort.cs create mode 100644 src/AgentCore.Application/Runtime/TurnResults.cs create mode 100644 src/AgentCore.Application/Scripting/ScriptRequest.cs create mode 100644 src/AgentCore.Application/Scripting/ScriptResult.cs create mode 100644 src/AgentCore.Application/Tools/Drawing/DrawingData.cs create mode 100644 src/AgentCore.Infrastructure/Scripting/Jint/JintScriptRunner.cs create mode 100644 tests/AgentCore.Application.Tests/Fakes/FakeScriptRunner.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs create mode 100644 tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Scripting/Jint/JintScriptRunnerTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index e66f07ec..fb862aff 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -36,6 +36,9 @@ + + + diff --git a/src/AgentCore.Application/Ports/KnowledgeRetrievalPortExtensions.cs b/src/AgentCore.Application/Knowledge/KnowledgeRetrievalPortExtensions.cs similarity index 92% rename from src/AgentCore.Application/Ports/KnowledgeRetrievalPortExtensions.cs rename to src/AgentCore.Application/Knowledge/KnowledgeRetrievalPortExtensions.cs index 1aab5823..a3000947 100644 --- a/src/AgentCore.Application/Ports/KnowledgeRetrievalPortExtensions.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeRetrievalPortExtensions.cs @@ -1,4 +1,6 @@ -namespace AgentCore.Application.Ports; +using AgentCore.Application.Ports; + +namespace AgentCore.Application.Knowledge; /// /// Typed helpers over . diff --git a/src/AgentCore.Application/Ports/IScriptRunnerPort.cs b/src/AgentCore.Application/Ports/IScriptRunnerPort.cs new file mode 100644 index 00000000..66180c93 --- /dev/null +++ b/src/AgentCore.Application/Ports/IScriptRunnerPort.cs @@ -0,0 +1,15 @@ +using AgentCore.Application.Scripting; + +namespace AgentCore.Application.Ports; + +/// +/// Runs a script a model wrote, over data the host supplies, and hands back what it produced. +/// +public interface IScriptRunnerPort +{ + /// Runs one script. + /// The code, the data it sees as data, and how it may hand its result back. + /// Cancels the run. + /// What the script produced, or why it produced nothing. + ValueTask RunAsync(ScriptRequest request, CancellationToken cancellationToken = default); +} diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 5f17d04f..8169a511 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -1055,7 +1055,7 @@ AgentCore.Application.Ports.IToolSource AgentCore.Application.Ports.IToolSource.ProvideAsync(AgentCore.Application.Tools.Registry.ToolSourceContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Ports.IVendorAdapter AgentCore.Application.Ports.IVendorAdapter.Kind.get -> string! -AgentCore.Application.Ports.KnowledgeRetrievalPortExtensions +AgentCore.Application.Knowledge.KnowledgeRetrievalPortExtensions AgentCore.Application.Providers.VendorAdapterSelector AgentCore.Application.Providers.VendorSeam AgentCore.Application.Providers.VendorSeam.Deconstruct(out string! DocumentPath, out string! Pointer, out string! RegistrationHint, out string! Plural) -> void @@ -1234,10 +1234,12 @@ 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.BuiltinToolPorts(AgentCore.Application.Ports.IChatClientFactory? ChatClients, AgentCore.Application.Ports.IScriptRunnerPort? Scripts = null) -> 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.Deconstruct(out AgentCore.Application.Ports.IChatClientFactory? ChatClients, out AgentCore.Application.Ports.IScriptRunnerPort? Scripts) -> void +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Scripts.get -> AgentCore.Application.Ports.IScriptRunnerPort? +AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Scripts.init -> void AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Equals(AgentCore.Application.Tools.Builtin.BuiltinToolPorts? other) -> bool AgentCore.Application.Tools.Builtin.BuiltinToolSource AgentCore.Application.Tools.Builtin.BuiltinToolSource.BuiltinToolSource(AgentCore.Application.Tools.Builtin.BuiltinToolPorts! ports) -> void @@ -1816,7 +1818,7 @@ static AgentCore.Application.Knowledge.KnowledgeCitationFormatterFactory.Resolve static AgentCore.Application.Knowledge.KnowledgePoint.operator !=(AgentCore.Application.Knowledge.KnowledgePoint? left, AgentCore.Application.Knowledge.KnowledgePoint? right) -> bool static AgentCore.Application.Knowledge.KnowledgePoint.operator ==(AgentCore.Application.Knowledge.KnowledgePoint? left, AgentCore.Application.Knowledge.KnowledgePoint? right) -> bool static AgentCore.Application.Llm.CompositeChatClientFactory.CreateAsync(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.Ports.KnowledgeRetrievalPortExtensions.GetService(this AgentCore.Application.Ports.IKnowledgeRetrievalPort! port, object? serviceKey = null) -> TService? +static AgentCore.Application.Knowledge.KnowledgeRetrievalPortExtensions.GetService(this AgentCore.Application.Ports.IKnowledgeRetrievalPort! port, object? serviceKey = null) -> TService? 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 @@ -1887,3 +1889,36 @@ virtual AgentCore.Application.Call.CallInput.PrintMembers(System.Text.StringBuil 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.Ports.IScriptRunnerPort +AgentCore.Application.Ports.IScriptRunnerPort.RunAsync(AgentCore.Application.Scripting.ScriptRequest! request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +AgentCore.Application.Scripting.ScriptRequest +AgentCore.Application.Scripting.ScriptRequest.$() -> AgentCore.Application.Scripting.ScriptRequest! +AgentCore.Application.Scripting.ScriptRequest.Code.get -> string! +AgentCore.Application.Scripting.ScriptRequest.Code.init -> void +AgentCore.Application.Scripting.ScriptRequest.Data.get -> System.Text.Json.Nodes.JsonNode! +AgentCore.Application.Scripting.ScriptRequest.Data.init -> void +AgentCore.Application.Scripting.ScriptRequest.Deconstruct(out string! Code, out System.Text.Json.Nodes.JsonNode! Data) -> void +AgentCore.Application.Scripting.ScriptRequest.Emit.get -> string? +AgentCore.Application.Scripting.ScriptRequest.Emit.init -> void +AgentCore.Application.Scripting.ScriptRequest.Equals(AgentCore.Application.Scripting.ScriptRequest? other) -> bool +AgentCore.Application.Scripting.ScriptRequest.ScriptRequest(string! Code, System.Text.Json.Nodes.JsonNode! Data) -> void +AgentCore.Application.Scripting.ScriptResult +AgentCore.Application.Scripting.ScriptResult.$() -> AgentCore.Application.Scripting.ScriptResult! +AgentCore.Application.Scripting.ScriptResult.Equals(AgentCore.Application.Scripting.ScriptResult? other) -> bool +AgentCore.Application.Scripting.ScriptResult.Error.get -> string? +AgentCore.Application.Scripting.ScriptResult.Error.init -> void +AgentCore.Application.Scripting.ScriptResult.ScriptResult() -> void +AgentCore.Application.Scripting.ScriptResult.Value.get -> System.Text.Json.Nodes.JsonNode? +AgentCore.Application.Scripting.ScriptResult.Value.init -> void +override AgentCore.Application.Scripting.ScriptRequest.Equals(object? obj) -> bool +override AgentCore.Application.Scripting.ScriptRequest.GetHashCode() -> int +override AgentCore.Application.Scripting.ScriptRequest.ToString() -> string! +override AgentCore.Application.Scripting.ScriptResult.Equals(object? obj) -> bool +override AgentCore.Application.Scripting.ScriptResult.GetHashCode() -> int +override AgentCore.Application.Scripting.ScriptResult.ToString() -> string! +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! +static AgentCore.Application.Scripting.ScriptResult.operator ==(AgentCore.Application.Scripting.ScriptResult? left, AgentCore.Application.Scripting.ScriptResult? right) -> bool +static AgentCore.Application.Scripting.ScriptResult.operator !=(AgentCore.Application.Scripting.ScriptResult? left, AgentCore.Application.Scripting.ScriptResult? right) -> bool +static AgentCore.Application.Scripting.ScriptResult.Returned(System.Text.Json.Nodes.JsonNode? value) -> AgentCore.Application.Scripting.ScriptResult! diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index 42732c08..cae7a05b 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -42,7 +42,14 @@ internal AuditingFunctionInvokingChatClient(IChatClient innerClient) try { - return await base.InvokeFunctionAsync(context, cancellationToken).ConfigureAwait(false); + var result = await base.InvokeFunctionAsync(context, cancellationToken).ConfigureAwait(false); + + if (!nested) + { + TurnAmbients.Current?.Results?.Record(context.Function.Name, result); + } + + return result; } catch (Exception failure) when (!IsCallerCancellation(failure, cancellationToken) && !IsBeyondTheModel(failure)) diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 2b9efed0..4e9d8eb7 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -738,6 +738,7 @@ private IDisposable EnterAmbients(Turn turn) State, turn.Renders, turn.Sources, + turn.Results, failure => _events.RaiseToolFailure(turn.Index, failure), TurnContextOf(turn), turn.Knowledge, @@ -868,6 +869,7 @@ private Turn BeginTurn(string userInput, AgentSession session, CallTurnOrigin? o _time.GetTimestamp(), _hasScreen ? new TurnRenders() : null, new TurnSources(), + new TurnResults(), knowledge, origin?.MessageId); } @@ -1414,6 +1416,10 @@ private AIAgent ResolveAgent() /// What this turn cites into. Built once per turn for the same reason is, /// and never null: a call with no screen still answers from documents. /// + /// + /// What this turn's tools answer into, so a drawing script can read the rows. Built once per + /// turn: a later turn's rows are not this turn's. + /// /// /// What this turn may see of the knowledge base. Built once per turn for the same reason /// is, and additionally because a scope that changed between two updates @@ -1435,6 +1441,7 @@ private sealed record Turn( long StartedAt, TurnRenders? Renders, TurnSources Sources, + TurnResults Results, KnowledgeScope? Knowledge, string? MessageId); diff --git a/src/AgentCore.Application/Runtime/TurnAmbients.cs b/src/AgentCore.Application/Runtime/TurnAmbients.cs index 1d3c20d8..e899933e 100644 --- a/src/AgentCore.Application/Runtime/TurnAmbients.cs +++ b/src/AgentCore.Application/Runtime/TurnAmbients.cs @@ -31,6 +31,9 @@ internal sealed record TurnAmbients /// Gets what a turn has cited and not yet attached to a message. public TurnSources? Sources { get; init; } + /// Gets what the turn's tools answered, for a script to read, or . + public TurnResults? Results { get; init; } + /// Gets what to do with a tool failure the run reports. public Action? OnToolFailure { get; init; } @@ -51,6 +54,7 @@ internal sealed record TurnAmbients /// The state document the call reads and writes. /// What this turn draws into, or when it has no screen. /// What this turn cites into. Never null: a call with no screen still has sources. + /// What this turn's tools answer into. /// What to do with a tool failure the run reports. /// The turn the tools are running inside. /// What this turn may see of the knowledge base, or when the document composes none. @@ -60,6 +64,7 @@ internal static IDisposable Enter( StateDocument state, TurnRenders? renders, TurnSources sources, + TurnResults results, Action onToolFailure, TurnContext context, KnowledgeScope? knowledge, @@ -68,6 +73,7 @@ internal static IDisposable Enter( ArgumentNullException.ThrowIfNull(callId); ArgumentNullException.ThrowIfNull(state); ArgumentNullException.ThrowIfNull(sources); + ArgumentNullException.ThrowIfNull(results); ArgumentNullException.ThrowIfNull(onToolFailure); ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(clarifications); @@ -81,6 +87,7 @@ internal static IDisposable Enter( Screen = renders, Renders = renders, Sources = sources, + Results = results, OnToolFailure = onToolFailure, Context = context, Knowledge = knowledge ?? current.Knowledge, diff --git a/src/AgentCore.Application/Runtime/TurnResults.cs b/src/AgentCore.Application/Runtime/TurnResults.cs new file mode 100644 index 00000000..e59a477c --- /dev/null +++ b/src/AgentCore.Application/Runtime/TurnResults.cs @@ -0,0 +1,127 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.Application.Tools; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +/// +/// What the tools the model called this turn answered, kept so a script can read the rows instead of +/// a model retyping them. +/// +internal sealed class TurnResults +{ + /// The key under which every result of one tool sits, oldest first. + internal const string AllKey = "$all"; + + private readonly Lock _gate = new(); + + private readonly Dictionary> _byTool = new(StringComparer.Ordinal); + + private readonly List _order = []; + + /// The tools that answered something structured, in first-answer order. + internal IReadOnlyList Tools + { + get + { + lock (_gate) + { + return [.. _order]; + } + } + } + + /// Keeps one tool's answer, when it is structured. + /// The tool's declared id. + /// What it returned. + internal void Record(string tool, object? result) + { + ArgumentNullException.ThrowIfNull(tool); + + if (AsStructured(result) is not { } node) + { + return; + } + + lock (_gate) + { + if (!_byTool.TryGetValue(tool, out var answers)) + { + answers = []; + _byTool[tool] = answers; + _order.Add(tool); + } + + answers.Add(node); + } + } + + /// The latest answer of one tool, or . + /// The tool's declared id. + /// A copy of the answer. + internal JsonNode? Latest(string tool) + { + lock (_gate) + { + return _byTool.TryGetValue(tool, out var answers) ? answers[^1].DeepClone() : null; + } + } + + /// + /// What a script sees as data: each tool's latest answer under its id, and every answer + /// under . + /// + /// A fresh object each time. A script may do what it likes to it. + internal JsonObject Data() + { + lock (_gate) + { + JsonObject data = []; + JsonObject all = []; + foreach (var tool in _order) + { + var answers = _byTool[tool]; + data[tool] = answers[^1].DeepClone(); + all[tool] = new JsonArray([.. answers.Select(answer => answer.DeepClone())]); + } + + data[AllKey] = all; + return data; + } + } + + private static JsonNode? AsStructured(object? result) + { + var node = result switch + { + null => null, + JsonNode direct => direct.DeepClone(), + JsonElement element => JsonSerializer.SerializeToNode(element), + string text => Parse(text), + _ => JsonSerializer.SerializeToNode(result, result.GetType(), AIJsonUtilities.DefaultOptions), + }; + + return node is JsonObject or JsonArray && !(node is JsonObject error && ToolErrorResult.IsError(error)) + ? node + : null; + } + + private static JsonNode? Parse(string text) + { + var trimmed = text.AsSpan().Trim(); + if (trimmed.Length == 0 || (trimmed[0] != '{' && trimmed[0] != '[')) + { + return null; + } + + try + { + return JsonNode.Parse(text); + } + catch (JsonException) + { + return null; + } + } +} diff --git a/src/AgentCore.Application/Scripting/ScriptRequest.cs b/src/AgentCore.Application/Scripting/ScriptRequest.cs new file mode 100644 index 00000000..57cb803f --- /dev/null +++ b/src/AgentCore.Application/Scripting/ScriptRequest.cs @@ -0,0 +1,21 @@ +using System.Text.Json.Nodes; + +namespace AgentCore.Application.Scripting; + +/// One script to run. +/// +/// What the model wrote. It is read as the body of a function with in scope +/// as data, ending in return; a bare function expression is called with data +/// instead. Markdown fences around it are ignored. +/// +/// What the script sees as data. +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 + /// 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. + /// + public string? Emit { get; init; } +} diff --git a/src/AgentCore.Application/Scripting/ScriptResult.cs b/src/AgentCore.Application/Scripting/ScriptResult.cs new file mode 100644 index 00000000..2e3227a2 --- /dev/null +++ b/src/AgentCore.Application/Scripting/ScriptResult.cs @@ -0,0 +1,23 @@ +using System.Text.Json.Nodes; + +namespace AgentCore.Application.Scripting; + +/// What one script run produced. +public sealed record ScriptResult +{ + /// The value the script returned or emitted, as JSON, or when it produced none. + public JsonNode? Value { get; init; } + + /// Why the script produced nothing, in words the model can act on, or when it ran. + public string? Error { get; init; } + + /// A run that finished. + /// What it produced, or when it returned nothing. + /// The result. + public static ScriptResult Returned(JsonNode? value) => new() { Value = value }; + + /// A run that did not finish. + /// Why, for the model. + /// The result. + public static ScriptResult Failed(string error) => new() { Error = error }; +} diff --git a/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs b/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs index 18892831..4059e967 100644 --- a/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs +++ b/src/AgentCore.Application/Tools/Builtin/IBuiltinToolDefinition.cs @@ -7,7 +7,8 @@ namespace AgentCore.Application.Tools.Builtin; /// The adapters a built-in may need. A built-in uses none or more of them. /// The factory a shipped agent runs on, or when the host bound none. -public sealed record BuiltinToolPorts(IChatClientFactory? ChatClients); +/// What runs a script a model wrote, or when the host bound none. +public sealed record BuiltinToolPorts(IChatClientFactory? ChatClients, IScriptRunnerPort? Scripts = null); /// What every uses: name AgentCore ships has, whatever kind of thing it builds. internal interface IToolDefinition diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs b/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs index c0b9d53b..e3272fc7 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs @@ -1,4 +1,6 @@ using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Shipped; using Microsoft.Extensions.AI; @@ -15,8 +17,10 @@ internal sealed class DrawingAgentDefinition : IShippedAgentDefinition /// public string DefaultDescription - => "Draw something on the caller's screen for them to look at. Whoever draws it cannot see " - + "the conversation, so anything it needs has to be in the request."; + => "Draw something on the caller's screen for them to look at. To draw what a tool answered, " + + "name the tool and say what to show, e.g. 'a table of the lookup_orders result with " + + "columns order, customer, total'; never copy the rows into the request. Whoever draws " + + "it cannot see the conversation, so anything else it needs has to be in the request."; /// public string Instructions => DrawingVocabulary.Text; @@ -26,8 +30,19 @@ public string DefaultDescription /// public IReadOnlyList InnerTools(ToolConfiguration tool, BuiltinToolPorts ports) - => [PresentTool.Create(tool.Id)]; + => [PresentTool.Create(tool.Id, ports.Scripts!)]; /// - public string? MissingPort(BuiltinToolPorts ports) => null; + public string? MissingPort(BuiltinToolPorts ports) + => ports.Scripts is null ? nameof(IScriptRunnerPort) : null; + + /// + /// + /// The drawing model cannot see the conversation, and it must not see the rows either: they go + /// to its script. What it gets is the request and, after it, the shape of each answer. + /// + public string Compose(string query) + => DrawingData.Describe(TurnAmbients.Current?.Results) is { } data + ? query + "\n\n" + data + : query; } diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingData.cs b/src/AgentCore.Application/Tools/Drawing/DrawingData.cs new file mode 100644 index 00000000..84b618df --- /dev/null +++ b/src/AgentCore.Application/Tools/Drawing/DrawingData.cs @@ -0,0 +1,132 @@ +using System.Globalization; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.Application.Runtime; + +namespace AgentCore.Application.Tools.Drawing; + +/// +/// Tells the drawing model what its script's data holds: each tool's answer by name, its +/// shape, and a few rows, so the model can write the script without ever reading the rows. +/// +/// +/// Three sample rows, strings cut at 60 characters, nesting cut at two levels, one line capped at +/// 600 characters. Measured on the same requests, a model given only this drew as faithfully as one +/// given every row, at half the input tokens; the rows do not help it and can only be retyped. +/// +internal static class DrawingData +{ + private const int SampleRows = 3; + + private const int StringLimit = 60; + + private const int DepthLimit = 2; + + private const int LineLimit = 600; + + /// The samples are prose for a model, not a wire format: no escaping of the cut mark. + private static readonly JsonSerializerOptions Prose = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + + /// Describes what a script will find in data. + /// What this turn's tools answered, or . + /// The block to append to the request, or when nothing was answered. + internal static string? Describe(TurnResults? results) + { + if (results is null || results.Tools.Count == 0) + { + return null; + } + + StringBuilder text = new(); + text.AppendLine("## Data"); + text.AppendLine(); + text.AppendLine("Your script's `data` holds what this turn's tools answered. Read the rows from it; never retype them."); + text.AppendLine(); + + foreach (var tool in results.Tools) + { + var answers = results.Data()[TurnResults.AllKey]![tool]!.AsArray(); + var latest = answers[^1]!; + var line = new StringBuilder(); + line.Append(CultureInfo.InvariantCulture, $"- `data.{tool}` — ").Append(Shape(latest)); + + if (answers.Count > 1) + { + line.Append(CultureInfo.InvariantCulture, $" Called {answers.Count} times; `data.{TurnResults.AllKey}.{tool}` holds every answer, oldest first. Latest: "); + } + else + { + line.Append(latest is JsonArray ? $" First {SampleRows}: " : " It is: "); + } + + line.Append(Sample(latest, depth: 0)); + text.AppendLine(Cap(line.ToString())); + } + + return text.ToString().TrimEnd(); + } + + private static string Shape(JsonNode node) + => node switch + { + JsonArray { Count: 0 } => "an empty array.", + JsonArray list when list.All(item => item is JsonObject) + => $"an array of {list.Count} objects with fields {Fields(list.OfType().Take(SampleRows))}.", + JsonArray list => $"an array of {list.Count} values.", + JsonObject item => $"an object with fields {Fields([item])}.", + _ => "a value.", + }; + + private static string Fields(IEnumerable items) + { + List names = []; + foreach (var item in items) + { + foreach (var pair in item) + { + if (!names.Contains(pair.Key, StringComparer.Ordinal)) + { + names.Add(pair.Key); + } + } + } + + return string.Join(", ", names); + } + + private static string Sample(JsonNode? node, int depth) + { + switch (node) + { + case null: + return "null"; + case JsonArray list: + if (depth >= DepthLimit) + { + return "[…]"; + } + + var items = list.Take(SampleRows).Select(item => Sample(item, depth + 1)); + var more = list.Count > SampleRows ? $", …+{list.Count - SampleRows}" : string.Empty; + return $"[{string.Join(",", items)}{more}]"; + case JsonObject item: + if (depth >= DepthLimit) + { + return "{…}"; + } + + var pairs = item.Select(pair => $"\"{pair.Key}\":{Sample(pair.Value, depth + 1)}"); + return $"{{{string.Join(",", pairs)}}}"; + case JsonValue value when value.TryGetValue(out var text): + var shown = text.Length > StringLimit ? text[..StringLimit] + "…" : text; + return JsonSerializer.Serialize(shown, Prose); + default: + return node.ToJsonString(); + } + } + + private static string Cap(string line) + => line.Length > LineLimit ? line[..LineLimit] + "…" : line; +} diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingVocabulary.cs b/src/AgentCore.Application/Tools/Drawing/DrawingVocabulary.cs index 071ac201..96d76d0b 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingVocabulary.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingVocabulary.cs @@ -5,8 +5,8 @@ namespace AgentCore.Application.Tools.Drawing; /// The prose vocabulary the drawing agent is instructed with. /// /// Prose rather than a JSON Schema: the shipped schema for the same 27 components is 19,355 bytes -/// and would ride every request of every turn of every agent that may draw. The prose is a third of -/// that and rides only the drawing call. +/// and would ride every request of every turn of every agent that may draw. The prose is under half +/// of that and rides only the drawing call. /// internal static class DrawingVocabulary { diff --git a/src/AgentCore.Application/Tools/Drawing/PresentTool.cs b/src/AgentCore.Application/Tools/Drawing/PresentTool.cs index 52435de4..ebeda0f4 100644 --- a/src/AgentCore.Application/Tools/Drawing/PresentTool.cs +++ b/src/AgentCore.Application/Tools/Drawing/PresentTool.cs @@ -1,7 +1,8 @@ using System.ComponentModel; -using System.Text.Json; using System.Text.Json.Nodes; +using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Scripting; using Microsoft.Extensions.AI; namespace AgentCore.Application.Tools.Drawing; @@ -9,6 +10,11 @@ namespace AgentCore.Application.Tools.Drawing; /// /// The inner tool the drawing agent calls. It is never declared in a document. /// +/// +/// The model hands over code, not a tree. The code runs over what this turn's tools answered, and +/// the tree it builds is what gets drawn. A model that types a hundred rows into a tree gets the +/// sums wrong and takes twenty seconds; a script that maps them takes two and gets them right. +/// internal static class PresentTool { /// The name the drawing agent calls. @@ -18,18 +24,26 @@ internal static class PresentTool internal const string RendererName = "generative-ui"; /// Builds the inner tool for one declared drawing tool. - internal static AIFunction Create(string toolId) - => AIFunctionFactory.Create( - ([Description("The tree to draw. One object with $type and its props, nested with children.")] - JsonElement tree) => Publish(toolId, tree), + /// The declared id, named in every error the model reads. + /// What runs the model's code. + internal static AIFunction Create(string toolId, IScriptRunnerPort scripts) + { + ArgumentNullException.ThrowIfNull(scripts); + + return AIFunctionFactory.Create( + async ([Description("JavaScript: the body of a function that reads `data` and returns the tree to draw.")] string code, + CancellationToken cancellationToken) + => await PublishAsync(toolId, scripts, code, cancellationToken).ConfigureAwait(false), new AIFunctionFactoryOptions { Name = Name, - Description = "Draw one tree for the caller. Call this once.", + Description = "Run code that builds one tree for the caller and draw it. Call this once.", ExcludeResultSchema = true, }); + } - private static JsonObject Publish(string toolId, JsonElement tree) + private static async ValueTask PublishAsync( + string toolId, IScriptRunnerPort scripts, string code, CancellationToken cancellationToken) { if (CallRenderScope.Current is not { } screen) { @@ -37,13 +51,22 @@ private static JsonObject Publish(string toolId, JsonElement tree) toolId, "this call has no screen, so nothing can be drawn on it. Say it in words instead."); } - try + var data = TurnAmbients.Current?.Results?.Data() ?? new JsonObject { [TurnResults.AllKey] = new JsonObject() }; + var run = await scripts.RunAsync(new ScriptRequest(code, data) { Emit = Name }, cancellationToken).ConfigureAwait(false); + + if (run.Error is { } error) { - if (JsonSerializer.SerializeToNode(tree) is not JsonObject node) - { - return ToolErrorResult.Create(toolId, "the tree was not a JSON object."); - } + return ToolErrorResult.Create(toolId, $"the script failed: {error} Fix it and call {Name} again."); + } + if (run.Value is not JsonObject node) + { + return ToolErrorResult.Create( + toolId, $"the script did not return a tree. End it with `return` and one object with $type, then call {Name} again."); + } + + try + { if (DrawingTree.Validate(node) is { } fault) { return ToolErrorResult.Create(toolId, $"that tree is not valid: {fault} Fix it and call {Name} again."); diff --git a/src/AgentCore.Application/Tools/Drawing/vocabulary.md b/src/AgentCore.Application/Tools/Drawing/vocabulary.md index 573b341f..6785f447 100644 --- a/src/AgentCore.Application/Tools/Drawing/vocabulary.md +++ b/src/AgentCore.Application/Tools/Drawing/vocabulary.md @@ -2,14 +2,36 @@ You draw one thing for the caller to look at, then you report what you drew. You cannot see the conversation. Everything you need is in the request. -Call `present` exactly once with a tree, then reply with ONE line naming every -button you drew and its payload, like: +Call `present` exactly once with `code`: JavaScript that builds the tree. Then +reply with ONE line naming every button you drew and its payload, like: drew a confirm card; buttons: approve id=42, cancel id=43 Say `buttons: none` when there are none. Nobody sees your reply except the agent that asked you, and it never sees the tree, so that line is all it will know. +## How you draw + +You do not write the tree by hand. You write code that builds it. + +`code` is the BODY of a function. It ends with `return ;` where the tree is a +plain object in the shape below. Plain ES2020. No imports, no require, no fetch, no +console, no clock. + +`data` is in scope. It holds what the tools of this turn answered, one key per tool, +described at the end of the request: `data.lookup_orders` is that tool's latest +answer; `data.$all.lookup_orders` is every answer it gave, oldest first. Read the +rows from `data`. Never retype them. Do the sorting, filtering, grouping and sums in +code, never in your head. + + var rows = data.lookup_orders.map(function (o) { return [o.id, o.customer, o.total]; }); + return { $type: "Table", + columns: [{ label: "Order" }, { label: "Customer" }, { label: "Total" }], + rows: rows }; + +A small value the request gives you in words goes straight into the tree as a +literal. A request that names no data needs no `data` at all: just return the tree. + ## The tree Every node is an object with `$type` and its props inline. Nest with `children`. @@ -96,7 +118,7 @@ A control inside a form needs a `name`, or its value is not collected. ## Rules - Draw what was asked and nothing more. One `Card` beats three boxes. -- Never invent data. Use only what the request gives you. +- Never invent data. Use only what the request and `data` give you. - Prefer `Fact` over `Text` for numbers, and `Table` over many `Fact`s. - Add a button only when the request asks for a decision. - A prop that is not listed above is dropped silently. Do not guess prop names. diff --git a/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs b/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs index 02f58b29..a205e4b0 100644 --- a/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs +++ b/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs @@ -29,4 +29,9 @@ internal interface IShippedAgentDefinition : IToolDefinition /// The adapters the host bound. /// The port name, or when everything it needs is bound. string? MissingPort(BuiltinToolPorts ports); + + /// Builds the request this agent reads from what the outer agent wrote. + /// The outer agent's one string. + /// The request. Most agents hand the string through unchanged. + string Compose(string query); } diff --git a/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs b/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs index 3107b3a0..30464497 100644 --- a/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs +++ b/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs @@ -54,16 +54,61 @@ internal static AIFunction Build( }); return new SpentRoundsAreAnError( - agent.AsAIFunction(new AIFunctionFactoryOptions - { - Name = tool.Id, - Description = described.Description!, - ExcludeResultSchema = true, - }), + new ComposedRequest( + agent.AsAIFunction(new AIFunctionFactoryOptions + { + Name = tool.Id, + Description = described.Description!, + ExcludeResultSchema = true, + }), + definition), tool.Id, rounds); } + /// + /// Hands the inner agent the request its definition composes from the outer agent's string. + /// + private sealed class ComposedRequest : DelegatingAIFunction + { + /// The one parameter AsAIFunction advertises. + private const string QueryParameter = "query"; + + private readonly IShippedAgentDefinition _definition; + + internal ComposedRequest(AIFunction inner, IShippedAgentDefinition definition) + : base(inner) + { + _definition = definition; + } + + protected override ValueTask InvokeCoreAsync( + AIFunctionArguments arguments, + CancellationToken cancellationToken) + { + if (arguments.TryGetValue(QueryParameter, out var value) && Text(value) is { } query) + { + var composed = new AIFunctionArguments(new Dictionary(arguments, StringComparer.Ordinal)) + { + Services = arguments.Services, + Context = arguments.Context, + }; + composed[QueryParameter] = _definition.Compose(query); + return InnerFunction.InvokeAsync(composed, cancellationToken); + } + + return InnerFunction.InvokeAsync(arguments, cancellationToken); + } + + private static string? Text(object? value) + => value switch + { + string text => text, + JsonElement { ValueKind: JsonValueKind.String } element => element.GetString(), + _ => null, + }; + } + /// /// Answers the outer agent a section 8.7 error when the inner agent finished with no words. /// diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index 6ad46b5c..1e18616d 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -39,6 +39,9 @@ public sealed class AgentCoreOptions /// Gets the seam that resolves a model reference, or . internal Func>? ChatClients { get; private set; } + /// Gets what runs a script a model wrote, or . + internal IScriptRunnerPort? Scripts { get; private set; } + /// Gets the embedding vendors the host registered, or . internal IReadOnlyList? Embeddings { get; private set; } @@ -117,6 +120,16 @@ public AgentCoreOptions UseChatClients(FuncBinds what runs a script a model wrote. ui.draw reads it. + /// The runner. + /// These options, so a host chains its calls. + public AgentCoreOptions UseScripts(IScriptRunnerPort scripts) + { + ArgumentNullException.ThrowIfNull(scripts); + Scripts = scripts; + return this; + } + /// Binds 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. diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs index 5f4b6be4..41966375 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ToolRegistryStartup.cs @@ -45,7 +45,7 @@ internal static async ValueTask BuildAsync( { List sources = [ - new BuiltinToolSource(new BuiltinToolPorts(chatClients)), + new BuiltinToolSource(new BuiltinToolPorts(chatClients, options.Scripts)), new BindingToolSource(options.Bindings), ]; diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 84e44e34..486198b9 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -71,3 +71,4 @@ static AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensi 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.UseScripts(AgentCore.Application.Ports.IScriptRunnerPort! scripts) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! diff --git a/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs b/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs index 63e5e9c6..57dfeec2 100644 --- a/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs +++ b/src/AgentCore.Hosting/AgentCoreHostBuilderExtensions.cs @@ -8,6 +8,7 @@ using AgentCore.Infrastructure.Evaluation.OpenAiModeration; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Llm.OpenAI; +using AgentCore.Infrastructure.Scripting.Jint; using AgentCore.Infrastructure.Secrets; using AgentCore.Infrastructure.Telemetry.Grafana; using AgentCore.Infrastructure.Tools; @@ -100,6 +101,9 @@ private static void Configure( // providers.llm[].kind picks the adapter for each entry. options.UseChatClients(new OpenAiChatClientAdapter()); + // ui.draw runs the drawing model's script in it. + options.UseScripts(new JintScriptRunner()); + // providers.embeddings.kind picks the adapter. options.UseEmbeddings(new OpenAiEmbeddingGeneratorAdapter()); diff --git a/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj b/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj index 1796d2fb..94f54925 100644 --- a/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj +++ b/src/AgentCore.Infrastructure/AgentCore.Infrastructure.csproj @@ -13,6 +13,7 @@ + diff --git a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt index c8ca8d2a..b1105625 100644 --- a/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Infrastructure/PublicAPI.Unshipped.txt @@ -87,3 +87,6 @@ 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.Scripting.Jint.JintScriptRunner +AgentCore.Infrastructure.Scripting.Jint.JintScriptRunner.JintScriptRunner() -> void +AgentCore.Infrastructure.Scripting.Jint.JintScriptRunner.RunAsync(AgentCore.Application.Scripting.ScriptRequest! request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/AgentCore.Infrastructure/Scripting/Jint/JintScriptRunner.cs b/src/AgentCore.Infrastructure/Scripting/Jint/JintScriptRunner.cs new file mode 100644 index 00000000..36518665 --- /dev/null +++ b/src/AgentCore.Infrastructure/Scripting/Jint/JintScriptRunner.cs @@ -0,0 +1,140 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Ports; +using AgentCore.Application.Scripting; +using Jint; +using Jint.Native; +using Jint.Runtime; + +namespace AgentCore.Infrastructure.Scripting.Jint; + +/// +/// Runs a model's script in a Jint engine that can reach nothing but data. +/// +/// +/// A fresh engine per run: nothing one script defines survives into the next, and the budgets below +/// are per run. Jint never exposes the CLR unless asked to, and this class does not ask. The engine +/// is pinned to UTC because new Date("2026-03-01").getMonth() otherwise depends on where the +/// host machine sits, and a script that groups by month must not. +/// +public sealed class JintScriptRunner : IScriptRunnerPort +{ + private static readonly TimeSpan TimeBudget = TimeSpan.FromSeconds(2); + + private const long MemoryBudgetBytes = 64L * 1024 * 1024; + + private const int RecursionBudget = 64; + + private const int StatementBudget = 500_000; + + /// + public ValueTask RunAsync(ScriptRequest request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + cancellationToken.ThrowIfCancellationRequested(); + + var code = Unfence(request.Code); + + try + { + var engine = new Engine(options => options + .TimeoutInterval(TimeBudget) + .LimitMemory(MemoryBudgetBytes) + .LimitRecursion(RecursionBudget) + .MaxStatements(StatementBudget) + .LocalTimeZone(TimeZoneInfo.Utc) + .CancellationToken(cancellationToken)); + + engine.SetValue("__json", request.Data.ToJsonString()); + engine.Execute("var data = JSON.parse(__json); var __emitted;"); + if (request.Emit is { Length: > 0 } emit) + { + engine.Execute($"function {emit}(value) {{ __emitted = value; return value; }}"); + } + + return ValueTask.FromResult(ScriptResult.Returned(ToJson(engine, Evaluate(engine, code)))); + } + catch (ExecutionCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + catch (Exception failure) when (failure is not OperationCanceledException) + { + return ValueTask.FromResult(ScriptResult.Failed(Describe(failure))); + } + } + + /// Runs the code as a body, then as an expression when the body answered nothing. + private static JsValue Evaluate(Engine engine, string code) + { + JsValue returned; + try + { + returned = engine.Evaluate($"(function () {{\n{code}\n}})()"); + } + catch (JavaScriptException bodyFailure) + { + // A body that does not parse may be a bare function expression. When it is not, the + // body's own error is the one the model wrote and the one it can act on. + try + { + return engine.Evaluate($"({code})(data)"); + } + catch (JavaScriptException) + { + throw bodyFailure; + } + } + + if (!returned.IsUndefined()) + { + return returned; + } + + var emitted = engine.GetValue("__emitted"); + if (!emitted.IsUndefined()) + { + return emitted; + } + + // A statement that is one function expression evaluates to the function and returns nothing. + try + { + return engine.Evaluate($"({code})(data)"); + } + catch (JavaScriptException) + { + return JsValue.Undefined; + } + } + + private static JsonNode? ToJson(Engine engine, JsValue value) + { + engine.SetValue("__result", value); + var text = engine.Evaluate("JSON.stringify(__result)"); + return text.IsString() ? JsonNode.Parse(text.AsString()) : null; + } + + private static string Describe(Exception failure) + => failure switch + { + TimeoutException => $"the script ran longer than {TimeBudget.TotalSeconds:0} seconds and was stopped.", + MemoryLimitExceededException => $"the script used more than {MemoryBudgetBytes / (1024 * 1024)} MB and was stopped.", + RecursionDepthOverflowException => $"the script recursed deeper than {RecursionBudget} calls and was stopped.", + StatementsCountOverflowException => $"the script ran more than {StatementBudget} statements and was stopped.", + JavaScriptException script => script.Message, + _ => failure.GetType().Name + ": " + failure.Message, + }; + + private static string Unfence(string code) + { + var text = code.Trim(); + if (!text.StartsWith("```", StringComparison.Ordinal)) + { + return text; + } + + var firstBreak = text.IndexOf('\n'); + text = firstBreak < 0 ? string.Empty : text[(firstBreak + 1)..]; + return text.EndsWith("```", StringComparison.Ordinal) ? text[..^3].TrimEnd() : text; + } +} diff --git a/tests/AgentCore.Application.Tests/Fakes/FakeScriptRunner.cs b/tests/AgentCore.Application.Tests/Fakes/FakeScriptRunner.cs new file mode 100644 index 00000000..8b67807e --- /dev/null +++ b/tests/AgentCore.Application.Tests/Fakes/FakeScriptRunner.cs @@ -0,0 +1,38 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.Application.Ports; +using AgentCore.Application.Scripting; + +namespace AgentCore.Application.Tests.Fakes; + +/// +/// A script runner for tests that cannot run JavaScript. The "code" is the JSON the script would +/// have returned, or throw: message for a script that fails. +/// +internal sealed class FakeScriptRunner : IScriptRunnerPort +{ + private const string ThrowPrefix = "throw:"; + + /// Gets every request this runner was handed, in call order. + public List Requests { get; } = []; + + public ValueTask RunAsync(ScriptRequest request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + Requests.Add(request); + + if (request.Code.StartsWith(ThrowPrefix, StringComparison.Ordinal)) + { + return ValueTask.FromResult(ScriptResult.Failed(request.Code[ThrowPrefix.Length..].Trim())); + } + + try + { + return ValueTask.FromResult(ScriptResult.Returned(JsonNode.Parse(request.Code))); + } + catch (JsonException failure) + { + return ValueTask.FromResult(ScriptResult.Failed(failure.Message)); + } + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs index a2852d17..92ca1840 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs @@ -148,7 +148,7 @@ public async Task ADrawingMadeInsideTheNestedDrawingAgent_AttachesToTheOuterDraw var drawTool = ShippedAgentBuilder.Build( new DrawingAgentDefinition(), DrawDeclaration, - new BuiltinToolPorts(new RecordingChatClientFactory(new PresentCallingChatClient(Card)))); + new BuiltinToolPorts(new RecordingChatClientFactory(new PresentCallingChatClient(Card)), new FakeScriptRunner())); TurnRenders renders = new(); using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); diff --git a/tests/AgentCore.Application.Tests/Runtime/RuntimeFakes.cs b/tests/AgentCore.Application.Tests/Runtime/RuntimeFakes.cs index 4b11e642..f7e30996 100644 --- a/tests/AgentCore.Application.Tests/Runtime/RuntimeFakes.cs +++ b/tests/AgentCore.Application.Tests/Runtime/RuntimeFakes.cs @@ -626,12 +626,13 @@ public void Publish(string name, string renderId, object data, bool transient = /// /// A drawing model: it answers each request with one call to present carrying the next -/// scripted tree, and answers with plain text once the script runs out. +/// scripted piece of code, and answers with plain text once the script runs out. /// /// /// Enough to drive a real ChatClientAgent end to end, including recovery: a tree the /// validator rejects comes back to the agent as present's error result, the agent asks again, -/// and this client hands it the next tree. The text answer is what ends the run. +/// and this client hands it the next code. The text answer is what ends the run. Under +/// the code is the JSON the script would have returned. /// internal sealed class PresentCallingChatClient : IChatClient { @@ -643,6 +644,9 @@ internal sealed class PresentCallingChatClient : IChatClient /// Gets how many requests this client answered. public int Calls => Volatile.Read(ref _calls); + /// Gets the text of the last user message of each request, in call order. + public List Prompts { get; } = []; + public async IAsyncEnumerable GetStreamingResponseAsync( IEnumerable messages, ChatOptions? options = null, @@ -653,6 +657,11 @@ public async IAsyncEnumerable GetStreamingResponseAsync( var index = Interlocked.Increment(ref _calls) - 1; await Task.Yield(); + lock (Prompts) + { + Prompts.Add(messages.LastOrDefault(message => message.Role == ChatRole.User)?.Text ?? string.Empty); + } + var responseId = Guid.NewGuid().ToString("N"); if (index >= _trees.Length) @@ -672,7 +681,7 @@ [new FunctionCallContent( "present", new Dictionary(StringComparer.Ordinal) { - ["tree"] = JsonSerializer.Deserialize(_trees[index]), + ["code"] = _trees[index], })]) { ResponseId = responseId, diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs b/tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs new file mode 100644 index 00000000..44f76c4c --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs @@ -0,0 +1,139 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// : what the turn's tools answered, kept so a drawing script can read the +/// rows instead of a model retyping them. +/// +public sealed class TurnResultsTests +{ + private static readonly JsonNode Orders = JsonNode.Parse("""[{"id":"SO-1"},{"id":"SO-2"}]""")!; + + [Fact] + public void ARecordedObject_IsTheLatestAndTheOnlyOne() + { + TurnResults results = new(); + + results.Record("lookup_orders", Orders); + + var data = results.Data(); + Assert.Equal(Orders.ToJsonString(), data["lookup_orders"]!.ToJsonString()); + Assert.Equal($"[{Orders.ToJsonString()}]", data["$all"]!["lookup_orders"]!.ToJsonString()); + Assert.Equal(["lookup_orders"], results.Tools); + } + + [Fact] + public void ASecondRecord_BecomesTheLatest_AndBothStayInOrder() + { + TurnResults results = new(); + results.Record("lookup_order", JsonNode.Parse("""{"id":"SO-1"}""")!); + + results.Record("lookup_order", JsonNode.Parse("""{"id":"SO-2"}""")!); + + var data = results.Data(); + Assert.Equal("""{"id":"SO-2"}""", data["lookup_order"]!.ToJsonString()); + Assert.Equal("""[{"id":"SO-1"},{"id":"SO-2"}]""", data["$all"]!["lookup_order"]!.ToJsonString()); + Assert.Equal(["lookup_order"], results.Tools); + } + + [Fact] + public void TheDataHandedOut_IsACopy_SoAScriptCannotChangeWhatWasRecorded() + { + TurnResults results = new(); + results.Record("lookup_orders", Orders); + + results.Data()["lookup_orders"]!.AsArray().Clear(); + + Assert.Equal(Orders.ToJsonString(), results.Data()["lookup_orders"]!.ToJsonString()); + } + + [Theory] + [MemberData(nameof(StructuredResults))] + public void AStructuredResult_IsRecorded_WhateverShapeTheToolAnsweredIn(object result, string expected) + { + TurnResults results = new(); + + results.Record("tool", result); + + Assert.Equal(expected, results.Data()["tool"]!.ToJsonString()); + } + + public static TheoryData StructuredResults => new() + { + { JsonNode.Parse("""{"a":1}""")!, """{"a":1}""" }, + { JsonSerializer.Deserialize("""[1,2]"""), "[1,2]" }, + { """{"from":"a string holding json"}""", """{"from":"a string holding json"}""" }, + { new { name = "an object" }, """{"name":"an object"}""" }, + }; + + [Theory] + [MemberData(nameof(UnstructuredResults))] + public void AnUnstructuredResult_IsNotRecorded(object? result) + { + TurnResults results = new(); + + results.Record("tool", result); + + Assert.Empty(results.Tools); + Assert.Null(results.Data()["tool"]); + } + + public static TheoryData UnstructuredResults => new() + { + (object?)null, + "Order SO-1 shipped on Tuesday.", + 42, + ToolErrorResult.Create("tool", "it failed."), + }; + + [Fact] + public async Task AnOutermostToolCall_IsRecordedUnderTheToolsName() + { + TurnResults results = new(); + using var scope = TurnAmbients.Amend(ambients => ambients with { Results = results }); + var tool = AIFunctionFactory.Create(() => Orders, "lookup_orders"); + + await Run(tool); + + Assert.Equal(["lookup_orders"], results.Tools); + Assert.Equal(Orders.ToJsonString(), results.Data()["lookup_orders"]!.ToJsonString()); + } + + [Fact] + public async Task AToolCallNestedInsideAnother_IsNotRecorded() + { + // The outer model never saw a nested result, so it cannot ask to draw it. + TurnResults results = new(); + using var scope = TurnAmbients.Amend(ambients => ambients with { Results = results }); + var inner = AIFunctionFactory.Create(() => Orders, "inner_lookup"); + var outer = AIFunctionFactory.Create( + async () => + { + await Run(inner); + return JsonNode.Parse("""{"outer":true}"""); + }, + "delegate"); + + await Run(outer); + + Assert.Equal(["delegate"], results.Tools); + } + + private static async Task Run(AIFunction tool) + { + ToolCallingChatClient model = new("done."); + using AuditingFunctionInvokingChatClient client = new(model); + + await client.GetResponseAsync( + [new ChatMessage(ChatRole.User, "go")], + new ChatOptions { Tools = [tool] }, + TestContext.Current.CancellationToken); + } +} diff --git a/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs b/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs index 73a8b052..8116cc06 100644 --- a/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/BuiltinToolTests.cs @@ -1,6 +1,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Tests.Configuration; +using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tools.Registry; using AgentCore.Application.Tools; using AgentCore.Application.Tools.Builtin; @@ -82,10 +83,11 @@ public async Task AUsesNameAgentCoreDoesNotShip_FailsTheBoot() /// Builds one declared tool through , synchronously. private sealed class BuiltinFactory { - // The chat client factory is always bound: ui.draw is a shipped agent, and one declared in - // a document with no factory behind it fails the boot rather than building. + // The chat client factory and the script runner are always bound: ui.draw is a shipped + // agent that reads both, and one declared in a document with either missing fails the boot + // rather than building. private readonly BuiltinToolSource _source = - new(new BuiltinToolPorts(new RecordingChatClientFactory())); + new(new BuiltinToolPorts(new RecordingChatClientFactory(), new FakeScriptRunner())); public AITool? Create(ToolConfiguration tool) { diff --git a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs index 96db51de..d2f17cd0 100644 --- a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs @@ -2,7 +2,9 @@ using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; using AgentCore.Application.Tools; using AgentCore.Application.Tools.Builtin; @@ -16,7 +18,8 @@ namespace AgentCore.Application.Tests.Tools; /// -/// ui.draw: a shipped agent whose one inner tool is present. +/// ui.draw: a shipped agent whose one inner tool is present, which runs the script +/// the drawing model wrote over what this turn's tools answered. /// /// /// The point of the design is what the calling agent never sees. The 27-component vocabulary is @@ -184,6 +187,53 @@ public async Task TheSource_WithNoChatClientFactory_FailsTheBoot() Assert.Contains("IChatClientFactory", failure.Message, StringComparison.Ordinal); } + [Fact] + public async Task TheSource_WithNoScriptRunner_FailsTheBoot() + { + var failure = await Assert.ThrowsAsync( + async () => await Provide(Declaration, new RecordingChatClientFactory(), scripts: null)); + + Assert.Contains("draw", failure.Message, StringComparison.Ordinal); + Assert.Contains(nameof(IScriptRunnerPort), failure.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task TheDrawingModel_IsToldWhatThisTurnsToolsAnswered_AfterTheRequest() + { + // The whole point of the script: the calling agent names the result, the drawing model reads + // its shape and three rows, and the rows themselves go to the script and never to a model. + RecordingRenderPort screen = new(); + TurnResults results = new(); + results.Record("lookup_orders", JsonNode.Parse("""[{"id":"SO-1","total":5},{"id":"SO-2","total":7}]""")!); + using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = results }); + PresentCallingChatClient model = new(Card); + + var function = Build(new RecordingChatClientFactory(model)); + await function.InvokeAsync( + new AIFunctionArguments(new Dictionary { ["query"] = "a table of the lookup_orders result" }), + TestContext.Current.CancellationToken); + + var prompt = model.Prompts[0]; + Assert.StartsWith("a table of the lookup_orders result", prompt, StringComparison.Ordinal); + Assert.Contains("`data.lookup_orders`", prompt, StringComparison.Ordinal); + Assert.Contains("SO-2", prompt, StringComparison.Ordinal); + } + + [Fact] + public async Task WithNothingAnswered_TheRequestGoesThroughUntouched() + { + RecordingRenderPort screen = new(); + using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = new TurnResults() }); + PresentCallingChatClient model = new(Card); + + var function = Build(new RecordingChatClientFactory(model)); + await function.InvokeAsync( + new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }), + TestContext.Current.CancellationToken); + + Assert.Equal("draw a card", model.Prompts[0]); + } + [Fact] public async Task AUsesNameNobodyShips_IsToldWhatIsShipped_IncludingTheShippedAgents() { @@ -250,12 +300,16 @@ public void TheVocabulary_TeachesEveryComponentTheValidatorAllows() private static AIFunction Build(RecordingChatClientFactory factory) => ShippedAgentBuilder.Build( - new DrawingAgentDefinition(), Declaration, new BuiltinToolPorts(factory)); + new DrawingAgentDefinition(), Declaration, new BuiltinToolPorts(factory, new FakeScriptRunner())); /// Builds one declared tool through . private static async Task Provide(ToolConfiguration tool, RecordingChatClientFactory? factory) + => await Provide(tool, factory, new FakeScriptRunner()); + + private static async Task Provide( + ToolConfiguration tool, RecordingChatClientFactory? factory, IScriptRunnerPort? scripts) { - BuiltinToolSource source = new(new BuiltinToolPorts(factory)); + BuiltinToolSource source = new(new BuiltinToolPorts(factory, scripts)); var context = new ToolSourceContext(new AgentCoreConfiguration { ApiVersion = "agentcore/v1", diff --git a/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs b/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs new file mode 100644 index 00000000..0878d5c1 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs @@ -0,0 +1,95 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tools.Drawing; +using Xunit; + +namespace AgentCore.Application.Tests.Tools; + +/// +/// : the few lines that tell the drawing model what its script's +/// data holds, so it never needs the rows themselves. +/// +public sealed class DrawingDataTests +{ + [Fact] + public void AnArrayOfObjects_IsDescribedByCountFieldsAndThreeSamples() + { + TurnResults results = new(); + results.Record("lookup_orders", Orders(100)); + + var text = DrawingData.Describe(results)!; + + Assert.Contains("`data.lookup_orders`", text, StringComparison.Ordinal); + Assert.Contains("100", text, StringComparison.Ordinal); + Assert.Contains("id, customer, total", text, StringComparison.Ordinal); + Assert.Contains("SO-1003", text, StringComparison.Ordinal); + Assert.DoesNotContain("SO-1004", text, StringComparison.Ordinal); + } + + [Fact] + public void AnObject_IsDescribedByItsFieldsAndItself() + { + TurnResults results = new(); + results.Record("lookup_order", JsonNode.Parse("""{"id":"SO-7","total":12.5}""")!); + + var text = DrawingData.Describe(results)!; + + Assert.Contains("`data.lookup_order`", text, StringComparison.Ordinal); + Assert.Contains("an object", text, StringComparison.Ordinal); + Assert.Contains("id, total", text, StringComparison.Ordinal); + Assert.Contains("SO-7", text, StringComparison.Ordinal); + } + + [Fact] + public void AToolCalledTwice_PointsAtAllOfItsAnswers() + { + TurnResults results = new(); + results.Record("lookup_order", JsonNode.Parse("""{"id":"SO-1"}""")!); + results.Record("lookup_order", JsonNode.Parse("""{"id":"SO-2"}""")!); + + var text = DrawingData.Describe(results)!; + + Assert.Contains("2 times", text, StringComparison.Ordinal); + Assert.Contains("`data.$all.lookup_order`", text, StringComparison.Ordinal); + Assert.Contains("SO-2", text, StringComparison.Ordinal); + } + + [Fact] + public void ALongString_IsCutShort() + { + TurnResults results = new(); + var essay = new string('x', 300); + results.Record("fetch_page", JsonNode.Parse($$"""{"body":"{{essay}}"}""")!); + + var text = DrawingData.Describe(results)!; + + Assert.DoesNotContain(essay, text, StringComparison.Ordinal); + Assert.Contains("…", text, StringComparison.Ordinal); + } + + [Fact] + public void DeepNesting_IsElided() + { + TurnResults results = new(); + results.Record("tree", JsonNode.Parse("""{"a":{"b":{"c":{"secret":"deep"}}}}""")!); + + var text = DrawingData.Describe(results)!; + + Assert.DoesNotContain("deep", text, StringComparison.Ordinal); + } + + [Fact] + public void NoResults_DescribesNothing() + { + Assert.Null(DrawingData.Describe(new TurnResults())); + Assert.Null(DrawingData.Describe(null)); + } + + private static JsonArray Orders(int count) + => new([.. Enumerable.Range(1, count).Select(i => (JsonNode)new JsonObject + { + ["id"] = $"SO-{1000 + i}", + ["customer"] = $"Customer {i}", + ["total"] = 10 * i, + })]); +} diff --git a/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs b/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs index 38c2de88..3684449b 100644 --- a/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; using AgentCore.Application.Tools; using AgentCore.Application.Tools.Drawing; @@ -10,9 +11,14 @@ namespace AgentCore.Application.Tests.Tools; /// -/// The inner present tool: it validates the tree itself and returns a section 8.7 error, so -/// the agent loop that calls it can retry on its own. +/// The inner present tool: it runs the model's script, validates the tree that came out, and +/// returns a section 8.7 error for either fault, so the agent loop that calls it can retry on its own. /// +/// +/// reads the code as the JSON the script would have returned, so +/// every tree below is written as the script's output. What a real script can do is +/// JintScriptRunnerTests' business. +/// public sealed class PresentToolTests { [Fact] @@ -21,7 +27,7 @@ public async Task Present_AValidTree_PublishesItAndReturnsTheReceipt() RecordingRenderPort screen = new(); using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(PresentTool.Create("draw"), """ + var result = await Invoke(Tool(), """ { "$type": "Card", "children": [{ "$type": "Text", "children": ["hi"] }] } """); @@ -35,7 +41,7 @@ public async Task Present_AnUnknownComponent_ReturnsAnErrorAndDrawsNothing() RecordingRenderPort screen = new(); using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(PresentTool.Create("draw"), """{ "$type": "Wombat" }"""); + var result = await Invoke(Tool(), """{ "$type": "Wombat" }"""); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -45,7 +51,7 @@ public async Task Present_AnUnknownComponent_ReturnsAnErrorAndDrawsNothing() [Fact] public async Task Present_NoScreen_ReturnsAnError() { - var result = await Invoke(PresentTool.Create("draw"), """{ "$type": "Card" }"""); + var result = await Invoke(Tool(), """{ "$type": "Card" }"""); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); } @@ -56,7 +62,7 @@ public async Task Present_ATreeThatIsNotAnObject_ReturnsAnErrorAndDrawsNothing() RecordingRenderPort screen = new(); using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(PresentTool.Create("draw"), "[1, 2, 3]"); + var result = await Invoke(Tool(), "[1, 2, 3]"); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -65,7 +71,7 @@ public async Task Present_ATreeThatIsNotAnObject_ReturnsAnErrorAndDrawsNothing() [Fact] public async Task Present_NamesTheDeclaredToolInTheErrorResult() { - var result = await Invoke(PresentTool.Create("draw"), """{ "$type": "Wombat" }"""); + var result = await Invoke(Tool(), """{ "$type": "Wombat" }"""); Assert.Equal("draw", result[ToolErrorResult.ToolProperty]!.GetValue()); } @@ -76,7 +82,7 @@ public async Task Present_ANumericType_ReturnsAnActionableErrorAndDrawsNothing() RecordingRenderPort screen = new(); using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(PresentTool.Create("draw"), """{ "$type": 123 }"""); + var result = await Invoke(Tool(), """{ "$type": 123 }"""); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -92,7 +98,7 @@ public async Task Present_ANonStringActionType_ReturnsAnActionableErrorAndDrawsN using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); var result = await Invoke( - PresentTool.Create("draw"), + Tool(), """{ "$type": "Button", "label": "Yes", "$action": { "type": 42 } }"""); Assert.Empty(screen.Published); @@ -115,7 +121,7 @@ public async Task Present_ANonStringActionTypeUnderAReservedKey_FinishesWithoutT using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); var result = await Invoke( - PresentTool.Create("draw"), """{ "$type": "Card", "$key": { "$action": { "type": 42 } } }"""); + Tool(), """{ "$type": "Card", "$key": { "$action": { "type": 42 } } }"""); // The validator accepts this tree, so the tool must finish it: one publish, one receipt, and // no button named off a type that is not a string. What must never happen again is the @@ -125,21 +131,81 @@ public async Task Present_ANonStringActionTypeUnderAReservedKey_FinishesWithoutT Assert.Contains("buttons: none", result["drew"]!.GetValue(), StringComparison.Ordinal); } + [Fact] + public async Task Present_AScriptThatFails_ReturnsItsErrorAndAsksForAnotherTry() + { + RecordingRenderPort screen = new(); + using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); + + var result = await Invoke(Tool(), "throw: data.orders is undefined"); + + Assert.Empty(screen.Published); + Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); + var message = result[ToolErrorResult.MessageProperty]!.GetValue(); + Assert.Contains("data.orders is undefined", message, StringComparison.Ordinal); + Assert.Contains(PresentTool.Name, message, StringComparison.Ordinal); + } + + [Fact] + public async Task Present_AScriptThatReturnsNothing_ReturnsAnErrorAndDrawsNothing() + { + RecordingRenderPort screen = new(); + using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); + + var result = await Invoke(Tool(), "null"); + + Assert.Empty(screen.Published); + Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); + Assert.Contains("return", result[ToolErrorResult.MessageProperty]!.GetValue(), StringComparison.Ordinal); + } + + [Fact] + public async Task TheScript_SeesThisTurnsToolResultsAsData_AndMayCallPresentItself() + { + RecordingRenderPort screen = new(); + TurnResults results = new(); + results.Record("lookup_orders", JsonNode.Parse("""[{"id":"SO-1"}]""")!); + using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = results }); + FakeScriptRunner runner = new(); + + await Invoke(PresentTool.Create("draw", runner), """{ "$type": "Text", "value": "hi" }"""); + + var request = Assert.Single(runner.Requests); + Assert.Equal("""[{"id":"SO-1"}]""", request.Data["lookup_orders"]!.ToJsonString()); + Assert.NotNull(request.Data[TurnResults.AllKey]); + Assert.Equal(PresentTool.Name, request.Emit); + } + + [Fact] + public async Task WithNoToolResultsThisTurn_TheScriptStillSeesAnEmptyData() + { + RecordingRenderPort screen = new(); + using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = null }); + FakeScriptRunner runner = new(); + + await Invoke(PresentTool.Create("draw", runner), """{ "$type": "Text", "value": "hi" }"""); + + var data = Assert.IsType(Assert.Single(runner.Requests).Data); + Assert.Empty(data[TurnResults.AllKey]!.AsObject()); + } + [Fact] public void TheTool_AdvertisesNoResultSchema() { - var tool = PresentTool.Create("draw"); + var tool = Tool(); Assert.Equal(PresentTool.Name, tool.Name); Assert.Null(tool.ReturnJsonSchema); } - /// Calls the tool with one tree argument and reads the result as a node tree. - private static async Task Invoke(AIFunction tool, string treeJson) + private static AIFunction Tool() => PresentTool.Create("draw", new FakeScriptRunner()); + + /// Calls the tool with one script and reads the result as a node tree. + private static async Task Invoke(AIFunction tool, string code) { var arguments = new AIFunctionArguments { - ["tree"] = JsonSerializer.Deserialize(treeJson), + ["code"] = code, }; var result = await tool.InvokeAsync(arguments, TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs b/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs index 7b6a16da..9bbeef8c 100644 --- a/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs @@ -284,5 +284,7 @@ public FakeDefinition(string? missingPort = null, IReadOnlyList? innerTo public IReadOnlyList InnerTools(ToolConfiguration tool, BuiltinToolPorts ports) => _innerTools; public string? MissingPort(BuiltinToolPorts ports) => _missingPort; + + public string Compose(string query) => query; } } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index 5459f036..32e3aa82 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -9,6 +9,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Evaluation; +using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.Application.Secrets; diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetReadTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetReadTests.cs index 91061aea..195ff7bb 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetReadTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetReadTests.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; diff --git a/tests/AgentCore.Infrastructure.Tests/Scripting/Jint/JintScriptRunnerTests.cs b/tests/AgentCore.Infrastructure.Tests/Scripting/Jint/JintScriptRunnerTests.cs new file mode 100644 index 00000000..607ebf45 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Scripting/Jint/JintScriptRunnerTests.cs @@ -0,0 +1,158 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using AgentCore.Application.Ports; +using AgentCore.Application.Scripting; +using AgentCore.Infrastructure.Scripting.Jint; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Scripting.Jint; + +/// +/// : what a model-written script can and cannot do. The expected +/// values are ECMAScript, not this code. +/// +public sealed class JintScriptRunnerTests +{ + private static readonly JsonNode Orders = JsonNode.Parse(""" + [ { "id": "SO-1", "total": 10.5, "date": "2026-03-01" }, + { "id": "SO-2", "total": 20, "date": "2026-03-09" }, + { "id": "SO-3", "total": 30, "date": "2026-04-02" } ] + """)!; + + [Fact] + public async Task ABody_ThatReturns_HandsBackWhatItReturnedAsJson() + { + var result = await Run("return { n: data.length, sum: data.reduce(function (a, o) { return a + o.total; }, 0) };"); + + Assert.Null(result.Error); + Assert.Equal("""{"n":3,"sum":60.5}""", result.Value!.ToJsonString()); + } + + [Fact] + public async Task ABareArrowFunction_IsCalledWithTheData() + { + var result = await Run("(data) => ({ first: data[0].id })"); + + Assert.Null(result.Error); + Assert.Equal("""{"first":"SO-1"}""", result.Value!.ToJsonString()); + } + + [Fact] + public async Task ANamedFunctionDeclaration_StillReadsAsABody() + { + // A body that starts with a helper function is a body, not an expression to call. + var result = await Run("function name(o) { return o.id; }\nreturn data.map(name);"); + + Assert.Null(result.Error); + Assert.Equal("""["SO-1","SO-2","SO-3"]""", result.Value!.ToJsonString()); + } + + [Fact] + public async Task AMarkdownFence_IsIgnored() + { + var result = await Run("```js\nreturn data.length;\n```"); + + Assert.Null(result.Error); + Assert.Equal("3", result.Value!.ToJsonString()); + } + + [Fact] + public async Task ACallToTheEmitFunction_CountsAsReturning() + { + var result = await Run("present({ ids: data.map(function (o) { return o.id; }) });", emit: "present"); + + Assert.Null(result.Error); + Assert.Equal("""{"ids":["SO-1","SO-2","SO-3"]}""", result.Value!.ToJsonString()); + } + + [Fact] + public async Task RedeclaringData_ShadowsItInsteadOfFailing() + { + // Small models write `const data = [...]` at the top of their body. That shadows the + // outer binding in ECMAScript, so it must run, not clash. + var result = await Run("const data = [1, 2]; return data.length;"); + + Assert.Null(result.Error); + Assert.Equal("2", result.Value!.ToJsonString()); + } + + [Fact] + public async Task ABody_ThatReturnsNothing_HandsBackNoValueAndNoError() + { + var result = await Run("var x = 1;"); + + Assert.Null(result.Error); + Assert.Null(result.Value); + } + + [Fact] + public async Task AThrow_ComesBackAsAnErrorNamingTheMessage() + { + var result = await Run("throw new Error('no such column');"); + + Assert.Null(result.Value); + Assert.Contains("no such column", result.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task ASyntaxError_ComesBackAsAnError() + { + var result = await Run("return { $type: 'Card', ;"); + + Assert.Null(result.Value); + Assert.NotNull(result.Error); + } + + [Fact] + public async Task AnEndlessLoop_IsStoppedInsideTheBudget() + { + var clock = Stopwatch.StartNew(); + + var result = await Run("while (true) { }"); + + Assert.NotNull(result.Error); + Assert.True(clock.Elapsed < TimeSpan.FromSeconds(10), $"took {clock.Elapsed}"); + } + + [Fact] + public async Task ARunawayAllocation_IsStopped() + { + var result = await Run("var a = []; while (true) { a.push(new Array(100000).fill('x')); }"); + + Assert.NotNull(result.Error); + } + + [Fact] + public async Task TheHost_IsOutOfReach() + { + var result = await Run("return [typeof require, typeof fetch, typeof process, typeof System, typeof importScripts];"); + + Assert.Null(result.Error); + Assert.Equal("""["undefined","undefined","undefined","undefined","undefined"]""", result.Value!.ToJsonString()); + } + + [Fact] + public async Task ADateOnlyString_ReadsBackItsOwnMonth_WhereverTheHostIs() + { + // ECMAScript parses "2026-03-01" as UTC midnight. On a host west of Greenwich a local-time + // getMonth() answers February; the runner pins the engine to UTC so it answers March. + var result = await Run("return new Date(data[0].date).getMonth();"); + + Assert.Null(result.Error); + Assert.Equal("2", result.Value!.ToJsonString()); + } + + [Fact] + public async Task TheCallersCancellation_Throws() + { + using CancellationTokenSource cancelled = new(); + await cancelled.CancelAsync(); + + await Assert.ThrowsAnyAsync( + async () => await new JintScriptRunner().RunAsync(new ScriptRequest("return 1;", Orders), cancelled.Token)); + } + + private static async Task Run(string code, string? emit = null) + => await new JintScriptRunner().RunAsync( + new ScriptRequest(code, Orders) { Emit = emit }, TestContext.Current.CancellationToken); +} From baf6d5e584aa4ce9771743b556229035af262b97 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 15:49:40 -0600 Subject: [PATCH 04/32] feat: Introduce agent memory and file configurations --- Directory.Packages.props | 28 +-- .../Schema/AgentLoopConfiguration.cs | 27 +++ .../Schema/AgentMemoryConfiguration.cs | 34 ++++ .../Schema/AgentShellConfiguration.cs | 40 ++++ .../Schema/AgentsConfiguration.cs | 36 ++++ .../Schema/ApprovalConfiguration.cs | 14 ++ .../Schema/agentcore-v1.schema.json | 190 ++++++++++++++++++ .../Validation/ConfigurationValidator.cs | 12 ++ .../PublicAPI.Unshipped.txt | 125 ++++++++++++ .../Configuration/AgenticKeySchemaTests.cs | 83 ++++++++ .../ConfigurationRoundTripTests.cs | 68 +++++++ .../ConfigurationSchemaValidatorTests.cs | 110 ++++++++++ .../Validation/ConfigurationValidatorTests.cs | 18 ++ 13 files changed, 771 insertions(+), 14 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs create mode 100644 src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs create mode 100644 src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs create mode 100644 src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs create mode 100644 tests/AgentCore.Application.Tests/Configuration/AgenticKeySchemaTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index fb862aff..af6e4163 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,29 +7,29 @@ - - - + + + - - - + + + - - + + - + - + @@ -55,10 +55,10 @@ - - - - + + + + diff --git a/src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs new file mode 100644 index 00000000..6e1716ad --- /dev/null +++ b/src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs @@ -0,0 +1,27 @@ +namespace AgentCore.Application.Configuration.Schema; + +/// +/// The options one loop.until: entry carries. Empty today: the entry names the condition by +/// its key. A condition that ever takes options adds members here. +/// +public sealed record LoopConditionOptions { } + +/// One loop.until: entry. Exactly one member is set. +public sealed record LoopUntilConfiguration +{ + /// Gets the condition that the todo list drains to empty. Set, or . + public LoopConditionOptions? Todos { get; init; } + + /// Gets the condition that every background task finishes. Set, or . + public LoopConditionOptions? Background { get; init; } +} + +/// One agent's loop: block: how many model rounds the agent owns may run, and when none stays. +public sealed record LoopConfiguration +{ + /// Gets the most rounds the loop may run, or for the framework default. + public int? MaxRounds { get; init; } + + /// Gets the conditions that end the loop early, in document order, or for none. + public IReadOnlyList? Until { get; init; } +} \ No newline at end of file diff --git a/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs new file mode 100644 index 00000000..4b9247a1 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs @@ -0,0 +1,34 @@ +namespace AgentCore.Application.Configuration.Schema; + +/// The stores an agentic file block may name. +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. + /// + 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. +/// +public sealed record AgentMemoryConfiguration +{ + /// Gets the store the file-memory tools reach. + public required AgentFileStoreKind Store { get; init; } +} + +/// +/// One agent's files: block: the file_access_* tools over a store. Today every +/// file_access_* tool is approval-required by default, reads included (§3.6). +/// +public sealed record AgentFilesConfiguration +{ + /// Gets the store the file-access tools reach. + public required AgentFileStoreKind Store { get; init; } + + /// Gets whether the write tools are enabled. write: false leaves read, read_lines, ls, grep. + public bool Write { get; init; } = true; +} \ No newline at end of file diff --git a/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs new file mode 100644 index 00000000..9f76730f --- /dev/null +++ b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs @@ -0,0 +1,40 @@ +namespace AgentCore.Application.Configuration.Schema; + +/// The executors a shell: block may name. +public enum ShellKind +{ + /// A throwaway container: network "none", read-only root, nobody user (§3.6). + Docker, + + /// The process's own executable environment, confined to the workspace directory. + Local, +} + +/// +/// One agent's shell policy: the regexes that refuse a command before it dispatches. A guardrail +/// for the model, not a security boundary — the executor confinement is the boundary. +/// +public sealed record ShellPolicyConfiguration +{ + /// Gets the patterns whose match refuses a command. + public IReadOnlyList Deny { get; init; } = []; + + /// Gets the patterns an allowed command must match. + public IReadOnlyList Allow { get; init; } = []; +} + +/// One agent's shell: block: one executor per call, 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 + /// no default exists here (§4.5.1). + /// + public required ShellKind Kind { get; init; } + + /// Gets the command policy, or for none. + public ShellPolicyConfiguration? Policy { get; init; } + + /// Gets how long one command may run, or for the executor default. + public int? TimeoutSeconds { get; init; } +} \ No newline at end of file diff --git a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs index f2948f57..db0045ed 100644 --- a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs @@ -50,6 +50,15 @@ public sealed record AgentDefaults /// Gets the shared compaction: block, or when the document declares none. public CompactionConfiguration? Compaction { get; init; } + + /// Gets whether agents inherit the todo tools, or to name nothing. + public bool? Todos { get; init; } + + /// Gets whether agents inherit the mode tools, or to name nothing. + public bool? Mode { get; init; } + + /// Gets the shared approval: block, or when the document declares none. + public ApprovalConfiguration? Approval { get; init; } } /// @@ -77,6 +86,33 @@ public sealed record AgentConfiguration /// Gets this agent's compaction: block, or to inherit key by key. public CompactionConfiguration? Compaction { get; init; } + + /// Gets whether this agent gets the todo tools, or to inherit. + public bool? Todos { get; init; } + + /// Gets whether this agent gets the mode tools, or to inherit. + public bool? Mode { get; init; } + + /// Gets this agent's memory: block, or for none. + public AgentMemoryConfiguration? Memory { get; init; } + + /// Gets this agent's files: block, or for none. + public AgentFilesConfiguration? Files { get; init; } + + /// + /// Gets this agent's shell: block, or for none. One executor per + /// call, never a process singleton. + /// + public ShellConfiguration? Shell { get; init; } + + /// Gets this agent's approval: block, or to inherit key by key. + public ApprovalConfiguration? Approval { get; init; } + + /// Gets the ids of the background children this agent may start. Same list as agents.items. + public IReadOnlyList Background { get; init; } = []; + + /// Gets this agent's loop: block, or for none. + public LoopConfiguration? Loop { get; init; } } /// diff --git a/src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs new file mode 100644 index 00000000..beae44bf --- /dev/null +++ b/src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs @@ -0,0 +1,14 @@ +namespace AgentCore.Application.Configuration.Schema; + +/// +/// One agent's approval: block: the standing rules that answer an approval request before it +/// surfaces. Everything a rule does not name still asks. +/// +public sealed record ApprovalConfiguration +{ + /// + /// Gets the tool-name patterns a request never surfaces for. A pattern names one tool exactly, + /// or a prefix with a trailing *. + /// + public IReadOnlyList Auto { get; init; } = []; +} \ No newline at end of file diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index 5636e7b2..b3ea57de 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -661,6 +661,18 @@ }, "compaction": { "$ref": "#/$defs/compaction" + }, + "todos": { + "type": "boolean", + "description": "Whether agents inherit the todos tools." + }, + "mode": { + "type": "boolean", + "description": "Whether agents inherit the mode tools." + }, + "approval": { + "$ref": "#/$defs/approval", + "description": "The standing approval rules every agent inherits." } } }, @@ -719,6 +731,38 @@ "compaction": { "$ref": "#/$defs/compaction" }, + "todos": { + "type": "boolean", + "description": "The agent gets the todos tools (TodoProvider)." + }, + "mode": { + "type": "boolean", + "description": "The agent gets the mode tools (AgentModeProvider)." + }, + "memory": { + "$ref": "#/$defs/memory", + "description": "The file-memory tools over a store." + }, + "files": { + "$ref": "#/$defs/files", + "description": "The file-access tools over a store." + }, + "shell": { + "$ref": "#/$defs/shell", + "description": "One shell executor per call." + }, + "approval": { + "$ref": "#/$defs/approval", + "description": "The standing approval rules; everything else still asks." + }, + "background": { + "$ref": "#/$defs/background", + "description": "The background children this agent may start." + }, + "loop": { + "$ref": "#/$defs/loop", + "description": "How the agent's own loop runs." + }, "tools": { "type": "array", "items": { @@ -759,6 +803,152 @@ "foldResultChars": { "type": "integer", "minimum": 1 } } }, + "agentStore": { + "type": "string", + "enum": [ + "workspace" + ], + "description": "The host-created per-call directory, deleted with the call. The only store today." + }, + "approval": { + "type": "object", + "additionalProperties": false, + "properties": { + "auto": { + "type": "array", + "items": { + "$ref": "#/$defs/toolPattern" + } + } + } + }, + "background": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/identifier" + }, + "description": "The ids of the background children this agent may start. Same list as agents.items." + }, + "files": { + "type": "object", + "required": [ + "store" + ], + "additionalProperties": false, + "properties": { + "store": { + "$ref": "#/$defs/agentStore" + }, + "write": { + "type": "boolean", + "default": true, + "description": "false leaves the read tools only." + } + } + }, + "loop": { + "type": "object", + "additionalProperties": false, + "properties": { + "maxRounds": { + "type": "integer", + "minimum": 1 + }, + "until": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/loopUntil" + }, + "description": "The conditions that end the loop early, in document order." + } + } + }, + "loopUntil": { + "type": "object", + "additionalProperties": false, + "minProperties": 1, + "maxProperties": 1, + "description": "Exactly one condition per entry.", + "properties": { + "todos": { + "type": "object", + "description": "The todo list drains to empty." + }, + "background": { + "type": "object", + "description": "Every background task finishes." + } + } + }, + "memory": { + "type": "object", + "required": [ + "store" + ], + "additionalProperties": false, + "properties": { + "store": { + "$ref": "#/$defs/agentStore" + } + } + }, + "shell": { + "type": "object", + "required": [ + "kind" + ], + "additionalProperties": false, + "properties": { + "kind": { + "$ref": "#/$defs/shellKind" + }, + "policy": { + "$ref": "#/$defs/shellPolicy" + }, + "timeoutSeconds": { + "type": "integer", + "minimum": 1 + } + } + }, + "shellKind": { + "type": "string", + "enum": [ + "docker", + "local" + ], + "description": "Where a shell runs is the consumer's call, so the document names one: there is no default." + }, + "shellPattern": { + "type": "string", + "minLength": 1, + "description": "A pattern the executor policy compiles. A guardrail for the model, not a security boundary." + }, + "shellPolicy": { + "type": "object", + "additionalProperties": false, + "properties": { + "deny": { + "type": "array", + "items": { + "$ref": "#/$defs/shellPattern" + } + }, + "allow": { + "type": "array", + "items": { + "$ref": "#/$defs/shellPattern" + } + } + } + }, + "toolPattern": { + "type": "string", + "minLength": 1, + "description": "Names one tool exactly, or a prefix with a trailing *." + }, "policy": { "type": "object", "required": [ diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index 7e337529..ed9e20ff 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -223,6 +223,18 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar 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")); + } + } } if (configuration.Policy is { } policy) diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 8169a511..b34816f0 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -290,19 +290,35 @@ AgentCore.Application.Configuration.Parsing.YamlToJson AgentCore.Application.Configuration.Schema.AgentConfiguration AgentCore.Application.Configuration.Schema.AgentConfiguration.$() -> AgentCore.Application.Configuration.Schema.AgentConfiguration! AgentCore.Application.Configuration.Schema.AgentConfiguration.AgentConfiguration() -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Approval.get -> AgentCore.Application.Configuration.Schema.ApprovalConfiguration? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Approval.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Background.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Configuration.Schema.AgentConfiguration.Background.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Compaction.get -> AgentCore.Application.Configuration.Schema.CompactionConfiguration? AgentCore.Application.Configuration.Schema.AgentConfiguration.Compaction.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Equals(AgentCore.Application.Configuration.Schema.AgentConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.AgentConfiguration.Files.get -> AgentCore.Application.Configuration.Schema.AgentFilesConfiguration? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Files.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Id.get -> string! AgentCore.Application.Configuration.Schema.AgentConfiguration.Id.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Instructions.get -> string? AgentCore.Application.Configuration.Schema.AgentConfiguration.Instructions.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Knowledge.get -> AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration? AgentCore.Application.Configuration.Schema.AgentConfiguration.Knowledge.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Loop.get -> AgentCore.Application.Configuration.Schema.LoopConfiguration? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Loop.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Memory.get -> AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Memory.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Mode.get -> bool? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Mode.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Model.get -> AgentCore.Application.Configuration.Schema.ModelReference? AgentCore.Application.Configuration.Schema.AgentConfiguration.Model.init -> void +AgentCore.Application.Configuration.Schema.AgentConfiguration.Shell.get -> AgentCore.Application.Configuration.Schema.ShellConfiguration? +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.Todos.get -> bool? +AgentCore.Application.Configuration.Schema.AgentConfiguration.Todos.init -> void AgentCore.Application.Configuration.Schema.AgentConfiguration.Tools.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Configuration.Schema.AgentConfiguration.Tools.init -> void AgentCore.Application.Configuration.Schema.AgentCoreConfiguration @@ -342,6 +358,8 @@ AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.Tools.init -> AgentCore.Application.Configuration.Schema.AgentDefaults AgentCore.Application.Configuration.Schema.AgentDefaults.$() -> AgentCore.Application.Configuration.Schema.AgentDefaults! AgentCore.Application.Configuration.Schema.AgentDefaults.AgentDefaults() -> void +AgentCore.Application.Configuration.Schema.AgentDefaults.Approval.get -> AgentCore.Application.Configuration.Schema.ApprovalConfiguration? +AgentCore.Application.Configuration.Schema.AgentDefaults.Approval.init -> void AgentCore.Application.Configuration.Schema.AgentDefaults.Compaction.get -> AgentCore.Application.Configuration.Schema.CompactionConfiguration? AgentCore.Application.Configuration.Schema.AgentDefaults.Compaction.init -> void AgentCore.Application.Configuration.Schema.AgentDefaults.Equals(AgentCore.Application.Configuration.Schema.AgentDefaults? other) -> bool @@ -349,8 +367,22 @@ AgentCore.Application.Configuration.Schema.AgentDefaults.Instructions.get -> str AgentCore.Application.Configuration.Schema.AgentDefaults.Instructions.init -> void AgentCore.Application.Configuration.Schema.AgentDefaults.Knowledge.get -> AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration? AgentCore.Application.Configuration.Schema.AgentDefaults.Knowledge.init -> void +AgentCore.Application.Configuration.Schema.AgentDefaults.Mode.get -> bool? +AgentCore.Application.Configuration.Schema.AgentDefaults.Mode.init -> void AgentCore.Application.Configuration.Schema.AgentDefaults.Model.get -> AgentCore.Application.Configuration.Schema.ModelReference? AgentCore.Application.Configuration.Schema.AgentDefaults.Model.init -> void +AgentCore.Application.Configuration.Schema.AgentDefaults.Todos.get -> bool? +AgentCore.Application.Configuration.Schema.AgentDefaults.Todos.init -> void +AgentCore.Application.Configuration.Schema.AgentFileStoreKind +AgentCore.Application.Configuration.Schema.AgentFileStoreKind.Workspace = 0 -> AgentCore.Application.Configuration.Schema.AgentFileStoreKind +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.$() -> AgentCore.Application.Configuration.Schema.AgentFilesConfiguration! +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.AgentFilesConfiguration() -> void +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.Equals(AgentCore.Application.Configuration.Schema.AgentFilesConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.Store.get -> AgentCore.Application.Configuration.Schema.AgentFileStoreKind +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.Store.init -> void +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.Write.get -> bool +AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.Write.init -> void AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.$() -> AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration! AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.AgentKnowledgeConfiguration() -> void @@ -363,6 +395,12 @@ AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Mode.get AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Mode.init -> void AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Scoped.get -> bool? AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Scoped.init -> void +AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration +AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.$() -> AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration! +AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.AgentMemoryConfiguration() -> void +AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.Equals(AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.Store.get -> AgentCore.Application.Configuration.Schema.AgentFileStoreKind +AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.Store.init -> void AgentCore.Application.Configuration.Schema.AgentsConfiguration AgentCore.Application.Configuration.Schema.AgentsConfiguration.$() -> AgentCore.Application.Configuration.Schema.AgentsConfiguration! AgentCore.Application.Configuration.Schema.AgentsConfiguration.AgentsConfiguration() -> void @@ -371,6 +409,12 @@ AgentCore.Application.Configuration.Schema.AgentsConfiguration.Defaults.init -> AgentCore.Application.Configuration.Schema.AgentsConfiguration.Equals(AgentCore.Application.Configuration.Schema.AgentsConfiguration? other) -> bool AgentCore.Application.Configuration.Schema.AgentsConfiguration.Items.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Configuration.Schema.AgentsConfiguration.Items.init -> void +AgentCore.Application.Configuration.Schema.ApprovalConfiguration +AgentCore.Application.Configuration.Schema.ApprovalConfiguration.$() -> AgentCore.Application.Configuration.Schema.ApprovalConfiguration! +AgentCore.Application.Configuration.Schema.ApprovalConfiguration.ApprovalConfiguration() -> void +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 @@ -632,6 +676,26 @@ AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.ReasoningEff AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.ReasoningEffort.init -> void AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.WebSearch.get -> bool? AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.WebSearch.init -> void +AgentCore.Application.Configuration.Schema.LoopConditionOptions +AgentCore.Application.Configuration.Schema.LoopConditionOptions.$() -> AgentCore.Application.Configuration.Schema.LoopConditionOptions! +AgentCore.Application.Configuration.Schema.LoopConditionOptions.Equals(AgentCore.Application.Configuration.Schema.LoopConditionOptions? other) -> bool +AgentCore.Application.Configuration.Schema.LoopConditionOptions.LoopConditionOptions() -> void +AgentCore.Application.Configuration.Schema.LoopConfiguration +AgentCore.Application.Configuration.Schema.LoopConfiguration.$() -> AgentCore.Application.Configuration.Schema.LoopConfiguration! +AgentCore.Application.Configuration.Schema.LoopConfiguration.Equals(AgentCore.Application.Configuration.Schema.LoopConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.LoopConfiguration.LoopConfiguration() -> void +AgentCore.Application.Configuration.Schema.LoopConfiguration.MaxRounds.get -> int? +AgentCore.Application.Configuration.Schema.LoopConfiguration.MaxRounds.init -> void +AgentCore.Application.Configuration.Schema.LoopConfiguration.Until.get -> System.Collections.Generic.IReadOnlyList? +AgentCore.Application.Configuration.Schema.LoopConfiguration.Until.init -> void +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.$() -> AgentCore.Application.Configuration.Schema.LoopUntilConfiguration! +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.Background.get -> AgentCore.Application.Configuration.Schema.LoopConditionOptions? +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.Background.init -> void +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.Equals(AgentCore.Application.Configuration.Schema.LoopUntilConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.LoopUntilConfiguration() -> void +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.Todos.get -> AgentCore.Application.Configuration.Schema.LoopConditionOptions? +AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.Todos.init -> void AgentCore.Application.Configuration.Schema.McpAllowEntry AgentCore.Application.Configuration.Schema.McpAllowEntry.$() -> AgentCore.Application.Configuration.Schema.McpAllowEntry! AgentCore.Application.Configuration.Schema.McpAllowEntry.As.get -> string? @@ -718,6 +782,27 @@ AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Telemetry.init AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Telephony.get -> AgentCore.Application.Configuration.Schema.VendorProviderConfiguration? AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Telephony.init -> void AgentCore.Application.Configuration.Schema.ReservedStateSlots +AgentCore.Application.Configuration.Schema.ShellConfiguration +AgentCore.Application.Configuration.Schema.ShellConfiguration.$() -> AgentCore.Application.Configuration.Schema.ShellConfiguration! +AgentCore.Application.Configuration.Schema.ShellConfiguration.Equals(AgentCore.Application.Configuration.Schema.ShellConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.ShellConfiguration.Kind.get -> AgentCore.Application.Configuration.Schema.ShellKind +AgentCore.Application.Configuration.Schema.ShellConfiguration.Kind.init -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.Policy.get -> AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration? +AgentCore.Application.Configuration.Schema.ShellConfiguration.Policy.init -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.ShellConfiguration() -> void +AgentCore.Application.Configuration.Schema.ShellConfiguration.TimeoutSeconds.get -> int? +AgentCore.Application.Configuration.Schema.ShellConfiguration.TimeoutSeconds.init -> void +AgentCore.Application.Configuration.Schema.ShellKind +AgentCore.Application.Configuration.Schema.ShellKind.Docker = 0 -> AgentCore.Application.Configuration.Schema.ShellKind +AgentCore.Application.Configuration.Schema.ShellKind.Local = 1 -> AgentCore.Application.Configuration.Schema.ShellKind +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.$() -> AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration! +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.Allow.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.Allow.init -> void +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.Deny.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.Deny.init -> void +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.Equals(AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.ShellPolicyConfiguration() -> void AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.$() -> AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.Equals(AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? other) -> bool @@ -1473,12 +1558,21 @@ override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.ToStr override AgentCore.Application.Configuration.Schema.AgentDefaults.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.AgentDefaults.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.AgentDefaults.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.ToString() -> string! override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.ToString() -> string! override AgentCore.Application.Configuration.Schema.AgentsConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.AgentsConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.AgentsConfiguration.ToString() -> string! +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! @@ -1542,6 +1636,15 @@ override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfigurati override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.LoopConditionOptions.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.LoopConditionOptions.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.LoopConditionOptions.ToString() -> string! +override AgentCore.Application.Configuration.Schema.LoopConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.LoopConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.LoopConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.ToString() -> string! override AgentCore.Application.Configuration.Schema.McpAllowEntry.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.McpAllowEntry.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.McpAllowEntry.ToString() -> string! @@ -1560,6 +1663,12 @@ override AgentCore.Application.Configuration.Schema.PolicyConfiguration.ToString override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ShellConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ShellConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ShellConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.ToString() -> string! override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.GetHashCode() -> int override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.ToString() -> string! @@ -1706,10 +1815,16 @@ static AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.operato static AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.operator ==(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration? left, AgentCore.Application.Configuration.Schema.AgentCoreConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.AgentDefaults.operator !=(AgentCore.Application.Configuration.Schema.AgentDefaults? left, AgentCore.Application.Configuration.Schema.AgentDefaults? right) -> bool static AgentCore.Application.Configuration.Schema.AgentDefaults.operator ==(AgentCore.Application.Configuration.Schema.AgentDefaults? left, AgentCore.Application.Configuration.Schema.AgentDefaults? right) -> bool +static AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.operator !=(AgentCore.Application.Configuration.Schema.AgentFilesConfiguration? left, AgentCore.Application.Configuration.Schema.AgentFilesConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.AgentFilesConfiguration.operator ==(AgentCore.Application.Configuration.Schema.AgentFilesConfiguration? left, AgentCore.Application.Configuration.Schema.AgentFilesConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.operator !=(AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration? left, AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.operator ==(AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration? left, AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.operator !=(AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration? left, AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration.operator ==(AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration? left, AgentCore.Application.Configuration.Schema.AgentMemoryConfiguration? right) -> bool 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.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.CompactionConfiguration.operator !=(AgentCore.Application.Configuration.Schema.CompactionConfiguration? left, AgentCore.Application.Configuration.Schema.CompactionConfiguration? right) -> bool @@ -1754,6 +1869,12 @@ static AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration static AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.operator ==(AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.LlmProviderConfiguration? left, AgentCore.Application.Configuration.Schema.LlmProviderConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.operator ==(AgentCore.Application.Configuration.Schema.LlmProviderConfiguration? left, AgentCore.Application.Configuration.Schema.LlmProviderConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.LoopConditionOptions.operator !=(AgentCore.Application.Configuration.Schema.LoopConditionOptions? left, AgentCore.Application.Configuration.Schema.LoopConditionOptions? right) -> bool +static AgentCore.Application.Configuration.Schema.LoopConditionOptions.operator ==(AgentCore.Application.Configuration.Schema.LoopConditionOptions? left, AgentCore.Application.Configuration.Schema.LoopConditionOptions? right) -> bool +static AgentCore.Application.Configuration.Schema.LoopConfiguration.operator !=(AgentCore.Application.Configuration.Schema.LoopConfiguration? left, AgentCore.Application.Configuration.Schema.LoopConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.LoopConfiguration.operator ==(AgentCore.Application.Configuration.Schema.LoopConfiguration? left, AgentCore.Application.Configuration.Schema.LoopConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.operator !=(AgentCore.Application.Configuration.Schema.LoopUntilConfiguration? left, AgentCore.Application.Configuration.Schema.LoopUntilConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.LoopUntilConfiguration.operator ==(AgentCore.Application.Configuration.Schema.LoopUntilConfiguration? left, AgentCore.Application.Configuration.Schema.LoopUntilConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.McpAllowEntry.operator !=(AgentCore.Application.Configuration.Schema.McpAllowEntry? left, AgentCore.Application.Configuration.Schema.McpAllowEntry? right) -> bool static AgentCore.Application.Configuration.Schema.McpAllowEntry.operator ==(AgentCore.Application.Configuration.Schema.McpAllowEntry? left, AgentCore.Application.Configuration.Schema.McpAllowEntry? right) -> bool static AgentCore.Application.Configuration.Schema.McpRetryConfiguration.operator !=(AgentCore.Application.Configuration.Schema.McpRetryConfiguration? left, AgentCore.Application.Configuration.Schema.McpRetryConfiguration? right) -> bool @@ -1768,6 +1889,10 @@ static AgentCore.Application.Configuration.Schema.ProvidersConfiguration.operato static AgentCore.Application.Configuration.Schema.ProvidersConfiguration.operator ==(AgentCore.Application.Configuration.Schema.ProvidersConfiguration? left, AgentCore.Application.Configuration.Schema.ProvidersConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.ReservedStateSlots.All.get -> System.Collections.Generic.IReadOnlyList! static AgentCore.Application.Configuration.Schema.ReservedStateSlots.Contains(string! name) -> bool +static AgentCore.Application.Configuration.Schema.ShellConfiguration.operator !=(AgentCore.Application.Configuration.Schema.ShellConfiguration? left, AgentCore.Application.Configuration.Schema.ShellConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.ShellConfiguration.operator ==(AgentCore.Application.Configuration.Schema.ShellConfiguration? left, AgentCore.Application.Configuration.Schema.ShellConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.operator !=(AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration? left, AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration.operator ==(AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration? left, AgentCore.Application.Configuration.Schema.ShellPolicyConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? left, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.operator ==(AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? left, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.StageConfiguration.operator !=(AgentCore.Application.Configuration.Schema.StageConfiguration? left, AgentCore.Application.Configuration.Schema.StageConfiguration? right) -> bool diff --git a/tests/AgentCore.Application.Tests/Configuration/AgenticKeySchemaTests.cs b/tests/AgentCore.Application.Tests/Configuration/AgenticKeySchemaTests.cs new file mode 100644 index 00000000..b15f8990 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Configuration/AgenticKeySchemaTests.cs @@ -0,0 +1,83 @@ +using System.Text.Json.Nodes; +using Xunit; + +namespace AgentCore.Application.Tests.Configuration; + +/// +/// The agentic keys and the values agentcore-v1.schema.json allows for them. The schema hardcodes +/// every spelling, so this is what catches the day someone changes a record and forgets the +/// document it describes. +/// +public sealed class AgenticKeySchemaTests +{ + [Fact] + public void TheSchema_DeclaresEveryAgenticKeyTheRecordCarries() + { + var agent = Schema()["$defs"]!["agent"]!["properties"]!; + + List keys = ["todos", "mode", "memory", "files", "shell", "approval", "background", "loop"]; + foreach (string key in keys) + { + Assert.True(agent[key] is not null, $"agentcore-v1.schema.json does not declare 'agent.{key}'."); + } + } + + [Fact] + public void TheDefaults_DeclareTheInheritableKeysTheRecordCarries() + { + var defaults = Schema()["$defs"]!["agents"]!["properties"]!["defaults"]!["properties"]!; + + List keys = ["todos", "mode", "approval"]; + foreach (string key in keys) + { + Assert.True(defaults[key] is not null, $"agentcore-v1.schema.json does not declare 'defaults.{key}'."); + } + } + + [Fact] + public void TheStoresTheSchemaAllows_AreWorkspace() + { + Assert.True(JsonNode.DeepEquals(Enum("agentStore"), Parse("[\"workspace\"]"))); + } + + [Fact] + public void TheShellKindsTheSchemaAllows_AreDockerAndLocal() + { + Assert.True(JsonNode.DeepEquals(Enum("shellKind"), Parse("[\"docker\", \"local\"]"))); + } + + [Fact] + public void TheLoopConditionsTheSchemaAllows_AreTodosAndBackground() + { + var until = Schema()["$defs"]!["loopUntil"]!["properties"]!; + + Assert.True(until["todos"] is not null); + Assert.True(until["background"] is not null); + } + + private static JsonNode Enum(string name) + => Schema()["$defs"]![name]!["enum"]!; + + private static JsonNode Parse(string json) + => JsonNode.Parse(json)!; + + private static JsonNode Schema() + { + var path = Path.Combine(RepositoryRoot(), "src", "AgentCore.Application", "Configuration", "Schema", "agentcore-v1.schema.json"); + Assert.True(File.Exists(path), $"The shipped schema is missing at '{path}'."); + + return JsonNode.Parse(File.ReadAllText(path))!; + } + + private static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "AgentCore.sln"))) + { + directory = directory.Parent; + } + + Assert.NotNull(directory); + return directory!.FullName; + } +} \ No newline at end of file diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationRoundTripTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationRoundTripTests.cs index 5894175a..86bc7fc1 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationRoundTripTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationRoundTripTests.cs @@ -204,4 +204,72 @@ public void APlainFloatScalar_ReadsAsANumber() Assert.Equal(0.3, document["value"]!.GetValue()); } + + [Fact] + public void TheAgenticKeys_ReadTheSameFromYamlAndFromJson() + { + const string yaml = """ + apiVersion: agentcore/v1 + name: agentic + agents: + defaults: + todos: true + mode: true + approval: { auto: [get_time] } + items: + - id: coder + todos: true + mode: true + memory: { store: workspace } + files: { store: workspace, write: false } + shell: + kind: local + policy: { deny: ["^rm "] } + timeoutSeconds: 30 + approval: { auto: [get_time, "file_access_read*"] } + background: [searcher] + loop: + maxRounds: 5 + until: + - todos: {} + - background: {} + """; + const string json = $$""" + { + "apiVersion": "agentcore/v1", + "name": "agentic", + "agents": { + "defaults": { + "todos": true, + "mode": true, + "approval": { "auto": ["get_time"] } + }, + "items": [ + { + "id": "coder", + "todos": true, + "mode": true, + "memory": { "store": "workspace" }, + "files": { "store": "workspace", "write": false }, + "shell": { + "kind": "local", + "policy": { "deny": ["^rm "] }, + "timeoutSeconds": 30 + }, + "approval": { "auto": ["get_time", "file_access_read*"] }, + "background": ["searcher"], + "loop": { + "maxRounds": 5, + "until": [ { "todos": {} }, { "background": {} } ] + } + } + ] + } + } + """; + + var fromYaml = ConfigurationLoader.LoadYaml(yaml); + + Assert.Equal(Content(fromYaml), Content(ConfigurationLoader.LoadJson(json))); + } } diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs index 6b4edd39..76e55089 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationSchemaValidatorTests.cs @@ -621,4 +621,114 @@ public void ACompactionTriggerNotNamingExactlyOneCondition_FailsWithThePointerOf Assert.Equal(ConfigurationCheck.DocumentSchema, failure.Check); Assert.Contains(failure.Errors, error => error.Pointer == "/agents/defaults/compaction/trigger"); } + + [Fact] + public void AFullAgenticAgent_PassesCheckOne() + { + const string document = """ + apiVersion: agentcore/v1 + name: agentic + agents: + defaults: + todos: false + mode: true + approval: { auto: [get_time] } + items: + - id: searcher + instructions: Answer only the task you were given. + - id: coder + todos: true + mode: true + memory: { store: workspace } + files: { store: workspace, write: false } + shell: + kind: docker + policy: { deny: ["^rm "], allow: ["^echo "] } + timeoutSeconds: 30 + approval: { auto: [get_time, "file_access_read*"] } + background: [searcher] + loop: + maxRounds: 5 + until: + - todos: {} + - background: {} + """; + + var parsed = ConfigurationLoader.ReadDocument(document, ConfigurationFormat.Yaml); + + Assert.Empty(ConfigurationSchemaValidator.Evaluate(parsed)); + Assert.NotNull(ConfigurationLoader.LoadYaml(document).Agents!.Items[1].Shell); + } + + [Fact] + public void AnUnknownShellKind_FailsWithThePointerOfThatKind() + { + const string document = """ + apiVersion: agentcore/v1 + name: broken + agents: + items: + - id: coder + shell: { kind: k8s } + """; + + var failure = Assert.Throws(() => ConfigurationLoader.LoadYaml(document)); + + Assert.Equal(ConfigurationCheck.DocumentSchema, failure.Check); + Assert.Contains(failure.Errors, error => error.Pointer == "/agents/items/0/shell/kind"); + } + + [Fact] + public void AMemoryBlockWithoutAStore_FailsWithThePointerOfTheBlock() + { + const string document = """ + apiVersion: agentcore/v1 + name: broken + agents: + items: + - id: coder + memory: {} + """; + + var failure = Assert.Throws(() => ConfigurationLoader.LoadYaml(document)); + + Assert.Contains(failure.Errors, error => error.Pointer == "/agents/items/0/memory"); + } + + [Fact] + public void ATwoConditionUntilEntry_FailsWithThePointerOfThatEntry() + { + const string document = """ + apiVersion: agentcore/v1 + name: broken + agents: + items: + - id: coder + loop: + until: + - todos: {} + background: {} + """; + + var failure = Assert.Throws(() => ConfigurationLoader.LoadYaml(document)); + + Assert.Contains(failure.Errors, error => error.Pointer == "/agents/items/0/loop/until/0"); + } + + [Fact] + public void ADuplicateBackgroundChild_FailsWithThePointerOfTheList() + { + const string document = """ + apiVersion: agentcore/v1 + name: broken + agents: + items: + - id: coder + background: [searcher, searcher] + """; + + var failure = Assert.Throws(() => ConfigurationLoader.LoadYaml(document)); + + Assert.Contains(failure.Errors, error => error.Pointer == "/agents/items/0/background"); + } } diff --git a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs index 52aa9bb9..7a442ac7 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs @@ -111,6 +111,24 @@ public void AnUnknownTool_FailsCheckTwoWithThePointerOfTheSlot() Assert.Equal("nothing serves the tool 'lookup_order'. Declare it in tools:, or check that an mcp: server offers it.", error.Message); } + [Fact] + public void ABackgroundChildThatIsNotAnAgent_FailsCheckTwoWithThePointerOfThatChild() + { + const string document = """ + apiVersion: agentcore/v1 + name: broken + agents: + items: + - id: coder + background: [searcher] + """; + + var error = Assert.Single(Evaluate(document, ConfigurationCheck.ReferenceResolution)); + + Assert.Equal("/agents/items/0/background/0", error.Pointer); + Assert.Equal("the agent 'searcher' is not declared in agents.items", error.Message); + } + [Fact] public void AnUnknownGuard_FailsCheckTwoWithThePointerOfTheExit() { From aaa818e070610e0d72351a39ebeee63c4060acdd Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 16:56:38 -0600 Subject: [PATCH 05/32] feat: Implement AgentHarness and related tests for todos and mode switches --- .../AgentContextProviderCompiler.cs | 12 ++ .../Configuration/Compilation/AgentHarness.cs | 27 ++++ .../PublicAPI.Unshipped.txt | 16 +++ .../Compilation/HarnessCompilationTests.cs | 129 ++++++++++++++++++ .../Configuration/AgentHarnessTests.cs | 55 ++++++++ 5 files changed, 239 insertions(+) create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs create mode 100644 tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs create mode 100644 tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index c66b36d6..8168c4eb 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -69,6 +69,18 @@ public static List Build( #pragma warning restore MAAI001 } + var harness = AgentHarness.Compose(defaults, item); + + if (harness.Todos) + { + providers.Add(new TodoProvider()); + } + + if (harness.Mode) + { + providers.Add(new AgentModeProvider()); + } + if (AgentKnowledge.Compose(defaults, item) is not { } composed) { return providers; diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs new file mode 100644 index 00000000..2b0feac7 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs @@ -0,0 +1,27 @@ +using AgentCore.Application.Configuration.Schema; + +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); + +/// +/// Composes one agent's harness switches (todos:, mode:) from +/// agents.defaults and the agent's own keys, key by key. +/// +public static class AgentHarness +{ + /// Composes one agent's resolved harness switches. + /// The agents.defaults section, or . + /// The agent to resolve. + public static ResolvedHarness Compose(AgentDefaults? defaults, AgentConfiguration agent) + { + ArgumentNullException.ThrowIfNull(agent); + + return new ResolvedHarness( + agent.Todos ?? defaults?.Todos ?? false, + agent.Mode ?? defaults?.Mode ?? false); + } +} diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index b34816f0..01718221 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -141,6 +141,7 @@ AgentCore.Application.Calls.Memory.InMemoryCallStore.SetStatusAsync(string! call 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.Configuration.Compilation.AgentCompaction +AgentCore.Application.Configuration.Compilation.AgentHarness 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? @@ -211,6 +212,15 @@ AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Strategy.get AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Strategy.init -> void AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Trigger.get -> AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration! 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.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.Todos.get -> bool +AgentCore.Application.Configuration.Compilation.ResolvedHarness.Todos.init -> void AgentCore.Application.Configuration.Compilation.ResolvedKnowledge AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.$() -> AgentCore.Application.Configuration.Compilation.ResolvedKnowledge! AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.Citations.get -> bool @@ -1534,6 +1544,9 @@ override AgentCore.Application.Configuration.Compilation.ResolvedClarification.T override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.GetHashCode() -> int override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.ToString() -> string! +override AgentCore.Application.Configuration.Compilation.ResolvedHarness.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Compilation.ResolvedHarness.GetHashCode() -> int +override AgentCore.Application.Configuration.Compilation.ResolvedHarness.ToString() -> string! override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.Equals(object? obj) -> bool override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.GetHashCode() -> int override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.ToString() -> string! @@ -1773,6 +1786,7 @@ static AgentCore.Application.Calls.CallSessionState.operator ==(AgentCore.Applic 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.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? static AgentCore.Application.Configuration.Compilation.AgentKnowledge.AllScoped(AgentCore.Application.Configuration.Schema.AgentsConfiguration! agents) -> bool static AgentCore.Application.Configuration.Compilation.AgentKnowledge.AnyDeclared(AgentCore.Application.Configuration.Schema.AgentsConfiguration! agents) -> bool @@ -1785,6 +1799,8 @@ static AgentCore.Application.Configuration.Compilation.ResolvedClarification.ope static AgentCore.Application.Configuration.Compilation.ResolvedClarification.operator ==(AgentCore.Application.Configuration.Compilation.ResolvedClarification? left, AgentCore.Application.Configuration.Compilation.ResolvedClarification? right) -> bool static AgentCore.Application.Configuration.Compilation.ResolvedCompaction.operator !=(AgentCore.Application.Configuration.Compilation.ResolvedCompaction? left, AgentCore.Application.Configuration.Compilation.ResolvedCompaction? right) -> bool static AgentCore.Application.Configuration.Compilation.ResolvedCompaction.operator ==(AgentCore.Application.Configuration.Compilation.ResolvedCompaction? left, AgentCore.Application.Configuration.Compilation.ResolvedCompaction? right) -> bool +static AgentCore.Application.Configuration.Compilation.ResolvedHarness.operator !=(AgentCore.Application.Configuration.Compilation.ResolvedHarness? left, AgentCore.Application.Configuration.Compilation.ResolvedHarness? right) -> bool +static AgentCore.Application.Configuration.Compilation.ResolvedHarness.operator ==(AgentCore.Application.Configuration.Compilation.ResolvedHarness? left, AgentCore.Application.Configuration.Compilation.ResolvedHarness? right) -> bool static AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.operator !=(AgentCore.Application.Configuration.Compilation.ResolvedKnowledge? left, AgentCore.Application.Configuration.Compilation.ResolvedKnowledge? right) -> bool static AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.operator ==(AgentCore.Application.Configuration.Compilation.ResolvedKnowledge? left, AgentCore.Application.Configuration.Compilation.ResolvedKnowledge? right) -> bool static AgentCore.Application.Configuration.Parsing.ConfigurationError.AppendPointer(string! pointer, int index) -> string! diff --git a/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs b/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs new file mode 100644 index 00000000..321693c0 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs @@ -0,0 +1,129 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using Microsoft.Agents.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Compilation; + +/// +/// The todos: / mode: switches reaching a compiled agent's context providers, and the +/// tools they add reaching the model. +/// +public sealed class HarnessCompilationTests +{ + private static readonly string[] ExpectedTodoTools = + ["todos_add", "todos_complete", "todos_remove", "todos_get_remaining", "todos_get_all"]; + + private static readonly string[] ExpectedModeTools = ["mode_set", "mode_get"]; + + + [Fact] + public void Compile_TodosTrue_GetsATodoProvider() + { + var providers = Providers(CompileOne(withTodos: true, withMode: false)); + + Assert.Contains(providers, provider => provider is TodoProvider); + } + + [Fact] + public void Compile_ModeTrue_GetsAnAgentModeProvider() + { + var providers = Providers(CompileOne(withTodos: false, withMode: true)); + + Assert.Contains(providers, provider => provider is AgentModeProvider); + } + + [Fact] + public void Compile_NeitherKey_GetsNeitherProvider() + { + var providers = Providers(CompileOne(withTodos: false, withMode: false)); + + Assert.DoesNotContain(providers, provider => provider is TodoProvider); + Assert.DoesNotContain(providers, provider => provider is AgentModeProvider); + } + + [Fact] + public async Task Compile_TodosTrue_ModelSeesTheFiveTodoTools() + { + using SequencedChatClient reply = new("hello there."); + + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-todos", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only", Todos = true }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(reply))); + + var agent = Assert.Single(compiled.Agents.Values); + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + + await agent.RunAsync("hi", session, cancellationToken: token); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + + Assert.Equal(ExpectedTodoTools, toolNames, StringComparer.Ordinal); + } + + [Fact] + public async Task Compile_ModeTrue_ModelSeesTheTwoModeTools() + { + using SequencedChatClient reply = new("hello there."); + + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-mode", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only", Mode = true }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(reply))); + + var agent = Assert.Single(compiled.Agents.Values); + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + + await agent.RunAsync("hi", session, cancellationToken: token); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + + Assert.Equal(ExpectedModeTools, toolNames, StringComparer.Ordinal); + } + + private static AIAgent CompileOne(bool withTodos, bool withMode) + { + using SequencedChatClient reply = new("hello there."); + + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-only", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only", Todos = withTodos, Mode = withMode }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(reply))); + + return Assert.Single(compiled.Agents.Values); + } + + private static IEnumerable Providers(AIAgent agent) + { + var inner = agent.GetService(); + Assert.NotNull(inner); + return inner.AIContextProviders ?? []; + } +} diff --git a/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs b/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs new file mode 100644 index 00000000..ceb2273f --- /dev/null +++ b/tests/AgentCore.Application.Tests/Configuration/AgentHarnessTests.cs @@ -0,0 +1,55 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Schema; +using Xunit; + +namespace AgentCore.Application.Tests.Configuration; + +/// +/// : the key-by-key merge of one agent's todos: / mode: +/// switches against agents.defaults. +/// +public sealed class AgentHarnessTests +{ + [Fact] + public void Compose_NoKeyAnywhere_BothFalse() + { + var resolved = AgentHarness.Compose(defaults: null, Agent(todos: null, mode: null)); + + Assert.False(resolved.Todos); + Assert.False(resolved.Mode); + } + + [Fact] + public void Compose_DefaultsOnly_IsInherited() + { + var resolved = AgentHarness.Compose( + new AgentDefaults { Todos = true, Mode = true }, + Agent(todos: null, mode: null)); + + Assert.True(resolved.Todos); + Assert.True(resolved.Mode); + } + + [Fact] + public void Compose_AgentFalseOverridesDefaultsTrue_TakesTheAgent() + { + var resolved = AgentHarness.Compose( + new AgentDefaults { Todos = true, Mode = true }, + Agent(todos: false, mode: false)); + + Assert.False(resolved.Todos); + Assert.False(resolved.Mode); + } + + [Fact] + public void Compose_AgentTrueOverNullDefaults_IsTrue() + { + var resolved = AgentHarness.Compose(defaults: null, Agent(todos: true, mode: true)); + + Assert.True(resolved.Todos); + Assert.True(resolved.Mode); + } + + private static AgentConfiguration Agent(bool? todos, bool? mode) => + new() { Id = "reply", Todos = todos, Mode = mode }; +} From 02362598867ed54d591a19e9bac0b47a15db6c18 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 17:51:05 -0600 Subject: [PATCH 06/32] feat: add workspace management for call sessions --- src/AgentCore.Application/Diagnostics/Log.cs | 10 + .../PublicAPI.Unshipped.txt | 9 +- .../Runtime/CallSession.cs | 24 ++- .../Runtime/CallSessionFactory.cs | 20 +- .../Runtime/CallWorkspace.cs | 88 ++++++++ .../Runtime/ToolCallScopes.cs | 2 +- .../Runtime/TurnAmbients.cs | 8 +- .../Tools/ToolCallScope.cs | 3 +- .../DependencyInjection/AgentCoreOptions.cs | 14 ++ .../Startup/CallSessionStartup.cs | 20 +- .../PublicAPI.Unshipped.txt | 1 + .../Runtime/CallSessionWorkspaceTests.cs | 202 ++++++++++++++++++ .../Runtime/CallWorkspaceTests.cs | 93 ++++++++ .../DependencyInjection/AddAgentCoreTests.cs | 80 +------ .../DependencyInjection/StartedHost.cs | 16 ++ .../DependencyInjection/StartedHostFixture.cs | 91 ++++++++ .../WorkspaceStartupTests.cs | 73 +++++++ 17 files changed, 662 insertions(+), 92 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/CallWorkspace.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHost.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index db398a39..883def66 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -249,4 +249,14 @@ public static partial void KnowledgeScopeComposed( + "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); + + /// A call's workspace folder could not be deleted when the call 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}'.")] + public static partial void WorkspaceDeleteFailed(ILogger logger, string path, Exception exception); } diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 01718221..bb4e17cb 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -1222,8 +1222,9 @@ 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.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) -> void +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.CallSourceScope AgentCore.Application.Runtime.CallStateScope @@ -1381,13 +1382,15 @@ 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) -> void +AgentCore.Application.Tools.ToolCallScope.Deconstruct(out string! CallId, 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) -> void +AgentCore.Application.Tools.ToolCallScope.ToolCallScope(string! CallId, 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 diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 4e9d8eb7..81e2be70 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -98,6 +98,8 @@ public sealed class CallSession : IConversationPort private readonly Clarifications _clarifications = new(); + private readonly CallWorkspace? _workspace; + // Whether the running turn has already handed the host something to speak. One rule for both // run shapes: a run that has handed the host nothing cannot be the turn the caller was hearing, // so a barge-in in that window belongs to the turn that finished before it. A streaming turn @@ -122,7 +124,8 @@ internal CallSession( StateExtractor? extractor, TimeProvider timeProvider, CallObserverDispatcher? observers = null, - ILogger? logger = null) + ILogger? logger = null, + CallWorkspace? workspace = null) { ArgumentException.ThrowIfNullOrEmpty(callId); ArgumentNullException.ThrowIfNull(compiled); @@ -133,6 +136,8 @@ internal CallSession( _logger = logger ?? NullLogger.Instance; + _workspace = workspace; + _compiled = compiled; _history = compiled.History; @@ -180,6 +185,12 @@ internal CallSession( /// public string CallId { 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. + /// + public string? Workspace => _workspace?.Path; + /// /// Gets the stage the machine holds. It is empty when the document declares no policy. /// @@ -482,9 +493,16 @@ public bool EndCall(CallEndReason reason) // no call and writes nothing. var wrote = _events.EndCall(reason, _time.GetUtcNow()); 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. + /// + private void DeleteWorkspace() => _workspace?.Delete(_logger); + /// /// 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. @@ -742,7 +760,8 @@ private IDisposable EnterAmbients(Turn turn) failure => _events.RaiseToolFailure(turn.Index, failure), TurnContextOf(turn), turn.Knowledge, - _clarifications); + _clarifications, + Workspace); /// /// Reads what one turn adds to its own model invocation. @@ -1274,6 +1293,7 @@ private async Task CompleteTurnAsync( // The stage rides as detail, because the reason a report counts is the same one for // every terminal stage the document declares. _events.EndCall(CallEndReason.AgentCompleted, endedAt, stageAfter); + DeleteWorkspace(); } return result; diff --git a/src/AgentCore.Application/Runtime/CallSessionFactory.cs b/src/AgentCore.Application/Runtime/CallSessionFactory.cs index abb04a49..1c14cc92 100644 --- a/src/AgentCore.Application/Runtime/CallSessionFactory.cs +++ b/src/AgentCore.Application/Runtime/CallSessionFactory.cs @@ -25,14 +25,20 @@ public sealed class CallSessionFactory : ICallSessionFactory private readonly ILogger? _logger; - /// Creates the factory. + private readonly string? _workspaceRoot; + + /// + /// Creates the factory. When is bound, every call this factory + /// builds gets its own folder under it; unbound, a session it builds has no workspace. + /// public CallSessionFactory( 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); ArgumentNullException.ThrowIfNull(guards); @@ -42,6 +48,7 @@ public CallSessionFactory( _extractor = extractor; _time = timeProvider ?? TimeProvider.System; _logger = logger; + _workspaceRoot = workspaceRoot; // 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 @@ -72,14 +79,19 @@ public CallSessionFactory( /// public CallSession Create(string? callId = null, CallSessionState? state = null) { + var resolvedCallId = string.IsNullOrWhiteSpace(callId) ? Guid.NewGuid().ToString("N") : callId; + + var workspace = _workspaceRoot is null ? null : CallWorkspace.Create(_workspaceRoot, resolvedCallId); + CallSession session = new( - string.IsNullOrWhiteSpace(callId) ? Guid.NewGuid().ToString("N") : callId, + resolvedCallId, _compiled, _guards, _extractor, _time, new CallObserverDispatcher(_observers, _logger), - _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. diff --git a/src/AgentCore.Application/Runtime/CallWorkspace.cs b/src/AgentCore.Application/Runtime/CallWorkspace.cs new file mode 100644 index 00000000..975e4573 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallWorkspace.cs @@ -0,0 +1,88 @@ +using AgentCore.Application.Diagnostics; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Runtime; + +/// +/// The folder one call owns on disk: created with the call, and deleted when it ends. +/// +internal sealed class CallWorkspace +{ + private CallWorkspace(string path) => Path = path; + + /// Gets the folder's path. + public string Path { get; } + + /// + /// Creates (or, for a resumed call, reuses) the folder root/callId. + /// + /// 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 + /// would otherwise resolve straight back to the root. + /// + /// + /// 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) + { + ArgumentException.ThrowIfNullOrEmpty(root); + ArgumentException.ThrowIfNullOrWhiteSpace(callId); + + if (callId.Contains('/', StringComparison.Ordinal) || callId.Contains('\\', StringComparison.Ordinal)) + { + throw new ArgumentException( + $"The call id '{callId}' must not contain a directory separator.", nameof(callId)); + } + + var fullRoot = System.IO.Path.GetFullPath(root); + var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(fullRoot, callId)); + + 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, + // 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)) + { + throw new ArgumentException( + $"The call id '{callId}' must resolve to a folder under the workspace root.", nameof(callId)); + } + + Directory.CreateDirectory(path); + return new CallWorkspace(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. + /// + /// Where a failed delete is logged, at Warning. May be . + public void Delete(ILogger? logger) + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (DirectoryNotFoundException) + { + // Already gone: this is the second call, or the host removed it out of band. + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A concurrent delete from outside this call 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)) + { + Log.WorkspaceDeleteFailed(logger, Path, exception); + } + } + } +} diff --git a/src/AgentCore.Application/Runtime/ToolCallScopes.cs b/src/AgentCore.Application/Runtime/ToolCallScopes.cs index 578e041e..9802eeec 100644 --- a/src/AgentCore.Application/Runtime/ToolCallScopes.cs +++ b/src/AgentCore.Application/Runtime/ToolCallScopes.cs @@ -27,6 +27,6 @@ internal static ToolCallScope Current() throw new InvalidOperationException(NoTurnMessage); } - return new ToolCallScope(callId, state.TurnIndex, state.Stage); + return new ToolCallScope(callId, state.TurnIndex, state.Stage, ambients.Workspace); } } diff --git a/src/AgentCore.Application/Runtime/TurnAmbients.cs b/src/AgentCore.Application/Runtime/TurnAmbients.cs index e899933e..b6bf71a9 100644 --- a/src/AgentCore.Application/Runtime/TurnAmbients.cs +++ b/src/AgentCore.Application/Runtime/TurnAmbients.cs @@ -49,6 +49,9 @@ internal sealed record TurnAmbients /// Gets the call's ambiguity holder (K36), or inside a nested tool call (K42). public Clarifications? Clarifications { get; init; } + /// Gets the folder this call owns on disk, or when the host bound no workspace root. + public string? Workspace { get; init; } + /// Opens what a turn owns, and carries every other ambient through unchanged. /// The id of the call the turn belongs to. /// The state document the call reads and writes. @@ -59,6 +62,7 @@ internal sealed record TurnAmbients /// The turn the tools are running inside. /// What this turn may see of the knowledge base, or when the document composes none. /// The call's ambiguity holder. + /// The folder this call owns on disk, or when the host bound no workspace root. internal static IDisposable Enter( string callId, StateDocument state, @@ -68,7 +72,8 @@ internal static IDisposable Enter( Action onToolFailure, TurnContext context, KnowledgeScope? knowledge, - Clarifications clarifications) + Clarifications clarifications, + string? workspace) { ArgumentNullException.ThrowIfNull(callId); ArgumentNullException.ThrowIfNull(state); @@ -92,6 +97,7 @@ internal static IDisposable Enter( Context = context, Knowledge = knowledge ?? current.Knowledge, Clarifications = clarifications, + Workspace = workspace, }); } diff --git a/src/AgentCore.Application/Tools/ToolCallScope.cs b/src/AgentCore.Application/Tools/ToolCallScope.cs index 022da574..4112c642 100644 --- a/src/AgentCore.Application/Tools/ToolCallScope.cs +++ b/src/AgentCore.Application/Tools/ToolCallScope.cs @@ -4,4 +4,5 @@ namespace AgentCore.Application.Tools; /// The call 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. -public sealed record ToolCallScope(string CallId, int TurnIndex, string Stage); +/// 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); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index 1e18616d..4e541ede 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -84,6 +84,9 @@ public sealed class AgentCoreOptions /// Gets the call transports this host supports, or . internal IReadOnlyList? Call { get; private set; } + /// Gets the folder under which every call 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; @@ -293,6 +296,17 @@ public AgentCoreOptions AddToolSource(Func toolSo return this; } + /// + /// Binds the folder under which every call gets its own workspace directory, + /// <root>/<callId>/, created with the call and deleted when the call ends. + /// + public AgentCoreOptions UseWorkspace(string root) + { + ArgumentException.ThrowIfNullOrWhiteSpace(root); + WorkspaceRoot = root; + return this; + } + /// Registers one host delegate behind a binds: name. /// The name a binds: field writes, such as CreateCase. /// The delegate the tool calls. diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs index 9ff41f1e..ccf8af63 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs @@ -1,5 +1,6 @@ using AgentCore.Application.Audit; using AgentCore.Application.Audit.Memory; +using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; @@ -50,13 +51,30 @@ internal static async ValueTask OpenAsync( var sessionLogger = loggers.CreateLogger(); + if (options.WorkspaceRoot is { } root) + { + try + { + Directory.CreateDirectory(root); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + throw new ConfigurationLoadException( + $"The configuration document did not load. The workspace root '{root}' could not be " + + $"created: {exception.Message} Check the path passed to options.UseWorkspace(...), " + + "and that the process has permission to create it.", + exception); + } + } + CallSessionFactory sessions = new( graph.Compiled, graph.Guards, CallSessionFactory.CreateExtractor(graph.Compiled, graph.ChatClients), options.TimeProvider, sessionLogger, - CallObservers.Standard(auditSink, sessionLogger, options.Observers)); + CallObservers.Standard(auditSink, sessionLogger, options.Observers), + options.WorkspaceRoot); return new CallSessionSeam(sessions, new AgentCoreAgent(sessions, configuration.Name), auditSink); } diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 486198b9..969d4bce 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -40,6 +40,7 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseObservers(params Ag 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! +AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseWorkspace(string! root) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseTelemetry(params AgentCore.Application.Ports.ITelemetryAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs new file mode 100644 index 00000000..748618f9 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionWorkspaceTests.cs @@ -0,0 +1,202 @@ +using AgentCore.TestSupport; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools; +using AgentCore.Application.Tools.Binding; +using AgentCore.Application.Tools.Registry; +using AgentCore.Domain.Audit; +using Microsoft.Extensions.AI; +using Xunit; + +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 . +/// +/// +/// Every test here runs offline. There is no network call and no API key anywhere in this file. +/// +public sealed class CallSessionWorkspaceTests : IDisposable +{ + private const string SimpleYaml = + """ + apiVersion: agentcore/v1 + name: one-agent + agents: + items: + - { id: only, instructions: "I answer everything" } + """; + + private const string TerminalYaml = + """ + apiVersion: agentcore/v1 + name: two-stage + state: + callerSaidGoodbye: + type: boolean + default: false + writer: extractor + description: whether the caller said goodbye + guards: + saidGoodbye: { var: callerSaidGoodbye } + extractor: + model: { ref: fill } + when: after_reply + agents: + defaults: + model: { ref: reply } + items: + - { id: greeter, instructions: "greet the caller" } + - { id: closer, instructions: "close the call" } + policy: + initial: greeting + stages: + - id: greeting + agent: greeter + to: [ { stage: close, when: saidGoodbye } ] + - id: close + agent: closer + terminal: true + """; + + private const string ScopeYaml = + """ + apiVersion: agentcore/v1 + name: scope-check + tools: + - { id: request_human, kind: binding, binds: RequestHuman, description: "Ask a human to take the call." } + agents: + items: + - { id: only, instructions: "help the caller", tools: [ request_human ] } + """; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-ws-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [Fact] + public void ARootBound_CreatesTheCallsFolder() + { + using SequencedChatClient reply = new("hi there."); + var factory = Build(SimpleYaml, reply, fill: null, _root); + + var session = factory.Create("call-1"); + + Assert.Equal(Path.Combine(_root, "call-1"), session.Workspace); + Assert.True(Directory.Exists(session.Workspace)); + } + + [Fact] + 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"); + + Assert.Null(session.Workspace); + Assert.False(Directory.Exists(_root)); + } + + [Fact] + public void EndCall_DeletesTheFolder_AndIsSafeToCallTwice() + { + using SequencedChatClient reply = new("hi there."); + var factory = Build(SimpleYaml, reply, fill: null, _root); + var session = factory.Create("call-1"); + var path = session.Workspace!; + + session.EndCall(CallEndReason.CallerHungUp); + + Assert.False(Directory.Exists(path)); + Assert.False(session.EndCall(CallEndReason.CallerHungUp)); + } + + [Fact] + 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 path = session.Workspace!; + + var turn = await session.RunTurnAsync("goodbye", TestContext.Current.CancellationToken); + + Assert.True(turn.IsTerminal); + Assert.True(session.IsComplete); + Assert.False(Directory.Exists(path)); + } + + [Fact] + public async Task ABoundTool_SeesTheRunningCallsWorkspace() + { + List captured = []; + ToolBindingRegistry bindings = new(); + bindings.Register("RequestHuman", (string reason, ToolCallScope scope) => captured.Add(scope)); + + var document = ConfigurationLoader.LoadYaml(ScopeYaml); + var chatClients = new RoutingChatClientFactory( + new ToolCallingChatClient( + "connecting you now.", + new Dictionary(StringComparer.Ordinal) { ["reason"] = "the caller wants a person" })); + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) + { + Tools = await ToolRegistryBuilder.BuildAsync( + [new BindingToolSource(bindings)], + new ToolSourceContext(document), + TestContext.Current.CancellationToken), + }); + + var factory = new CallSessionFactory( + compiled, + new GuardEvaluator(compiled.Configuration.Guards), + workspaceRoot: _root); + var session = factory.Create("call-1"); + + await session.RunTurnAsync("I need a person", TestContext.Current.CancellationToken); + + var scope = Assert.Single(captured); + Assert.Equal(session.Workspace, scope.Workspace); + Assert.NotNull(scope.Workspace); + } + + private static CallSessionFactory Build( + string yaml, + IChatClient reply, + IChatClient? fill, + string? workspaceRoot) + { + var document = ConfigurationLoader.LoadYaml(yaml); + var chatClients = new RoutingChatClientFactory(reply); + if (fill is not null) + { + chatClients.Route("fill", fill); + } + + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) + { + Tools = TestToolRegistry.From(document, builder: null, TestContext.Current.CancellationToken), + }); + + return new CallSessionFactory( + compiled, + new GuardEvaluator(compiled.Configuration.Guards), + CallSessionFactory.CreateExtractor(compiled, chatClients), + workspaceRoot: workspaceRoot); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs new file mode 100644 index 00000000..44fe3ad8 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallWorkspaceTests.cs @@ -0,0 +1,93 @@ +using AgentCore.Application.Runtime; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// in isolation: the folder it creates and the folder it deletes. +/// +public sealed class CallWorkspaceTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "agentcore-ws-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [Fact] + public void Create_MakesTheFolder() + { + var workspace = CallWorkspace.Create(_root, "call-1"); + + Assert.Equal(Path.Combine(_root, "call-1"), workspace.Path); + Assert.True(Directory.Exists(workspace.Path)); + } + + [Fact] + public void Delete_RemovesTheFolder_AndIsSafeToCallTwice() + { + var workspace = CallWorkspace.Create(_root, "call-1"); + + workspace.Delete(logger: null); + Assert.False(Directory.Exists(workspace.Path)); + + var exception = Record.Exception(() => workspace.Delete(logger: null)); + Assert.Null(exception); + } + + [Theory] + [InlineData("../escape")] + [InlineData("a/b")] + [InlineData(@"a\b")] + [InlineData("..")] + [InlineData(".")] + [InlineData("")] + [InlineData(" ")] + public void Create_RefusesACallIdThatCouldEscapeTheRoot(string callId) + { + Assert.Throws(() => CallWorkspace.Create(_root, callId)); + 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 + /// 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) + { + if (OperatingSystem.IsWindows()) + { + Assert.ThrowsAny(() => CallWorkspace.Create(_root, callId)); + Assert.False(Directory.Exists(_root)); + return; + } + + var workspace = CallWorkspace.Create(_root, callId); + + Assert.StartsWith(_root + Path.DirectorySeparatorChar, workspace.Path, StringComparison.Ordinal); + Assert.Equal(callId, Path.GetFileName(workspace.Path)); + } + + [Fact] + public void Create_TwiceWithTheSameCallId_ReusesTheFolderAndKeepsWhatWasWrittenIntoIt() + { + var first = CallWorkspace.Create(_root, "call-1"); + var marker = Path.Combine(first.Path, "marker.txt"); + File.WriteAllText(marker, "kept"); + + var second = CallWorkspace.Create(_root, "call-1"); + + Assert.Equal(first.Path, second.Path); + Assert.Equal("kept", File.ReadAllText(marker)); + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index 32e3aa82..5ab15794 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -32,6 +32,7 @@ using Xunit; using AgentCore.AspNetCore.DependencyInjection.Startup; using Microsoft.Agents.AI; +using static AgentCore.AspNetCore.Tests.DependencyInjection.StartedHostFixture; namespace AgentCore.AspNetCore.Tests.DependencyInjection; @@ -62,16 +63,6 @@ public sealed class AddAgentCoreTests - { kind: openai, model: gpt-4.1-mini, as: reply } """; - private const string OneAgentYaml = - $$""" - apiVersion: agentcore/v1 - name: composed - agents: - items: - - { id: only, instructions: "I answer everything" } - {{MinimalProviders}} - """; - // The same agent, and a document that names a telemetry vendor. private const string TelemetryYaml = $$""" @@ -1875,62 +1866,6 @@ private static Task BuildGuardedGraphAsync() OccurredAt = DateTimeOffset.UnixEpoch.AddSeconds(secondsPastEpoch), }; - /// Starts a host on one document, which is where the whole boot happens. - /// The document to boot. - /// The host's own word on the options. - /// The started host, read as the container it is. - private static async Task BuildAsync(string yaml, Action? configure = null) - { - HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); - ConfigureServices(builder.Services, yaml, configure); - - return await StartAsync(builder.Build()); - } - - /// Starts one host, and closes it itself when the start fails. - /// The host to start. - /// The started host. - /// - /// A failed start never stops what already started, so disposal is the only cleanup path — and - /// it is the one a real host takes too, inside RunAsync's own finally. StopAsync is - /// deliberately not called here: on net10 a host that failed to start throws - /// out of StopAsync when the failure was a constructor. - /// - private static async Task StartAsync(IHost host) - { - try - { - await host.StartAsync(TestContext.Current.CancellationToken); - } - catch - { - host.Dispose(); - throw; - } - - return new StartedHost(host); - } - - /// Starts a host on nothing but the options a test writes, with no document default. - /// The only word on the options. - /// The started host, for the tests that expect it never to get one. - private static async Task StartBareAsync(Action configure) - { - HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); - builder.Services.AddAgentCore(configure); - - return await StartAsync(builder.Build()); - } - - private static void ConfigureServices( - IServiceCollection services, string yaml, Action? configure) - => services.AddAgentCore(options => - { - options.Configuration = ConfigurationLoader.LoadYaml(yaml); - options.UseChatClients(_ => new RoutingChatClientFactory(new FragmentingChatClient("hello"))); - configure?.Invoke(options); - }); - /// An adapter that starts nothing and hands back a session that records its flush. private sealed class FlushRecordingTelemetryAdapter(string kind) : ITelemetryAdapter { @@ -2149,19 +2084,6 @@ public ValueTask> ProvideAsync( } } - /// A started host, read as the container it is. - /// The host to read services from, and to close on the way out. - /// - /// Disposing this disposes the host, which disposes the container. That is the whole shutdown - /// path: nothing here calls StopAsync, because a host that failed to start never gets one. - /// - private sealed class StartedHost(IHost host) : IServiceProvider, IDisposable - { - public object? GetService(Type serviceType) => host.Services.GetService(serviceType); - - public void Dispose() => host.Dispose(); - } - /// A tool source a host registers, which records whether it was ever closed. /// One id to serve, or to serve nothing. private sealed class DisposeTrackingToolSource(string? servedId = null) : IToolSource, IAsyncDisposable diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHost.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHost.cs new file mode 100644 index 00000000..5be7fd8e --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHost.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.Hosting; + +namespace AgentCore.AspNetCore.Tests.DependencyInjection; + +/// A started host, read as the container it is. +/// The host to read services from, and to close on the way out. +/// +/// Disposing this disposes the host, which disposes the container. That is the whole shutdown +/// path: nothing here calls StopAsync, because a host that failed to start never gets one. +/// +internal sealed class StartedHost(IHost host) : IServiceProvider, IDisposable +{ + public object? GetService(Type serviceType) => host.Services.GetService(serviceType); + + public void Dispose() => host.Dispose(); +} diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs new file mode 100644 index 00000000..fed53f44 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/StartedHostFixture.cs @@ -0,0 +1,91 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.AspNetCore.DependencyInjection; +using AgentCore.AspNetCore.Tests.Fakes; +using AgentCore.TestSupport; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Xunit; + +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 +/// or directly. +/// +internal static class StartedHostFixture +{ + /// The one-agent document every test that needs no more than that boots on. + internal const string OneAgentYaml = + """ + apiVersion: agentcore/v1 + name: composed + agents: + items: + - { id: only, instructions: "I answer everything" } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + /// Starts a host on one document. + /// The document to boot. + /// The host's own word on the options. + /// The started host, read as the container it is. + internal static async Task BuildAsync(string yaml, Action? configure = null) + { + HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); + ConfigureServices(builder.Services, yaml, configure); + + return await StartAsync(builder.Build()); + } + + /// Starts one host, and closes it itself when the start fails. + /// The host to start. + /// The started host. + /// + /// A failed start never stops what already started, so disposal is the only cleanup path — and + /// it is the one a real host takes too, inside RunAsync's own finally. StopAsync is + /// deliberately not called here: on net10 a host that failed to start throws + /// out of StopAsync when the failure was a constructor. + /// + internal static async Task StartAsync(IHost host) + { + try + { + await host.StartAsync(TestContext.Current.CancellationToken); + } + catch + { + host.Dispose(); + throw; + } + + return new StartedHost(host); + } + + /// Starts a host on nothing but the options a test writes, with no document default. + /// The only word on the options. + /// The started host, for the tests that expect it never to get one. + internal static async Task StartBareAsync(Action configure) + { + HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(new()); + builder.Services.AddAgentCore(configure); + + return await StartAsync(builder.Build()); + } + + internal static void ConfigureServices( + IServiceCollection services, string yaml, Action? configure) + => services.AddAgentCore(options => + { + options.Configuration = ConfigurationLoader.LoadYaml(yaml); + options.UseChatClients(_ => new RoutingChatClientFactory(new FragmentingChatClient("hello"))); + configure?.Invoke(options); + }); +} diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs new file mode 100644 index 00000000..bc81aac2 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs @@ -0,0 +1,73 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.AspNetCore.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using Xunit; +using static AgentCore.AspNetCore.Tests.DependencyInjection.StartedHostFixture; + +namespace AgentCore.AspNetCore.Tests.DependencyInjection; + +/// +/// and the folder it binds a call's +/// to. +/// +public sealed class WorkspaceStartupTests : IDisposable +{ + private readonly string _tempRoot = + Path.Combine(Path.GetTempPath(), "agentcore-ws-" + Guid.NewGuid().ToString("N")); + + [Fact] + public void UseWorkspace_AnEmptyPath_ThrowsArgumentException() + { + AgentCoreOptions options = new(); + + Assert.Throws(() => options.UseWorkspace("")); + } + + [Fact] + public async Task AHostBoundToAWorkspaceRoot_CreatesTheCallsFolderWhenACallOpens() + { + using var provider = await BuildAsync(OneAgentYaml, options => options.UseWorkspace(_tempRoot)); + + var sessions = provider.GetRequiredService(); + var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + + Assert.Equal(Path.Combine(_tempRoot, "call-1"), session.Workspace); + Assert.True(Directory.Exists(Path.Combine(_tempRoot, "call-1"))); + } + + [Fact] + public async Task AHostWithNoWorkspaceBound_CreatesNothingAndLeavesWorkspaceNull() + { + using var provider = await BuildAsync(OneAgentYaml); + + var sessions = provider.GetRequiredService(); + var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + + Assert.Null(session.Workspace); + } + + [Fact] + public async Task ARootThatCannotBeCreated_FailsStartupWithThePathAndTheOption() + { + var blockingFile = Path.Combine(_tempRoot, "blocks-the-root"); + Directory.CreateDirectory(_tempRoot); + await File.WriteAllTextAsync(blockingFile, "not a directory", TestContext.Current.CancellationToken); + var unusableRoot = Path.Combine(blockingFile, "x"); + + var failure = await Assert.ThrowsAsync( + () => BuildAsync(OneAgentYaml, options => options.UseWorkspace(unusableRoot))); + + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + Assert.Contains(unusableRoot, failure.Message, StringComparison.Ordinal); + } + + public void Dispose() + { + if (Directory.Exists(_tempRoot)) + { + Directory.Delete(_tempRoot, recursive: true); + } + } +} From c15f249d0b3d1bcb6fb3f680a7eaee603fba8b3d Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 18:24:03 -0600 Subject: [PATCH 07/32] feat: add workspace root support for memory agents and enhance related functionality --- .../Compilation/AgentCompilationContext.cs | 6 + .../AgentContextProviderCompiler.cs | 12 +- .../Compilation/AgentHarnessProviders.cs | 95 +++++ .../PublicAPI.Unshipped.txt | 2 + .../Runtime/CallSession.cs | 8 + .../DependencyInjection/AgentCoreBoot.cs | 3 +- .../Startup/CompilationStartup.cs | 5 +- .../Compilation/MemoryCompilationTests.cs | 337 ++++++++++++++++++ .../WorkspaceStartupTests.cs | 51 +++ 9 files changed, 506 insertions(+), 13 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs create mode 100644 tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs index f5238c9d..d22225a8 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs @@ -74,4 +74,10 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// Gets or sets where the compiled agents write their own diagnostics, or . /// public ILoggerFactory? Loggers { get; init; } + + /// + /// Gets or sets the root a memory: block's files are kept under, or + /// when the host bound no workspace root. + /// + public string? WorkspaceRoot { get; init; } } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index 8168c4eb..63e1a0dd 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -69,17 +69,7 @@ public static List Build( #pragma warning restore MAAI001 } - var harness = AgentHarness.Compose(defaults, item); - - if (harness.Todos) - { - providers.Add(new TodoProvider()); - } - - if (harness.Mode) - { - providers.Add(new AgentModeProvider()); - } + AgentHarnessProviders.Add(providers, defaults, item, context, pointer); 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 new file mode 100644 index 00000000..7db1bd99 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -0,0 +1,95 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +/// +/// The context providers behind one agent's harness switches (todos:, mode:, +/// memory:), added into the provider list builds. +/// +internal static class AgentHarnessProviders +{ + /// Adds this agent's harness providers, in declaration order: todos, mode, memory. + /// The provider list under construction. + /// The agents.defaults section, or . + /// The agent being compiled. + /// The compile-time seams, including the bound workspace root. + /// This agent's JSON pointer, for a memory: failure. + public static void Add( + List providers, + AgentDefaults? defaults, + AgentConfiguration item, + AgentCompilationContext context, + string pointer) + { + var harness = AgentHarness.Compose(defaults, item); + + if (harness.Todos) + { + providers.Add(new TodoProvider()); + } + + if (harness.Mode) + { + providers.Add(new AgentModeProvider()); + } + + if (item.Memory is { Store: AgentFileStoreKind.Workspace }) + { + providers.Add(BuildMemoryProvider(item, context, pointer)); + } + } + + private static FileMemoryProvider BuildMemoryProvider( + AgentConfiguration item, AgentCompilationContext context, string pointer) + { + if (context.WorkspaceRoot is not { } root) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "memory"), + $"the agent '{item.Id}' declares a memory: block and this host bound no workspace " + + "root, so there is nowhere to keep the files. Call options.UseWorkspace(...) with " + + "the folder, or remove the memory: block."); + } + + try + { +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. + return new FileMemoryProvider(new FileSystemAgentFileStore(root), InitializeWorkingFolder); +#pragma warning restore MAAI001 + } + 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 + // must fail with the same named cause an operator gets from that later guard. + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "memory"), + $"the agent '{item.Id}' declares a memory: block and the workspace root '{root}' " + + $"could not be created: {exception.Message} Check the path passed to " + + "options.UseWorkspace(...), and that the process has permission to create it."); + } + } + + /// + /// 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. + /// +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. + private static FileMemoryState InitializeWorkingFolder(AgentSession? session) + { + if (TurnAmbients.Current?.CallId is not { } callId) + { + throw new InvalidOperationException( + "A memory: block's FileMemoryProvider needs the running call's id, and no turn is " + + "open on this flow of execution. The provider's working folder is bound only while " + + "a turn runs through a CallSession. Run the agent through a CallSession."); + } + + return new FileMemoryState { WorkingFolder = callId }; + } +#pragma warning restore MAAI001 +} diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index bb4e17cb..96a67614 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -163,6 +163,8 @@ AgentCore.Application.Configuration.Compilation.AgentCompilationContext.StateSna AgentCore.Application.Configuration.Compilation.AgentCompilationContext.StateSnapshot.init -> void AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Tools.get -> AgentCore.Application.Tools.Registry.ToolRegistry? AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Tools.init -> void +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.WorkspaceRoot.get -> string? +AgentCore.Application.Configuration.Compilation.AgentCompilationContext.WorkspaceRoot.init -> void AgentCore.Application.Configuration.Compilation.AgentInstructions AgentCore.Application.Configuration.Compilation.AgentKnowledge AgentCore.Application.Configuration.Compilation.CompiledAgent diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 81e2be70..d822cc2a 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -1293,6 +1293,14 @@ private async Task CompleteTurnAsync( // The stage rides as detail, because the reason a report counts is the same one for // every terminal stage the document declares. _events.EndCall(CallEndReason.AgentCompleted, endedAt, stageAfter); + } + + if (IsComplete || _events.HasEnded) + { + // 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. DeleteWorkspace(); } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index ded79520..ae7610fb 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -226,7 +226,8 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) knowledge, skills, KnowledgeCitationFormatterFactory.Resolve(configuration, _options.KnowledgeCitations), - _loggers) + _loggers, + _options.WorkspaceRoot) .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 efb50af7..95515094 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -39,6 +39,7 @@ internal static class CompilationStartup /// 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 compiled graph, and the seams that made it. /// The document does not compile. internal static ValueTask CompileAsync( @@ -50,7 +51,8 @@ internal static ValueTask CompileAsync( IKnowledgeRetrievalPort? knowledge, SkillCatalog? skills, IKnowledgeCitationFormatter citations, - ILoggerFactory loggers) + ILoggerFactory loggers, + string? workspaceRoot = null) { GuardEvaluator guards = new(configuration.Guards, loggers.CreateLogger()); CompiledAgentRegistry registry = new(); @@ -68,6 +70,7 @@ internal static ValueTask CompileAsync( Skills = skills, Citations = citations, Loggers = loggers, + WorkspaceRoot = workspaceRoot, }); return ValueTask.FromResult(new CompiledGraph(chatClients, guards, registry, compiled)); diff --git a/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs b/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs new file mode 100644 index 00000000..2cf047a5 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs @@ -0,0 +1,337 @@ +using System.Runtime.CompilerServices; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using AgentCore.Domain.Audit; +using AgentCore.TestSupport; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.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. +/// +public sealed class MemoryCompilationTests : IDisposable +{ + private static readonly string[] ExpectedMemoryTools = + [ + "file_memory_write", + "file_memory_read", + "file_memory_delete", + "file_memory_ls", + "file_memory_grep", + "file_memory_replace", + "file_memory_replace_lines", + ]; + + private const string MemoryYaml = + """ + apiVersion: agentcore/v1 + name: harness-memory + agents: + items: + - { id: only, instructions: "remember things", memory: { store: workspace } } + """; + + private const string NoMemoryYaml = + """ + apiVersion: agentcore/v1 + name: harness-no-memory + agents: + items: + - { id: only, instructions: "remember nothing" } + """; + + private const string MemoryPolicyYaml = + """ + apiVersion: agentcore/v1 + name: harness-memory-policy + state: + done: + type: boolean + default: false + writer: const + value: false + guards: + isDone: { var: done } + agents: + items: + - { id: only, instructions: "remember things", memory: { store: workspace } } + policy: + initial: working + stages: + - id: working + agent: only + to: [ { stage: finished, when: isDone } ] + - id: finished + agent: only + terminal: true + """; + + private readonly string _root = + Path.Combine(Path.GetTempPath(), "agentcore-memory-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [Fact] + public async Task Compile_MemoryWorkspaceWithARoot_GetsAFileMemoryProviderAndTheSevenTools() + { + using SequencedChatClient reply = new("hello there."); + var document = ConfigurationLoader.LoadYaml(MemoryYaml); + var chatClients = new RoutingChatClientFactory(reply); + + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { WorkspaceRoot = _root }); + var agent = Assert.Single(compiled.Agents.Values); + Assert.Contains(Providers(agent), provider => provider is FileMemoryProvider); + + var factory = new CallSessionFactory( + compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); + var session = factory.Create("call-1"); + + // A turn must be open for the FileMemoryProvider's state initializer to read the call id off + // TurnAmbients, so the tool list is read through a real call rather than agent.RunAsync + // directly, unlike the todos/mode providers in HarnessCompilationTests. + await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + Assert.Equal(ExpectedMemoryTools, toolNames, StringComparer.Ordinal); + } + + [Fact] + public async Task Compile_NoMemoryBlock_GetsNoFileMemoryProviderAndNoTool() + { + using SequencedChatClient reply = new("hello there."); + + var agent = CompileOne(NoMemoryYaml, reply, _root); + Assert.DoesNotContain(Providers(agent), provider => provider is FileMemoryProvider); + + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + await agent.RunAsync("hi", session, cancellationToken: token); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + Assert.DoesNotContain(toolNames, name => name.StartsWith("file_memory_", StringComparison.Ordinal)); + } + + [Fact] + public void Compile_MemoryWorkspaceWithNoRoot_FailsNamingTheMemoryPointer() + { + using SequencedChatClient reply = new("hello there."); + var document = ConfigurationLoader.LoadYaml(MemoryYaml); + + var failure = Assert.Throws(() => ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new FakeChatClientFactory(reply)))); + + Assert.Equal("/agents/items/0/memory", failure.Pointer); + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task EndToEnd_TheModelWritesAFile_ItLandsUnderTheCallsFolder_AndIsGoneWhenTheCallEnds() + { + var factory = BuildFactory(MemoryYaml, _root); + var session = factory.Create("call-1"); + var callFolder = session.Workspace!; + + await session.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); + + var notes = FindRecursive(callFolder, "notes.md"); + Assert.NotEmpty(notes); + Assert.Contains("hello", await File.ReadAllTextAsync(notes[0], TestContext.Current.CancellationToken)); + + session.EndCall(CallEndReason.CallerHungUp); + + Assert.False(Directory.Exists(callFolder)); + } + + [Fact] + public async Task TwoSessions_DifferentCallIds_WriteToDifferentFolders() + { + var factory = BuildFactory(MemoryYaml, _root); + + var first = factory.Create("call-a"); + await first.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); + + var second = factory.Create("call-b"); + await second.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); + + var firstNotes = FindRecursive(first.Workspace!, "notes.md"); + var secondNotes = FindRecursive(second.Workspace!, "notes.md"); + + Assert.NotEmpty(firstNotes); + Assert.NotEmpty(secondNotes); + Assert.DoesNotContain(firstNotes[0], secondNotes); + } + + [Fact] + public async Task MidTurnEndCall_DuringAFileMemoryWrite_StillDeletesTheFolder_EvenWhenThePolicyIsNotTerminal() + { + var document = ConfigurationLoader.LoadYaml(MemoryPolicyYaml); + EndCallDuringToolChatClient chatClient = new( + "hello there.", + new Dictionary(StringComparer.Ordinal) + { + ["fileName"] = "notes.md", + ["content"] = "hello", + }); + var chatClients = new RoutingChatClientFactory(chatClient); + + var compiled = ConfigurationCompiler.Compile( + document, new AgentCompilationContext(chatClients) { WorkspaceRoot = _root }); + var factory = new CallSessionFactory( + compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); + var session = factory.Create("call-1"); + var callFolder = 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); + + var turn = await session.RunTurnAsync("please remember this", TestContext.Current.CancellationToken); + + Assert.False(turn.IsTerminal); + Assert.False(Directory.Exists(callFolder)); + } + + private static CallSessionFactory BuildFactory(string yaml, string root) + { + var document = ConfigurationLoader.LoadYaml(yaml); + var chatClients = new RoutingChatClientFactory(new ToolCallingChatClient( + "hello there.", + new Dictionary(StringComparer.Ordinal) + { + ["fileName"] = "notes.md", + ["content"] = "hello", + })); + + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { WorkspaceRoot = root }); + + return new CallSessionFactory( + compiled, + new GuardEvaluator(compiled.Configuration.Guards), + workspaceRoot: root); + } + + private static string[] FindRecursive(string root, string fileName) + => Directory.Exists(root) + ? Directory.GetFiles(root, fileName, SearchOption.AllDirectories) + : []; + + private static AIAgent CompileOne(string yaml, SequencedChatClient reply, string root) + { + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(yaml), + new AgentCompilationContext(new FakeChatClientFactory(reply)) { WorkspaceRoot = root }); + + return Assert.Single(compiled.Agents.Values); + } + + private static IEnumerable Providers(AIAgent agent) + { + var inner = agent.GetService(); + Assert.NotNull(inner); + return inner.AIContextProviders ?? []; + } + + /// + /// 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. + /// + private sealed class EndCallDuringToolChatClient : IChatClient + { + private const string CallId = "call_1"; + + private readonly string _reply; + private readonly Dictionary _arguments; + private bool _answered; + + public EndCallDuringToolChatClient(string reply, Dictionary arguments) + { + _reply = reply; + _arguments = arguments; + } + + public Action? BeforeToolCall { get; set; } + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + await Task.Yield(); + + var answeredAlready = messages.Any( + message => message.Contents.Any(content => content is FunctionResultContent)); + var tool = options?.Tools?.OfType().FirstOrDefault(); + var responseId = Guid.NewGuid().ToString("N"); + + if (tool is not null && !answeredAlready && !_answered) + { + _answered = true; + BeforeToolCall?.Invoke(); + + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent(CallId, tool.Name, _arguments)]) + { + ResponseId = responseId, + MessageId = responseId, + }; + + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, _reply) + { + ResponseId = responseId, + MessageId = responseId, + }; + } + + 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) + { + ArgumentNullException.ThrowIfNull(serviceType); + return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; + } + + public void Dispose() + { + // Nothing to release. + } + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs index bc81aac2..7e0ab9f4 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs @@ -63,6 +63,41 @@ public async Task ARootThatCannotBeCreated_FailsStartupWithThePathAndTheOption() Assert.Contains(unusableRoot, failure.Message, StringComparison.Ordinal); } + [Fact] + public async Task AMemoryAgent_WithAWorkspaceRootBound_Starts() + { + using var provider = await BuildAsync(MemoryAgentYaml, options => options.UseWorkspace(_tempRoot)); + + var sessions = provider.GetRequiredService(); + var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + + Assert.StartsWith(_tempRoot, session.Workspace, StringComparison.Ordinal); + } + + [Fact] + public async Task AMemoryAgent_WithNoWorkspaceRootBound_FailsStartupNamingUseWorkspace() + { + var failure = await Assert.ThrowsAsync( + () => BuildAsync(MemoryAgentYaml)); + + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AMemoryAgent_WithARootThatCannotBeCreated_FailsStartupWithThePathAndTheOption() + { + var blockingFile = Path.Combine(_tempRoot, "blocks-the-root"); + Directory.CreateDirectory(_tempRoot); + await File.WriteAllTextAsync(blockingFile, "not a directory", TestContext.Current.CancellationToken); + var unusableRoot = Path.Combine(blockingFile, "x"); + + var failure = await Assert.ThrowsAsync( + () => BuildAsync(MemoryAgentYaml, options => options.UseWorkspace(unusableRoot))); + + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + Assert.Contains(unusableRoot, failure.Message, StringComparison.Ordinal); + } + public void Dispose() { if (Directory.Exists(_tempRoot)) @@ -70,4 +105,20 @@ public void Dispose() Directory.Delete(_tempRoot, recursive: true); } } + + private const string MemoryAgentYaml = + """ + apiVersion: agentcore/v1 + name: composed + agents: + items: + - { id: only, instructions: "I answer everything", memory: { store: workspace } } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; } From 40824d7b7972e3af83adf93c802e298ec957d94f Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 19:10:46 -0600 Subject: [PATCH 08/32] feat: implement file access and memory management for agent harness --- .../Compilation/AgentHarnessProviders.cs | 82 +++- .../Runtime/CallScopedAgentFileStore.cs | 37 ++ .../Compilation/FilesCompilationTests.cs | 368 ++++++++++++++++++ .../Compilation/MemoryCompilationTests.cs | 21 + .../Runtime/CallScopedAgentFileStoreTests.cs | 47 +++ .../Runtime/TurnAmbientsTestScope.cs | 4 + .../WorkspaceStartupTests.cs | 36 ++ 7 files changed, 591 insertions(+), 4 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs create mode 100644 tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 7db1bd99..d406725e 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -7,16 +7,57 @@ namespace AgentCore.Application.Configuration.Compilation; /// /// The context providers behind one agent's harness switches (todos:, mode:, -/// memory:), added into the provider list builds. +/// memory:, files:), added into the provider list builds. /// internal static class AgentHarnessProviders { - /// Adds this agent's harness providers, in declaration order: todos, mode, memory. + /// + /// 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. + /// + 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" + + "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" + + "- Before starting new tasks, use file_memory_ls and file_memory_grep to check for relevant existing memories to avoid duplicate work.\n" + + "- Keep memories up-to-date by overwriting files when information changes, or by using file_memory_replace and file_memory_replace_lines to make small edits.\n" + + "- When you receive large amounts of data (e.g., downloaded web pages, API responses, research results),\n" + + " write them to files if they will be required later, so that they are not lost when older context is compacted or truncated.\n" + + " This ensures important data remains accessible across long-running sessions."; + + /// + /// 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 — CallScopedAgentFileStore + /// resolves to the call's workspace, deleted at EndCall. 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" + + "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" + + " or `file_access_grep` to search file contents recursively across the whole store.\n" + + "- To make small edits to an existing file, prefer `file_access_replace` (substring replacement) or\n" + + " `file_access_replace_lines` (whole-line replacement) over rewriting the whole file.\n" + + "- To change part of a file, find the line numbers with `file_access_grep`, read the range around them\n" + + " with `file_access_read_lines`, then edit with `file_access_replace_lines`. Reading the whole file\n" + + " first is rarely necessary."; + + /// Adds this agent's harness providers, in declaration order: todos, mode, memory, files. /// The provider list under construction. /// The agents.defaults section, or . /// The agent being compiled. /// The compile-time seams, including the bound workspace root. - /// This agent's JSON pointer, for a memory: failure. + /// This agent's JSON pointer, for a memory: or files: failure. public static void Add( List providers, AgentDefaults? defaults, @@ -40,6 +81,11 @@ public static void Add( { providers.Add(BuildMemoryProvider(item, context, pointer)); } + + if (item.Files is { Store: AgentFileStoreKind.Workspace } files) + { + providers.Add(BuildFilesProvider(item, files, context, pointer)); + } } private static FileMemoryProvider BuildMemoryProvider( @@ -57,7 +103,10 @@ private static FileMemoryProvider BuildMemoryProvider( try { #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. - return new FileMemoryProvider(new FileSystemAgentFileStore(root), InitializeWorkingFolder); + return new FileMemoryProvider( + new FileSystemAgentFileStore(root), + InitializeWorkingFolder, + new FileMemoryProviderOptions { Instructions = MemoryInstructions }); #pragma warning restore MAAI001 } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) @@ -73,6 +122,31 @@ private static FileMemoryProvider BuildMemoryProvider( } } +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. + private static FileAccessProvider BuildFilesProvider( + AgentConfiguration item, AgentFilesConfiguration files, AgentCompilationContext context, string pointer) + { + if (context.WorkspaceRoot is null) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "files"), + $"the agent '{item.Id}' declares a files: block and this host bound no workspace " + + "root, so there is nowhere to keep the files. Call options.UseWorkspace(...) with " + + "the folder, or remove the files: block."); + } + + return new FileAccessProvider( + new CallScopedAgentFileStore(), + new FileAccessProviderOptions + { + DisableWriteTools = !files.Write, + DisableReadOnlyToolApproval = true, + DisableWriteToolApproval = true, + Instructions = FilesInstructions, + }); + } +#pragma warning restore MAAI001 + /// /// 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 diff --git a/src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs b/src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs new file mode 100644 index 00000000..9cb75f78 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs @@ -0,0 +1,37 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime; + +/// +/// The store behind an agent's files: block. One instance serves every call: each operation +/// resolves the running call's workspace folder off and forwards to a +/// fresh rooted there. +/// +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. +internal sealed class CallScopedAgentFileStore : AgentFileStore +{ + private const string NoTurnMessage = + "A files: tool runs only while a turn runs through a CallSession with a workspace root bound."; + + private static FileSystemAgentFileStore Inner() => + new(TurnAmbients.Current?.Workspace ?? throw new InvalidOperationException(NoTurnMessage)); + + public override Task WriteAsync(string path, string content, CancellationToken cancellationToken = default) => + Inner().WriteAsync(path, content, cancellationToken); + + public override Task ReadAsync(string path, CancellationToken cancellationToken = default) => + Inner().ReadAsync(path, cancellationToken); + + public override Task DeleteAsync(string path, CancellationToken cancellationToken = default) => + Inner().DeleteAsync(path, cancellationToken); + + public override Task> ListChildrenAsync(string directory, CancellationToken cancellationToken = default) => + Inner().ListChildrenAsync(directory, cancellationToken); + + public override Task FileExistsAsync(string path, CancellationToken cancellationToken = default) => + Inner().FileExistsAsync(path, cancellationToken); + + public override Task CreateDirectoryAsync(string path, CancellationToken cancellationToken = default) => + Inner().CreateDirectoryAsync(path, cancellationToken); +} +#pragma warning restore MAAI001 diff --git a/tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs b/tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs new file mode 100644 index 00000000..b9f804d1 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs @@ -0,0 +1,368 @@ +using System.Runtime.CompilerServices; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using AgentCore.Domain.Audit; +using AgentCore.TestSupport; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.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. +/// +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. +public sealed class FilesCompilationTests : IDisposable +{ + private static readonly string[] ExpectedFilesTools = + [ + "file_access_read", + "file_access_read_lines", + "file_access_ls", + "file_access_grep", + "file_access_write", + "file_access_delete", + "file_access_replace", + "file_access_replace_lines", + ]; + + private static readonly string[] ExpectedReadOnlyFilesTools = + [ + "file_access_read", + "file_access_read_lines", + "file_access_ls", + "file_access_grep", + ]; + + private const string FilesYaml = + """ + apiVersion: agentcore/v1 + name: harness-files + agents: + items: + - { id: only, instructions: "work with files", files: { store: workspace } } + """; + + private const string ReadOnlyFilesYaml = + """ + apiVersion: agentcore/v1 + name: harness-files-readonly + agents: + items: + - { id: only, instructions: "read files", files: { store: workspace, write: false } } + """; + + private const string NoFilesYaml = + """ + apiVersion: agentcore/v1 + name: harness-no-files + agents: + items: + - { id: only, instructions: "no files here" } + """; + + private readonly string _root = + Path.Combine(Path.GetTempPath(), "agentcore-files-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [Fact] + public async Task Compile_FilesWorkspaceWithARoot_GetsAFileAccessProviderAndTheEightTools() + { + using SequencedChatClient reply = new("hello there."); + var agent = CompileOne(FilesYaml, reply, _root); + Assert.Contains(Providers(agent), provider => provider is FileAccessProvider); + + var factory = BuildFactory(FilesYaml, _root, reply); + var session = factory.Create("call-1"); + await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); + + var tools = reply.Options[^1]?.Tools?.OfType().ToArray() ?? []; + AssertSameNames(ExpectedFilesTools, tools.Select(tool => tool.Name).ToArray()); + Assert.True( + tools.All(tool => tool is not ApprovalRequiredAIFunction), + "expected no file_access_* tool to require approval"); + } + + [Fact] + public async Task Compile_FilesWorkspaceWithARoot_TheModelsInstructionsAreTruthfulAboutDeletion() + { + using SequencedChatClient reply = new("hello there."); + var factory = BuildFactory(FilesYaml, _root, reply); + var session = factory.Create("call-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.DoesNotContain("persist beyond", instructions, StringComparison.Ordinal); + } + + [Fact] + public async Task Compile_FilesWorkspaceWriteFalse_GetsOnlyTheFourReadOnlyTools() + { + using SequencedChatClient reply = new("hello there."); + var factory = BuildFactory(ReadOnlyFilesYaml, _root, reply); + var session = factory.Create("call-1"); + await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + AssertSameNames(ExpectedReadOnlyFilesTools, toolNames); + } + + [Fact] + public async Task Compile_NoFilesBlock_GetsNoFileAccessProviderAndNoTool() + { + using SequencedChatClient reply = new("hello there."); + + var agent = CompileOne(NoFilesYaml, reply, _root); + Assert.DoesNotContain(Providers(agent), provider => provider is FileAccessProvider); + + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + await agent.RunAsync("hi", session, cancellationToken: token); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + Assert.DoesNotContain(toolNames, name => name.StartsWith("file_access_", StringComparison.Ordinal)); + } + + [Fact] + public void Compile_FilesWorkspaceWithNoRoot_FailsNamingTheFilesPointer() + { + var document = ConfigurationLoader.LoadYaml(FilesYaml); + + var failure = Assert.Throws(() => ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))))); + + Assert.Equal("/agents/items/0/files", failure.Pointer); + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task EndToEnd_WriteReadLsGrep_ThenEndCallDeletesTheFolder() + { + var client = new SequencedToolCallClient( + (FileAccessProvider.WriteToolName, Args(("fileName", "out.txt"), ("content", "hello"))), + (FileAccessProvider.ReadFileToolName, Args(("fileName", "out.txt"))), + (FileAccessProvider.LsToolName, Args()), + (FileAccessProvider.GrepToolName, Args(("regexPattern", "hell")))); + + var factory = BuildFactory(FilesYaml, _root, client); + var session = factory.Create("call-1"); + var callFolder = 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)); + + 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); + + 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)); + } + + [Fact] + public async Task Escape_WriteOutsideTheCallFolder_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"); + + // The point of the assertion is that this completes at all: an escape attempt must not + // throw out of RunTurnAsync. + await session.RunTurnAsync("escape", TestContext.Current.CancellationToken); + + // The real string, not the probe's "Error: Function failed." (that string is what a store + // exception looks like when it escapes uncaught, e.g. the missing-ambient case; a rejected + // path is instead refused before it throws, as a JSON error object naming the tool.) + Assert.Contains("\"error\": true", client.ToolResults[0], StringComparison.Ordinal); + Assert.Contains("file_access_write", client.ToolResults[0], StringComparison.Ordinal); + + var escaped = Directory.Exists(_root) + ? Directory.EnumerateFiles(_root, "escape.txt", SearchOption.AllDirectories).ToList() + : []; + Assert.Empty(escaped); + } + + [Fact] + public async Task TwoSessions_DifferentCallIds_SeeOnlyTheirOwnFile() + { + var clientA = new SequencedToolCallClient( + (FileAccessProvider.WriteToolName, Args(("fileName", "out.txt"), ("content", "A")))); + var clientB = new SequencedToolCallClient( + (FileAccessProvider.WriteToolName, Args(("fileName", "out.txt"), ("content", "B")))); + + var factoryA = BuildFactory(FilesYaml, _root, clientA); + var sessionA = factoryA.Create("call-a"); + await sessionA.RunTurnAsync("write A", TestContext.Current.CancellationToken); + + var factoryB = BuildFactory(FilesYaml, _root, clientB); + var sessionB = factoryB.Create("call-b"); + await sessionB.RunTurnAsync("write B", TestContext.Current.CancellationToken); + + var pathA = Path.Combine(sessionA.Workspace!, "out.txt"); + var pathB = Path.Combine(sessionB.Workspace!, "out.txt"); + + Assert.Equal("A", await File.ReadAllTextAsync(pathA, TestContext.Current.CancellationToken)); + Assert.Equal("B", await File.ReadAllTextAsync(pathB, TestContext.Current.CancellationToken)); + } + + private static void AssertSameNames(string[] expected, string[] actual) + { + var expectedSorted = expected.OrderBy(n => n, StringComparer.Ordinal).ToArray(); + var actualSorted = actual.OrderBy(n => n, StringComparer.Ordinal).ToArray(); + Assert.Equal(expectedSorted, actualSorted, StringComparer.Ordinal); + } + + private static Dictionary Args(params (string Key, object? Value)[] pairs) + { + var args = new Dictionary(StringComparer.Ordinal); + foreach (var (key, value) in pairs) + { + args[key] = value; + } + + return args; + } + + private static CallSessionFactory BuildFactory(string yaml, string root, IChatClient? client = null) + { + var document = ConfigurationLoader.LoadYaml(yaml); + var chatClients = new RoutingChatClientFactory(client ?? new SequencedChatClient("done")); + + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { WorkspaceRoot = root }); + + return new CallSessionFactory( + compiled, + new GuardEvaluator(compiled.Configuration.Guards), + workspaceRoot: root); + } + + private static AIAgent CompileOne(string yaml, SequencedChatClient reply, string root) + { + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(yaml), + new AgentCompilationContext(new FakeChatClientFactory(reply)) { WorkspaceRoot = root }); + + return Assert.Single(compiled.Agents.Values); + } + + private static IEnumerable Providers(AIAgent agent) + { + var inner = agent.GetService(); + Assert.NotNull(inner); + return inner.AIContextProviders ?? []; + } + + /// + /// A deterministic offline model that plays a queue of specific named tool calls, one per turn: + /// it calls the next queued tool when the last message is a fresh user turn, and replies with + /// text once the framework has fed the tool's result back mid-turn. + /// + private sealed class SequencedToolCallClient : IChatClient + { + private readonly Queue<(string Name, Dictionary Args)> _steps; + + public SequencedToolCallClient(params (string Name, Dictionary Args)[] steps) + => _steps = new(steps); + + /// Gets the text of each tool result this client was fed back, in call order. + public List ToolResults { get; } = []; + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + await Task.Yield(); + + var transcript = messages.ToList(); + var responseId = Guid.NewGuid().ToString("N"); + + var lastResults = transcript.Count > 0 + ? transcript[^1].Contents.OfType().ToList() + : []; + + foreach (var result in lastResults) + { + lock (ToolResults) + { + ToolResults.Add(result.Result?.ToString() ?? string.Empty); + } + } + + if (lastResults.Count == 0 && _steps.Count > 0) + { + var (name, args) = _steps.Dequeue(); + + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent("call_" + Guid.NewGuid().ToString("N"), name, args)]) + { + ResponseId = responseId, + MessageId = responseId, + }; + + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, "done") + { + ResponseId = responseId, + MessageId = responseId, + }; + } + + 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) + { + ArgumentNullException.ThrowIfNull(serviceType); + return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; + } + + public void Dispose() + { + // Nothing to release. + } + } +} +#pragma warning restore MAAI001 diff --git a/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs b/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs index 2cf047a5..5ebf168e 100644 --- a/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs @@ -112,6 +112,27 @@ public async Task Compile_MemoryWorkspaceWithARoot_GetsAFileMemoryProviderAndThe Assert.Equal(ExpectedMemoryTools, toolNames, StringComparer.Ordinal); } + [Fact] + public async Task Compile_MemoryWorkspaceWithARoot_TheModelsInstructionsAreTruthfulAboutDeletion() + { + using SequencedChatClient reply = new("hello there."); + var document = ConfigurationLoader.LoadYaml(MemoryYaml); + var chatClients = new RoutingChatClientFactory(reply); + + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { WorkspaceRoot = _root }); + var factory = new CallSessionFactory( + compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); + var session = factory.Create("call-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.DoesNotContain("persist beyond", instructions, StringComparison.Ordinal); + } + [Fact] public async Task Compile_NoMemoryBlock_GetsNoFileMemoryProviderAndNoTool() { diff --git a/tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs new file mode 100644 index 00000000..098ec98a --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs @@ -0,0 +1,47 @@ +using AgentCore.Application.Runtime; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// as a unit: it resolves the running call's workspace off +/// at each operation, with no root and no cache of its own. +/// +public sealed class CallScopedAgentFileStoreTests +{ + [Fact] + public async Task NoAmbientWorkspace_ReadAsyncThrowsInvalidOperationException() + { + var store = new CallScopedAgentFileStore(); + + var exception = await Assert.ThrowsAsync( + () => store.ReadAsync("out.txt", TestContext.Current.CancellationToken)); + + Assert.Contains("files: tool", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AmbientWorkspaceOpen_WriteThenReadRoundTrips_UnderThatWorkspace() + { + var workspace = Directory.CreateTempSubdirectory("call-scoped-file-store-").FullName; + try + { + var store = new CallScopedAgentFileStore(); + + using (TurnAmbientsTestScope.WithWorkspace(workspace)) + { + await store.WriteAsync("out.txt", "hello", TestContext.Current.CancellationToken); + var read = await store.ReadAsync("out.txt", TestContext.Current.CancellationToken); + + Assert.Equal("hello", read); + } + + Assert.Equal("hello", await File.ReadAllTextAsync( + Path.Combine(workspace, "out.txt"), TestContext.Current.CancellationToken)); + } + finally + { + Directory.Delete(workspace, recursive: true); + } + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs b/tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs index 88a485de..5a6a598e 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs +++ b/tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs @@ -19,6 +19,10 @@ internal static IDisposable WithSources(TurnSources sources) internal static IDisposable WithClarifications(Clarifications clarifications) => TurnAmbients.Amend(ambients => ambients with { Clarifications = clarifications }); + /// Opens the call's workspace folder over this flow, the way CallSession does. + internal static IDisposable WithWorkspace(string? workspace) + => TurnAmbients.Amend(ambients => ambients with { Workspace = workspace }); + /// /// Opens a turn context whose is /// — true for a row 1 or 2 turn, false for a graph row's own participant invocation (K39). diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs index 7e0ab9f4..0a0aec34 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/WorkspaceStartupTests.cs @@ -98,6 +98,26 @@ public async Task AMemoryAgent_WithARootThatCannotBeCreated_FailsStartupWithTheP Assert.Contains(unusableRoot, failure.Message, StringComparison.Ordinal); } + [Fact] + public async Task AFilesAgent_WithAWorkspaceRootBound_Starts() + { + using var provider = await BuildAsync(FilesAgentYaml, options => options.UseWorkspace(_tempRoot)); + + var sessions = provider.GetRequiredService(); + var session = await sessions.OpenAsync("call-1", TestContext.Current.CancellationToken); + + Assert.StartsWith(_tempRoot, session.Workspace, StringComparison.Ordinal); + } + + [Fact] + public async Task AFilesAgent_WithNoWorkspaceRootBound_FailsStartupNamingUseWorkspace() + { + var failure = await Assert.ThrowsAsync( + () => BuildAsync(FilesAgentYaml)); + + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + } + public void Dispose() { if (Directory.Exists(_tempRoot)) @@ -121,4 +141,20 @@ public void Dispose() llm: - { kind: openai, model: gpt-4.1-mini, as: reply } """; + + private const string FilesAgentYaml = + """ + apiVersion: agentcore/v1 + name: composed + agents: + items: + - { id: only, instructions: "I answer everything", files: { store: workspace } } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; } From ceb19340a1d8829481649721db8aaa2b0bc7b308 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 20:18:55 -0600 Subject: [PATCH 09/32] feat: enhance CallSessionState and related components to manage harness provider states --- .../Calls/CallSessionState.cs | 12 + .../Compilation/AgentHarnessProviders.cs | 26 ++ .../Compilation/CompiledAgent.cs | 9 + .../Compilation/ConfigurationCompiler.cs | 36 ++- .../PublicAPI.Unshipped.txt | 2 + .../Runtime/CallSession.cs | 51 ++-- .../Runtime/HarnessSessionState.cs | 67 +++++ .../Calls/CallSessionStateTests.cs | 40 +++ .../Compilation/HarnessCompilationTests.cs | 71 +++++ .../Runtime/CallSessionProviderStateTests.cs | 254 ++++++++++++++++++ .../Runtime/HarnessSessionStateTests.cs | 72 +++++ 11 files changed, 612 insertions(+), 28 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/HarnessSessionState.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Calls/CallSessionState.cs index e7dbb0c0..ca35f831 100644 --- a/src/AgentCore.Application/Calls/CallSessionState.cs +++ b/src/AgentCore.Application/Calls/CallSessionState.cs @@ -1,4 +1,5 @@ using System.Collections.ObjectModel; +using System.Text.Json; using System.Text.Json.Nodes; namespace AgentCore.Application.Calls; @@ -14,6 +15,10 @@ public sealed record CallSessionState private static readonly IReadOnlyDictionary NoClarifications = ReadOnlyDictionary.Empty; + /// The providers of a call whose document declares no harness switch. + private static readonly IReadOnlyDictionary NoProviders = + ReadOnlyDictionary.Empty; + /// The shape this version of the library writes. public const int CurrentVersion = 1; @@ -37,4 +42,11 @@ public sealed record CallSessionState /// nothing has asked about is absent. /// public IReadOnlyDictionary Clarifications { get; init; } = NoClarifications; + + /// + /// Gets the MAF provider state a harness switch (todos:, mode:, memory:, + /// files:) held, keyed by that provider's state key. A document with no harness switch + /// holds none. Absent in an old blob, which restores its stage and slots as before. + /// + public IReadOnlyDictionary Providers { get; init; } = NoProviders; } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index d406725e..2744664e 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -88,6 +88,32 @@ public static void Add( } } + /// + /// The state keys of the harness providers among — never the + /// history provider's key, which is the transcript and belongs to store 1. + /// +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. + internal static IReadOnlySet StateKeysOf(IEnumerable providers) + { + HashSet keys = new(StringComparer.Ordinal); + + foreach (var provider in providers) + { + if (provider is not (TodoProvider or AgentModeProvider or FileMemoryProvider or FileAccessProvider)) + { + continue; + } + + foreach (var key in provider.StateKeys) + { + keys.Add(key); + } + } + + return keys; + } +#pragma warning restore MAAI001 + private static FileMemoryProvider BuildMemoryProvider( AgentConfiguration item, AgentCompilationContext context, string pointer) { diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs index d2351f59..bb769328 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs @@ -27,6 +27,7 @@ internal CompiledAgent( Dictionary agentIdByStage, IReadOnlySet? spokenBy, AgentCoreChatHistoryProvider history, + IReadOnlySet harnessStateKeys, Func turnLayers) { Configuration = configuration; @@ -36,6 +37,7 @@ internal CompiledAgent( CallStore = calls; SpokenBy = spokenBy; History = history; + HarnessStateKeys = harnessStateKeys; _byAgentId = byAgentId; _agentIdByStage = agentIdByStage; @@ -82,6 +84,13 @@ internal CompiledAgent( /// Gets the store this agent's calls and every word of them are kept in. internal ICallStore CallStore { 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. + /// + internal IReadOnlySet HarnessStateKeys { get; } + /// /// Gets the agent a turn runs, with the turn-disposition layers on it. /// diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index b73dfe23..71546867 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -141,7 +141,7 @@ public static CompiledAgent Compile(AgentCoreConfiguration configuration, AgentC AgentCoreChatHistoryProvider history = new(calls); - var agents = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null); + var (agents, harnessStateKeys) = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null); var (entry, stages) = row.BuildEntry(configuration, agents, context); @@ -156,6 +156,7 @@ public static CompiledAgent Compile(AgentCoreConfiguration configuration, AgentC stages, spokenBy, history, + harnessStateKeys, inner => WithTurnDisposition(inner, configuration, context.Moderation, spokenBy)); } @@ -182,16 +183,18 @@ 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. - private static Dictionary BuildAgents( + /// The agents, keyed by id, and the union of every harness provider's state keys. + private static (Dictionary Agents, IReadOnlySet HarnessStateKeys) BuildAgents( AgentCoreConfiguration configuration, AgentCompilationContext context, AgentCoreChatHistoryProvider? history) { Dictionary agents = new(StringComparer.Ordinal); + HashSet harnessStateKeys = new(StringComparer.Ordinal); + if (configuration.Agents is not { } section) { - return agents; + return (agents, harnessStateKeys); } var clarification = ResolvedClarification.From(configuration); @@ -224,7 +227,7 @@ private static Dictionary BuildAgents( Resolve(item.Id); } - return agents; + return (agents, harnessStateKeys); AIAgent? Resolve(string id) { @@ -253,6 +256,19 @@ private static Dictionary BuildAgents( } path.Add(id); + + 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); + harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); + var built = new ChatClientAgent( WithToolFailureAuditing(context.ChatClients.GetChatClient(item.Model ?? section.Defaults?.Model)), new ChatClientAgentOptions @@ -261,16 +277,10 @@ private static Dictionary BuildAgents( ChatOptions = new ChatOptions { Instructions = AgentInstructions.Compose(section.Defaults, item), - Tools = AgentToolCompiler.Build(item, item.Model ?? section.Defaults?.Model, tools, context, pointer, Resolve), + Tools = compiledTools, }, ChatHistoryProvider = history, - AIContextProviders = AgentContextProviderCompiler.Build( - section.Defaults, - item, - context, - pointer, - clarification, - configuration.Providers?.Knowledge?.Scope), + AIContextProviders = providers, }); path.RemoveAt(path.Count - 1); diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 96a67614..f791e9ed 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -107,6 +107,8 @@ 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! diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index d822cc2a..4b1710f6 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -551,12 +551,34 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell return opened; } - var session = _sessionCarriesHistory - ? await _compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false) - : new CallHistorySession(); - var record = await _compiled.CallStore.CreateAsync(CallId, cancellationToken).ConfigureAwait(false); + CallSessionState? checkpoint; + lock (_interruptLock) + { + checkpoint = _checkpoint; + } + + // One restore point for both sources, and store 0 outranks the host's checkpoint outright + // 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. + var stored = record.State ?? checkpoint; + + AgentSession session; + if (_sessionCarriesHistory) + { + session = stored is { Version: CallSessionState.CurrentVersion, Providers.Count: > 0 } + ? await _compiled.TurnAgent.DeserializeSessionAsync( + HarnessSessionState.Wrap(stored.Providers), cancellationToken: cancellationToken).ConfigureAwait(false) + : await _compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + else + { + session = new CallHistorySession(); + } + IReadOnlyList spoken = record.LastMessageAt is null ? [] : await _compiled.CallStore.ReadAsync(CallId, cancellationToken).ConfigureAwait(false); @@ -572,21 +594,14 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell CallId, spoken, _events.RaiseDroppedTranscriptWrite, - new TranscriptMarks( - record.NextOrdinal, (record.State ?? _checkpoint)?.NextTurnIndex ?? 0)); + new TranscriptMarks(record.NextOrdinal, stored?.NextTurnIndex ?? 0)); // After the constructor, never inside it. The const writer has already run by now, // so a slot a previous session filled lands on top of the const default rather than // under it — and the record it is read from only exists after an async store read. - // - // One restore point for both sources, and store 0 outranks the host's checkpoint - // outright 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. - if ((record.State ?? _checkpoint) is { } stored) + if (stored is { } s) { - Restore(stored); + Restore(s); } } @@ -594,7 +609,11 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell } } - /// Reads the state this call would resume from, as it stands right now. + /// + /// Reads the state this call 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. + /// internal CallSessionState Snapshot() { lock (_interruptLock) @@ -621,6 +640,8 @@ internal CallSessionState Snapshot() NextTurnIndex = State.TurnIndex, Clarifications = _clarifications.Spent(), + + Providers = HarnessSessionState.Capture(_agentSession, _compiled.HarnessStateKeys), }; } diff --git a/src/AgentCore.Application/Runtime/HarnessSessionState.cs b/src/AgentCore.Application/Runtime/HarnessSessionState.cs new file mode 100644 index 00000000..32032c20 --- /dev/null +++ b/src/AgentCore.Application/Runtime/HarnessSessionState.cs @@ -0,0 +1,67 @@ +using System.Collections.ObjectModel; +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime; + +/// +/// Moves the harness providers' MAF state — todos:, mode:, memory:, +/// files: — between a live 's state bag and +/// . +/// +internal static class HarnessSessionState +{ + private static readonly IReadOnlyDictionary Empty = + ReadOnlyDictionary.Empty; + + /// + /// Reads the harness providers' state out of , keeping only the keys + /// names. + /// + /// The live session, or . + /// The harness providers' state keys this document declares. + /// + /// The kept keys, each value cloned off the bag's own serialization. Empty for a + /// session or an empty — the bag is never + /// serialized in that case, because it also holds the transcript. + /// + public static IReadOnlyDictionary Capture(AgentSession? session, IReadOnlySet keys) + { + if (session is null || keys.Count == 0) + { + return Empty; + } + + var serialized = session.StateBag.Serialize(); + Dictionary providers = new(StringComparer.Ordinal); + + foreach (var property in serialized.EnumerateObject()) + { + if (keys.Contains(property.Name)) + { + providers[property.Name] = property.Value.Clone(); + } + } + + return providers.Count == 0 ? Empty : providers; + } + + /// + /// Builds the envelope expects: { "stateBag": + /// { key: element, ... } }, with no other member. + /// + public static JsonElement Wrap(IReadOnlyDictionary providers) + { + JsonObject stateBag = []; + + foreach (var (key, element) in providers) + { + stateBag[key] = JsonSerializer.SerializeToNode(element); + } + + JsonObject envelope = new() { ["stateBag"] = stateBag }; + + return JsonSerializer.SerializeToElement(envelope); + } +} diff --git a/tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs b/tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs index 0211be55..5264f22c 100644 --- a/tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/CallSessionStateTests.cs @@ -49,4 +49,44 @@ public void ItRoundTripsThroughJson() [Fact] public void ANewStateCarriesTheCurrentVersion() => Assert.Equal(CallSessionState.CurrentVersion, new CallSessionState().Version); + + [Fact] + public void ItRoundTripsProvidersThroughJson() + { + CallSessionState state = new() + { + Providers = new Dictionary(StringComparer.Ordinal) + { + ["TodoProvider"] = JsonDocument.Parse( + """{"items":[{"id":1,"title":"buy milk","isComplete":false}],"nextId":2}""").RootElement, + ["AgentModeProvider"] = JsonDocument.Parse("""{"currentMode":"plan"}""").RootElement, + }, + }; + + var json = JsonSerializer.Serialize(state, CallStateJson.Options); + var read = JsonSerializer.Deserialize(json, CallStateJson.Options); + + Assert.NotNull(read); + Assert.Equal(2, read.Providers.Count); + Assert.Equal( + state.Providers["TodoProvider"].GetRawText(), + read.Providers["TodoProvider"].GetRawText()); + Assert.Equal( + state.Providers["AgentModeProvider"].GetRawText(), + read.Providers["AgentModeProvider"].GetRawText()); + } + + [Fact] + public void ABlobWithNoProvidersMember_DeserializesWithEmptyProviders() + { + var read = JsonSerializer.Deserialize( + """{"version":1,"nextTurnIndex":0,"stage":"","isComplete":false}""", CallStateJson.Options); + + Assert.NotNull(read); + Assert.Empty(read.Providers); + } + + [Fact] + public void ANewState_HasEmptyProviders() + => Assert.Empty(new CallSessionState().Providers); } diff --git a/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs b/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs index 321693c0..65d0440d 100644 --- a/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs @@ -101,6 +101,77 @@ public async Task Compile_ModeTrue_ModelSeesTheTwoModeTools() Assert.Equal(ExpectedModeTools, toolNames, StringComparer.Ordinal); } + [Fact] + public void Compile_TodosAndModeTrue_HarnessStateKeysIsTheUnionOfBoth() + { + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-keys", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only", Todos = true, Mode = true }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); + + Assert.Equal( + new HashSet(StringComparer.Ordinal) + { + new TodoProvider().StateKeys[0], + new AgentModeProvider().StateKeys[0], + }, + compiled.HarnessStateKeys); + } + + [Fact] + public void Compile_NeitherTodosNorMode_HarnessStateKeysIsEmpty() + { + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-no-keys", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only" }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); + + Assert.Empty(compiled.HarnessStateKeys); + } + + private const string TwoAgentsOnlyOneWithTodosYaml = + """ + apiVersion: agentcore/v1 + name: harness-policy-keys + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: todoer, instructions: "track todos", todos: true } + - { id: plain, instructions: "just talk" } + policy: + initial: working + stages: + - { id: working, agent: todoer, to: [ { stage: done, when: always } ] } + - { id: done, agent: plain, terminal: true } + """; + + [Fact] + public void Compile_TwoAgentsOnlyOneWithTodos_HarnessStateKeysHasTheTodoKey() + { + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(TwoAgentsOnlyOneWithTodosYaml), + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); + + Assert.Equal( + new HashSet(StringComparer.Ordinal) { new TodoProvider().StateKeys[0] }, + compiled.HarnessStateKeys); + } + private static AIAgent CompileOne(bool withTodos, bool withMode) { using SequencedChatClient reply = new("hello there."); diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs new file mode 100644 index 00000000..154230be --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs @@ -0,0 +1,254 @@ +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.Json; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.Application.Tests.Fakes; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// 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 — +/// gets it re-injected by the framework's own . +/// +public sealed class CallSessionProviderStateTests +{ + private const string TodosYaml = + """ + apiVersion: agentcore/v1 + name: harness-provider-state + agents: + items: + - { id: only, instructions: "track todos", todos: true } + """; + + private const string NoTodosYaml = + """ + apiVersion: agentcore/v1 + name: harness-provider-state-none + agents: + items: + - { id: only, instructions: "just talk" } + """; + + [Fact] + public async Task AfterATurn_Store0HoldsOnlyTheTodoProviderKey_WithTheTodoInIt() + { + InMemoryCallStore 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"); + + await session.RunTurnAsync("please track this", TestContext.Current.CancellationToken); + + var record = await store.GetAsync("call-1", TestContext.Current.CancellationToken); + + Assert.NotNull(record); + Assert.NotNull(record.State); + var key = Assert.Single(record.State.Providers.Keys); + + // The one literal: it pins the on-disk shape of the todos: state, everywhere else the key + // comes from the real provider's own StateKeys. + Assert.Equal("TodoProvider", key); + Assert.Contains("buy milk", record.State.Providers[key].GetRawText(), StringComparison.Ordinal); + } + + [Fact] + public async Task ASecondSessionFromTheSameFactoryAndStore_ReInjectsTheTodo() + { + InMemoryCallStore store = new(); + TodoAddThenTextChatClient chatClient = new(); + var compiled = Compile(TodosYaml, chatClient, store); + var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + + var first = factory.Create("call-1"); + await first.RunTurnAsync("please track this", TestContext.Current.CancellationToken); + + var second = factory.Create("call-1"); + await second.RunTurnAsync("what's on my list", TestContext.Current.CancellationToken); + + Assert.Contains( + chatClient.Requests[^1], + message => message.Text.Contains("buy milk", StringComparison.Ordinal)); + } + + [Fact] + public async Task AResumeFromAHostCheckpoint_ThroughAgentCoreAgent_ReInjectsTheTodo() + { + InMemoryCallStore firstStore = new(); + TodoAddThenTextChatClient firstChatClient = new(); + var firstCompiled = Compile(TodosYaml, firstChatClient, firstStore); + AgentCoreAgent firstAgent = new( + new CallSessionFactory(firstCompiled, new GuardEvaluator(firstCompiled.Configuration.Guards))); + + var firstSession = await firstAgent.CreateSessionAsync( + "call-1", TestContext.Current.CancellationToken); + await firstAgent.RunAsync( + "please track this", firstSession, cancellationToken: TestContext.Current.CancellationToken); + + var serialized = await firstAgent.SerializeSessionAsync( + 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(); + SequencedChatClient secondChatClient = new("hello there."); + var secondCompiled = Compile(TodosYaml, secondChatClient, secondStore); + AgentCoreAgent secondAgent = new( + new CallSessionFactory(secondCompiled, new GuardEvaluator(secondCompiled.Configuration.Guards))); + + var revived = await secondAgent.DeserializeSessionAsync( + serialized, cancellationToken: TestContext.Current.CancellationToken); + await secondAgent.RunAsync( + "what's on my list", revived, cancellationToken: TestContext.Current.CancellationToken); + + Assert.Contains( + secondChatClient.Requests[^1], + message => message.Text.Contains("buy milk", StringComparison.Ordinal)); + } + + [Fact] + public async Task AVersion99StoredState_DropsTheProviders_TheTodoNeverReachesTheRequest() + { + InMemoryCallStore store = new(); + SequencedChatClient chatClient = new("hello there."); + var compiled = Compile(TodosYaml, chatClient, store); + var factory = new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + + CallSessionState fabricated = new() + { + Version = 99, + Providers = new Dictionary(StringComparer.Ordinal) + { + [new TodoProvider().StateKeys[0]] = JsonDocument.Parse( + """{"items":[{"id":1,"title":"buy milk","isComplete":false}],"nextId":2}""").RootElement, + }, + }; + + var session = factory.Create("call-1", fabricated); + + await session.RunTurnAsync("what's on my list", TestContext.Current.CancellationToken); + + Assert.DoesNotContain( + chatClient.Requests[^1], + message => message.Text.Contains("buy milk", StringComparison.Ordinal)); + } + + [Fact] + public async Task NoTodosBlock_AfterATurn_Store0HoldsNoProviders() + { + InMemoryCallStore 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"); + + await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); + + var record = await store.GetAsync("call-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) + => ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(yaml), + new AgentCompilationContext(new FakeChatClientFactory(chatClient)) { CallStore = store }); + + /// + /// 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. + /// + private sealed class TodoAddThenTextChatClient : IChatClient + { + private int _calls; + + public List> Requests { get; } = []; + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + + var index = Interlocked.Increment(ref _calls) - 1; + var transcript = messages.ToList(); + lock (Requests) + { + Requests.Add(transcript); + } + + await Task.Yield(); + + var responseId = Guid.NewGuid().ToString("N"); + var tool = options?.Tools?.OfType().FirstOrDefault(); + + if (index == 0 && tool is not null) + { + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent( + "call_1", + tool.Name, + new Dictionary(StringComparer.Ordinal) + { + ["todos"] = new List + { + new Dictionary(StringComparer.Ordinal) { ["title"] = "buy milk" }, + }, + })]) + { + ResponseId = responseId, + MessageId = responseId, + }; + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, "hello there.") + { + ResponseId = responseId, + MessageId = responseId, + }; + } + + 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) + { + ArgumentNullException.ThrowIfNull(serviceType); + return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; + } + + public void Dispose() + { + // Nothing to release. + } + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs new file mode 100644 index 00000000..7421ff6d --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs @@ -0,0 +1,72 @@ +using System.Text.Json; +using AgentCore.Application.Runtime; +using Microsoft.Agents.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// and — the two +/// halves of moving MAF's per-provider state bag beside CallSessionState. +/// +public sealed class HarnessSessionStateTests +{ + [Fact] + public void Capture_NullSession_IsEmpty() + => Assert.Empty(HarnessSessionState.Capture(null, new HashSet(StringComparer.Ordinal) { "TodoProvider" })); + + [Fact] + public void Capture_EmptyKeys_IsEmpty() + { + var element = JsonDocument.Parse("""{"TodoProvider":{"items":[],"nextId":1}}""").RootElement; + var session = new TestAgentSession(AgentSessionStateBag.Deserialize(element)); + + Assert.Empty(HarnessSessionState.Capture(session, new HashSet(StringComparer.Ordinal))); + } + + [Fact] + public void Capture_KeepsOnlyTheNamedKeys_AndClonesTheirRawText() + { + const string TodoJson = """{"items":[{"id":1,"title":"buy milk","isComplete":false}],"nextId":2}"""; + var element = JsonDocument.Parse( + """{"TodoProvider":""" + TodoJson + ""","SomeForeignProvider":{"anything":1}}""").RootElement; + + var session = new TestAgentSession(AgentSessionStateBag.Deserialize(element)); + var keys = new HashSet(StringComparer.Ordinal) { "TodoProvider" }; + + var captured = HarnessSessionState.Capture(session, keys); + + var key = Assert.Single(captured.Keys); + Assert.Equal("TodoProvider", key); + Assert.Equal( + JsonDocument.Parse(TodoJson).RootElement.GetRawText(), + captured["TodoProvider"].GetRawText()); + } + + [Fact] + public void Wrap_OneKey_ProducesTheStateBagEnvelope() + { + var element = JsonDocument.Parse("""{"items":[],"nextId":1}""").RootElement; + var providers = new Dictionary(StringComparer.Ordinal) { ["TodoProvider"] = element }; + + var wrapped = HarnessSessionState.Wrap(providers); + + Assert.Equal( + JsonSerializer.Serialize(new Dictionary + { + ["stateBag"] = new Dictionary + { + ["TodoProvider"] = new Dictionary { ["items"] = Array.Empty(), ["nextId"] = 1 }, + }, + }), + wrapped.GetRawText()); + } + + private sealed class TestAgentSession : AgentSession + { + public TestAgentSession(AgentSessionStateBag stateBag) + : base(stateBag) + { + } + } +} From 0e293f776e6e4da7b5f4639d64e17d16cbe3dc0a Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 21:34:11 -0600 Subject: [PATCH 10/32] feat: add shell tool provider --- Directory.Packages.props | 1 + .../AgentCore.Application.csproj | 6 + src/AgentCore.Application/Call/.editorconfig | 8 - .../{Call => Calls}/CallChannel.cs | 2 +- .../{Call => Calls}/CallChannelContext.cs | 2 +- .../{Call => Calls}/CallInput.cs | 2 +- .../{Call => Calls}/CallSpeechPairing.cs | 2 +- .../Compilation/AgentHarnessProviders.cs | 67 ++++- src/AgentCore.Application/Diagnostics/Log.cs | 10 + .../Ports/ICallAdapter.cs | 2 +- .../Ports/ICallChannelFactory.cs | 2 +- .../Ports/ICallInputPort.cs | 2 +- .../Ports/ICallOutputPort.cs | 2 +- .../Ports/ICallSessions.cs | 3 +- .../Ports/ISpeechAdapter.cs | 4 +- .../PublicAPI.Unshipped.txt | 179 ++++++------- .../Runtime/CallSession.cs | 26 +- .../Runtime/CallShellOptions.cs | 13 + .../Runtime/CallShellProvider.cs | 34 +++ .../Runtime/CallShells.cs | 137 ++++++++++ .../Runtime/TurnAmbients.cs | 8 +- .../Sessions/Memory/InMemoryCallSessions.cs | 11 +- .../Startup/CallSeamStartup.cs | 2 +- .../TelnyxRelayCallChannelFactory.cs | 2 +- .../TelnyxRelay/TelnyxRelayConnection.cs | 2 +- .../AgentCore.Application.Tests.csproj | 1 + .../Call/.editorconfig | 11 - .../{Call => Calls}/CallChannelTests.cs | 4 +- .../{Call => Calls}/CallSpeechPairingTests.cs | 4 +- .../Compilation/.editorconfig | 5 - .../Compilation/AgentToolTests.cs | 2 +- .../ClarificationWiringBindingTests.cs | 2 +- .../Compilation/CompactionCompilationTests.cs | 2 +- .../Compilation/CompileTableTests.cs | 2 +- .../CompiledAgentConcurrencyTests.cs | 2 +- .../Compilation/CompiledAgentRunTests.cs | 2 +- .../ConfigurationCompilerModelFacingTests.cs | 2 +- .../DiscoveredToolReferenceTests.cs | 2 +- .../Compilation/FilesCompilationTests.cs | 2 +- .../Compilation/GraphNoMatchTests.cs | 2 +- .../Compilation/GuardedGraphEdgeTests.cs | 2 +- .../Compilation/HarnessCompilationTests.cs | 74 +++++- .../Compilation/HostedWebSearchDropTests.cs | 2 +- .../KnowledgeProviderBindingTests.cs | 2 +- .../KnowledgeProviderSchemaTests.cs | 2 +- .../Compilation/MemoryCompilationTests.cs | 2 +- .../Compilation/SkillsProviderBindingTests.cs | 2 +- .../Fakes/ShellScriptedClient.cs | 97 +++++++ .../Runtime/CallSessionShellTests.cs | 243 ++++++++++++++++++ .../Runtime/CallShellsTests.cs | 153 +++++++++++ .../Runtime/ProcHelpers.cs | 33 +++ .../Call/CallChannelShapeTests.cs | 2 +- .../Call/CallInputPortTests.cs | 2 +- .../Fakes/FakeCallInput.cs | 2 +- 54 files changed, 1036 insertions(+), 156 deletions(-) delete mode 100644 src/AgentCore.Application/Call/.editorconfig rename src/AgentCore.Application/{Call => Calls}/CallChannel.cs (98%) rename src/AgentCore.Application/{Call => Calls}/CallChannelContext.cs (93%) rename src/AgentCore.Application/{Call => Calls}/CallInput.cs (98%) rename src/AgentCore.Application/{Call => Calls}/CallSpeechPairing.cs (99%) create mode 100644 src/AgentCore.Application/Runtime/CallShellOptions.cs create mode 100644 src/AgentCore.Application/Runtime/CallShellProvider.cs create mode 100644 src/AgentCore.Application/Runtime/CallShells.cs delete mode 100644 tests/AgentCore.Application.Tests/Call/.editorconfig rename tests/AgentCore.Application.Tests/{Call => Calls}/CallChannelTests.cs (96%) rename tests/AgentCore.Application.Tests/{Call => Calls}/CallSpeechPairingTests.cs (98%) delete mode 100644 tests/AgentCore.Application.Tests/Compilation/.editorconfig rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/AgentToolTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/ClarificationWiringBindingTests.cs (98%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/CompactionCompilationTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/CompileTableTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/CompiledAgentConcurrencyTests.cs (98%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/CompiledAgentRunTests.cs (98%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/ConfigurationCompilerModelFacingTests.cs (97%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/DiscoveredToolReferenceTests.cs (98%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/FilesCompilationTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/GraphNoMatchTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/GuardedGraphEdgeTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/HarnessCompilationTests.cs (73%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/HostedWebSearchDropTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/KnowledgeProviderBindingTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/KnowledgeProviderSchemaTests.cs (98%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/MemoryCompilationTests.cs (99%) rename tests/AgentCore.Application.Tests/{ => Configuration}/Compilation/SkillsProviderBindingTests.cs (98%) create mode 100644 tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index af6e4163..3fe3173d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -21,6 +21,7 @@ + diff --git a/src/AgentCore.Application/AgentCore.Application.csproj b/src/AgentCore.Application/AgentCore.Application.csproj index 0b947998..598d11cd 100644 --- a/src/AgentCore.Application/AgentCore.Application.csproj +++ b/src/AgentCore.Application/AgentCore.Application.csproj @@ -4,6 +4,11 @@ true Orchestration, configuration compilation, and every port interface. agent;ai;voice;chat;orchestration + + $(NoWarn);NU5104 @@ -16,6 +21,7 @@ + diff --git a/src/AgentCore.Application/Call/.editorconfig b/src/AgentCore.Application/Call/.editorconfig deleted file mode 100644 index 5f2976f4..00000000 --- a/src/AgentCore.Application/Call/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -[*.cs] - -# CA1716: "Rename namespace AgentCore.Application.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.Application/Call/CallChannel.cs b/src/AgentCore.Application/Calls/CallChannel.cs similarity index 98% rename from src/AgentCore.Application/Call/CallChannel.cs rename to src/AgentCore.Application/Calls/CallChannel.cs index c2a90c26..104d6384 100644 --- a/src/AgentCore.Application/Call/CallChannel.cs +++ b/src/AgentCore.Application/Calls/CallChannel.cs @@ -1,6 +1,6 @@ using AgentCore.Application.Ports; -namespace AgentCore.Application.Call; +namespace AgentCore.Application.Calls; /// /// The two halves of one call, opened together and disposed together. diff --git a/src/AgentCore.Application/Call/CallChannelContext.cs b/src/AgentCore.Application/Calls/CallChannelContext.cs similarity index 93% rename from src/AgentCore.Application/Call/CallChannelContext.cs rename to src/AgentCore.Application/Calls/CallChannelContext.cs index c6102a36..e863df44 100644 --- a/src/AgentCore.Application/Call/CallChannelContext.cs +++ b/src/AgentCore.Application/Calls/CallChannelContext.cs @@ -1,4 +1,4 @@ -namespace AgentCore.Application.Call; +namespace AgentCore.Application.Calls; /// What one call needs to open its channel. /// The AgentCore call id, which the channel must not invent for itself. diff --git a/src/AgentCore.Application/Call/CallInput.cs b/src/AgentCore.Application/Calls/CallInput.cs similarity index 98% rename from src/AgentCore.Application/Call/CallInput.cs rename to src/AgentCore.Application/Calls/CallInput.cs index 576a3163..5121e606 100644 --- a/src/AgentCore.Application/Call/CallInput.cs +++ b/src/AgentCore.Application/Calls/CallInput.cs @@ -1,4 +1,4 @@ -namespace AgentCore.Application.Call; +namespace AgentCore.Application.Calls; /// /// One thing the caller did, in the order it happened. diff --git a/src/AgentCore.Application/Call/CallSpeechPairing.cs b/src/AgentCore.Application/Calls/CallSpeechPairing.cs similarity index 99% rename from src/AgentCore.Application/Call/CallSpeechPairing.cs rename to src/AgentCore.Application/Calls/CallSpeechPairing.cs index 17e07cc0..38a30b13 100644 --- a/src/AgentCore.Application/Call/CallSpeechPairing.cs +++ b/src/AgentCore.Application/Calls/CallSpeechPairing.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; -namespace AgentCore.Application.Call; +namespace AgentCore.Application.Calls; /// /// Refuses a document whose call transport and speech vendors cannot coexist. diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 2744664e..3bf8a9aa 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -1,13 +1,15 @@ +using System.Text.RegularExpressions; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; using Microsoft.Agents.AI; +using Microsoft.Agents.AI.Tools.Shell; namespace AgentCore.Application.Configuration.Compilation; /// /// The context providers behind one agent's harness switches (todos:, mode:, -/// memory:, files:), added into the provider list builds. +/// memory:, files:, shell:), added into the provider list builds. /// internal static class AgentHarnessProviders { @@ -86,6 +88,11 @@ public static void Add( { providers.Add(BuildFilesProvider(item, files, context, pointer)); } + + if (item.Shell is { } shell) + { + providers.Add(BuildShellProvider(item, shell, context, pointer)); + } } /// @@ -173,6 +180,64 @@ private static FileAccessProvider BuildFilesProvider( } #pragma warning restore MAAI001 + private static CallShellProvider BuildShellProvider( + 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 CallShellProvider(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); + return true; + } + catch (ArgumentException) + { + return false; + } + } + /// /// 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 diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index 883def66..3b3822ed 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -259,4 +259,14 @@ public static partial void KnowledgeScopeComposed( Level = LogLevel.Warning, Message = "Could not delete the call 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. + /// The logger of the session. + /// The call'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}'.")] + public static partial void ShellDisposeFailed(ILogger logger, string workspace, Exception exception); } diff --git a/src/AgentCore.Application/Ports/ICallAdapter.cs b/src/AgentCore.Application/Ports/ICallAdapter.cs index c3deb4d0..9c364f8c 100644 --- a/src/AgentCore.Application/Ports/ICallAdapter.cs +++ b/src/AgentCore.Application/Ports/ICallAdapter.cs @@ -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/ICallChannelFactory.cs b/src/AgentCore.Application/Ports/ICallChannelFactory.cs index b3e5ebae..30e998c8 100644 --- a/src/AgentCore.Application/Ports/ICallChannelFactory.cs +++ b/src/AgentCore.Application/Ports/ICallChannelFactory.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; namespace AgentCore.Application.Ports; diff --git a/src/AgentCore.Application/Ports/ICallInputPort.cs b/src/AgentCore.Application/Ports/ICallInputPort.cs index 02a84af3..752e2c44 100644 --- a/src/AgentCore.Application/Ports/ICallInputPort.cs +++ b/src/AgentCore.Application/Ports/ICallInputPort.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; namespace AgentCore.Application.Ports; diff --git a/src/AgentCore.Application/Ports/ICallOutputPort.cs b/src/AgentCore.Application/Ports/ICallOutputPort.cs index c492db25..27cb8027 100644 --- a/src/AgentCore.Application/Ports/ICallOutputPort.cs +++ b/src/AgentCore.Application/Ports/ICallOutputPort.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; namespace AgentCore.Application.Ports; diff --git a/src/AgentCore.Application/Ports/ICallSessions.cs b/src/AgentCore.Application/Ports/ICallSessions.cs index 845746f2..c0ef9136 100644 --- a/src/AgentCore.Application/Ports/ICallSessions.cs +++ b/src/AgentCore.Application/Ports/ICallSessions.cs @@ -39,7 +39,8 @@ public interface ICallSessions /// 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. + /// 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/ISpeechAdapter.cs b/src/AgentCore.Application/Ports/ISpeechAdapter.cs index facdc9bc..4e89e045 100644 --- a/src/AgentCore.Application/Ports/ISpeechAdapter.cs +++ b/src/AgentCore.Application/Ports/ISpeechAdapter.cs @@ -25,7 +25,7 @@ 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 +/// 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 /// 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 @@ -40,7 +40,7 @@ namespace AgentCore.Application.Ports; /// 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/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index f791e9ed..c6feb6b6 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -12,52 +12,52 @@ 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.Call.CallChannel -AgentCore.Application.Call.CallChannel.$() -> AgentCore.Application.Call.CallChannel! -AgentCore.Application.Call.CallChannel.CallChannel(AgentCore.Application.Ports.ICallInputPort! Input, AgentCore.Application.Ports.ICallOutputPort! Output) -> void -AgentCore.Application.Call.CallChannel.Deconstruct(out AgentCore.Application.Ports.ICallInputPort! Input, out AgentCore.Application.Ports.ICallOutputPort! Output) -> void -AgentCore.Application.Call.CallChannel.DisposeAsync() -> System.Threading.Tasks.ValueTask -AgentCore.Application.Call.CallChannel.Equals(AgentCore.Application.Call.CallChannel? other) -> bool -AgentCore.Application.Call.CallChannel.Input.get -> AgentCore.Application.Ports.ICallInputPort! -AgentCore.Application.Call.CallChannel.Input.init -> void -AgentCore.Application.Call.CallChannel.Output.get -> AgentCore.Application.Ports.ICallOutputPort! -AgentCore.Application.Call.CallChannel.Output.init -> void -AgentCore.Application.Call.CallChannelContext -AgentCore.Application.Call.CallChannelContext.$() -> AgentCore.Application.Call.CallChannelContext! -AgentCore.Application.Call.CallChannelContext.CallChannelContext(string! CallId, System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void -AgentCore.Application.Call.CallChannelContext.CallId.get -> string! -AgentCore.Application.Call.CallChannelContext.CallId.init -> void -AgentCore.Application.Call.CallChannelContext.CustomParameters.get -> System.Collections.Generic.IReadOnlyDictionary? -AgentCore.Application.Call.CallChannelContext.CustomParameters.init -> void -AgentCore.Application.Call.CallChannelContext.Deconstruct(out string! CallId, out System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void -AgentCore.Application.Call.CallChannelContext.Equals(AgentCore.Application.Call.CallChannelContext? other) -> bool -AgentCore.Application.Call.CallInput -AgentCore.Application.Call.CallInput.Barge -AgentCore.Application.Call.CallInput.Barge.Barge(string! HeardText, System.TimeSpan PlayedDuration) -> void -AgentCore.Application.Call.CallInput.Barge.Deconstruct(out string! HeardText, out System.TimeSpan PlayedDuration) -> void -AgentCore.Application.Call.CallInput.Barge.Equals(AgentCore.Application.Call.CallInput.Barge? other) -> bool -AgentCore.Application.Call.CallInput.Barge.HeardText.get -> string! -AgentCore.Application.Call.CallInput.Barge.HeardText.init -> void -AgentCore.Application.Call.CallInput.Barge.PlayedDuration.get -> System.TimeSpan -AgentCore.Application.Call.CallInput.Barge.PlayedDuration.init -> void -AgentCore.Application.Call.CallInput.CallInput(AgentCore.Application.Call.CallInput! original) -> void -AgentCore.Application.Call.CallInput.Keypress -AgentCore.Application.Call.CallInput.Keypress.Deconstruct(out string! Key) -> void -AgentCore.Application.Call.CallInput.Keypress.Equals(AgentCore.Application.Call.CallInput.Keypress? other) -> bool -AgentCore.Application.Call.CallInput.Keypress.Key.get -> string! -AgentCore.Application.Call.CallInput.Keypress.Key.init -> void -AgentCore.Application.Call.CallInput.Keypress.Keypress(string! Key) -> void -AgentCore.Application.Call.CallInput.Utterance -AgentCore.Application.Call.CallInput.Utterance.Deconstruct(out string! Text, out string! Language, out bool IsFinal) -> void -AgentCore.Application.Call.CallInput.Utterance.Equals(AgentCore.Application.Call.CallInput.Utterance? other) -> bool -AgentCore.Application.Call.CallInput.Utterance.IsFinal.get -> bool -AgentCore.Application.Call.CallInput.Utterance.IsFinal.init -> void -AgentCore.Application.Call.CallInput.Utterance.Language.get -> string! -AgentCore.Application.Call.CallInput.Utterance.Language.init -> void -AgentCore.Application.Call.CallInput.Utterance.Text.get -> string! -AgentCore.Application.Call.CallInput.Utterance.Text.init -> void -AgentCore.Application.Call.CallInput.Utterance.Utterance(string! Text, string! Language, bool IsFinal) -> void -AgentCore.Application.Call.CallSpeechPairing +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.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.CallSpeechPairing AgentCore.Application.Calls.CallClarificationState AgentCore.Application.Calls.CallClarificationState.$() -> AgentCore.Application.Calls.CallClarificationState! AgentCore.Application.Calls.CallClarificationState.CallClarificationState() -> void @@ -1072,9 +1072,9 @@ AgentCore.Application.Ports.IAuditSinkPort.AppendManyAsync(System.Collections.Ge AgentCore.Application.Ports.ICallAdapter AgentCore.Application.Ports.ICallAdapter.CarriesText.get -> bool AgentCore.Application.Ports.ICallChannelFactory -AgentCore.Application.Ports.ICallChannelFactory.OpenAsync(AgentCore.Application.Call.CallChannelContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +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.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 @@ -1211,6 +1211,7 @@ AgentCore.Application.Runtime.CallRenderScope 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 @@ -1439,7 +1440,7 @@ 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.Call.CallInput.$() -> AgentCore.Application.Call.CallInput! +abstract AgentCore.Application.Calls.CallInput.$() -> AgentCore.Application.Calls.CallInput! 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 @@ -1512,27 +1513,27 @@ const AgentCore.Application.Tools.Builtin.BuiltinToolNames.WebSearch = "web.sear 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.Call.CallChannel.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallChannel.GetHashCode() -> int -override AgentCore.Application.Call.CallChannel.ToString() -> string! -override AgentCore.Application.Call.CallChannelContext.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallChannelContext.GetHashCode() -> int -override AgentCore.Application.Call.CallChannelContext.ToString() -> string! -override AgentCore.Application.Call.CallInput.Barge.$() -> AgentCore.Application.Call.CallInput.Barge! -override AgentCore.Application.Call.CallInput.Barge.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.Barge.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Barge.ToString() -> string! -override AgentCore.Application.Call.CallInput.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Keypress.$() -> AgentCore.Application.Call.CallInput.Keypress! -override AgentCore.Application.Call.CallInput.Keypress.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.Keypress.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Keypress.ToString() -> string! -override AgentCore.Application.Call.CallInput.ToString() -> string! -override AgentCore.Application.Call.CallInput.Utterance.$() -> AgentCore.Application.Call.CallInput.Utterance! -override AgentCore.Application.Call.CallInput.Utterance.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.Utterance.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Utterance.ToString() -> 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.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.CallClarificationState.Equals(object? obj) -> bool override AgentCore.Application.Calls.CallClarificationState.GetHashCode() -> int override AgentCore.Application.Calls.CallClarificationState.ToString() -> string! @@ -1762,24 +1763,24 @@ 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.Call.CallInput.Barge.Equals(AgentCore.Application.Call.CallInput? other) -> bool -override sealed AgentCore.Application.Call.CallInput.Keypress.Equals(AgentCore.Application.Call.CallInput? other) -> bool -override sealed AgentCore.Application.Call.CallInput.Utterance.Equals(AgentCore.Application.Call.CallInput? other) -> bool +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 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.Call.CallChannel.operator !=(AgentCore.Application.Call.CallChannel? left, AgentCore.Application.Call.CallChannel? right) -> bool -static AgentCore.Application.Call.CallChannel.operator ==(AgentCore.Application.Call.CallChannel? left, AgentCore.Application.Call.CallChannel? right) -> bool -static AgentCore.Application.Call.CallChannelContext.operator !=(AgentCore.Application.Call.CallChannelContext? left, AgentCore.Application.Call.CallChannelContext? right) -> bool -static AgentCore.Application.Call.CallChannelContext.operator ==(AgentCore.Application.Call.CallChannelContext? left, AgentCore.Application.Call.CallChannelContext? right) -> bool -static AgentCore.Application.Call.CallInput.Barge.operator !=(AgentCore.Application.Call.CallInput.Barge? left, AgentCore.Application.Call.CallInput.Barge? right) -> bool -static AgentCore.Application.Call.CallInput.Barge.operator ==(AgentCore.Application.Call.CallInput.Barge? left, AgentCore.Application.Call.CallInput.Barge? right) -> bool -static AgentCore.Application.Call.CallInput.Keypress.operator !=(AgentCore.Application.Call.CallInput.Keypress? left, AgentCore.Application.Call.CallInput.Keypress? right) -> bool -static AgentCore.Application.Call.CallInput.Keypress.operator ==(AgentCore.Application.Call.CallInput.Keypress? left, AgentCore.Application.Call.CallInput.Keypress? right) -> bool -static AgentCore.Application.Call.CallInput.Utterance.operator !=(AgentCore.Application.Call.CallInput.Utterance? left, AgentCore.Application.Call.CallInput.Utterance? right) -> bool -static AgentCore.Application.Call.CallInput.Utterance.operator ==(AgentCore.Application.Call.CallInput.Utterance? left, AgentCore.Application.Call.CallInput.Utterance? right) -> bool -static AgentCore.Application.Call.CallInput.operator !=(AgentCore.Application.Call.CallInput? left, AgentCore.Application.Call.CallInput? right) -> bool -static AgentCore.Application.Call.CallInput.operator ==(AgentCore.Application.Call.CallInput? left, AgentCore.Application.Call.CallInput? right) -> bool -static AgentCore.Application.Call.CallSpeechPairing.Validate(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! call, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! speech, AgentCore.Application.Ports.ICallAdapter! selectedCall) -> void +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.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.CallSpeechPairing.Validate(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! call, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! speech, AgentCore.Application.Ports.ICallAdapter! selectedCall) -> void 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! @@ -2031,9 +2032,9 @@ static readonly AgentCore.Application.Secrets.KnownSecrets.OpenAi -> AgentCore.A 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.Call.CallInput.EqualityContract.get -> System.Type! -virtual AgentCore.Application.Call.CallInput.Equals(AgentCore.Application.Call.CallInput? other) -> bool -virtual AgentCore.Application.Call.CallInput.PrintMembers(System.Text.StringBuilder! builder) -> bool +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 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 diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 4b1710f6..59d6ae48 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -25,7 +25,7 @@ namespace AgentCore.Application.Runtime; /// /// The turn loop of one call. It owns the state, the stage machine, and the transcript. /// -public sealed class CallSession : IConversationPort +public sealed class CallSession : IConversationPort, IAsyncDisposable { /// /// The line the caller hears when a turn fails and the document names none. @@ -100,6 +100,8 @@ public sealed class CallSession : IConversationPort private readonly CallWorkspace? _workspace; + private readonly CallShells? _shells; + // Whether the running turn has already handed the host something to speak. One rule for both // run shapes: a run that has handed the host nothing cannot be the turn the caller was hearing, // so a barge-in in that window belongs to the turn that finished before it. A streaming turn @@ -138,6 +140,8 @@ internal CallSession( _workspace = workspace; + _shells = workspace is null ? null : new CallShells(workspace.Path, _logger); + _compiled = compiled; _history = compiled.History; @@ -503,6 +507,19 @@ public bool EndCall(CallEndReason reason) /// private void DeleteWorkspace() => _workspace?.Delete(_logger); + /// + /// 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 + /// only the turn-end path and tear it down. + /// + private ValueTask DisposeShellsAsync() => _shells?.DisposeAsync() ?? ValueTask.CompletedTask; + + /// + /// Disposes this call's shell executors. Idempotent: a session already disposed, or one that + /// never had a workspace, disposes nothing. + /// + public ValueTask DisposeAsync() => DisposeShellsAsync(); + /// /// 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. @@ -782,7 +799,8 @@ private IDisposable EnterAmbients(Turn turn) TurnContextOf(turn), turn.Knowledge, _clarifications, - Workspace); + Workspace, + _shells); /// /// Reads what one turn adds to its own model invocation. @@ -1318,6 +1336,10 @@ private async Task CompleteTurnAsync( if (IsComplete || _events.HasEnded) { + // 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 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 diff --git a/src/AgentCore.Application/Runtime/CallShellOptions.cs b/src/AgentCore.Application/Runtime/CallShellOptions.cs new file mode 100644 index 00000000..112979de --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallShellOptions.cs @@ -0,0 +1,13 @@ +using AgentCore.Application.Configuration.Schema; +using Microsoft.Agents.AI.Tools.Shell; + +namespace AgentCore.Application.Runtime; + +/// +/// 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. +/// +/// 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); diff --git a/src/AgentCore.Application/Runtime/CallShellProvider.cs b/src/AgentCore.Application/Runtime/CallShellProvider.cs new file mode 100644 index 00000000..b55708ac --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallShellProvider.cs @@ -0,0 +1,34 @@ +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime; + +/// +/// 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 +/// description is what the model reads — and no StateKeys, because the shell keeps no +/// session state. +/// +internal sealed class CallShellProvider : AIContextProvider +{ + private const string NoTurnMessage = + "A shell: tool runs only while a turn runs through a CallSession with a workspace root bound."; + + private readonly CallShellOptions _options; + + public CallShellProvider(CallShellOptions options) + { + ArgumentNullException.ThrowIfNull(options); + _options = options; + } + + protected override ValueTask ProvideAIContextAsync( + InvokingContext context, CancellationToken cancellationToken = default) + { + var shells = TurnAmbients.Current?.Shells ?? throw new InvalidOperationException(NoTurnMessage); + + return new ValueTask(new AIContext + { + Tools = [shells.Get(_options).AsAIFunction(requireApproval: false)], + }); + } +} diff --git a/src/AgentCore.Application/Runtime/CallShells.cs b/src/AgentCore.Application/Runtime/CallShells.cs new file mode 100644 index 00000000..3657530f --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallShells.cs @@ -0,0 +1,137 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Diagnostics; +using Microsoft.Agents.AI.Tools.Shell; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Runtime; + +/// +/// The shell executors one call has started. One per +/// instance the agent declares, created on the first command it +/// runs — a call that never runs a command starts no bash and no container. +/// +internal sealed class CallShells : IAsyncDisposable +{ + private readonly string _workspace; + + private readonly ILogger? _logger; + + private readonly Lock _lock = new(); + + private readonly Dictionary _executors = new(ReferenceEqualityComparer.Instance); + + private bool _disposed; + + /// Creates the holder for one call. + /// The call's workspace folder, the executor's working directory. + /// Where a failed dispose is logged, at Warning. May be . + public CallShells(string workspace, ILogger? logger) + { + ArgumentException.ThrowIfNullOrEmpty(workspace); + _workspace = workspace; + _logger = logger; + } + + /// + /// Gets this call's executor for , creating it on first ask. + /// + /// This call's shells have already been torn down. + public ShellExecutor Get(CallShellOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + lock (_lock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (_executors.TryGetValue(options, out var existing)) + { + return existing; + } + + var created = Create(options); + _executors.Add(options, created); + return created; + } + } + + private ShellExecutor Create(CallShellOptions options) + { + switch (options.Kind) + { + case ShellKind.Local: + LocalShellExecutorOptions localOptions = new() + { + WorkingDirectory = _workspace, + Mode = ShellMode.Persistent, + ConfineWorkingDirectory = true, + AcknowledgeUnsafe = true, + Policy = options.Policy, + }; + if (options.Timeout is { } localTimeout) + { + localOptions.Timeout = localTimeout; + } + + 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. + DockerShellExecutorOptions dockerOptions = new() + { + HostWorkdir = _workspace, + MountReadonly = false, + Policy = options.Policy, + }; + if (options.Timeout is { } dockerTimeout) + { + dockerOptions.Timeout = dockerTimeout; + } + + return new DockerShellExecutor(dockerOptions); + + default: + throw new ArgumentOutOfRangeException(nameof(options), options.Kind, "Unknown shell kind."); + } + } + + /// + /// Disposes every executor this call 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. + /// + public async ValueTask DisposeAsync() + { + List toDispose; + + lock (_lock) + { + if (_disposed) + { + return; + } + + _disposed = true; + toDispose = [.. _executors.Values]; + _executors.Clear(); + } + + foreach (var executor in toDispose) + { + try + { + await executor.DisposeAsync().ConfigureAwait(false); + } + catch (Exception exception) + { + if (_logger is not null) + { + Log.ShellDisposeFailed(_logger, _workspace, exception); + } + } + } + } +} diff --git a/src/AgentCore.Application/Runtime/TurnAmbients.cs b/src/AgentCore.Application/Runtime/TurnAmbients.cs index b6bf71a9..ad569c7c 100644 --- a/src/AgentCore.Application/Runtime/TurnAmbients.cs +++ b/src/AgentCore.Application/Runtime/TurnAmbients.cs @@ -52,6 +52,9 @@ internal sealed record TurnAmbients /// Gets the folder this call owns on disk, or when the host bound no workspace root. public string? Workspace { get; init; } + /// Gets this call's shell executors, or when the call has no workspace. + public CallShells? Shells { get; init; } + /// Opens what a turn owns, and carries every other ambient through unchanged. /// The id of the call the turn belongs to. /// The state document the call reads and writes. @@ -63,6 +66,7 @@ internal sealed record TurnAmbients /// What this turn may see of the knowledge base, or when the document composes none. /// The call's ambiguity holder. /// The folder this call owns on disk, or when the host bound no workspace root. + /// This call's shell executors, or when the call has no workspace. internal static IDisposable Enter( string callId, StateDocument state, @@ -73,7 +77,8 @@ internal static IDisposable Enter( TurnContext context, KnowledgeScope? knowledge, Clarifications clarifications, - string? workspace) + string? workspace, + CallShells? shells) { ArgumentNullException.ThrowIfNull(callId); ArgumentNullException.ThrowIfNull(state); @@ -98,6 +103,7 @@ internal static IDisposable Enter( Knowledge = knowledge ?? current.Knowledge, Clarifications = clarifications, Workspace = workspace, + Shells = shells, }); } diff --git a/src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs b/src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs index 93621d84..90a2a197 100644 --- a/src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs +++ b/src/AgentCore.Application/Sessions/Memory/InMemoryCallSessions.cs @@ -85,7 +85,16 @@ public async ValueTask CloseAsync(string callId, CancellationToken cancellationT // then flushed while this method still holds the only reference to it. if (_sessions.TryRemove(callId, out var entry)) { - await entry.Session.FlushTranscriptAsync().ConfigureAwait(false); + // A store that throws on flush must not leave the session's shells running with + // nothing left to hold a reference to them. + try + { + await entry.Session.FlushTranscriptAsync().ConfigureAwait(false); + } + finally + { + await entry.Session.DisposeAsync().ConfigureAwait(false); + } } } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs index 64e7d450..36d2bb36 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSeamStartup.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs index bb02b33c..8055de62 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayCallChannelFactory.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using AgentCore.Application.Ports; namespace AgentCore.AspNetCore.Vendors.TelnyxRelay; diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs index 11ecbdc5..46f4bda0 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; using System.Text.Json; using System.Threading.Channels; -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.AspNetCore.Call; diff --git a/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj b/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj index 12bb653f..52210c94 100644 --- a/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj +++ b/tests/AgentCore.Application.Tests/AgentCore.Application.Tests.csproj @@ -15,6 +15,7 @@ + diff --git a/tests/AgentCore.Application.Tests/Call/.editorconfig b/tests/AgentCore.Application.Tests/Call/.editorconfig deleted file mode 100644 index 12592eb8..00000000 --- a/tests/AgentCore.Application.Tests/Call/.editorconfig +++ /dev/null @@ -1,11 +0,0 @@ -[*.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 - -# CA1716: "Rename namespace AgentCore.Application.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.Application/Call, which task 0 of -# the call-transport-seam plan named deliberately. -dotnet_diagnostic.CA1716.severity = none diff --git a/tests/AgentCore.Application.Tests/Call/CallChannelTests.cs b/tests/AgentCore.Application.Tests/Calls/CallChannelTests.cs similarity index 96% rename from tests/AgentCore.Application.Tests/Call/CallChannelTests.cs rename to tests/AgentCore.Application.Tests/Calls/CallChannelTests.cs index afa06e57..f8bbd00c 100644 --- a/tests/AgentCore.Application.Tests/Call/CallChannelTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/CallChannelTests.cs @@ -1,8 +1,8 @@ using AgentCore.Application.Ports; -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using Xunit; -namespace AgentCore.Application.Tests.Call; +namespace AgentCore.Application.Tests.Calls; /// /// The channel pair, including the case where one object fills both slots. diff --git a/tests/AgentCore.Application.Tests/Call/CallSpeechPairingTests.cs b/tests/AgentCore.Application.Tests/Calls/CallSpeechPairingTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Call/CallSpeechPairingTests.cs rename to tests/AgentCore.Application.Tests/Calls/CallSpeechPairingTests.cs index bb3399f0..e887e483 100644 --- a/tests/AgentCore.Application.Tests/Call/CallSpeechPairingTests.cs +++ b/tests/AgentCore.Application.Tests/Calls/CallSpeechPairingTests.cs @@ -1,10 +1,10 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using Xunit; -namespace AgentCore.Application.Tests.Call; +namespace AgentCore.Application.Tests.Calls; public sealed class CallSpeechPairingTests { diff --git a/tests/AgentCore.Application.Tests/Compilation/.editorconfig b/tests/AgentCore.Application.Tests/Compilation/.editorconfig deleted file mode 100644 index 3d6eebe7..00000000 --- a/tests/AgentCore.Application.Tests/Compilation/.editorconfig +++ /dev/null @@ -1,5 +0,0 @@ -[*.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/Compilation/AgentToolTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/AgentToolTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs index b88135f3..3ca23b9b 100644 --- a/tests/AgentCore.Application.Tests/Compilation/AgentToolTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/AgentToolTests.cs @@ -6,7 +6,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The fourth tool kind of section 8.1: kind: agent, which is agent-as-tool. diff --git a/tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs index b23015af..6fda3d99 100644 --- a/tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs @@ -9,7 +9,7 @@ using Microsoft.Agents.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// Where the document's providers.knowledge ambiguity wiring becomes part of the agent's own diff --git a/tests/AgentCore.Application.Tests/Compilation/CompactionCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/CompactionCompilationTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs index 00bf057e..aa051e33 100644 --- a/tests/AgentCore.Application.Tests/Compilation/CompactionCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompactionCompilationTests.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The compaction: block reaching a compiled agent's context providers, and the trimming diff --git a/tests/AgentCore.Application.Tests/Compilation/CompileTableTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/CompileTableTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs index 441f697d..a805f9ea 100644 --- a/tests/AgentCore.Application.Tests/Compilation/CompileTableTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompileTableTests.cs @@ -6,7 +6,7 @@ using Microsoft.Agents.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The five rows of the section 8.2 compile table. The compiler is a table, not a heuristic. diff --git a/tests/AgentCore.Application.Tests/Compilation/CompiledAgentConcurrencyTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Compilation/CompiledAgentConcurrencyTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs index 588da835..7ffcf24e 100644 --- a/tests/AgentCore.Application.Tests/Compilation/CompiledAgentConcurrencyTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentConcurrencyTests.cs @@ -3,7 +3,7 @@ using AgentCore.Application.Tests.Fakes; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +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 diff --git a/tests/AgentCore.Application.Tests/Compilation/CompiledAgentRunTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Compilation/CompiledAgentRunTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs index dd104022..1ef04877 100644 --- a/tests/AgentCore.Application.Tests/Compilation/CompiledAgentRunTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/CompiledAgentRunTests.cs @@ -4,7 +4,7 @@ using Microsoft.Agents.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// Rule 13 of section 11. A one-agent configuration compiles to a ChatClientAgent and answers diff --git a/tests/AgentCore.Application.Tests/Compilation/ConfigurationCompilerModelFacingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs similarity index 97% rename from tests/AgentCore.Application.Tests/Compilation/ConfigurationCompilerModelFacingTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs index 2e81b820..5639c9b2 100644 --- a/tests/AgentCore.Application.Tests/Compilation/ConfigurationCompilerModelFacingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs @@ -7,7 +7,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// ConfigurationCompiler.WithToolFailureAuditing is one of the two sites, besides diff --git a/tests/AgentCore.Application.Tests/Compilation/DiscoveredToolReferenceTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/DiscoveredToolReferenceTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Compilation/DiscoveredToolReferenceTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/DiscoveredToolReferenceTests.cs index 9bb6ab37..3c565892 100644 --- a/tests/AgentCore.Application.Tests/Compilation/DiscoveredToolReferenceTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/DiscoveredToolReferenceTests.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// Decision 15 at the compile layer: an agent's tools: entry may name an id the registry diff --git a/tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs index b9f804d1..d8b74f56 100644 --- a/tests/AgentCore.Application.Tests/Compilation/FilesCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs @@ -11,7 +11,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The files: block reaching a compiled agent as a , the diff --git a/tests/AgentCore.Application.Tests/Compilation/GraphNoMatchTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/GraphNoMatchTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs index 35e04b38..ce35c3a1 100644 --- a/tests/AgentCore.Application.Tests/Compilation/GraphNoMatchTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs @@ -9,7 +9,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// Row 4 of the section 8.2 compile table, where no edge guard is true. diff --git a/tests/AgentCore.Application.Tests/Compilation/GuardedGraphEdgeTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/GuardedGraphEdgeTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs index 7a169f43..a5149080 100644 --- a/tests/AgentCore.Application.Tests/Compilation/GuardedGraphEdgeTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// Row 4 of the section 8.2 compile table, with a guarded edge. diff --git a/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs similarity index 73% rename from tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs index 65d0440d..48b2ee1a 100644 --- a/tests/AgentCore.Application.Tests/Compilation/HarnessCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs @@ -6,7 +6,7 @@ using Microsoft.Agents.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The todos: / mode: switches reaching a compiled agent's context providers, and the @@ -172,6 +172,78 @@ public void Compile_TwoAgentsOnlyOneWithTodos_HarnessStateKeysHasTheTodoKey() compiled.HarnessStateKeys); } + private const string ShellYaml = + """ + apiVersion: agentcore/v1 + name: harness-shell + agents: + items: + - { id: only, instructions: "run commands", shell: { kind: local } } + """; + + private const string ShellBadPolicyYaml = + """ + apiVersion: agentcore/v1 + name: harness-shell-bad-policy + agents: + items: + - { id: only, instructions: "run commands", shell: { kind: local, policy: { deny: ["("] } } } + """; + + [Fact] + public void Compile_ShellWithNoWorkspaceRoot_FailsNamingTheShellPointer() + { + var document = ConfigurationLoader.LoadYaml(ShellYaml); + + var failure = Assert.Throws(() => ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))))); + + Assert.Equal("/agents/items/0/shell", failure.Pointer); + Assert.Contains("options.UseWorkspace(", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Compile_ShellWithABadPolicyRegex_FailsNamingTheShellPolicyPointerAndThePattern() + { + var document = ConfigurationLoader.LoadYaml(ShellBadPolicyYaml); + + var failure = Assert.Throws(() => ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))) + { + WorkspaceRoot = Path.Combine(Path.GetTempPath(), "agentcore-shell-" + Guid.NewGuid().ToString("N")), + })); + + Assert.Equal("/agents/items/0/shell/policy", failure.Pointer); + Assert.Contains("'('", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Compile_ShellWithAValidBlockAndARoot_Compiles() + { + var root = Path.Combine(Path.GetTempPath(), "agentcore-shell-" + Guid.NewGuid().ToString("N")); + try + { + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(ShellYaml), + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))) + { + WorkspaceRoot = root, + }); + + Assert.Single(compiled.Agents.Values); + Assert.Empty(compiled.HarnessStateKeys); + } + finally + { + if (Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + } + } + private static AIAgent CompileOne(bool withTodos, bool withMode) { using SequencedChatClient reply = new("hello there."); diff --git a/tests/AgentCore.Application.Tests/Compilation/HostedWebSearchDropTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/HostedWebSearchDropTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs index ac61308c..2fc7a78d 100644 --- a/tests/AgentCore.Application.Tests/Compilation/HostedWebSearchDropTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/HostedWebSearchDropTests.cs @@ -9,7 +9,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The hosted web-search marker reaching, or not reaching, one compiled agent. diff --git a/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs index 6dee8d76..cea84b8c 100644 --- a/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs @@ -10,7 +10,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// Where the knowledge: block becomes a bound provider. The block is per agent, so the diff --git a/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderSchemaTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderSchemaTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs index c0b717cf..cd7d81e4 100644 --- a/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderSchemaTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderSchemaTests.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Configuration.Schema; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The providers.knowledge block. It ships no payload field names at all, so the block a deployment diff --git a/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs index 5ebf168e..a407e70c 100644 --- a/tests/AgentCore.Application.Tests/Compilation/MemoryCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs @@ -11,7 +11,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// The memory: block reaching a compiled agent as a , the diff --git a/tests/AgentCore.Application.Tests/Compilation/SkillsProviderBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/SkillsProviderBindingTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Compilation/SkillsProviderBindingTests.cs rename to tests/AgentCore.Application.Tests/Configuration/Compilation/SkillsProviderBindingTests.cs index 72019fb0..e5675b70 100644 --- a/tests/AgentCore.Application.Tests/Compilation/SkillsProviderBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/SkillsProviderBindingTests.cs @@ -7,7 +7,7 @@ using Microsoft.Agents.AI; using Xunit; -namespace AgentCore.Application.Tests.Compilation; +namespace AgentCore.Application.Tests.Configuration.Compilation; /// /// An agent that declares skills: must carry the provider even when it declares no knowledge: diff --git a/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs b/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs new file mode 100644 index 00000000..d68d3ecd --- /dev/null +++ b/tests/AgentCore.Application.Tests/Fakes/ShellScriptedClient.cs @@ -0,0 +1,97 @@ +using System.Runtime.CompilerServices; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Tests.Fakes; + +/// One request a answered: what it saw, and what it was offered. +internal sealed record RecordedRequest(IReadOnlyList Messages, ChatOptions? Options); + +/// +/// A deterministic offline model that calls the shell tool once per queued command, feeding the +/// prior tool result back into before asking for the next, then answers +/// "done" once the queue is empty. +/// +internal sealed class ShellScriptedClient : IChatClient +{ + private readonly string _toolName; + private readonly Queue _commands; + + public ShellScriptedClient(string toolName, params string[] commands) + { + _toolName = toolName; + _commands = new(commands); + } + + public List Requests { get; } = []; + + public List ToolResults { get; } = []; + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + await Task.Yield(); + + var transcript = messages.ToList(); + Requests.Add(new RecordedRequest(transcript, options)); + var responseId = Guid.NewGuid().ToString("N"); + + var lastResults = transcript.Count > 0 + ? transcript[^1].Contents.OfType().ToList() + : []; + + foreach (var result in lastResults) + { + ToolResults.Add(result.Result?.ToString() ?? string.Empty); + } + + if (_commands.Count > 0) + { + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent( + "call_" + Guid.NewGuid().ToString("N"), + _toolName, + new Dictionary(StringComparer.Ordinal) { ["command"] = _commands.Dequeue() })]) + { + ResponseId = responseId, + MessageId = responseId, + }; + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, "done") + { + ResponseId = responseId, + MessageId = responseId, + }; + } + + 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) + { + ArgumentNullException.ThrowIfNull(serviceType); + return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; + } + + public void Dispose() + { + // Nothing to release. + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs new file mode 100644 index 00000000..1220e30d --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs @@ -0,0 +1,243 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.Sessions.Memory; +using AgentCore.Application.Tests.Fakes; +using AgentCore.TestSupport; +using Microsoft.Agents.AI.Tools.Shell; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// 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. +/// +public sealed class CallSessionShellTests : IDisposable +{ + private const string ShellYaml = + """ + apiVersion: agentcore/v1 + name: harness-shell-session + agents: + items: + - { id: only, instructions: "run commands", shell: { kind: local, policy: { deny: ["^rm "] } } } + """; + + private const string NoShellYaml = + """ + apiVersion: agentcore/v1 + name: harness-no-shell-session + agents: + items: + - { id: only, instructions: "just talk" } + """; + + private const string TerminalShellYaml = + """ + apiVersion: agentcore/v1 + name: harness-shell-terminal + agents: + items: + - { id: only, instructions: "run one command then stop", shell: { kind: local } } + policy: + initial: only + stages: + - { id: only, agent: only, terminal: true } + """; + + private readonly string _root = + Path.Combine(Path.GetTempPath(), "agentcore-shell-session-" + Guid.NewGuid().ToString("N")); + + /// The name the model sees for the shell tool, read off a throwaway real executor. + private static readonly string RunShellToolName = ToolName(); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [Fact] + public async Task FirstRequest_ListsATool_NamedRunShell() + { + // One literal assertion, as the brief allows: it pins the name the model actually sees. + Assert.Equal("run_shell", RunShellToolName); + + var client = new ShellScriptedClient(RunShellToolName, "pwd", "rm -rf x", "echo $$"); + var factory = BuildFactory(ShellYaml, client); + await using var session = factory.Create("call-1"); + + await session.RunTurnAsync("go", TestContext.Current.CancellationToken); + + var tools = client.Requests[0].Options?.Tools ?? []; + Assert.Contains(tools, tool => tool.Name == RunShellToolName); + } + + [Fact] + public async Task PwdResult_ContainsTheCallsWorkspace() + { + // 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 session.RunTurnAsync("go", TestContext.Current.CancellationToken); + + Assert.Contains(session.Workspace!, client.ToolResults[0], StringComparison.Ordinal); + } + + [Fact] + 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"); + + var turn = await session.RunTurnAsync("go", TestContext.Current.CancellationToken); + + Assert.Contains("rejected", client.ToolResults[1], StringComparison.OrdinalIgnoreCase); + Assert.Equal("done", turn.ReplyText); + } + + [Fact] + public async Task AfterTheCallIsClosed_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); + + var session = await sessions.OpenAsync("call-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"); + + await sessions.CloseAsync("call-1", TestContext.Current.CancellationToken); + + await ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); + } + + [Fact] + 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 + // 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(); + var client = new ShellScriptedClient(RunShellToolName, "echo $$"); + var document = ConfigurationLoader.LoadYaml(ShellYaml); + var chatClients = new RoutingChatClientFactory(client); + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { WorkspaceRoot = _root, CallStore = store }); + var factory = new CallSessionFactory( + compiled, new GuardEvaluator(compiled.Configuration.Guards), workspaceRoot: _root); + InMemoryCallSessions sessions = new(factory, TimeSpan.FromMinutes(30), TimeProvider.System); + + var session = await sessions.OpenAsync("call-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 ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); + } + + [Fact] + public async Task ASecondCallFromTheSameFactory_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 sessionA.RunTurnAsync("go", TestContext.Current.CancellationToken); + + await using var sessionB = factory.Create("call-b"); + await sessionB.RunTurnAsync("go", TestContext.Current.CancellationToken); + + var pidA = ParsePid(client.ToolResults[0]); + var pidB = ParsePid(client.ToolResults[1]); + + Assert.NotEqual(pidA, pidB); + } + + [Fact] + 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 session.RunTurnAsync("hi", TestContext.Current.CancellationToken); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + Assert.DoesNotContain(RunShellToolName, toolNames); + } + + [Fact] + public async Task ATurnThatReachesATerminalStage_DisposesTheShellWithoutCloseAsync() + { + var client = new ShellScriptedClient(RunShellToolName, "echo $$"); + var factory = BuildFactory(TerminalShellYaml, client); + var session = factory.Create("call-1"); + + var turn = await session.RunTurnAsync("go", TestContext.Current.CancellationToken); + Assert.True(turn.IsTerminal); + + var pid = ParsePid(client.ToolResults[0]); + + await ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); + } + + /// + /// Reads the pid off the first line of a run_shell tool result: MAF's own formatting + /// appends an exit_code: line after the command's stdout. + /// + private static int ParsePid(string toolResult) => + int.Parse(toolResult.Split('\n', StringSplitOptions.TrimEntries)[0]); + + private static string ToolName() + { + var workspace = Directory.CreateTempSubdirectory("shell-tool-name-").FullName; + try + { + return new LocalShellExecutor(new LocalShellExecutorOptions + { + WorkingDirectory = workspace, + AcknowledgeUnsafe = true, + }).AsAIFunction(requireApproval: false).Name; + } + finally + { + Directory.Delete(workspace, recursive: true); + } + } + + private CallSessionFactory BuildFactory(string yaml, IChatClient client) + { + var document = ConfigurationLoader.LoadYaml(yaml); + var chatClients = new RoutingChatClientFactory(client); + + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { WorkspaceRoot = _root }); + + return new CallSessionFactory( + compiled, + new GuardEvaluator(compiled.Configuration.Guards), + workspaceRoot: _root); + } + +} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs new file mode 100644 index 00000000..6f545559 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs @@ -0,0 +1,153 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; +using Microsoft.Agents.AI.Tools.Shell; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// : one executor per instance, created on +/// first ask, torn down together. +/// +public sealed class CallShellsTests : IDisposable +{ + private readonly string _workspace = + Directory.CreateTempSubdirectory("call-shells-tests-").FullName; + + public void Dispose() + { + try + { + Directory.Delete(_workspace, recursive: true); + } + catch (IOException) + { + } + } + + [Fact] + public async Task Get_Local_RunsInTheCallsWorkspace() + { + await using CallShells shells = new(_workspace, logger: null); + CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); + + var result = await shells.Get(options).RunAsync("pwd", TestContext.Current.CancellationToken); + + var expected = new DirectoryInfo(_workspace).FullName.TrimEnd('/'); + Assert.Contains(expected, result.Stdout, StringComparison.Ordinal); + } + + [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)); + + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + var result = await shells.Get(options).RunAsync("sleep 3", TestContext.Current.CancellationToken); + stopwatch.Stop(); + + Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(3), + $"expected the timed-out run to return in under 3s; took {stopwatch.Elapsed}"); + Assert.True(result is { TimedOut: true, ExitCode: 124 }, + $"expected TimedOut=true and ExitCode=124; got TimedOut={result.TimedOut}, ExitCode={result.ExitCode}"); + } + + [Fact] + public async Task Get_Local_DenyPolicyRejectsTheCommand_AndTheFileSurvives() + { + await using CallShells shells = new(_workspace, logger: null); + CallShellOptions options = new( + ShellKind.Local, new ShellPolicy(denyList: ["^rm "]), Timeout: null); + + var file = Path.Combine(_workspace, "keepme.txt"); + await File.WriteAllTextAsync(file, "do not delete", TestContext.Current.CancellationToken); + + await Assert.ThrowsAsync( + () => shells.Get(options).RunAsync($"rm -f {file}", TestContext.Current.CancellationToken)); + + Assert.True(File.Exists(file)); + } + + [Fact] + public async Task Get_NullAllowListPlusOneDeny_AllowsWhatItDoesNotDeny() + { + // This proves ShellPolicy's own semantics directly, at the CallShells 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( + ShellKind.Local, new ShellPolicy(denyList: ["^rm "], allowList: null), Timeout: null); + + var ok = await shells.Get(options).RunAsync("echo hi", TestContext.Current.CancellationToken); + Assert.Contains("hi", ok.Stdout, StringComparison.Ordinal); + + await Assert.ThrowsAsync( + () => shells.Get(options).RunAsync("rm -f x", TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Get_SameOptionsTwice_ReturnsTheSameExecutorInstance() + { + await using CallShells shells = new(_workspace, logger: null); + CallShellOptions options = new(ShellKind.Local, Policy: null, Timeout: null); + + var first = shells.Get(options); + var second = shells.Get(options); + + Assert.Same(first, second); + } + + [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); + + Assert.NotSame(shells.Get(a), shells.Get(b)); + } + + [Fact] + public async Task DisposeAsync_TwiceIsFine_AndKillsTheLocalBash() + { + CallShells shells = new(_workspace, logger: null); + CallShellOptions 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()); + Assert.True(Directory.Exists($"/proc/{pid}"), "the bash should be alive before dispose"); + + await shells.DisposeAsync(); + await shells.DisposeAsync(); + + await ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Get_AfterDispose_ThrowsObjectDisposedException() + { + CallShells shells = new(_workspace, logger: null); + await shells.DisposeAsync(); + + Assert.Throws( + () => shells.Get(new CallShellOptions(ShellKind.Local, Policy: null, Timeout: null))); + } + + [Fact] + 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); + + var executor = shells.Get(options); + + Assert.IsType(executor); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs b/tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs new file mode 100644 index 00000000..7aacc5fd --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs @@ -0,0 +1,33 @@ +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// Waits for a Linux process to actually be gone, instead of guessing a fixed delay: dispose is +/// async but the OS reaping a killed process is not synchronous with it. +/// +internal static class ProcHelpers +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2); + + private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(20); + + /// + /// Polls /proc/<pid> until the process is gone or a zombie, up to , + /// then asserts it. + /// + public static async Task AssertGoneAsync(int pid, CancellationToken cancellationToken) + { + var deadline = DateTime.UtcNow + Timeout; + + while (!IsGone(pid) && DateTime.UtcNow < deadline) + { + await Task.Delay(PollInterval, cancellationToken); + } + + Assert.True(IsGone(pid), $"the bash pid {pid} should be gone (or a zombie) within {Timeout}"); + } + + private static bool IsGone(int pid) => + !Directory.Exists($"/proc/{pid}") || File.ReadAllText($"/proc/{pid}/stat").Contains(" Z "); +} diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs b/tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs index cea6dc5c..6e6473ad 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Call/CallChannelShapeTests.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.Tests.Fakes; using Xunit; diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs b/tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs index 68d469c7..4a5a0e48 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Call/CallInputPortTests.cs @@ -1,5 +1,5 @@ using AgentCore.Application.Ports; -using AgentCore.Application.Call; +using AgentCore.Application.Calls; using AgentCore.AspNetCore.Tests.Fakes; using Xunit; diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs index 8b307c6b..1b7501f4 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/FakeCallInput.cs @@ -1,6 +1,6 @@ using System.Runtime.CompilerServices; using AgentCore.Application.Ports; -using AgentCore.Application.Call; +using AgentCore.Application.Calls; namespace AgentCore.AspNetCore.Tests.Fakes; From 7f2da8497d36cb3e1722c87e663ae16d597143a2 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 22:03:30 -0600 Subject: [PATCH 11/32] feat: wire background agent to harness --- .../Calls/CallSessionState.cs | 4 +- .../AgentContextProviderCompiler.cs | 5 +- .../Compilation/AgentHarnessProviders.cs | 63 +++++- .../Compilation/ConfigurationCompiler.cs | 3 +- .../Runtime/CallSession.cs | 1 + .../{ => Harness}/CallScopedAgentFileStore.cs | 3 +- .../Runtime/{ => Harness}/CallShellOptions.cs | 2 +- .../{ => Harness}/CallShellProvider.cs | 3 +- .../Runtime/{ => Harness}/CallShells.cs | 2 +- .../{ => Harness}/HarnessSessionState.cs | 4 +- .../Runtime/TurnAmbients.cs | 1 + .../Compilation/BackgroundCompilationTests.cs | 196 ++++++++++++++++++ .../CallScopedAgentFileStoreTests.cs | 3 +- .../CallSessionProviderStateTests.cs | 3 +- .../{ => Harness}/CallSessionShellTests.cs | 3 +- .../Runtime/{ => Harness}/CallShellsTests.cs | 3 +- .../{ => Harness}/HarnessSessionStateTests.cs | 3 +- .../Runtime/{ => Harness}/ProcHelpers.cs | 2 +- 18 files changed, 281 insertions(+), 23 deletions(-) rename src/AgentCore.Application/Runtime/{ => Harness}/CallScopedAgentFileStore.cs (95%) rename src/AgentCore.Application/Runtime/{ => Harness}/CallShellOptions.cs (93%) rename src/AgentCore.Application/Runtime/{ => Harness}/CallShellProvider.cs (93%) rename src/AgentCore.Application/Runtime/{ => Harness}/CallShells.cs (98%) rename src/AgentCore.Application/Runtime/{ => Harness}/HarnessSessionState.cs (94%) create mode 100644 tests/AgentCore.Application.Tests/Configuration/Compilation/BackgroundCompilationTests.cs rename tests/AgentCore.Application.Tests/Runtime/{ => Harness}/CallScopedAgentFileStoreTests.cs (94%) rename tests/AgentCore.Application.Tests/Runtime/{ => Harness}/CallSessionProviderStateTests.cs (99%) rename tests/AgentCore.Application.Tests/Runtime/{ => Harness}/CallSessionShellTests.cs (98%) rename tests/AgentCore.Application.Tests/Runtime/{ => Harness}/CallShellsTests.cs (98%) rename tests/AgentCore.Application.Tests/Runtime/{ => Harness}/HarnessSessionStateTests.cs (96%) rename tests/AgentCore.Application.Tests/Runtime/{ => Harness}/ProcHelpers.cs (95%) diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Calls/CallSessionState.cs index ca35f831..bad90feb 100644 --- a/src/AgentCore.Application/Calls/CallSessionState.cs +++ b/src/AgentCore.Application/Calls/CallSessionState.cs @@ -45,8 +45,8 @@ public sealed record CallSessionState /// /// Gets the MAF provider state a harness switch (todos:, mode:, memory:, - /// files:) held, keyed by that provider's state key. A document with no harness switch - /// holds none. Absent in an old blob, which restores its stage and slots as before. + /// files:, background:) held, keyed by that provider's state key. A document with + /// no harness switch holds none. Absent in an old blob, which restores its stage and slots as before. /// public IReadOnlyDictionary Providers { get; init; } = NoProviders; } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index 63e1a0dd..c638662a 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -28,7 +28,8 @@ public static List Build( AgentCompilationContext context, string pointer, ResolvedClarification clarification, - KnowledgeScopeConfiguration? scope) + KnowledgeScopeConfiguration? scope, + Func resolve) { List providers = [new TurnContextProvider()]; @@ -69,7 +70,7 @@ public static List Build( #pragma warning restore MAAI001 } - AgentHarnessProviders.Add(providers, defaults, item, context, pointer); + AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve); 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 3bf8a9aa..50b1bff6 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Tools.Shell; @@ -9,7 +10,8 @@ namespace AgentCore.Application.Configuration.Compilation; /// /// The context providers behind one agent's harness switches (todos:, mode:, -/// memory:, files:, shell:), added into the provider list builds. +/// memory:, files:, shell:, background:), added into the provider list +/// builds. /// internal static class AgentHarnessProviders { @@ -53,19 +55,20 @@ internal static class AgentHarnessProviders + "- To change part of a file, find the line numbers with `file_access_grep`, read the range around them\n" + " with `file_access_read_lines`, then edit with `file_access_replace_lines`. Reading the whole file\n" + " first is rarely necessary."; - - /// Adds this agent's harness providers, in declaration order: todos, mode, memory, files. + /// Adds this agent's harness providers, in declaration order: todos, mode, memory, files, shell, background. /// The provider list under construction. /// The agents.defaults section, or . /// The agent being compiled. /// The compile-time seams, including the bound workspace root. - /// This agent's JSON pointer, for a memory: or files: failure. + /// 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. public static void Add( List providers, AgentDefaults? defaults, AgentConfiguration item, AgentCompilationContext context, - string pointer) + string pointer, + Func resolve) { var harness = AgentHarness.Compose(defaults, item); @@ -93,6 +96,11 @@ public static void Add( { providers.Add(BuildShellProvider(item, shell, context, pointer)); } + + if (item.Background.Count > 0) + { + providers.Add(BuildBackgroundProvider(item, pointer, resolve)); + } } /// @@ -106,7 +114,7 @@ internal static IReadOnlySet StateKeysOf(IEnumerable foreach (var provider in providers) { - if (provider is not (TodoProvider or AgentModeProvider or FileMemoryProvider or FileAccessProvider)) + if (provider is not (TodoProvider or AgentModeProvider or FileMemoryProvider or FileAccessProvider or BackgroundAgentsProvider)) { continue; } @@ -121,6 +129,49 @@ internal static IReadOnlySet StateKeysOf(IEnumerable } #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( AgentConfiguration item, AgentCompilationContext context, string pointer) { diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index 71546867..6825d840 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -266,7 +266,8 @@ private static (Dictionary Agents, IReadOnlySet Harness context, pointer, clarification, - configuration.Providers?.Knowledge?.Scope); + configuration.Providers?.Knowledge?.Scope, + Resolve); harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); var built = new ChatClientAgent( diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 59d6ae48..563c87c9 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -9,6 +9,7 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Policy; using AgentCore.Application.Ports; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.State; using AgentCore.Application.Tools; using AgentCore.Application.Transcript; diff --git a/src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs b/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs similarity index 95% rename from src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs rename to src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs index 9cb75f78..2dafded0 100644 --- a/src/AgentCore.Application/Runtime/CallScopedAgentFileStore.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs @@ -1,6 +1,7 @@ +using AgentCore.Application.Runtime; using Microsoft.Agents.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Harness; /// /// The store behind an agent's files: block. One instance serves every call: each operation diff --git a/src/AgentCore.Application/Runtime/CallShellOptions.cs b/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs similarity index 93% rename from src/AgentCore.Application/Runtime/CallShellOptions.cs rename to src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs index 112979de..33e92661 100644 --- a/src/AgentCore.Application/Runtime/CallShellOptions.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShellOptions.cs @@ -1,7 +1,7 @@ using AgentCore.Application.Configuration.Schema; using Microsoft.Agents.AI.Tools.Shell; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Harness; /// /// What one agent's shell: block resolved to. Built once at compile time and shared by every diff --git a/src/AgentCore.Application/Runtime/CallShellProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs similarity index 93% rename from src/AgentCore.Application/Runtime/CallShellProvider.cs rename to src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs index b55708ac..f12c7a0d 100644 --- a/src/AgentCore.Application/Runtime/CallShellProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs @@ -1,6 +1,7 @@ +using AgentCore.Application.Runtime; using Microsoft.Agents.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Harness; /// /// The context provider behind an agent's shell: block: on every invocation it hands the diff --git a/src/AgentCore.Application/Runtime/CallShells.cs b/src/AgentCore.Application/Runtime/Harness/CallShells.cs similarity index 98% rename from src/AgentCore.Application/Runtime/CallShells.cs rename to src/AgentCore.Application/Runtime/Harness/CallShells.cs index 3657530f..32cd6a6d 100644 --- a/src/AgentCore.Application/Runtime/CallShells.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShells.cs @@ -3,7 +3,7 @@ using Microsoft.Agents.AI.Tools.Shell; using Microsoft.Extensions.Logging; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Harness; /// /// The shell executors one call has started. One per diff --git a/src/AgentCore.Application/Runtime/HarnessSessionState.cs b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs similarity index 94% rename from src/AgentCore.Application/Runtime/HarnessSessionState.cs rename to src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs index 32032c20..88ee5a6b 100644 --- a/src/AgentCore.Application/Runtime/HarnessSessionState.cs +++ b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs @@ -3,11 +3,11 @@ using System.Text.Json.Nodes; using Microsoft.Agents.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Harness; /// /// Moves the harness providers' MAF state — todos:, mode:, memory:, -/// files: — between a live 's state bag and +/// files:, background: — between a live 's state bag and /// . /// internal static class HarnessSessionState diff --git a/src/AgentCore.Application/Runtime/TurnAmbients.cs b/src/AgentCore.Application/Runtime/TurnAmbients.cs index ad569c7c..c8362cf2 100644 --- a/src/AgentCore.Application/Runtime/TurnAmbients.cs +++ b/src/AgentCore.Application/Runtime/TurnAmbients.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Ports; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.State; using AgentCore.Domain.Knowledge; diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/BackgroundCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/BackgroundCompilationTests.cs new file mode 100644 index 00000000..3db59e01 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/BackgroundCompilationTests.cs @@ -0,0 +1,196 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tests.Runtime; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Configuration.Compilation; + +/// +/// The background: list reaching a compiled agent as a , +/// the background_agents_* tools it puts in front of the model, and the state key it +/// contributes to resume. +/// +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. +public sealed class BackgroundCompilationTests +{ + private static readonly string[] ExpectedBackgroundTools = + [ + "background_agents_start_task", + "background_agents_wait_for_first_completion", + "background_agents_get_task_results", + "background_agents_get_all_tasks", + "background_agents_continue_task", + "background_agents_clear_completed_task", + ]; + + private const string ParentWithChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: parent, instructions: "delegate work", background: [coder] } + - { id: coder, instructions: "write code" } + policy: + initial: working + stages: + - { id: working, agent: parent, to: [ { stage: done, when: always } ] } + - { id: done, agent: coder, terminal: true } + """; + + private const string ParentWithTodosAndChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background-keys + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: parent, instructions: "delegate work", todos: true, background: [coder] } + - { id: coder, instructions: "write code" } + policy: + initial: working + stages: + - { id: working, agent: parent, to: [ { stage: done, when: always } ] } + - { id: done, agent: coder, terminal: true } + """; + + [Fact] + public void Compile_BackgroundWithAChild_GetsABackgroundAgentsProvider() + { + var compiled = Compile(ParentWithChildYaml); + + var parent = compiled.Agents["parent"].GetService(); + Assert.NotNull(parent); + Assert.Contains(parent.AIContextProviders ?? [], provider => provider is BackgroundAgentsProvider); + } + + [Fact] + public void Compile_NoBackground_GetsNoBackgroundAgentsProvider() + { + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-no-background", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only" }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); + + var agent = Assert.Single(compiled.Agents.Values).GetService(); + Assert.NotNull(agent); + Assert.DoesNotContain(agent.AIContextProviders ?? [], provider => provider is BackgroundAgentsProvider); + } + + [Fact] + public async Task Compile_BackgroundWithAChild_ModelSeesTheSixBackgroundTools() + { + using SequencedChatClient reply = new("hello there."); + + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(ParentWithChildYaml), + new AgentCompilationContext(new FakeChatClientFactory(reply))); + + var agent = compiled.Agents["parent"]; + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + + await agent.RunAsync("hi", session, cancellationToken: token); + + var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; + + Assert.Equal(ExpectedBackgroundTools, toolNames, StringComparer.Ordinal); + } + + [Fact] + public void Compile_BackgroundWithTodos_HarnessStateKeysIncludeTheBackgroundKey() + { + using SequencedChatClient childReply = new("hi"); + var backgroundKeys = new BackgroundAgentsProvider( + [new ChatClientAgent(childReply, new ChatClientAgentOptions { Name = "coder" })]).StateKeys; + + var compiled = Compile(ParentWithTodosAndChildYaml); + HashSet expected = [new TodoProvider().StateKeys[0]]; + expected.UnionWith(backgroundKeys); + + Assert.Equal(expected, compiled.HarnessStateKeys); + } + + [Fact] + public void Compile_BackgroundChildDeclaredLater_ResolvesForward() + { + var compiled = Compile(ParentWithChildYaml); + + Assert.True(compiled.Agents.ContainsKey("coder")); + var parent = compiled.Agents["parent"].GetService(); + Assert.NotNull(parent); + Assert.Contains(parent.AIContextProviders ?? [], provider => provider is BackgroundAgentsProvider); + } + + private const string UnknownChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background-unknown + agents: + items: + - { id: parent, instructions: "delegate work", background: [ghost] } + """; + + [Fact] + public void Compile_BackgroundUnknownChild_FailsNamingTheBackgroundPointer() + { + var failure = Assert.Throws(() => Compile(UnknownChildYaml)); + + Assert.Equal("/agents/items/0/background/0", failure.Pointer); + Assert.Contains("not declared in agents.items", failure.Message, StringComparison.Ordinal); + } + + private const string SelfChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background-self + agents: + items: + - { id: parent, instructions: "delegate work", background: [parent] } + """; + + private const string CollidingChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background-collision + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: parent, instructions: "delegate work", background: [Coder, coder] } + - { id: Coder, instructions: "write code loudly" } + - { id: coder, instructions: "write code quietly" } + policy: + initial: working + stages: + - { id: working, agent: parent, to: [ { stage: done, when: always } ] } + - { id: done, agent: coder, terminal: true } + """; + + [Fact] + public void Compile_BackgroundChildrenWithCollidingNames_FailsNamingTheBackgroundPointer() + { + var failure = Assert.Throws(() => Compile(CollidingChildYaml)); + + Assert.Equal("/agents/items/0/background", failure.Pointer); + } + + private static CompiledAgent Compile(string yaml) => ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(yaml), + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); +} +#pragma warning restore MAAI001 diff --git a/tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs similarity index 94% rename from tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs index 098ec98a..52e7eea1 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallScopedAgentFileStoreTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs @@ -1,7 +1,8 @@ using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Harness; /// /// as a unit: it resolves the running call's workspace off diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionProviderStateTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionProviderStateTests.cs index 154230be..3694838c 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionProviderStateTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionProviderStateTests.cs @@ -8,12 +8,13 @@ using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Tests.Fakes; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +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 diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs index 1220e30d..109472b0 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionShellTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Sessions.Memory; using AgentCore.Application.Tests.Fakes; using AgentCore.TestSupport; @@ -9,7 +10,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Harness; /// /// The end-to-end path of a shell: block: the tool the model is handed, the workspace it diff --git a/tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs index 6f545559..f7afbf57 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallShellsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs @@ -1,9 +1,10 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using Microsoft.Agents.AI.Tools.Shell; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Harness; /// /// : one executor per instance, created on diff --git a/tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs similarity index 96% rename from tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs index 7421ff6d..07eec1c2 100644 --- a/tests/AgentCore.Application.Tests/Runtime/HarnessSessionStateTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/HarnessSessionStateTests.cs @@ -1,9 +1,10 @@ using System.Text.Json; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using Microsoft.Agents.AI; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Harness; /// /// and — the two diff --git a/tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/ProcHelpers.cs similarity index 95% rename from tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs rename to tests/AgentCore.Application.Tests/Runtime/Harness/ProcHelpers.cs index 7aacc5fd..e504d0db 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ProcHelpers.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/ProcHelpers.cs @@ -1,6 +1,6 @@ using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Harness; /// /// Waits for a Linux process to actually be gone, instead of guessing a fixed delay: dispose is From eff7aec2898bfb1fe486bbbd5d4891bbaf401c7d Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 22:32:31 -0600 Subject: [PATCH 12/32] feat: implement background agent session management and release mechanism --- .../AgentContextProviderCompiler.cs | 8 +- .../Compilation/AgentHarnessProviders.cs | 82 +++++++- .../Compilation/CompiledAgent.cs | 14 +- .../Compilation/ConfigurationCompiler.cs | 24 ++- src/AgentCore.Application/Diagnostics/Log.cs | 10 + .../Runtime/CallSession.cs | 36 +++- .../Harness/BackgroundSessionRelease.cs | 56 ++++++ .../Compilation/LoopCompilationTests.cs | 174 +++++++++++++++++ .../Harness/CallSessionBackgroundTests.cs | 178 ++++++++++++++++++ 9 files changed, 562 insertions(+), 20 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs create mode 100644 tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index c638662a..e1341c68 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -22,6 +22,7 @@ internal static class AgentContextProviderCompiler /// 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. public static List Build( AgentDefaults? defaults, AgentConfiguration item, @@ -29,7 +30,8 @@ public static List Build( string pointer, ResolvedClarification clarification, KnowledgeScopeConfiguration? scope, - Func resolve) + Func resolve, + ICollection? background = null) { List providers = [new TurnContextProvider()]; @@ -69,8 +71,7 @@ public static List Build( loggerFactory: context.Loggers)); #pragma warning restore MAAI001 } - - AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve); + AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background); if (AgentKnowledge.Compose(defaults, item) is not { } composed) { @@ -101,4 +102,5 @@ public static List Build( return providers; } +#pragma warning restore MAAI001 } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 50b1bff6..3fa94f4b 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -55,6 +55,7 @@ internal static class AgentHarnessProviders + "- To change part of a file, find the line numbers with `file_access_grep`, read the range around them\n" + " with `file_access_read_lines`, then edit with `file_access_replace_lines`. Reading the whole file\n" + " first is rarely necessary."; +#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. /// The provider list under construction. /// The agents.defaults section, or . @@ -62,13 +63,15 @@ 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. public static void Add( List providers, AgentDefaults? defaults, AgentConfiguration item, AgentCompilationContext context, string pointer, - Func resolve) + Func resolve, + ICollection? background = null) { var harness = AgentHarness.Compose(defaults, item); @@ -99,9 +102,84 @@ public static void Add( if (item.Background.Count > 0) { - providers.Add(BuildBackgroundProvider(item, pointer, resolve)); + var provider = BuildBackgroundProvider(item, pointer, resolve); + providers.Add(provider); + background?.Add(provider); } } +#pragma warning restore MAAI001 +#pragma warning disable MAAI001 // The loop family is evaluation-only in Microsoft.Agents.AI 1.21.0. + + /// + /// Wraps one compiled agent in its loop: block: a over the + /// until: evaluators in document order, capped at maxRounds:. No block, no wrap. + /// + /// The compiled agent. + /// The agents.defaults section, or . + /// The agent being compiled. + /// This agent's JSON pointer, for a loop: failure. + /// The loop-wrapped agent, or unchanged. + public static AIAgent ApplyLoop(AIAgent agent, AgentDefaults? defaults, AgentConfiguration item, string pointer) + { + ArgumentNullException.ThrowIfNull(agent); + ArgumentNullException.ThrowIfNull(item); + + if (item.Loop is not { } loop) + { + return agent; + } + + if (loop.Until is not { Count: > 0 }) + { + throw ConfigurationCompiler.Fail( + ConfigurationError.AppendPointer(pointer, "loop"), + $"the agent '{item.Id}' declares a loop: block with no until: entries, so the loop would " + + "run exactly once and maxRounds: would never apply. Name what ends the loop, or remove " + + "the loop: block."); + } + + var harness = AgentHarness.Compose(defaults, item); + List evaluators = new(loop.Until.Count); + + for (var index = 0; index < loop.Until.Count; index++) + { + var untilPointer = ConfigurationError.AppendPointer( + ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "loop"), "until"), index); + var until = loop.Until[index]; + + if (until.Todos is not null) + { + if (!harness.Todos) + { + throw ConfigurationCompiler.Fail( + untilPointer, + $"the agent '{item.Id}' declares loop: until: todos: and no todos: switch, so the " + + "evaluator would fault every turn resolving its provider. Set todos: true, or " + + "remove the entry."); + } + + evaluators.Add(new TodoCompletionLoopEvaluator(new TodoCompletionLoopEvaluatorOptions())); + } + + if (until.Background is not null) + { + if (item.Background.Count == 0) + { + throw ConfigurationCompiler.Fail( + untilPointer, + $"the agent '{item.Id}' declares loop: until: background: and no background: children, " + + "so the evaluator would fault every turn resolving its provider. Name the children, " + + "or remove the entry."); + } + + evaluators.Add(new BackgroundTaskCompletionLoopEvaluator(new BackgroundTaskCompletionLoopEvaluatorOptions())); + } + } + + // Every iteration's text reaches the stream; there are no per-iteration entries (decision 14). + return new LoopAgent(agent, evaluators, new LoopAgentOptions { MaxIterations = loop.MaxRounds }); + } +#pragma warning restore MAAI001 /// /// The state keys of the harness providers among — never the diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs index bb769328..e062f198 100644 --- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs +++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs @@ -18,6 +18,7 @@ public sealed class CompiledAgent private readonly Dictionary _turnByAgentId; +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. internal CompiledAgent( AgentCoreConfiguration configuration, CompileTableRow row, @@ -28,6 +29,7 @@ internal CompiledAgent( IReadOnlySet? spokenBy, AgentCoreChatHistoryProvider history, IReadOnlySet harnessStateKeys, + IReadOnlyList backgroundProviders, Func turnLayers) { Configuration = configuration; @@ -38,7 +40,7 @@ internal CompiledAgent( SpokenBy = spokenBy; History = history; HarnessStateKeys = harnessStateKeys; - + BackgroundProviders = backgroundProviders; _byAgentId = byAgentId; _agentIdByStage = agentIdByStage; @@ -50,6 +52,7 @@ internal CompiledAgent( _turnByAgentId[id] = turnLayers(agent); } } +#pragma warning restore MAAI001 /// /// Gets whether the row answers its runs out of store 1 on its own session, rather than the @@ -83,7 +86,6 @@ internal CompiledAgent( /// Gets the store this agent's calls and every word of them are kept in. internal ICallStore CallStore { 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 @@ -91,6 +93,14 @@ internal CompiledAgent( /// 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 + /// each one's session when it ends, so children still running cannot outlive it. + /// + internal IReadOnlyList BackgroundProviders { get; } +#pragma warning restore MAAI001 + /// /// Gets the agent a turn runs, with the turn-disposition layers on it. /// diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index 6825d840..d70d7bb2 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -141,7 +141,7 @@ public static CompiledAgent Compile(AgentCoreConfiguration configuration, AgentC AgentCoreChatHistoryProvider history = new(calls); - var (agents, harnessStateKeys) = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null); + var (agents, harnessStateKeys, backgroundProviders) = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null); var (entry, stages) = row.BuildEntry(configuration, agents, context); @@ -157,6 +157,7 @@ public static CompiledAgent Compile(AgentCoreConfiguration configuration, AgentC spokenBy, history, harnessStateKeys, + backgroundProviders, inner => WithTurnDisposition(inner, configuration, context.Moderation, spokenBy)); } @@ -178,23 +179,23 @@ private static AIAgent WithTurnDisposition( ? layered : new ModerationAgent(layered, moderation, configuration.RefusalReply, ModerationAgent.DefaultTimeout); } - /// Builds one ChatClientAgent for each agents.items entry. /// The loaded document. /// The seams the document names. /// Store 1, or to leave the framework default in place. - /// The agents, keyed by id, and the union of every harness provider's state keys. - private static (Dictionary Agents, IReadOnlySet HarnessStateKeys) BuildAgents( + /// The agents keyed by id, the union of every harness provider's state keys, and every background provider for the call-end release. +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. + private static (Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders) BuildAgents( AgentCoreConfiguration configuration, AgentCompilationContext context, AgentCoreChatHistoryProvider? history) { Dictionary agents = new(StringComparer.Ordinal); HashSet harnessStateKeys = new(StringComparer.Ordinal); - + List backgroundProviders = []; if (configuration.Agents is not { } section) { - return (agents, harnessStateKeys); + return (agents, harnessStateKeys, backgroundProviders); } var clarification = ResolvedClarification.From(configuration); @@ -227,7 +228,7 @@ private static (Dictionary Agents, IReadOnlySet Harness Resolve(item.Id); } - return (agents, harnessStateKeys); + return (agents, harnessStateKeys, backgroundProviders); AIAgent? Resolve(string id) { @@ -267,7 +268,8 @@ private static (Dictionary Agents, IReadOnlySet Harness pointer, clarification, configuration.Providers?.Knowledge?.Scope, - Resolve); + Resolve, + backgroundProviders); harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); var built = new ChatClientAgent( @@ -289,10 +291,12 @@ private static (Dictionary Agents, IReadOnlySet Harness .UseOpenTelemetry(configure: static agent => agent.EnableSensitiveData = false) .Build(); - agents[id] = instrumented; - return instrumented; + var looped = AgentHarnessProviders.ApplyLoop(instrumented, section.Defaults, item, pointer); + agents[id] = looped; + return looped; } } +#pragma warning restore MAAI001 /// Puts the auditing function-invocation loop into the pipeline of one agent. private static AuditingFunctionInvokingChatClient WithToolFailureAuditing(IChatClient model) diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs index 3b3822ed..37b20fd2 100644 --- a/src/AgentCore.Application/Diagnostics/Log.cs +++ b/src/AgentCore.Application/Diagnostics/Log.cs @@ -269,4 +269,14 @@ public static partial void KnowledgeScopeComposed( Level = LogLevel.Warning, Message = "Could not dispose a shell: executor of the call 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. + /// The logger of the session. + /// The id of the call 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); } diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 563c87c9..d4756247 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -103,6 +103,10 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private readonly CallShells? _shells; + // The background release runs once per call: both DisposeAsync and the turn-end path below + // reach it, and a second release would re-cancel children that already went away. + private int _backgroundReleased; + // Whether the running turn has already handed the host something to speak. One rule for both // run shapes: a run that has handed the host nothing cannot be the turn the caller was hearing, // so a barge-in in that window belongs to the turn that finished before it. A streaming turn @@ -516,10 +520,32 @@ public bool EndCall(CallEndReason reason) private ValueTask DisposeShellsAsync() => _shells?.DisposeAsync() ?? ValueTask.CompletedTask; /// - /// Disposes this call's shell executors. Idempotent: a session already disposed, or one that - /// never had a workspace, disposes nothing. + /// Disposes this call's background sessions and shell executors. Idempotent: a session already + /// disposed, or one that never had either, disposes nothing. /// - public ValueTask DisposeAsync() => DisposeShellsAsync(); + public async ValueTask DisposeAsync() + { + await ReleaseBackgroundSessionsAsync().ConfigureAwait(false); + await DisposeShellsAsync().ConfigureAwait(false); + } + + /// + /// 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 + /// children. Release precedes the shells: a child cancelled here may be inside a shell tool. + /// + private async ValueTask ReleaseBackgroundSessionsAsync() + { + if (Interlocked.Exchange(ref _backgroundReleased, 1) == 1 + || _compiled.BackgroundProviders.Count == 0 + || Session() is not { } session) + { + return; + } + + await BackgroundSessionRelease.ReleaseAsync( + _compiled.BackgroundProviders, session, CallId, _logger, CancellationToken.None).ConfigureAwait(false); + } /// /// Brings the session's words back in line with store 1 before a turn after the first, when and @@ -1337,6 +1363,10 @@ private async Task CompleteTurnAsync( if (IsComplete || _events.HasEnded) { + // Children before shells: a cancelled child may be inside a shell tool the next line + // tears down. + await 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 DisposeShellsAsync().ConfigureAwait(false); diff --git a/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs b/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs new file mode 100644 index 00000000..312d4771 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/BackgroundSessionRelease.cs @@ -0,0 +1,56 @@ +using AgentCore.Application.Diagnostics; +using Microsoft.Agents.AI; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Runtime.Harness; + +/// +/// Releases the harness background providers' sessions when a call 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 + /// on a child. + /// + private static readonly TimeSpan ReleaseTimeout = TimeSpan.FromSeconds(5); + + /// + /// Cancels each provider's running tasks on and releases the + /// 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 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, + ILogger logger, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(providers); + ArgumentNullException.ThrowIfNull(session); + ArgumentException.ThrowIfNullOrEmpty(callId); + ArgumentNullException.ThrowIfNull(logger); + + foreach (var provider in providers) + { + try + { + await provider.ReleaseSessionAsync(session, cancelRunning: true, ReleaseTimeout, cancellationToken) + .ConfigureAwait(false); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + Log.BackgroundReleaseFailed(logger, callId, exception); + } + } + } +#pragma warning restore MAAI001 +} diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs new file mode 100644 index 00000000..6229fb61 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/LoopCompilationTests.cs @@ -0,0 +1,174 @@ +using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Tests.Fakes; +using Microsoft.Agents.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Configuration.Compilation; + +/// +/// The loop: block reaching a compiled agent as a , the evaluator +/// each until: entry selects, and the failures a block names that its agent cannot honor. +/// +#pragma warning disable MAAI001 // The loop family is evaluation-only in Microsoft.Agents.AI 1.21.0. +public sealed class LoopCompilationTests +{ + private const string TodosLoopYaml = + """ + apiVersion: agentcore/v1 + name: harness-loop-todos + agents: + items: + - { id: coder, instructions: "fix bugs", todos: true, loop: { maxRounds: 3, until: [{ todos: {} }] } } + """; + + private const string BackgroundLoopYaml = + """ + apiVersion: agentcore/v1 + name: harness-loop-background + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: parent, instructions: "delegate work", background: [coder], loop: { maxRounds: 2, until: [{ background: {} }] } } + - { id: coder, instructions: "write code" } + policy: + initial: working + stages: + - { id: working, agent: parent, to: [ { stage: done, when: always } ] } + - { id: done, agent: coder, terminal: true } + """; + + [Fact] + public void Compile_LoopWithUntilTodosAndTodos_GetsALoopAgent() + { + var compiled = Compile(TodosLoopYaml); + + Assert.NotNull(compiled.Agents["coder"].GetService()); + } + + [Fact] + public void Compile_NoLoop_GetsNoLoopAgent() + { + var compiled = ConfigurationCompiler.Compile( + new AgentCoreConfiguration + { + ApiVersion = AgentCoreConfiguration.SupportedApiVersion, + Name = "harness-no-loop", + Agents = new AgentsConfiguration + { + Items = [new AgentConfiguration { Id = "only", Todos = true }], + }, + }, + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); + + Assert.Null(Assert.Single(compiled.Agents.Values).GetService()); + } + + [Fact] + public async Task Compile_LoopWithMaxRoundsThreeAndOpenTodos_RunsThreeIterationsThenStops() + { + var client = new ToolCallingChatClient( + "added", + new Dictionary(StringComparer.Ordinal) + { + ["todos"] = new object[] + { + new Dictionary(StringComparer.Ordinal) { ["title"] = "T" }, + }, + }); + + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(TodosLoopYaml), + new AgentCompilationContext(new FakeChatClientFactory(client))); + + var agent = compiled.Agents["coder"]; + var token = TestContext.Current.CancellationToken; + var session = await agent.CreateSessionAsync(token); + + var response = await agent.RunAsync("fix it", session, cancellationToken: token); + + // Each iteration replays the tool call and the text: iterations rerun from the initial + // 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. + Assert.Equal(3, client.Called.Count(name => name == "todos_add")); + Assert.Equal(6, client.Calls); + Assert.Contains("added", response.Text, StringComparison.Ordinal); + } + + [Fact] + public void Compile_LoopUntilTodosWithoutTodos_FailsNamingTheUntilPointer() + { + const string yaml = + """ + apiVersion: agentcore/v1 + name: harness-loop-todos-missing + agents: + items: + - { id: coder, instructions: "fix bugs", loop: { maxRounds: 3, until: [{ todos: {} }] } } + """; + + var failure = Assert.Throws(() => Compile(yaml)); + + Assert.Equal("/agents/items/0/loop/until/0", failure.Pointer); + Assert.Contains("todos:", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Compile_LoopUntilBackgroundWithoutBackground_FailsNamingTheUntilPointer() + { + const string yaml = + """ + apiVersion: agentcore/v1 + name: harness-loop-background-missing + agents: + items: + - { id: coder, instructions: "fix bugs", loop: { maxRounds: 3, until: [{ background: {} }] } } + """; + + var failure = Assert.Throws(() => Compile(yaml)); + + Assert.Equal("/agents/items/0/loop/until/0", failure.Pointer); + Assert.Contains("background:", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Compile_LoopWithNoUntil_FailsNamingTheLoopPointer() + { + const string yaml = + """ + apiVersion: agentcore/v1 + name: harness-loop-no-until + agents: + items: + - { id: coder, instructions: "fix bugs", loop: { maxRounds: 3 } } + """; + + var failure = Assert.Throws(() => Compile(yaml)); + + Assert.Equal("/agents/items/0/loop", failure.Pointer); + Assert.Contains("until:", failure.Message, StringComparison.Ordinal); + } + + [Fact] + public void Compile_LoopWithBackgroundUntilAndChildren_CompilesAndAddsNoStateKeys() + { + using SequencedChatClient childReply = new("hi"); + var backgroundKeys = new BackgroundAgentsProvider( + [new ChatClientAgent(childReply, new ChatClientAgentOptions { Name = "coder" })]).StateKeys; + + var compiled = Compile(BackgroundLoopYaml); + + Assert.NotNull(compiled.Agents["parent"].GetService()); + Assert.Equal(backgroundKeys.ToHashSet(StringComparer.Ordinal), compiled.HarnessStateKeys); + } + + private static CompiledAgent Compile(string yaml) => ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(yaml), + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hello there.")))); +} +#pragma warning restore MAAI001 diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs new file mode 100644 index 00000000..0770dc10 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionBackgroundTests.cs @@ -0,0 +1,178 @@ +using System.Runtime.CompilerServices; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.Sessions.Memory; +using AgentCore.Application.Tests.Fakes; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Xunit; + +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. +/// +#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0. +public sealed class CallSessionBackgroundTests +{ + private const string LingeringChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background-lingering + guards: + never: { "<": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: parent, instructions: "delegate work", model: { ref: parent }, background: [blocker] } + - { id: blocker, instructions: "work forever", model: { ref: blocker } } + policy: + initial: working + stages: + - { id: working, agent: parent, to: [ { stage: done, when: never } ] } + - { id: done, agent: blocker, terminal: true } + """; + + private const string TerminalChildYaml = + """ + apiVersion: agentcore/v1 + name: harness-background-terminal + guards: + always: { ">=": [ { var: turnIndex }, 0 ] } + agents: + items: + - { id: parent, instructions: "delegate work", model: { ref: parent }, background: [blocker] } + - { id: blocker, instructions: "work forever", model: { ref: blocker } } + policy: + initial: working + stages: + - { id: working, agent: parent, to: [ { stage: done, when: always } ] } + - { id: done, agent: blocker, terminal: true } + """; + + [Fact] + public async Task CloseAsync_WithAChildStillRunning_CancelsIt() + { + var token = TestContext.Current.CancellationToken; + var parent = new ToolCallingChatClient( + "started", + new Dictionary(StringComparer.Ordinal) + { + ["agentName"] = "blocker", + ["input"] = "work", + ["description"] = "d", + }); + var child = new BlockingChatClient(); + InMemoryCallSessions sessions = new(BuildFactory(LingeringChildYaml, parent, child), TimeSpan.FromMinutes(30), TimeProvider.System); + + var session = await sessions.OpenAsync("call-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 + // 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 child.Cancelled.WaitAsync(TimeSpan.FromSeconds(10), token); + } + + [Fact] + public async Task ATurnThatReachesATerminalStage_CancelsAChildStillRunningWithoutCloseAsync() + { + var token = TestContext.Current.CancellationToken; + var parent = new ToolCallingChatClient( + "started", + new Dictionary(StringComparer.Ordinal) + { + ["agentName"] = "blocker", + ["input"] = "work", + ["description"] = "d", + }); + var child = new BlockingChatClient(); + var factory = BuildFactory(TerminalChildYaml, parent, child); + + await using var session = factory.Create("call-1"); + var turn = await session.RunTurnAsync("go", token); + + Assert.True(turn.IsTerminal); + await child.Started.WaitAsync(TimeSpan.FromSeconds(10), token); + await child.Cancelled.WaitAsync(TimeSpan.FromSeconds(10), token); + } + + private static CallSessionFactory BuildFactory(string yaml, IChatClient parent, IChatClient child) + { + var chatClients = new RoutingChatClientFactory(parent); + chatClients.Route("parent", parent); + chatClients.Route("blocker", child); + + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(yaml), new AgentCompilationContext(chatClients)); + + return new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + } + + /// A model that stays inside its first request until the run is cancelled. + private sealed class BlockingChatClient : IChatClient + { + private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _cancelled = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// Completes when the child enters its model call. + public Task Started => _started.Task; + + /// Completes when the child observes the cancel. + public Task Cancelled => _cancelled.Task; + + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + _started.TrySetResult(); + + try + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + _cancelled.TrySetResult(); + throw; + } + + yield break; + } + + 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) + { + ArgumentNullException.ThrowIfNull(serviceType); + return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; + } + + public void Dispose() + { + // Nothing to release. + } + } +} +#pragma warning restore MAAI001 From 5e66489ccce4ac420fc68b6f619969f6691446e2 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sat, 12 Sep 2026 23:02:31 -0600 Subject: [PATCH 13/32] feat: add AgentApproval class and corresponding tests for auto-approval logic --- .../Compilation/AgentApproval.cs | 69 +++++++ .../Compilation/ConfigurationCompiler.cs | 3 +- .../Compilation/ApprovalCompilationTests.cs | 178 ++++++++++++++++++ 3 files changed, 249 insertions(+), 1 deletion(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs create mode 100644 tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs new file mode 100644 index 00000000..32975128 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs @@ -0,0 +1,69 @@ +using AgentCore.Application.Configuration.Schema; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +/// +/// One agent's approval: block: the standing rules that answer an approval request before +/// it surfaces. Everything a rule does not name still asks. +/// +internal static class AgentApproval +{ + /// Composes one agent's auto-approval patterns. + /// The agents.defaults section, or . + /// The agent to resolve. + /// + /// The agent's own auto: when it declares one, else the defaults', else empty. One key, + /// so key-by-key inheritance is a single fallback, the same as knowledge: and + /// compaction:. + /// + public static IReadOnlyList Compose(AgentDefaults? defaults, AgentConfiguration agent) + { + ArgumentNullException.ThrowIfNull(agent); + + return agent.Approval?.Auto ?? defaults?.Approval?.Auto ?? []; + } + + /// Whether auto-approves . + /// One auto: entry: a tool name, or a prefix with a trailing *. + /// 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. + /// + public static bool Matches(string pattern, string toolName) + { + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(toolName); + + return pattern.EndsWith('*') + ? toolName.StartsWith(pattern[..^1], StringComparison.Ordinal) + : toolName == pattern; + } + + /// + /// Bakes one agent's auto: into its pipeline as UseToolApproval rules. No + /// patterns, no layer — the document pays nothing for approval it never declares. + /// + /// The compiled agent. + /// The agents.defaults section, or . + /// The agent being compiled. + /// The approval-wrapped agent, or unchanged. + public static AIAgent Apply(AIAgent agent, AgentDefaults? defaults, AgentConfiguration item) + { + ArgumentNullException.ThrowIfNull(agent); + ArgumentNullException.ThrowIfNull(item); + + if (Compose(defaults, item) is not { Count: > 0 } auto) + { + return agent; + } + + return new AIAgentBuilder(agent) + .UseToolApproval(new ToolApprovalAgentOptions { AutoApprovalRules = auto.Select(ToRule).ToList() }) + .Build(); + } + + private static Func> ToRule(string pattern) + => context => ValueTask.FromResult(Matches(pattern, context.FunctionCallContent.Name)); +} diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index d70d7bb2..2fd26e15 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -291,7 +291,8 @@ private static (Dictionary Agents, IReadOnlySet Harness .UseOpenTelemetry(configure: static agent => agent.EnableSensitiveData = false) .Build(); - var looped = AgentHarnessProviders.ApplyLoop(instrumented, section.Defaults, item, pointer); + var approved = AgentApproval.Apply(instrumented, section.Defaults, item); + var looped = AgentHarnessProviders.ApplyLoop(approved, section.Defaults, item, pointer); agents[id] = looped; return looped; } diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs new file mode 100644 index 00000000..111f4816 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs @@ -0,0 +1,178 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Tests.Fakes; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.Application.Tests.Configuration.Compilation; + +/// +/// The approval: block reaching a compiled agent as UseToolApproval rules: an +/// auto: entry lets its tool run with no request surfacing, anything else still asks, and +/// the layer adds no state keys — toolApprovalState persistence rides with the Phase 2 +/// round trip, when standing rules can exist. +/// +public sealed class ApprovalCompilationTests +{ + private const string GatedToolYaml = + """ + apiVersion: agentcore/v1 + name: approval-auto + tools: + - { id: send_email, kind: builtin, uses: test.send, description: "Send an email." } + agents: + items: + - id: only + instructions: "send the mail" + tools: [ send_email ] + approval: { auto: [ send_email ] } + """; + + private const string UngatedToolYaml = + """ + apiVersion: agentcore/v1 + name: approval-auto + tools: + - { id: send_email, kind: builtin, uses: test.send, description: "Send an email." } + agents: + items: + - id: only + instructions: "send the mail" + tools: [ send_email ] + approval: { auto: [ get_time ] } + """; + + [Fact] + public void Compose_AgentAuto_ReturnsItsOwn() + { + var agent = new AgentConfiguration + { + Id = "coder", + Approval = new ApprovalConfiguration { Auto = ["send_email"] }, + }; + + Assert.Equal(["send_email"], AgentApproval.Compose(null, agent)); + } + + [Fact] + public void Compose_NoAgentAuto_ReturnsTheDefaults() + { + var defaults = new AgentDefaults { Approval = new ApprovalConfiguration { Auto = ["get_time"] } }; + var agent = new AgentConfiguration { Id = "coder" }; + + Assert.Equal(["get_time"], AgentApproval.Compose(defaults, agent)); + } + + [Fact] + public void Compose_BothAuto_AgentWins() + { + var defaults = new AgentDefaults { Approval = new ApprovalConfiguration { Auto = ["get_time"] } }; + var agent = new AgentConfiguration + { + Id = "coder", + Approval = new ApprovalConfiguration { Auto = ["send_email"] }, + }; + + Assert.Equal(["send_email"], AgentApproval.Compose(defaults, agent)); + } + + [Fact] + public void Compose_NoApprovalAnywhere_ReturnsEmpty() + { + var agent = new AgentConfiguration { Id = "coder" }; + + Assert.Empty(AgentApproval.Compose(null, agent)); + } + + [Fact] + public void Matches_ExactName_MatchesOnlyItself() + { + Assert.True(AgentApproval.Matches("send_email", "send_email")); + Assert.False(AgentApproval.Matches("send_email", "send_sms")); + Assert.False(AgentApproval.Matches("send_email", "Send_Email")); + } + + [Fact] + public void Matches_TrailingStar_MatchesByPrefix() + { + Assert.True(AgentApproval.Matches("file_access_read*", "file_access_read_lines")); + Assert.False(AgentApproval.Matches("file_access_read*", "file_access_write")); + } + + [Fact] + public void Matches_StarAlone_MatchesEverythingButMidStarIsLiteral() + { + Assert.True(AgentApproval.Matches("*", "send_email")); + Assert.False(AgentApproval.Matches("send*email", "send_email")); + } + + [Fact] + public async Task Compile_ApprovalAutoMatchingTool_RunsWithoutSurfacingRequest() + { + var token = TestContext.Current.CancellationToken; + int sent = 0; + using ToolCallingChatClient client = new( + "done.", + new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" }); + var compiled = Compile(GatedToolYaml, client, () => sent++, token); + + var response = await compiled.Agents["only"].RunAsync("send it", cancellationToken: token); + + Assert.Equal(1, sent); + Assert.DoesNotContain( + response.Messages.SelectMany(message => message.Contents), + content => content is ToolApprovalRequestContent); + Assert.Equal("done.", response.Text); + } + + [Fact] + public async Task Compile_ApprovalAutoNamingAnotherTool_RequestStillSurfaces() + { + var token = TestContext.Current.CancellationToken; + int sent = 0; + using ToolCallingChatClient client = new( + "done.", + new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" }); + var compiled = Compile(UngatedToolYaml, client, () => sent++, token); + + var response = await compiled.Agents["only"].RunAsync("send it", cancellationToken: token); + + Assert.Equal(0, sent); + Assert.Single(response.Messages.SelectMany(message => message.Contents).OfType()); + } + + [Fact] + public void Compile_ApprovalAuto_AddsNoStateKeys() + { + var token = TestContext.Current.CancellationToken; + using ToolCallingChatClient client = new("unused"); + var compiled = Compile(GatedToolYaml, client, () => { }, token); + + Assert.Empty(compiled.HarnessStateKeys); + } + + private static CompiledAgent Compile(string yaml, IChatClient client, Action onSend, CancellationToken token) + { + var document = ConfigurationLoader.LoadYaml(yaml); + return ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new FakeChatClientFactory(client)) + { + Tools = TestToolRegistry.From( + document, + declared => declared.Uses == "test.send" ? GatedSendEmail(onSend) : null, + token), + }); + } + + private static ApprovalRequiredAIFunction GatedSendEmail(Action onSend) => new ApprovalRequiredAIFunction(AIFunctionFactory.Create( + (string to) => + { + onSend(); + return "sent"; + }, + "send_email", + "Send an email.")); +} From 55a692e6bc1e521732347ea5b0931f9349010af3 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 00:03:32 -0600 Subject: [PATCH 14/32] feat: Implement approval handling for tool calls --- .../Compilation/AgentApproval.cs | 25 ++ .../Compilation/ConfigurationCompiler.cs | 1 + .../Ports/IConversationPort.cs | 20 ++ .../PublicAPI.Unshipped.txt | 7 + .../Runtime/AgentCoreAgent.cs | 26 +- .../Runtime/CallSession.cs | 158 ++++++++++- .../Runtime/FallbackAgent.cs | 24 +- .../Runtime/Harness/HarnessSessionState.cs | 4 +- .../Runtime/Harness/PendingApprovalQueue.cs | 117 +++++++++ .../Runtime/TurnMessages.cs | 2 +- .../Call/CallTurnArbiter.cs | 11 + .../Endpoints/ChatCompletionContracts.cs | 36 +++ .../Endpoints/ChatCompletionsEndpoints.cs | 149 +++++++++-- src/AgentCore.Domain/PendingApproval.cs | 12 + src/AgentCore.Domain/PublicAPI.Unshipped.txt | 18 ++ src/AgentCore.Domain/TurnResult.cs | 10 +- .../Compilation/ApprovalCompilationTests.cs | 24 +- .../Runtime/CallSessionApprovalTests.cs | 175 ++++++++++++ .../Call/CallTurnArbiterTests.cs | 34 ++- .../Endpoints/ApprovalWireTests.cs | 248 ++++++++++++++++++ .../Fakes/ChatCompletionsHost.cs | 43 ++- 21 files changed, 1089 insertions(+), 55 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/Harness/PendingApprovalQueue.cs create mode 100644 src/AgentCore.Domain/PendingApproval.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs index 32975128..0d26529f 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs @@ -1,5 +1,7 @@ using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Harness; using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; namespace AgentCore.Application.Configuration.Compilation; @@ -41,6 +43,29 @@ public static bool Matches(string pattern, string toolName) : toolName == pattern; } + /// Reads the state keys an agent's approval surface needs persisted across resume. + /// The agents.defaults section, or . + /// The agent being compiled. + /// The tools the agent offers the model, if any. + /// + /// The pending queue and the standing-rule keys when the agent may surface an approval — + /// through auto:, which adds the approval layer, or through an approval-required tool — + /// else empty. An absent key is never kept, so both ride together. + /// + public static IReadOnlyList StateKeysFor( + AgentDefaults? defaults, AgentConfiguration item, IEnumerable? tools) + { + ArgumentNullException.ThrowIfNull(item); + + if (Compose(defaults, item).Count == 0 + && tools?.OfType().Any() != true) + { + return []; + } + + return [PendingApprovalQueue.PendingStateKey, PendingApprovalQueue.StandingStateKey]; + } + /// /// Bakes one agent's auto: into its pipeline as UseToolApproval rules. No /// patterns, no layer — the document pays nothing for approval it never declares. diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index 2fd26e15..502b13e3 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -271,6 +271,7 @@ private static (Dictionary Agents, IReadOnlySet Harness Resolve, backgroundProviders); harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers)); + harnessStateKeys.UnionWith(AgentApproval.StateKeysFor(section.Defaults, item, compiledTools)); var built = new ChatClientAgent( WithToolFailureAuditing(context.ChatClients.GetChatClient(item.Model ?? section.Defaults?.Model)), diff --git a/src/AgentCore.Application/Ports/IConversationPort.cs b/src/AgentCore.Application/Ports/IConversationPort.cs index 0cc76d21..2cc2afa7 100644 --- a/src/AgentCore.Application/Ports/IConversationPort.cs +++ b/src/AgentCore.Application/Ports/IConversationPort.cs @@ -53,6 +53,15 @@ public interface IConversationPort /// Task RunTurnAsync(string userInput, CancellationToken cancellationToken = default); + /// Runs one turn end to end from a message the caller built, and returns what it did. + /// What the caller said or answered: words, an approval answer, or both. + /// 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. + /// + Task RunTurnMessageAsync(ChatMessage userInput, CancellationToken cancellationToken); + /// Runs one turn and streams the reply as it arrives. /// What the caller said. /// Cancels the model calls. @@ -69,6 +78,17 @@ IAsyncEnumerable RunTurnStreamingAsync( string userInput, CancellationToken cancellationToken = default); + /// Runs one turn from a message the caller built and streams the reply as it arrives. + /// What the caller said or answered: words, an approval answer, or both. + /// 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. + /// + IAsyncEnumerable RunTurnMessageStreamingAsync( + ChatMessage userInput, + CancellationToken cancellationToken); + /// Ends the running turn where the caller cut the reply off. /// The text the caller actually heard. /// How much of the reply played, as the relay reported it. diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index c6feb6b6..b7a425f9 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -1122,6 +1122,8 @@ AgentCore.Application.Ports.IConversationPort.Interrupt(string! utteranceUntilIn AgentCore.Application.Ports.IConversationPort.IsComplete.get -> bool AgentCore.Application.Ports.IConversationPort.LastTurn.get -> AgentCore.Domain.TurnResult? AgentCore.Application.Ports.IConversationPort.RunTurnAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +AgentCore.Application.Ports.IConversationPort.RunTurnMessageAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +AgentCore.Application.Ports.IConversationPort.RunTurnMessageStreamingAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Collections.Generic.IAsyncEnumerable! AgentCore.Application.Ports.IConversationPort.RunTurnStreamingAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! AgentCore.Application.Ports.IConversationPort.Stage.get -> string! AgentCore.Application.Ports.IEmbeddingGeneratorAdapter @@ -1220,6 +1222,10 @@ 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.SetDelegatedTools(string! delegatingToolId, System.Collections.Generic.IReadOnlyList! tools) -> void @@ -1227,6 +1233,7 @@ 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.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 diff --git a/src/AgentCore.Application/Runtime/AgentCoreAgent.cs b/src/AgentCore.Application/Runtime/AgentCoreAgent.cs index c4d88ba3..766307fd 100644 --- a/src/AgentCore.Application/Runtime/AgentCoreAgent.cs +++ b/src/AgentCore.Application/Runtime/AgentCoreAgent.cs @@ -202,7 +202,7 @@ protected override async Task RunCoreAsync( ArgumentNullException.ThrowIfNull(messages); var call = Resolve(session); - var turn = await call.RunTurnAsync(UserText(messages), cancellationToken).ConfigureAwait(false); + var turn = await call.RunTurnMessageAsync(UserMessage(messages), cancellationToken).ConfigureAwait(false); return new AgentResponse(new ChatMessage(ChatRole.Assistant, turn.ReplyText)) { @@ -225,7 +225,7 @@ protected override async IAsyncEnumerable RunCoreStreamingA // The stream is already filtered: CallSession drops the lifecycle updates, so every update // here carries content. The wrap changes the type and nothing else. - await foreach (var update in call.RunTurnStreamingAsync(UserText(messages), cancellationToken) + await foreach (var update in call.RunTurnMessageStreamingAsync(UserMessage(messages), cancellationToken) .ConfigureAwait(false)) { yield return new AgentResponseUpdate(update) { AgentId = Id }; @@ -253,29 +253,31 @@ protected override async IAsyncEnumerable RunCoreStreamingA nameof(session)), }; - /// Reads what the caller said out of the run's messages. + /// Reads what the caller said or answered out of the run's messages. /// The messages the caller passed to the run. - /// The text of the last user message. + /// The last user message that carries words or an approval answer. /// /// The same rule the /v1/chat/completions endpoint applies: the session owns the /// transcript, so an earlier message of the request is already in the call, and only the last /// user message is new. See the remarks on . /// - /// No user message carries text, so there is no turn to run. - private static string UserText(IEnumerable messages) + /// No user message carries words or an answer, so there is no turn to run. + private static ChatMessage UserMessage(IEnumerable messages) { - string? text = null; + ChatMessage? picked = null; foreach (var message in messages) { - if (message.Role == ChatRole.User && message.Text is { Length: > 0 } spoken) + if (message.Role == ChatRole.User + && (message.Text is { Length: > 0 } + || message.Contents.OfType().Any())) { - text = spoken; + picked = message; } } - return text ?? throw new ArgumentException( - "The run carries no user message with text, so there is no turn to run. The session owns " - + "the transcript: pass what the caller just said, not a history.", + return picked ?? throw new ArgumentException( + "The run carries no user message with words or an approval answer, so there is no turn " + + "to run. The session owns the transcript: pass what the caller just said, not a history.", nameof(messages)); } diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index d4756247..fac9753f 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; +using System.Text.Json; using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Schema; @@ -261,6 +262,14 @@ public void SetDelegatedTools(string delegatingToolId, IReadOnlyList too public Task RunTurnAsync(string userInput, CancellationToken cancellationToken = default) => RunTurnAtOriginAsync(userInput, origin: null, cancellationToken); + /// + /// Runs one turn end to end from a message the caller built, and returns what it did. + /// + /// What the caller said or answered: words, an approval answer, or both. + /// Cancels the turn. + public Task RunTurnMessageAsync(ChatMessage userInput, CancellationToken cancellationToken) + => RunTurnMessageAtOriginAsync(userInput, origin: null, cancellationToken); + /// /// Runs one turn that knows where it sits in the conversation the caller can see. /// @@ -276,6 +285,36 @@ public async Task RunTurnAtOriginAsync( { ArgumentNullException.ThrowIfNull(userInput); + return await RunTurnCoreAsync(new ChatMessage(ChatRole.User, userInput), origin, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Runs one turn from a message the caller built, that knows where it sits in the conversation + /// the caller can see. + /// + /// What the caller said or answered: words, an approval answer, or both. + /// + /// Where these words hang, or for a caller that does not track its + /// messages by name. See , which this mirrors. + /// + /// Cancels the turn. + public async Task RunTurnMessageAtOriginAsync( + ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(userInput); + + return await RunTurnCoreAsync(userInput, origin, cancellationToken).ConfigureAwait(false); + } + + /// 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. + /// Cancels the turn. + /// What the turn did. + private async Task RunTurnCoreAsync( + ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) + { var session = await OpenSessionAsync(cancellationToken).ConfigureAwait(false); var turn = BeginTurn(userInput, session, origin); @@ -334,6 +373,36 @@ public IAsyncEnumerable RunTurnStreamingAsync( string userInput, CancellationToken cancellationToken = default) => RunTurnStreamingAtOriginAsync(userInput, origin: null, cancellationToken); + /// Runs one turn from a message the caller built and streams the reply as it arrives. + /// What the caller said or answered: words, an approval answer, or both. + /// Cancels the model calls. + /// 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 + /// 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. + /// 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 + /// answer re-enters through on this same call — an answer + /// another call built is dropped in silence, so callers must match them. + /// + public ChatMessage? TryCreateApprovalAnswer(string requestId, bool approved) + { + ArgumentException.ThrowIfNullOrEmpty(requestId); + + return Session() is { } session + ? PendingApprovalQueue.AnswerFor(session.StateBag.Serialize(), requestId, approved) + : null; + } + /// /// Runs one streaming turn that knows where it sits in the conversation the caller can see. /// @@ -351,6 +420,49 @@ public async IAsyncEnumerable RunTurnStreamingAtOriginAsync( { ArgumentNullException.ThrowIfNull(userInput); + await foreach (var update in RunTurnStreamingCoreAsync( + new ChatMessage(ChatRole.User, userInput), origin, cancellationToken).ConfigureAwait(false)) + { + yield return update; + } + } + + /// + /// Runs one streaming turn from a message the caller built, that knows where it sits in the + /// conversation the caller can see. + /// + /// What the caller said or answered: words, an approval answer, or both. + /// + /// Where these words hang, or for a caller that does not track its + /// messages by name. See , which this mirrors. + /// + /// Cancels the model calls. + /// The reply, one update at a time. Every update carries content. + public async IAsyncEnumerable RunTurnMessageStreamingAtOriginAsync( + ChatMessage userInput, + CallTurnOrigin? origin, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(userInput); + + await foreach (var update in RunTurnStreamingCoreAsync(userInput, origin, cancellationToken).ConfigureAwait(false)) + { + yield return update; + } + } + + /// Streams 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. + /// Cancels the model calls. + /// The reply, one update at a time. + private async IAsyncEnumerable RunTurnStreamingCoreAsync( + ChatMessage userInput, + CallTurnOrigin? origin, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(userInput); + var session = await OpenSessionAsync(cancellationToken).ConfigureAwait(false); var turn = BeginTurn(userInput, session, origin); @@ -872,11 +984,11 @@ public async Task FlushTranscriptAsync() /// Picks the agent, withdraws whatever this turn replaces, builds the model input, and takes the /// turn. /// - /// What the caller said. + /// What the caller said or answered: words, an approval answer, or both. /// The session of this call. /// Where the turn hangs, or null for a caller that does not say. /// Everything the rest of the turn needs. - private Turn BeginTurn(string userInput, AgentSession session, CallTurnOrigin? origin = null) + private Turn BeginTurn(ChatMessage userInput, AgentSession session, CallTurnOrigin? origin = null) { if (IsComplete) { @@ -915,7 +1027,7 @@ private Turn BeginTurn(string userInput, AgentSession session, CallTurnOrigin? o // the framework appends for that invocation and stores nowhere. It reads the state document // and never the transcript. Only a document with a policy: has a stage that waits on a slot. var reminder = _policy is null ? null : UnfilledSlotReminder.Build(State, _policy.CurrentStage); - ChatMessage spoken = new(ChatRole.User, userInput); + ChatMessage spoken = userInput; // The framework has never heard of a turn, so the turn loop names this one before the run. _history.BeginTurn(session, State.TurnIndex); @@ -1140,6 +1252,10 @@ private async Task CompleteTurnAsync( var spokenReply = reply; TimeSpan? interruptedAfter = null; string? failure = toolFault is null ? null : 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. + var approvals = ApprovalRequestsOf(response); if (interruption is { } cut) { @@ -1149,9 +1265,9 @@ private async Task CompleteTurnAsync( reply = cut.HeardText.Trim(); interruptedAfter = cut.PlayedDuration; } - else if (failure is not null + else if (approvals.Count == 0 && (failure is not null || string.IsNullOrWhiteSpace(reply) - || disposition?.Fallback is FallbackCause.EmptyReply) + || 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 // failure even though nothing threw. @@ -1218,7 +1334,7 @@ private async Task CompleteTurnAsync( // 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) + if (!refused && approvals.Count == 0) { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TurnCompletionTimeout); @@ -1274,7 +1390,10 @@ private async Task CompleteTurnAsync( extractionFailure, failure, interruptedAfter, - endedAt); + endedAt) + { + Approvals = approvals, + }; // 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 @@ -1392,6 +1511,31 @@ private async Task CompleteTurnAsync( _ => AgentCoreTelemetry.OutcomeCompleted, }; + /// Reads the approval requests one finished turn still waits on. + /// What the agent answered. + /// One entry per request content, oldest first; empty when the turn asked nothing. + private static List ApprovalRequestsOf(AgentResponse response) + { + List approvals = []; + foreach (var request in response.Messages + .SelectMany(message => message.Contents) + .OfType()) + { + if (request.ToolCall is not FunctionCallContent call) + { + continue; + } + + approvals.Add(new PendingApproval( + request.RequestId, + call.Name, + JsonSerializer.SerializeToElement( + call.Arguments ?? new Dictionary(StringComparer.Ordinal)))); + } + + return approvals; + } + /// Reads what the turn layers reported about one finished turn. /// What the agent answered. /// The disposition, or when no layer marked the turn. diff --git a/src/AgentCore.Application/Runtime/FallbackAgent.cs b/src/AgentCore.Application/Runtime/FallbackAgent.cs index abd4280d..464e9748 100644 --- a/src/AgentCore.Application/Runtime/FallbackAgent.cs +++ b/src/AgentCore.Application/Runtime/FallbackAgent.cs @@ -85,7 +85,7 @@ protected override async Task RunCoreAsync( return spoken; } - if (!string.IsNullOrWhiteSpace(SpokenText(response))) + if (!string.IsNullOrWhiteSpace(SpokenText(response)) || HasApprovalRequest(response.Messages)) { return response; } @@ -139,7 +139,7 @@ protected override async IAsyncEnumerable RunCoreStreamingA break; } - spokeText = spokeText || (Speaks(current.AuthorName) && !string.IsNullOrWhiteSpace(current.Text)); + spokeText = spokeText || HasApprovalRequest(current) || (Speaks(current.AuthorName) && !string.IsNullOrWhiteSpace(current.Text)); yield return current; } } @@ -162,6 +162,26 @@ protected override async IAsyncEnumerable RunCoreStreamingA } } + /// Reads whether the run asks the caller to approve a tool call. + /// What the inner agent answered. + /// Whether any message carries an approval request. + /// + /// A request-only reply carries no text, so without this the run reads as silence and takes + /// the fallback. An approval the caller never hears is a tool that never runs, so a request + /// counts as spoken whoever authored it. + /// + private static bool HasApprovalRequest(IEnumerable messages) + => messages.Any(message => HasApprovalRequest(message.Contents)); + + /// Reads whether one update asks the caller to approve a tool call. + /// One update of the run. + /// Whether the update carries an approval request. + private static bool HasApprovalRequest(AgentResponseUpdate update) + => HasApprovalRequest(update.Contents); + + private static bool HasApprovalRequest(IEnumerable contents) + => contents.OfType().Any(); + /// Reads the words this run would put in the caller's ear. /// What the inner agent answered. /// The spoken text, or an empty string when nothing the caller hears was produced. diff --git a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs index 88ee5a6b..17175693 100644 --- a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs +++ b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs @@ -7,8 +7,8 @@ namespace AgentCore.Application.Runtime.Harness; /// /// Moves the harness providers' MAF state — todos:, mode:, memory:, -/// files:, background: — between a live 's state bag and -/// . +/// files:, background: — and the approval queue and standing rules between a live +/// '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 new file mode 100644 index 00000000..924a8e31 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/PendingApprovalQueue.cs @@ -0,0 +1,117 @@ +using System.Text.Json; +using AgentCore.Domain; +using Microsoft.Extensions.AI; + +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 +/// — 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 +/// however the queue looks. +/// +internal static class PendingApprovalQueue +{ + /// What the function-invocation layer names its queue in the state bag. + internal const string PendingStateKey = "_pendingApprovalRequests"; + + /// What the approval layer names its standing and auto rules in the state bag. + internal const string StandingStateKey = "toolApprovalState"; + + /// Reads the queue out of a serialized state bag. + /// What AgentSessionStateBag.Serialize produced. + /// The pending approvals, oldest first; empty when the bag carries no queue. + internal static IReadOnlyList Read(JsonElement bag) + { + if (!bag.TryGetProperty(PendingStateKey, out var queue) + || queue.ValueKind != JsonValueKind.Array) + { + return []; + } + + List pending = []; + foreach (var entry in queue.EnumerateArray()) + { + 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) + || name.ValueKind != JsonValueKind.String) + { + continue; + } + + using var empty = JsonDocument.Parse("{}"); + var arguments = call.TryGetProperty("arguments", out var args) && args.ValueKind == JsonValueKind.Object + ? args.Clone() + : empty.RootElement.Clone(); + + pending.Add(new PendingApproval( + id.GetString()!, + name.GetString()!, + arguments)); + } + + return pending; + } + + /// Builds the answer message for one pending request. + /// What AgentSessionStateBag.Serialize produced. + /// The id the caller answers. + /// Whether the tool may run. + /// The user message carrying the approval response, or when no queued request carries that id. + internal static ChatMessage? AnswerFor(JsonElement bag, string requestId, bool approved) + { + if (!bag.TryGetProperty(PendingStateKey, out var queue) + || queue.ValueKind != JsonValueKind.Array) + { + return null; + } + + foreach (var entry in queue.EnumerateArray()) + { + 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) + || name.ValueKind != JsonValueKind.String + || !call.TryGetProperty("callId", out var callId) + || callId.ValueKind != JsonValueKind.String) + { + continue; + } + + Dictionary arguments = new(StringComparer.Ordinal); + if (call.TryGetProperty("arguments", out var args) && args.ValueKind == JsonValueKind.Object) + { + foreach (var argument in args.EnumerateObject()) + { + arguments[argument.Name] = ValueOf(argument.Value); + } + } + + var toolCall = new FunctionCallContent(callId.GetString()!, name.GetString()!, arguments); + return new ChatMessage(ChatRole.User, [new ToolApprovalResponseContent(requestId, approved, toolCall)]); + } + + return null; + } + + private static object? ValueOf(JsonElement element) => element.ValueKind switch + { + JsonValueKind.Object => element.EnumerateObject() + .ToDictionary(property => property.Name, property => ValueOf(property.Value), StringComparer.Ordinal), + JsonValueKind.Array => element.EnumerateArray().Select(ValueOf).ToList(), + JsonValueKind.String => element.GetString(), + JsonValueKind.Number => element.TryGetInt64(out var integer) ? integer : element.GetDouble(), + JsonValueKind.True => true, + JsonValueKind.False => false, + _ => null, + }; +} diff --git a/src/AgentCore.Application/Runtime/TurnMessages.cs b/src/AgentCore.Application/Runtime/TurnMessages.cs index d9183c9a..853e47f1 100644 --- a/src/AgentCore.Application/Runtime/TurnMessages.cs +++ b/src/AgentCore.Application/Runtime/TurnMessages.cs @@ -86,7 +86,7 @@ internal static List FinishedToolMessages(IList messag }), ]; - if (!tools.Any(content => content is FunctionCallContent or FunctionResultContent)) + if (!tools.Any(content => content is FunctionCallContent or FunctionResultContent or ToolApprovalRequestContent)) { // Plain prose, or a message whose every call is still in flight. Neither belongs in // the next turn. diff --git a/src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs b/src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs index 6bd28ebb..e07d3ea5 100644 --- a/src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs +++ b/src/AgentCore.AspNetCore/Call/CallTurnArbiter.cs @@ -64,6 +64,10 @@ 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. + internal const string PendingApprovalNotice = + "That action needs a human approval, which this call can't take."; + /// Builds the arbiter one call runs its turns through. /// The call this arbiter runs turns against, until names another. /// Where a turn's reply goes, one fragment at a time. @@ -363,6 +367,13 @@ private async Task RunTurnAsync(IConversationPort session, string text, long tur if (Interlocked.Read(ref _interruptedTurnId) != turnId) { + if (session.LastTurn?.Approvals is { Count: > 0 }) + { + // A tool waits on a human answer, and a voice call 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); + } + // The vendor closes a reply on last: true, and the sample uses an empty final // token when the stream ended with no trailing text. A barge-in already ended // this turn, so a closing frame now would speak a reply the caller cut off. diff --git a/src/AgentCore.AspNetCore/Endpoints/ChatCompletionContracts.cs b/src/AgentCore.AspNetCore/Endpoints/ChatCompletionContracts.cs index 6c3dd4e5..480509c1 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ChatCompletionContracts.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ChatCompletionContracts.cs @@ -63,6 +63,10 @@ public string? ParentId } } + /// Gets the approval answer this request carries, or when its message holds words. + [JsonPropertyName("approval")] + public AgentCoreApprovalAnswer? Approval { get; init; } + /// Gets whether the body carried parent_id at all. [JsonIgnore] public bool NamesParent { get; private init; } @@ -70,6 +74,17 @@ public string? ParentId private readonly string? _parentId; } +/// One approval answer: which request the caller answers, and whether the tool may run. +internal sealed record AgentCoreApprovalAnswer +{ + /// Gets the id of the pending request this answers. + [JsonPropertyName("request_id")] + public required string RequestId { get; init; } + + /// Gets whether the tool may run. + public required bool Approved { get; init; } +} + /// What one finished turn did, carried beside the OpenAI shape. internal sealed record AgentCoreTurnInfo { @@ -94,6 +109,9 @@ internal sealed record AgentCoreTurnInfo /// Gets what the host calls the reply it just wrote, for a later edit to hang off. [JsonPropertyName("message_id")] public string? MessageId { get; init; } + + /// Gets the tool calls still waiting on a human answer when the turn ended, or when the turn asked nothing. + public IReadOnlyList? Approvals { get; init; } } /// One choice of a reply. It carries message when whole and delta when streamed. @@ -146,6 +164,10 @@ internal sealed record ChatCompletionResponse /// Gets the source this chunk carries, or when none. [JsonPropertyName("agentcore_source")] public SourcePayload? AgentCoreSource { get; init; } + + /// Gets the approval request this chunk carries, or when none. + [JsonPropertyName("agentcore_approval")] + public ApprovalPayload? AgentCoreApproval { get; init; } } /// One half of one tool call, as the browser reads it. @@ -170,6 +192,20 @@ internal sealed record ToolPayload public bool? Failed { get; init; } } +/// One tool call waiting on the caller, as the browser reads it. +internal sealed record ApprovalPayload +{ + /// Gets the id the approval answer carries back. + [JsonPropertyName("request_id")] + public required string RequestId { get; init; } + + /// Gets the name of the tool the model asked to call. + public required string Tool { get; init; } + + /// Gets what the model passed, or when it passed nothing. + public JsonNode? Arguments { get; init; } +} + /// Where one answer came from, as the browser reads it. internal sealed record SourcePayload { diff --git a/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs index bfacbd12..581b2a3c 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs @@ -80,25 +80,54 @@ await WriteErrorAsync( return; } - if (LastUserText(request) is not { Length: > 0 } input) - { - await WriteErrorAsync( - http, - StatusCodes.Status400BadRequest, - "the request carries no user message with text, so there is no turn to run.", - "invalid_request_error", - "no_user_message", - cancellationToken).ConfigureAwait(false); - return; - } - var sessions = http.RequestServices.GetRequiredService(); var named = http.Request.Headers[SessionHeaderName].ToString(); + // One turn carries either words or an approval answer, never both: the answer resumes + // the exact call the request suspended, and words would start something new instead. + ChatMessage input; CallSession session; - if (named is { Length: > 0 }) + if (request?.AgentCore?.Approval is { } approval) { - if (await sessions.TryGetAsync(named, cancellationToken).ConfigureAwait(false) is not { } found) + if (LastUserText(request) is { Length: > 0 }) + { + await 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.", + "invalid_request_error", + "mixed_turn", + cancellationToken).ConfigureAwait(false); + return; + } + + if (string.IsNullOrEmpty(approval.RequestId)) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the approval answer names no request.", + "invalid_request_error", + "missing_request_id", + cancellationToken).ConfigureAwait(false); + return; + } + + if (named is not { Length: > 0 }) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "an approval answer names the call it resumes. Send it with the " + + SessionHeaderName + " header the request arrived with.", + "invalid_request_error", + "missing_session", + cancellationToken).ConfigureAwait(false); + return; + } + + if (await sessions.TryGetAsync(named, cancellationToken).ConfigureAwait(false) is not { } open) { await WriteErrorAsync( http, @@ -111,11 +140,59 @@ await WriteErrorAsync( return; } - session = found; + session = open; + if (session.TryCreateApprovalAnswer(approval.RequestId, approval.Approved) is not { } answer) + { + await WriteErrorAsync( + http, + StatusCodes.Status409Conflict, + $"the call '{named}' queues no approval under id '{approval.RequestId}'. It was " + + "answered already, belongs to another call, or was never asked.", + "invalid_request_error", + "no_pending_approval", + cancellationToken).ConfigureAwait(false); + return; + } + + input = answer; } else { - session = await sessions.OpenAsync(null, cancellationToken).ConfigureAwait(false); + if (LastUserText(request) is not { Length: > 0 } text) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the request carries no user message with text, so there is no turn to run.", + "invalid_request_error", + "no_user_message", + cancellationToken).ConfigureAwait(false); + return; + } + + if (named is { Length: > 0 }) + { + if (await sessions.TryGetAsync(named, cancellationToken).ConfigureAwait(false) is not { } found) + { + await WriteErrorAsync( + http, + StatusCodes.Status404NotFound, + $"no call named '{named}' is open on this host. Send the request with no " + + SessionHeaderName + " header to start one.", + "invalid_request_error", + "session_not_found", + cancellationToken).ConfigureAwait(false); + return; + } + + session = found; + } + else + { + session = await sessions.OpenAsync(null, cancellationToken).ConfigureAwait(false); + } + + input = new ChatMessage(ChatRole.User, text); } var streaming = request?.Stream == true; @@ -171,12 +248,12 @@ await WriteErrorAsync( private static async Task WriteTurnAsync( HttpContext http, CallSession session, - string input, + ChatMessage input, string model, CallTurnOrigin? origin, CancellationToken cancellationToken) { - var turn = await session.RunTurnAtOriginAsync(input, origin, cancellationToken).ConfigureAwait(false); + var turn = await session.RunTurnMessageAtOriginAsync(input, origin, cancellationToken).ConfigureAwait(false); http.Response.StatusCode = StatusCodes.Status200OK; http.Response.Headers[SessionHeaderName] = session.CallId; @@ -214,7 +291,7 @@ private static async Task WriteTurnAsync( private static async Task StreamTurnAsync( HttpContext http, CallSession session, - string input, + ChatMessage input, string model, CallTurnOrigin? origin, CancellationToken cancellationToken) @@ -239,7 +316,7 @@ await WriteEventAsync( // One turn's worth of ids: the pairing dies with the stream. ToolCallNames toolNames = new(); - await foreach (var update in session.RunTurnStreamingAtOriginAsync(input, origin, cancellationToken).ConfigureAwait(false)) + await foreach (var update in session.RunTurnMessageStreamingAtOriginAsync(input, origin, cancellationToken).ConfigureAwait(false)) { foreach (var drawn in update.Contents.OfType()) { @@ -271,6 +348,30 @@ await WriteEventAsync( cancellationToken).ConfigureAwait(false); } + foreach (var asked in update.Contents.OfType()) + { + // A request arrives with no text, so without this the update falls into the + // empty-text skip below and the caller never learns a tool waits on them. + if (asked.ToolCall is not FunctionCallContent call) + { + continue; + } + + await WriteEventAsync( + http, + Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) + with + { + AgentCoreApproval = new ApprovalPayload + { + RequestId = asked.RequestId, + Tool = call.Name, + Arguments = ArgumentsOf(call), + }, + }, + cancellationToken).ConfigureAwait(false); + } + if (update.Text is not { Length: > 0 } text) { // A tool call and a tool result arrive as updates too, and neither is speech. @@ -473,6 +574,14 @@ private static AgentCoreTurnInfo Describe(CallSession session, TurnResult turn) IsTerminal = turn.IsTerminal, ExtractionFailure = turn.ExtractionFailure, MessageId = session.LastReplyMessageId, + Approvals = turn.Approvals.Count == 0 + ? null + : [.. turn.Approvals.Select(static approval => new ApprovalPayload + { + RequestId = approval.RequestId, + Tool = approval.ToolName, + Arguments = JsonNode.Parse(approval.Arguments.GetRawText()), + })], }; /// Builds the id of one reply. diff --git a/src/AgentCore.Domain/PendingApproval.cs b/src/AgentCore.Domain/PendingApproval.cs new file mode 100644 index 00000000..8d6609bf --- /dev/null +++ b/src/AgentCore.Domain/PendingApproval.cs @@ -0,0 +1,12 @@ +using System.Text.Json; + +namespace AgentCore.Domain; + +/// +/// One tool call waiting on a human answer: what the model wanted to run, and the id the +/// answer names. +/// +/// The id the approval answer carries back. +/// The tool the model asked to call. +/// The arguments the model produced, as it produced them. +public sealed record PendingApproval(string RequestId, string ToolName, JsonElement Arguments); diff --git a/src/AgentCore.Domain/PublicAPI.Unshipped.txt b/src/AgentCore.Domain/PublicAPI.Unshipped.txt index 8bf613ae..aca4a783 100644 --- a/src/AgentCore.Domain/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Domain/PublicAPI.Unshipped.txt @@ -97,8 +97,21 @@ AgentCore.Domain.Sources.SourceReference.Title.get -> string! AgentCore.Domain.Sources.SourceReference.Title.init -> void AgentCore.Domain.Sources.SourceReference.Url.get -> string? AgentCore.Domain.Sources.SourceReference.Url.init -> void +AgentCore.Domain.PendingApproval +AgentCore.Domain.PendingApproval.$() -> AgentCore.Domain.PendingApproval! +AgentCore.Domain.PendingApproval.Arguments.get -> System.Text.Json.JsonElement +AgentCore.Domain.PendingApproval.Arguments.init -> void +AgentCore.Domain.PendingApproval.Deconstruct(out string! RequestId, out string! ToolName, out System.Text.Json.JsonElement Arguments) -> void +AgentCore.Domain.PendingApproval.Equals(AgentCore.Domain.PendingApproval? other) -> bool +AgentCore.Domain.PendingApproval.PendingApproval(string! RequestId, string! ToolName, System.Text.Json.JsonElement Arguments) -> void +AgentCore.Domain.PendingApproval.RequestId.get -> string! +AgentCore.Domain.PendingApproval.RequestId.init -> void +AgentCore.Domain.PendingApproval.ToolName.get -> string! +AgentCore.Domain.PendingApproval.ToolName.init -> void 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 @@ -151,6 +164,9 @@ override AgentCore.Domain.Knowledge.KnowledgeScope.ToString() -> string! override AgentCore.Domain.Sources.SourceReference.Equals(object? obj) -> bool override AgentCore.Domain.Sources.SourceReference.GetHashCode() -> int override AgentCore.Domain.Sources.SourceReference.ToString() -> string! +override AgentCore.Domain.PendingApproval.Equals(object? obj) -> bool +override AgentCore.Domain.PendingApproval.GetHashCode() -> int +override AgentCore.Domain.PendingApproval.ToString() -> string! override AgentCore.Domain.TurnResult.Equals(object? obj) -> bool override AgentCore.Domain.TurnResult.GetHashCode() -> int override AgentCore.Domain.TurnResult.ToString() -> string! @@ -176,5 +192,7 @@ static AgentCore.Domain.Knowledge.KnowledgeScope.operator ==(AgentCore.Domain.Kn static AgentCore.Domain.Knowledge.PayloadPath.Read(System.Collections.Generic.IReadOnlyDictionary! payload, string? path) -> object? static AgentCore.Domain.Sources.SourceReference.operator !=(AgentCore.Domain.Sources.SourceReference? left, AgentCore.Domain.Sources.SourceReference? right) -> bool static AgentCore.Domain.Sources.SourceReference.operator ==(AgentCore.Domain.Sources.SourceReference? left, AgentCore.Domain.Sources.SourceReference? right) -> bool +static AgentCore.Domain.PendingApproval.operator !=(AgentCore.Domain.PendingApproval? left, AgentCore.Domain.PendingApproval? right) -> bool +static AgentCore.Domain.PendingApproval.operator ==(AgentCore.Domain.PendingApproval? left, AgentCore.Domain.PendingApproval? right) -> bool static AgentCore.Domain.TurnResult.operator !=(AgentCore.Domain.TurnResult? left, AgentCore.Domain.TurnResult? right) -> bool static AgentCore.Domain.TurnResult.operator ==(AgentCore.Domain.TurnResult? left, AgentCore.Domain.TurnResult? right) -> bool diff --git a/src/AgentCore.Domain/TurnResult.cs b/src/AgentCore.Domain/TurnResult.cs index bc752bd2..6d1a0c6c 100644 --- a/src/AgentCore.Domain/TurnResult.cs +++ b/src/AgentCore.Domain/TurnResult.cs @@ -69,4 +69,12 @@ public sealed record TurnResult( string? ExtractionFailure, string? Failure = null, TimeSpan? InterruptedAfter = null, - DateTimeOffset EndedAt = default); + DateTimeOffset EndedAt = default) +{ + /// + /// Gets the tool calls still waiting on a human answer when the turn ended, oldest first. + /// Empty on every other turn. A pending turn is not a failure: stays + /// and stays empty while these are set. + /// + public IReadOnlyList Approvals { get; init; } = []; +} diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs index 111f4816..09aa67f6 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ApprovalCompilationTests.cs @@ -144,12 +144,34 @@ public async Task Compile_ApprovalAutoNamingAnotherTool_RequestStillSurfaces() } [Fact] - public void Compile_ApprovalAuto_AddsNoStateKeys() + public void Compile_ApprovalSurface_KeepsTheQueueAndStandingKeys() { var token = TestContext.Current.CancellationToken; using ToolCallingChatClient client = new("unused"); var compiled = Compile(GatedToolYaml, client, () => { }, token); + Assert.Equal( + ["_pendingApprovalRequests", "toolApprovalState"], + compiled.HarnessStateKeys.OrderBy(key => key)); + } + + [Fact] + public void Compile_PlainAgent_KeepsNoApprovalKeys() + { + const string plainYaml = + """ + apiVersion: agentcore/v1 + name: plain + agents: + items: + - { id: only, instructions: "answer" } + """; + var token = TestContext.Current.CancellationToken; + using ToolCallingChatClient client = new("unused"); + var document = ConfigurationLoader.LoadYaml(plainYaml); + var compiled = ConfigurationCompiler.Compile( + document, new AgentCompilationContext(new FakeChatClientFactory(client))); + Assert.Empty(compiled.HarnessStateKeys); } diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs new file mode 100644 index 00000000..faad9074 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionApprovalTests.cs @@ -0,0 +1,175 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; +using AgentCore.Application.State; +using AgentCore.Application.Tests.Fakes; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Xunit; + +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. +/// +/// +/// Every test here runs offline. There is no network call and no API key anywhere in this file. +/// +public sealed class CallSessionApprovalTests +{ + private const string GatedYaml = + """ + apiVersion: agentcore/v1 + name: approval-roundtrip + tools: + - { id: send_email, kind: builtin, uses: test.send, description: "Send an email." } + agents: + items: + - id: only + instructions: "send the mail" + tools: [ send_email ] + """; + + [Fact] + public async Task AGatedToolCall_EndsTheTurnWithTheRequestAndNoFailure() + { + var token = TestContext.Current.CancellationToken; + int sent = 0; + var session = Session(GatedYaml, () => sent++, token); + + var turn = await session.RunTurnAsync("send it", token); + + Assert.Null(turn.Failure); + Assert.Equal(string.Empty, turn.ReplyText); + Assert.Equal(0, sent); + var approval = Assert.Single(turn.Approvals); + Assert.False(string.IsNullOrEmpty(approval.RequestId)); + Assert.Equal("send_email", approval.ToolName); + Assert.Equal("a@b.com", approval.Arguments.GetProperty("to").GetString()); + } + + [Fact] + public async Task AnApprovalAnswer_RunsTheToolAndReplies() + { + var token = TestContext.Current.CancellationToken; + int sent = 0; + var session = Session(GatedYaml, () => sent++, token); + + var asked = await session.RunTurnAsync("send it", token); + var answer = session.TryCreateApprovalAnswer(asked.Approvals[0].RequestId, approved: true); + Assert.NotNull(answer); + var replied = await session.RunTurnMessageAsync(answer!, token); + + Assert.Equal(1, sent); + Assert.Null(replied.Failure); + Assert.Equal("done.", replied.ReplyText); + Assert.Empty(replied.Approvals); + } + + [Fact] + public async Task ARejection_LeavesTheToolUnrun() + { + var token = TestContext.Current.CancellationToken; + int sent = 0; + var session = Session(GatedYaml, () => sent++, token); + + var asked = await session.RunTurnAsync("send it", token); + var answer = session.TryCreateApprovalAnswer(asked.Approvals[0].RequestId, approved: false); + Assert.NotNull(answer); + var replied = await session.RunTurnMessageAsync(answer!, token); + + Assert.Equal(0, sent); + Assert.Null(replied.Failure); + } + + [Fact] + public async Task AnUnknownRequestId_BuildsNoAnswer() + { + var token = TestContext.Current.CancellationToken; + var session = Session(GatedYaml, () => { }, token); + + _ = await session.RunTurnAsync("send it", token); + + Assert.Null(session.TryCreateApprovalAnswer("no-such-request", approved: true)); + } + + [Fact] + public async Task AnAnsweredRequest_BuildsNoSecondAnswer() + { + var token = TestContext.Current.CancellationToken; + var session = Session(GatedYaml, () => { }, token); + + var asked = await session.RunTurnAsync("send it", token); + var requestId = asked.Approvals[0].RequestId; + var answer = session.TryCreateApprovalAnswer(requestId, approved: true); + + Assert.NotNull(answer); + _ = await session.RunTurnMessageAsync(answer, token); + + Assert.Null(session.TryCreateApprovalAnswer(requestId, approved: true)); + } + + [Fact] + public async Task AGatedToolCall_StreamsTheRequestToTheHost() + { + var token = TestContext.Current.CancellationToken; + var session = Session(GatedYaml, () => { }, token); + + List updates = []; + await foreach (var update in session.RunTurnStreamingAsync("send it", token)) + { + updates.Add(update); + } + + Assert.Contains( + updates.SelectMany(update => update.Contents), + content => content is ToolApprovalRequestContent); + Assert.Null(session.LastTurn?.Failure); + Assert.NotEmpty(session.LastTurn?.Approvals ?? []); + } + + [Fact] + public async Task AGatedToolCall_KeepsTheQueueInTheSnapshot() + { + var token = TestContext.Current.CancellationToken; + var session = Session(GatedYaml, () => { }, token); + + _ = await session.RunTurnAsync("send it", token); + + Assert.True(session.Snapshot().Providers.ContainsKey("_pendingApprovalRequests")); + } + + private static CallSession Session(string yaml, Action onSend, CancellationToken token) + { + ToolCallingChatClient client = new( + "done.", + new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" }); + var document = ConfigurationLoader.LoadYaml(yaml); + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(new FakeChatClientFactory(client)) + { + Tools = TestToolRegistry.From( + document, + declared => declared.Uses == "test.send" ? GatedSendEmail(onSend) : null, + token), + }); + + return new CallSessionFactory( + compiled, + new TestGuardEvaluator(document), + extractor: null, + timeProvider: null).Create(); + } + + private static ApprovalRequiredAIFunction GatedSendEmail(Action onSend) => new(AIFunctionFactory.Create( + (string to) => + { + onSend(); + return "sent"; + }, + "send_email", + "Send an email.")); +} diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs b/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs index 8e7c8eed..56ba0935 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; +using System.Text.Json; using AgentCore.Application.Ports; using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.Tests.Fakes; @@ -31,6 +32,28 @@ public async Task ASecondUtteranceDuringATurn_IsHeldAndRunsWhenTheTurnEnds() Assert.Equal(["one", "two"], session.TurnsRun); } + [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 + // nothing. The arbiter says so instead of closing the reply in silence. + var session = new ScriptedConversationPort(); + var output = new FakeCallOutput(); + 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) + { + Approvals = [new PendingApproval("req-1", "send_email", empty.RootElement.Clone())], + }; + + await arbiter.StartTurnAsync("one"); + await arbiter.CurrentTurn; + + Assert.Contains(CallTurnArbiter.PendingApprovalNotice, output.Spoken); + } + [Fact(Timeout = 30_000)] public async Task AThirdUtteranceDuringATurn_IsDroppedRatherThanQueued() { @@ -179,7 +202,7 @@ internal sealed class ScriptedConversationPort : IConversationPort public bool IsComplete => false; /// - public TurnResult? LastTurn => null; + public TurnResult? LastTurn { get; set; } /// Gets what the caller was told it heard, or null before a barge-in. public string? LastHeardText { get; private set; } @@ -227,6 +250,9 @@ public void ReleaseTurn(int ordinal) /// public Task RunTurnAsync(string userInput, CancellationToken cancellationToken = default) => throw new NotSupportedException("the arbiter only ever streams a turn."); + /// + public Task RunTurnMessageAsync(ChatMessage userInput, CancellationToken cancellationToken) + => throw new NotSupportedException("the arbiter only ever streams a turn."); /// public async IAsyncEnumerable RunTurnStreamingAsync( @@ -246,6 +272,12 @@ public async IAsyncEnumerable RunTurnStreamingAsync( yield return new ChatResponseUpdate(ChatRole.Assistant, " done"); } + /// + public IAsyncEnumerable RunTurnMessageStreamingAsync( + ChatMessage userInput, + CancellationToken cancellationToken) + => RunTurnStreamingAsync(userInput.Text ?? string.Empty, cancellationToken); + /// public bool Interrupt( string utteranceUntilInterrupt, diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs new file mode 100644 index 00000000..dee5c88d --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/ApprovalWireTests.cs @@ -0,0 +1,248 @@ +using System.Net; +using System.Text.Json; +using AgentCore.Application.Ports; +using AgentCore.Application.Tools; +using AgentCore.Application.Tools.Registry; +using AgentCore.AspNetCore.Tests.Fakes; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.Endpoints; + +/// +/// The wire an approval travels: one SSE field that asks, and one request field that answers. +/// +/// +/// +/// Like the tool loop facts, an approval is host business the caller must see: the model asked to +/// run something it may not run alone, so the request rides its own agentcore_approval +/// field, and the answer comes back on agentcore.approval naming the same request id on the +/// same call. An ordinary OpenAI client ignores both fields. +/// +/// +/// Every test here runs offline against a fake model, on a real socket. +/// +/// +public sealed class ApprovalWireTests +{ + private const string ApprovalYaml = + """ + apiVersion: agentcore/v1 + name: approval-wire + agents: + defaults: + model: { ref: reply } + items: + - { id: greeter, instructions: "send the mail", tools: [ send_email ] } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + [Fact] + public async Task AGatedToolCall_StreamsAnApprovalEventWithTheCallFacts() + { + int sent = 0; + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => sent++)))); + + using var response = await host.PostStreamingAsync("send it"); + var events = await ChatCompletionsHost.ReadEventsAsync(response); + + var approval = Assert.Single(ApprovalEventsOf(events)); + Assert.False(string.IsNullOrEmpty(approval.GetProperty("request_id").GetString())); + Assert.Equal("send_email", approval.GetProperty("tool").GetString()); + Assert.Equal("a@b.com", approval.GetProperty("arguments").GetProperty("to").GetString()); + + Assert.Empty(ChatCompletionsHost.ContentDeltas(events)); + Assert.Equal(0, sent); + } + + [Fact] + public async Task AGatedToolCall_AnswersWholeWithTheRequestOnTheTurn() + { + int sent = 0; + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => sent++)))); + + using var response = await host.PostAsync("send it"); + var body = await ChatCompletionsHost.ReadJsonAsync(response); + + Assert.Equal(string.Empty, body["choices"]![0]!["message"]!["content"]!.GetValue()); + var approval = Assert.Single(body["agentcore"]!["approvals"]!.AsArray()); + Assert.Equal("send_email", approval!["tool"]!.GetValue()); + Assert.Equal(0, sent); + } + + [Fact] + public async Task AnApprovalAnswer_RunsTheToolAndReplies() + { + int sent = 0; + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => sent++)))); + + using var first = await host.PostAsync("send it"); + var asked = await ChatCompletionsHost.ReadJsonAsync(first); + var session = asked["agentcore"]!["session"]!.GetValue(); + var requestId = asked["agentcore"]!["approvals"]![0]!["request_id"]!.GetValue(); + + using var second = await host.PostApprovalAsync(session, requestId, approved: true, stream: false); + var replied = await ChatCompletionsHost.ReadJsonAsync(second); + + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + Assert.Equal(1, sent); + Assert.Equal("done.", replied["choices"]![0]!["message"]!["content"]!.GetValue()); + } + + [Fact] + public async Task ARejection_LeavesTheToolUnrun() + { + int sent = 0; + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => sent++)))); + + using var first = await host.PostAsync("send it"); + var asked = await ChatCompletionsHost.ReadJsonAsync(first); + var session = asked["agentcore"]!["session"]!.GetValue(); + var requestId = asked["agentcore"]!["approvals"]![0]!["request_id"]!.GetValue(); + + using var second = await host.PostApprovalAsync(session, requestId, approved: false, stream: false); + + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + Assert.Equal(0, sent); + } + + [Fact] + public async Task AnApprovalAnswerForAnUnknownCall_IsNotFound() + { + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => { })))); + + using var response = await host.PostApprovalAsync("call-that-never-existed", "req-1", approved: true, stream: false); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task AnApprovalAnswerWithNoCall_IsBadRequest() + { + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => { })))); + + using var response = await host.PostApprovalAsync(string.Empty, "req-1", approved: true, stream: false); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task AnApprovalAnswerForARequestNothingAsked_IsConflict() + { + await using var host = await ChatCompletionsHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => { })))); + + using var first = await host.PostAsync("send it"); + var asked = await ChatCompletionsHost.ReadJsonAsync(first); + var session = asked["agentcore"]!["session"]!.GetValue(); + + using var second = await host.PostApprovalAsync(session, "req-nothing-asked", approved: true, stream: false); + + Assert.Equal(HttpStatusCode.Conflict, second.StatusCode); + } + + private static ApprovalRequiredAIFunction GatedSendEmail(Action onSend) => new(AIFunctionFactory.Create( + (string to) => + { + onSend(); + return "sent"; + }, + "send_email", + "Send an email.")); + + /// Picks the agentcore_approval payloads out of events already read. + private static List ApprovalEventsOf(IEnumerable events) + { + return events + .Where(text => text != "[DONE]") + .Select(text => JsonDocument.Parse(text).RootElement) + .Where(chunk => chunk.TryGetProperty("agentcore_approval", out var approval) + && approval.ValueKind != JsonValueKind.Null) + .Select(chunk => chunk.GetProperty("agentcore_approval")) + .ToList(); + } + + /// A tool source that serves one gated id, standing in for an approval-required host tool. + private sealed class GatedSource(Func build) : IToolSource + { + public ValueTask> ProvideAsync( + ToolSourceContext context, CancellationToken cancellationToken = default) + => ValueTask.FromResult>( + [new ToolRegistration("send_email", "Send an email.", build)]); + } + + /// Calls the first tool it is offered, once, then answers in words. + private sealed class GatedToolCallingChatClient : IChatClient + { + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.Yield(); + + var alreadyCalled = messages.Any(message => message.Contents.OfType().Any()); + + if (!alreadyCalled && options?.Tools?.OfType().FirstOrDefault() is { } tool) + { + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent( + "call_1", + tool.Name, + new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" })]); + yield break; + } + + yield return new ChatResponseUpdate(ChatRole.Assistant, "done."); + } + + 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/Fakes/ChatCompletionsHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/ChatCompletionsHost.cs index 93ba6e0d..212640f8 100644 --- a/tests/AgentCore.AspNetCore.Tests/Fakes/ChatCompletionsHost.cs +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/ChatCompletionsHost.cs @@ -102,6 +102,24 @@ public Task PostAsync(string text, string? session = null) public Task PostStreamingAsync(string text, string? session = null) => SendAsync(text, session, stream: true, HttpCompletionOption.ResponseHeadersRead); + /// Answers one pending approval, and reads the answer as it arrives. + /// The id of the call the request suspended. + /// The id of the pending request. + /// Whether the tool may run. + /// Whether the client wants server-sent events. + /// The answer, with the body still open when streaming. + public Task PostApprovalAsync(string session, string requestId, bool approved, bool stream) + => SendJsonAsync( + new + { + model = "service-voice", + messages = Array.Empty(), + stream, + agentcore = new { approval = new { request_id = requestId, approved } }, + }, + session, + stream ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead); + /// Reads every server-sent event of one answer. /// The answer, with the body still open. /// The text after each data: prefix, in order. @@ -190,17 +208,26 @@ private Task SendAsync( string? session, bool stream, HttpCompletionOption completion) + { + return SendJsonAsync( + new + { + model = "service-voice", + messages = new[] { new { role = "user", content = text } }, + stream, + }, + session, + completion); + } + + private Task SendJsonAsync( + object body, + string? session, + HttpCompletionOption completion) { HttpRequestMessage request = new(HttpMethod.Post, ChatCompletionsEndpointRouteBuilderExtensions.DefaultPattern) { - Content = JsonContent.Create( - new - { - model = "service-voice", - messages = new[] { new { role = "user", content = text } }, - stream, - }, - options: JsonSerializerOptions.Web), + Content = JsonContent.Create(body, options: JsonSerializerOptions.Web), }; if (session is { Length: > 0 }) From 4eb9d38dde30a8adcd9ca41258764284869c255e Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 00:28:43 -0600 Subject: [PATCH 15/32] Add TurnSources and related tests for managing turn-specific source references - Introduced TurnSources class to handle source references during turns. - Implemented methods to publish and retrieve sources based on outer tool calls. - Updated DrawingAgentDefinition, DrawingData, and PresentTool to use the new Turn namespace. - Added unit tests for TurnSources to ensure correct behavior when publishing and retrieving sources. - Created TurnAmbientsTestScope for managing ambient contexts in tests. - Added TurnContextProviderTests and TurnResultsTests to validate turn context handling and results recording. - Refactored existing tests to align with the new Turn structure. --- .../AgentContextProviderCompiler.cs | 2 +- .../Compilation/AgentHarnessProviders.cs | 10 ++- .../Knowledge/KnowledgeProbe.cs | 1 + .../AuditingFunctionInvokingChatClient.cs | 1 + .../Runtime/CallRenderScope.cs | 1 + .../Runtime/CallSession.cs | 1 + .../Runtime/CallSourceScope.cs | 1 + .../Runtime/CallStateScope.cs | 1 + .../Runtime/Clarifications.cs | 1 + .../Harness/CallScopedAgentFileStore.cs | 2 +- .../Harness/CallShellEnvironmentProvider.cs | 38 +++++++++ .../Runtime/Harness/CallShellProvider.cs | 2 +- .../Runtime/Harness/CallShells.cs | 78 +++++++++++++++++-- .../Runtime/KnowledgeScopeScope.cs | 1 + .../Runtime/OuterToolCall.cs | 2 + .../Runtime/ToolCallScopes.cs | 1 + .../Runtime/ToolFailureScope.cs | 1 + .../Runtime/{ => Turn}/TurnAmbients.cs | 2 +- .../Runtime/{ => Turn}/TurnContextProvider.cs | 2 +- .../Runtime/{ => Turn}/TurnContextScope.cs | 2 +- .../Runtime/{ => Turn}/TurnMessages.cs | 2 +- .../Runtime/{ => Turn}/TurnRenders.cs | 2 +- .../Runtime/{ => Turn}/TurnResults.cs | 2 +- .../Runtime/{ => Turn}/TurnSources.cs | 2 +- .../Tools/Drawing/DrawingAgentDefinition.cs | 2 +- .../Tools/Drawing/DrawingData.cs | 2 +- .../Tools/Drawing/PresentTool.cs | 1 + .../ClarificationWiringBindingTests.cs | 1 + .../ConfigurationCompilerModelFacingTests.cs | 1 + .../Compilation/HarnessCompilationTests.cs | 28 +++++++ .../KnowledgeProviderBindingTests.cs | 2 +- .../Knowledge/Fakes/StubKnowledgePort.cs | 1 + .../Knowledge/KnowledgeProbeTests.cs | 3 +- .../KnowledgeProviderFactoryTests.cs | 3 +- ...ngFunctionInvokingChatClientRenderTests.cs | 1 + ...ingFunctionInvokingChatClientStripTests.cs | 1 + .../Runtime/CallRenderScopeTests.cs | 1 + .../Runtime/DelegatedToolsTests.cs | 1 + .../Harness/CallScopedAgentFileStoreTests.cs | 2 + .../Runtime/Harness/CallSessionShellTests.cs | 36 +++++++++ .../Runtime/Harness/CallShellsTests.cs | 39 ++++++++++ .../{ => Turn}/TurnAmbientsTestScope.cs | 3 +- .../{ => Turn}/TurnContextProviderTests.cs | 3 +- .../Runtime/{ => Turn}/TurnResultsTests.cs | 3 +- .../Runtime/{ => Turn}/TurnSourcesTests.cs | 3 +- .../Tools/DrawingAgentTests.cs | 2 +- .../Tools/DrawingDataTests.cs | 2 +- .../Tools/PresentToolTests.cs | 2 +- .../CallSessionGraphTranscriptTests.cs | 2 +- .../Transcript/CallSessionTranscriptTests.cs | 1 + 50 files changed, 270 insertions(+), 34 deletions(-) create mode 100644 src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs rename src/AgentCore.Application/Runtime/{ => Turn}/TurnAmbients.cs (99%) rename src/AgentCore.Application/Runtime/{ => Turn}/TurnContextProvider.cs (95%) rename src/AgentCore.Application/Runtime/{ => Turn}/TurnContextScope.cs (98%) rename src/AgentCore.Application/Runtime/{ => Turn}/TurnMessages.cs (98%) rename src/AgentCore.Application/Runtime/{ => Turn}/TurnRenders.cs (97%) rename src/AgentCore.Application/Runtime/{ => Turn}/TurnResults.cs (98%) rename src/AgentCore.Application/Runtime/{ => Turn}/TurnSources.cs (97%) rename tests/AgentCore.Application.Tests/Runtime/{ => Turn}/TurnAmbientsTestScope.cs (94%) rename tests/AgentCore.Application.Tests/Runtime/{ => Turn}/TurnContextProviderTests.cs (99%) rename tests/AgentCore.Application.Tests/Runtime/{ => Turn}/TurnResultsTests.cs (98%) rename tests/AgentCore.Application.Tests/Runtime/{ => Turn}/TurnSourcesTests.cs (97%) diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index e1341c68..f0e109d6 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -2,8 +2,8 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Compaction; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Skills; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Compaction; diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 3fa94f4b..79b66c34 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -1,8 +1,8 @@ using System.Text.RegularExpressions; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; using Microsoft.Agents.AI.Tools.Shell; @@ -97,7 +97,9 @@ public static void Add( if (item.Shell is { } shell) { - providers.Add(BuildShellProvider(item, shell, context, pointer)); + var options = BuildShellOptions(item, shell, context, pointer); + providers.Add(new CallShellProvider(options)); + providers.Add(new CallShellEnvironmentProvider(options)); } if (item.Background.Count > 0) @@ -309,7 +311,7 @@ private static FileAccessProvider BuildFilesProvider( } #pragma warning restore MAAI001 - private static CallShellProvider BuildShellProvider( + private static CallShellOptions BuildShellOptions( AgentConfiguration item, ShellConfiguration shell, AgentCompilationContext context, string pointer) { if (context.WorkspaceRoot is null) @@ -324,7 +326,7 @@ private static CallShellProvider BuildShellProvider( var policy = shell.Policy is { } declared ? BuildPolicy(item, declared, pointer) : null; var timeout = shell.TimeoutSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : (TimeSpan?)null; - return new CallShellProvider(new CallShellOptions(shell.Kind, policy, timeout)); + return new CallShellOptions(shell.Kind, policy, timeout); } private static ShellPolicy BuildPolicy( diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs index 107b74c7..1827760a 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Diagnostics; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Knowledge; using Microsoft.Agents.AI; using Microsoft.Extensions.Logging; diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index cae7a05b..bc5892c0 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -1,5 +1,6 @@ using System.Net.Sockets; using System.Security.Authentication; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools; using AgentCore.Domain.Audit; using Microsoft.Extensions.AI; diff --git a/src/AgentCore.Application/Runtime/CallRenderScope.cs b/src/AgentCore.Application/Runtime/CallRenderScope.cs index d5805245..ddf7fae3 100644 --- a/src/AgentCore.Application/Runtime/CallRenderScope.cs +++ b/src/AgentCore.Application/Runtime/CallRenderScope.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Ports; +using AgentCore.Application.Runtime.Turn; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index fac9753f..d54216ff 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -11,6 +11,7 @@ using AgentCore.Application.Policy; using AgentCore.Application.Ports; using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.State; using AgentCore.Application.Tools; using AgentCore.Application.Transcript; diff --git a/src/AgentCore.Application/Runtime/CallSourceScope.cs b/src/AgentCore.Application/Runtime/CallSourceScope.cs index 8e9738df..063fafbb 100644 --- a/src/AgentCore.Application/Runtime/CallSourceScope.cs +++ b/src/AgentCore.Application/Runtime/CallSourceScope.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Ports; +using AgentCore.Application.Runtime.Turn; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/CallStateScope.cs b/src/AgentCore.Application/Runtime/CallStateScope.cs index 0bcb734e..fa6fee9b 100644 --- a/src/AgentCore.Application/Runtime/CallStateScope.cs +++ b/src/AgentCore.Application/Runtime/CallStateScope.cs @@ -1,4 +1,5 @@ using System.Text.Json.Nodes; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.State; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/Clarifications.cs b/src/AgentCore.Application/Runtime/Clarifications.cs index 28aefa18..01eee47f 100644 --- a/src/AgentCore.Application/Runtime/Clarifications.cs +++ b/src/AgentCore.Application/Runtime/Clarifications.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Calls; +using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs b/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs index 2dafded0..4571c058 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; namespace AgentCore.Application.Runtime.Harness; diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs new file mode 100644 index 00000000..5f184b42 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs @@ -0,0 +1,38 @@ +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.Tools.Shell; + +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. +/// +internal sealed class CallShellEnvironmentProvider : AIContextProvider +{ + private const string NoTurnMessage = + "A shell: tool runs only while a turn runs through a CallSession with a workspace root bound."; + + private readonly CallShellOptions _options; + + public CallShellEnvironmentProvider(CallShellOptions options) + { + ArgumentNullException.ThrowIfNull(options); + _options = options; + } + + protected override async ValueTask ProvideAIContextAsync( + InvokingContext context, CancellationToken cancellationToken = default) + { + var shells = TurnAmbients.Current?.Shells ?? throw new InvalidOperationException(NoTurnMessage); + + var snapshot = await shells.GetEnvironmentAsync(_options, cancellationToken).ConfigureAwait(false); + + return new AIContext + { + Instructions = ShellEnvironmentProvider.DefaultInstructionsFormatter(snapshot), + }; + } +} diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs index f12c7a0d..23616190 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs @@ -1,4 +1,4 @@ -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; namespace AgentCore.Application.Runtime.Harness; diff --git a/src/AgentCore.Application/Runtime/Harness/CallShells.cs b/src/AgentCore.Application/Runtime/Harness/CallShells.cs index 32cd6a6d..5e0ff873 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShells.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShells.cs @@ -7,8 +7,8 @@ namespace AgentCore.Application.Runtime.Harness; /// /// The shell executors one call has started. One per -/// instance the agent declares, created on the first command it -/// runs — a call that never runs a command starts no bash and no container. +/// 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 { @@ -20,6 +20,8 @@ internal sealed class CallShells : IAsyncDisposable private readonly Dictionary _executors = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary> _environments = new(ReferenceEqualityComparer.Instance); + private bool _disposed; /// Creates the holder for one call. @@ -43,18 +45,80 @@ public ShellExecutor Get(CallShellOptions options) lock (_lock) { ObjectDisposedException.ThrowIf(_disposed, this); + return GetLocked(options); + } + } + + private ShellExecutor GetLocked(CallShellOptions options) + { + if (_executors.TryGetValue(options, out var existing)) + { + return existing; + } + + var created = Create(options); + _executors.Add(options, created); + return created; + } - if (_executors.TryGetValue(options, out var existing)) + /// + /// 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 + /// retries; resume re-probes a fresh environment. + /// + /// This call's shells have already been torn down. + public Task GetEnvironmentAsync( + CallShellOptions options, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(options); + + lock (_lock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (_environments.TryGetValue(options, out var cached)) { - return existing; + return cached; } - var created = Create(options); - _executors.Add(options, created); - return created; + var probe = ProbeAsync(GetLocked(options), cancellationToken); + _environments.Add(options, probe); + _ = probe.ContinueWith( + static (task, state) => + { + if (task.IsFaulted || task.IsCanceled) + { + var (shells, key) = ((CallShells, CallShellOptions))state!; + lock (shells._lock) + { + if (shells._environments.TryGetValue(key, out var current) + && ReferenceEquals(current, task)) + { + shells._environments.Remove(key); + } + } + } + }, + (this, options), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + return probe; } } + private static async Task ProbeAsync( + ShellExecutor executor, CancellationToken cancellationToken) + { + // A throwaway MAF prober per call: 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 + // before the first command. + ShellEnvironmentProvider prober = new(executor); + return await prober.RefreshAsync(cancellationToken).ConfigureAwait(false); + } + private ShellExecutor Create(CallShellOptions options) { switch (options.Kind) diff --git a/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs b/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs index 465b35d5..17a17ebc 100644 --- a/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs +++ b/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs @@ -1,3 +1,4 @@ +using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Knowledge; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/OuterToolCall.cs b/src/AgentCore.Application/Runtime/OuterToolCall.cs index 6c5f2c2b..00b45201 100644 --- a/src/AgentCore.Application/Runtime/OuterToolCall.cs +++ b/src/AgentCore.Application/Runtime/OuterToolCall.cs @@ -1,3 +1,5 @@ +using AgentCore.Application.Runtime.Turn; + namespace AgentCore.Application.Runtime; /// diff --git a/src/AgentCore.Application/Runtime/ToolCallScopes.cs b/src/AgentCore.Application/Runtime/ToolCallScopes.cs index 9802eeec..6d63ddf0 100644 --- a/src/AgentCore.Application/Runtime/ToolCallScopes.cs +++ b/src/AgentCore.Application/Runtime/ToolCallScopes.cs @@ -1,3 +1,4 @@ +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/ToolFailureScope.cs b/src/AgentCore.Application/Runtime/ToolFailureScope.cs index 4908009e..eb555db9 100644 --- a/src/AgentCore.Application/Runtime/ToolFailureScope.cs +++ b/src/AgentCore.Application/Runtime/ToolFailureScope.cs @@ -1,3 +1,4 @@ +using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Audit; namespace AgentCore.Application.Runtime; diff --git a/src/AgentCore.Application/Runtime/TurnAmbients.cs b/src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs similarity index 99% rename from src/AgentCore.Application/Runtime/TurnAmbients.cs rename to src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs index c8362cf2..da5fe994 100644 --- a/src/AgentCore.Application/Runtime/TurnAmbients.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs @@ -3,7 +3,7 @@ using AgentCore.Application.State; using AgentCore.Domain.Knowledge; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// /// Everything one turn makes ambient, carried as a single value on the flow of execution. diff --git a/src/AgentCore.Application/Runtime/TurnContextProvider.cs b/src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs similarity index 95% rename from src/AgentCore.Application/Runtime/TurnContextProvider.cs rename to src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs index 1bb235bd..a98d69e3 100644 --- a/src/AgentCore.Application/Runtime/TurnContextProvider.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs @@ -1,7 +1,7 @@ using Microsoft.Agents.AI; using Microsoft.Extensions.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// /// The framework's per-invocation seam, bound to every compiled agent. diff --git a/src/AgentCore.Application/Runtime/TurnContextScope.cs b/src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs similarity index 98% rename from src/AgentCore.Application/Runtime/TurnContextScope.cs rename to src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs index c5a01be5..c7408109 100644 --- a/src/AgentCore.Application/Runtime/TurnContextScope.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs @@ -1,7 +1,7 @@ using Microsoft.Agents.AI; using Microsoft.Extensions.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// /// What one turn adds to the model invocation, on top of what the compiled agent already carries. diff --git a/src/AgentCore.Application/Runtime/TurnMessages.cs b/src/AgentCore.Application/Runtime/Turn/TurnMessages.cs similarity index 98% rename from src/AgentCore.Application/Runtime/TurnMessages.cs rename to src/AgentCore.Application/Runtime/Turn/TurnMessages.cs index 853e47f1..f61180f1 100644 --- a/src/AgentCore.Application/Runtime/TurnMessages.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnMessages.cs @@ -1,7 +1,7 @@ using System.Text; using Microsoft.Extensions.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// /// The message shapes one turn builds and filters. Every member is pure: messages in, messages out. diff --git a/src/AgentCore.Application/Runtime/TurnRenders.cs b/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs similarity index 97% rename from src/AgentCore.Application/Runtime/TurnRenders.cs rename to src/AgentCore.Application/Runtime/Turn/TurnRenders.cs index 6caa5514..b9889944 100644 --- a/src/AgentCore.Application/Runtime/TurnRenders.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Ports; using AgentCore.Application.Transcript; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// What a turn has drawn and not yet attached to a message. internal sealed class TurnRenders : IRenderPort diff --git a/src/AgentCore.Application/Runtime/TurnResults.cs b/src/AgentCore.Application/Runtime/Turn/TurnResults.cs similarity index 98% rename from src/AgentCore.Application/Runtime/TurnResults.cs rename to src/AgentCore.Application/Runtime/Turn/TurnResults.cs index e59a477c..b78920bd 100644 --- a/src/AgentCore.Application/Runtime/TurnResults.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnResults.cs @@ -3,7 +3,7 @@ using AgentCore.Application.Tools; using Microsoft.Extensions.AI; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// /// What the tools the model called this turn answered, kept so a script can read the rows instead of diff --git a/src/AgentCore.Application/Runtime/TurnSources.cs b/src/AgentCore.Application/Runtime/Turn/TurnSources.cs similarity index 97% rename from src/AgentCore.Application/Runtime/TurnSources.cs rename to src/AgentCore.Application/Runtime/Turn/TurnSources.cs index 05dfa379..eeb50df7 100644 --- a/src/AgentCore.Application/Runtime/TurnSources.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnSources.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Transcript; using AgentCore.Domain.Sources; -namespace AgentCore.Application.Runtime; +namespace AgentCore.Application.Runtime.Turn; /// What a turn has cited and not yet attached to a message. internal sealed class TurnSources : ISourcePort diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs b/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs index e3272fc7..154a26e9 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs @@ -1,6 +1,6 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Shipped; using Microsoft.Extensions.AI; diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingData.cs b/src/AgentCore.Application/Tools/Drawing/DrawingData.cs index 84b618df..ca669ac2 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingData.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingData.cs @@ -3,7 +3,7 @@ using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; namespace AgentCore.Application.Tools.Drawing; diff --git a/src/AgentCore.Application/Tools/Drawing/PresentTool.cs b/src/AgentCore.Application/Tools/Drawing/PresentTool.cs index ebeda0f4..c3a874f7 100644 --- a/src/AgentCore.Application/Tools/Drawing/PresentTool.cs +++ b/src/AgentCore.Application/Tools/Drawing/PresentTool.cs @@ -2,6 +2,7 @@ using System.Text.Json.Nodes; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Scripting; using Microsoft.Extensions.AI; diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs index 6fda3d99..361d15be 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs @@ -4,6 +4,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Tests.Runtime.Turn; using AgentCore.Domain.Knowledge; using AgentCore.TestSupport; using Microsoft.Agents.AI; diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs index 5639c9b2..3ef67799 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs @@ -1,6 +1,7 @@ using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Transcript; using AgentCore.TestSupport; diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs index 48b2ee1a..71b62052 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/HarnessCompilationTests.cs @@ -1,6 +1,7 @@ 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 Microsoft.Agents.AI; @@ -244,6 +245,33 @@ public void Compile_ShellWithAValidBlockAndARoot_Compiles() } } + [Fact] + public void Compile_ShellBlock_GetsAToolProviderAndAnEnvironmentProvider() + { + var root = Path.Combine(Path.GetTempPath(), "agentcore-shell-env-" + Guid.NewGuid().ToString("N")); + try + { + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(ShellYaml), + new AgentCompilationContext(new FakeChatClientFactory(new SequencedChatClient("hi"))) + { + WorkspaceRoot = root, + }); + + var providers = Providers(Assert.Single(compiled.Agents.Values)); + + Assert.Contains(providers, provider => provider is CallShellProvider); + Assert.Contains(providers, provider => provider is CallShellEnvironmentProvider); + } + finally + { + if (Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + } + } + private static AIAgent CompileOne(bool withTodos, bool withMode) { using SequencedChatClient reply = new("hello there."); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs index cea84b8c..de7a8fc0 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Knowledge.Fakes; using AgentCore.Application.Tests.Runtime; diff --git a/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs b/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs index 0cfadd8a..e7c91c00 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Knowledge; namespace AgentCore.Application.Tests.Knowledge.Fakes; diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs index 8050e497..35ddaa5d 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs @@ -6,7 +6,8 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Tests.Runtime.Turn; using AgentCore.Domain.Knowledge; using AgentCore.TestSupport; using Microsoft.Agents.AI; diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs index b5e14cb6..051968db 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs @@ -6,8 +6,9 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Knowledge.Fakes; -using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Tests.Runtime.Turn; using AgentCore.Domain.Knowledge; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs index 92ca1840..9453c000 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs @@ -1,5 +1,6 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Drawing; diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs index 68f10688..8d334ec5 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Knowledge.Fakes; using AgentCore.Domain.Knowledge; diff --git a/tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs index 26e295f3..d19e62cb 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.TestSupport; using Microsoft.Extensions.AI; diff --git a/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs b/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs index 09687a56..7e7ed803 100644 --- a/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using Microsoft.Extensions.AI; using Xunit; diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs index 52e7eea1..d279dd66 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs @@ -1,5 +1,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Tests.Runtime.Turn; using Xunit; namespace AgentCore.Application.Tests.Runtime.Harness; diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs index 109472b0..25bc02de 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionShellTests.cs @@ -185,6 +185,8 @@ public async Task NoShellBlock_NoRunShellToolInTheRequest() var toolNames = reply.Options[^1]?.Tools?.Select(tool => tool.Name).ToArray() ?? []; Assert.DoesNotContain(RunShellToolName, toolNames); + Assert.DoesNotContain( + "## Shell environment", reply.Options[^1]?.Instructions ?? string.Empty, StringComparison.Ordinal); } [Fact] @@ -202,6 +204,40 @@ public async Task ATurnThatReachesATerminalStage_DisposesTheShellWithoutCloseAsy await ProcHelpers.AssertGoneAsync(pid, TestContext.Current.CancellationToken); } + [Fact] + public async Task FirstRequest_CarriesShellEnvironmentInstructions_NamingTheCallsWorkspace() + { + var client = new ShellScriptedClient(RunShellToolName, "pwd"); + var factory = BuildFactory(ShellYaml, client); + await using var session = factory.Create("call-1"); + + await session.RunTurnAsync("go", TestContext.Current.CancellationToken); + + var instructions = client.Requests[0].Options?.Instructions; + Assert.Contains("## Shell environment", instructions, StringComparison.Ordinal); + Assert.Contains(session.Workspace!, instructions, StringComparison.Ordinal); + } + + [Fact] + public async Task ASecondCall_GetsItsOwnWorkspaceInItsInstructions() + { + var client = new ShellScriptedClient(RunShellToolName); + var factory = BuildFactory(ShellYaml, client); + + await using var sessionA = factory.Create("call-a"); + await sessionA.RunTurnAsync("go", TestContext.Current.CancellationToken); + + await using var sessionB = factory.Create("call-b"); + await sessionB.RunTurnAsync("go", TestContext.Current.CancellationToken); + + var instructionsA = client.Requests[0].Options?.Instructions; + var instructionsB = client.Requests[1].Options?.Instructions; + + Assert.Contains(sessionA.Workspace!, instructionsA, StringComparison.Ordinal); + Assert.Contains(sessionB.Workspace!, instructionsB, StringComparison.Ordinal); + Assert.DoesNotContain(sessionB.Workspace!, instructionsA, StringComparison.Ordinal); + } + /// /// Reads the pid off the first line of a run_shell tool result: MAF's own formatting /// appends an exit_code: line after the command's stdout. diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs index f7afbf57..7f549b2d 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallShellsTests.cs @@ -151,4 +151,43 @@ public async Task Get_Docker_ReturnsADockerShellExecutor_WithNoDockerNeeded() Assert.IsType(executor); } + + [Fact] + public async Task GetEnvironmentAsync_ProbesThroughThisCallsExecutor_AndCachesTheSnapshot() + { + await using CallShells shells = new(_workspace, logger: null); + CallShellOptions 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); + + Assert.Same(first, second); + Assert.Contains( + new DirectoryInfo(_workspace).FullName, first.WorkingDirectory, StringComparison.Ordinal); + } + + [Fact] + public async Task GetEnvironmentAsync_WithADenyAllPolicy_StillReturnsARenderableSnapshot() + { + // 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); + + var snapshot = await shells.GetEnvironmentAsync(options, TestContext.Current.CancellationToken); + var text = ShellEnvironmentProvider.DefaultInstructionsFormatter(snapshot); + + Assert.StartsWith("## Shell environment", text, StringComparison.Ordinal); + } + + [Fact] + public async Task GetEnvironmentAsync_AfterDispose_ThrowsObjectDisposedException() + { + CallShells shells = new(_workspace, logger: null); + await shells.DisposeAsync(); + + await Assert.ThrowsAsync(() => shells.GetEnvironmentAsync( + new CallShellOptions(ShellKind.Local, Policy: null, Timeout: null), + TestContext.Current.CancellationToken)); + } } diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs similarity index 94% rename from tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs rename to tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs index 5a6a598e..701cd748 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnAmbientsTestScope.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs @@ -1,7 +1,8 @@ using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Turn; /// /// Opens one ambient at a time, so a collector can be tested without standing up a whole call. diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnContextProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs similarity index 99% rename from tests/AgentCore.Application.Tests/Runtime/TurnContextProviderTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs index c915ec53..b99aa67d 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnContextProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs @@ -4,6 +4,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.State; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Transcript; @@ -11,7 +12,7 @@ using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Turn; /// /// The per-invocation seam: what one turn hands the model on top of the agent's own instructions. diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs similarity index 98% rename from tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs index 44f76c4c..eaed832d 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnResultsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs @@ -1,12 +1,13 @@ using System.Text.Json; using System.Text.Json.Nodes; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tools; using Microsoft.Extensions.AI; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Turn; /// /// : what the turn's tools answered, kept so a drawing script can read the diff --git a/tests/AgentCore.Application.Tests/Runtime/TurnSourcesTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs similarity index 97% rename from tests/AgentCore.Application.Tests/Runtime/TurnSourcesTests.cs rename to tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs index ad637dc9..66197e19 100644 --- a/tests/AgentCore.Application.Tests/Runtime/TurnSourcesTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs @@ -1,8 +1,9 @@ using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Sources; using Xunit; -namespace AgentCore.Application.Tests.Runtime; +namespace AgentCore.Application.Tests.Runtime.Turn; /// /// What a turn has cited and not yet attached to a message. diff --git a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs index d2f17cd0..cc0f841d 100644 --- a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs @@ -3,7 +3,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; using AgentCore.Application.Tools; diff --git a/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs b/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs index 0878d5c1..7a0089dc 100644 --- a/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DrawingDataTests.cs @@ -1,5 +1,5 @@ using System.Text.Json.Nodes; -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools.Drawing; using Xunit; diff --git a/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs b/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs index 3684449b..116f34c4 100644 --- a/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs @@ -1,6 +1,6 @@ using System.Text.Json; using System.Text.Json.Nodes; -using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; using AgentCore.Application.Tools; diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs index e83b57dd..71bdbfb1 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionGraphTranscriptTests.cs @@ -5,8 +5,8 @@ using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Tests.Runtime; using Microsoft.Extensions.AI; using Xunit; diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs index cd65260c..72cfd3fd 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; using AgentCore.Application.Transcript; From 3793467f9fea978ea448e8f53d978c440862d433 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 01:27:29 -0600 Subject: [PATCH 16/32] feat: Add workflow state management to CallSession and related tests --- .../Calls/CallSessionState.cs | 8 + .../PublicAPI.Unshipped.txt | 2 + .../Runtime/CallSession.cs | 77 ++++++-- .../Runtime/Harness/HarnessSessionState.cs | 3 +- .../AgentCoreChatHistoryProvider.cs | 15 +- .../Harness/CallSessionGraphStateTests.cs | 168 ++++++++++++++++++ ...entCoreChatHistoryProviderStateBagTests.cs | 100 ----------- ...AgentCoreChatHistoryProviderTestSupport.cs | 15 +- .../AgentCoreChatHistoryProviderTests.cs | 25 ++- 9 files changed, 266 insertions(+), 147 deletions(-) create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs delete mode 100644 tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderStateBagTests.cs diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Calls/CallSessionState.cs index bad90feb..4bdb5368 100644 --- a/src/AgentCore.Application/Calls/CallSessionState.cs +++ b/src/AgentCore.Application/Calls/CallSessionState.cs @@ -49,4 +49,12 @@ public sealed record CallSessionState /// no harness switch holds none. Absent in an old blob, which restores its stage and slots as before. /// public IReadOnlyDictionary Providers { get; init; } = NoProviders; + + /// + /// Gets the opaque workflow session of a graph row's call, 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 + /// keeps neither. Absent in an old blob, which resumes with a fresh session. + /// + public JsonElement? WorkflowState { get; init; } } diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index b7a425f9..d49ba3c7 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -115,6 +115,8 @@ 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.CallStateJson AgentCore.Application.Calls.CallStatus AgentCore.Application.Calls.CallStatus.Archived = 1 -> AgentCore.Application.Calls.CallStatus diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index d54216ff..e99ae94b 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -89,6 +89,19 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private AgentSession? _agentSession; + /// + /// The call'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 . + /// + private AgentSession? _graphSession; + + /// + /// The last serialization of , read back at resume. Refreshed + /// at every turn end; a host snapshotting mid-turn gets the last turn boundary. + /// + private JsonElement? _graphBlob; + private CancellationTokenSource? _runCancellation; private Interruption? _interruption; @@ -734,6 +747,16 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell else { session = new CallHistorySession(); + + // 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 + // participant's provider state from its checkpoints whenever a turn runs on it. + if (ReusesGraphSession) + { + _graphSession = stored is { Version: CallSessionState.CurrentVersion, WorkflowState: { } blob } + ? await _compiled.TurnAgent.DeserializeSessionAsync(blob, cancellationToken: cancellationToken).ConfigureAwait(false) + : await _compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } } IReadOnlyList spoken = record.LastMessageAt is null @@ -769,7 +792,8 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell /// /// Reads the state this call 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. + /// 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() { @@ -799,6 +823,10 @@ internal CallSessionState Snapshot() Clarifications = _clarifications.Spent(), Providers = HarnessSessionState.Capture(_agentSession, _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. + WorkflowState = _graphBlob, }; } @@ -912,16 +940,33 @@ void Dropped(string reason) => _events.RaiseDiagnostic( }); } + /// + /// Whether this call 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. + /// + private bool ReusesGraphSession => !_sessionCarriesHistory && _compiled.HarnessStateKeys.Count > 0; + /// /// Reads the session one run is handed. /// /// The turn about to run. /// Cancels the open. - /// The call's session on rows 1 and 2, and a fresh workflow session on a graph row. + /// 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. private async ValueTask RunSessionAsync(Turn turn, CancellationToken cancellationToken) - => _sessionCarriesHistory - ? turn.Session - : await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + { + if (_sessionCarriesHistory) + { + return turn.Session; + } + + if (ReusesGraphSession) + { + return _graphSession ??= await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + + return await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } /// /// Opens the ambients this turn runs under. @@ -1034,19 +1079,19 @@ private Turn BeginTurn(ChatMessage userInput, AgentSession session, CallTurnOrig _history.BeginTurn(session, State.TurnIndex); // Rows 1 and 2 read the call out of the session, so the run carries the new message alone - // and the provider prepends the rest. A workflow takes no provider, so its history rides - // the request, rendered into the one role a node still recognises. Neither shape puts the - // caller's message in store 1 yet: the turn writes what it said and what it heard together, - // when it commits, so the run that is about to read the history does not find its own - // prompt already in it. - List request = _sessionCarriesHistory + // 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 + // still recognises. Neither shape puts the caller's message in store 1 yet: the turn + // writes what it said and what it heard together, when it commits, so the run that is + // about to read the history does not find its own prompt already in it. + List request = _sessionCarriesHistory || ReusesGraphSession ? [spoken] : TurnMessages.GraphHistory(_history.Read(session)) is { } rendered ? [rendered, spoken] : [spoken]; // One turn is one span. The call 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(CallId, State.TurnIndex, State.Stage); - var knowledge = StateKnowledgeScope.Compose( State, _compiled.Configuration.Providers?.Knowledge?.Scope, KnowledgeScopeScope.Current); @@ -1396,6 +1441,14 @@ private async Task CompleteTurnAsync( 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 (ReusesGraphSession && _graphSession is { } shared) + { + _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. diff --git a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs index 17175693..49c77935 100644 --- a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs +++ b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs @@ -24,7 +24,8 @@ internal static class HarnessSessionState /// /// The kept keys, each value cloned off the bag's own serialization. Empty for a /// session or an empty — the bag is never - /// serialized in that case, because it also holds the transcript. + /// serialized in that case. The transcript lives outside the bag, so what is serialized + /// here is provider and approval state only. /// public static IReadOnlyDictionary Capture(AgentSession? session, IReadOnlySet keys) { diff --git a/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs b/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs index 6a4c792c..0c95a6f5 100644 --- a/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs +++ b/src/AgentCore.Application/Transcript/AgentCoreChatHistoryProvider.cs @@ -16,14 +16,12 @@ namespace AgentCore.Application.Transcript; internal delegate void TranscriptWriteDropped(int turnIndex, Exception exception); /// -/// Store 1: the words of a call, held by the session and written through to a backing store. +/// Store 1: the words of a call, 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 ProviderSessionState _state; - private readonly ICallStore _store; private readonly ILogger _logger; @@ -35,7 +33,6 @@ public AgentCoreChatHistoryProvider(ICallStore? store = null, ILogger? logger = _logger = logger ?? NullLogger.Instance; - _state = new(static _ => new CallTranscript(), StateKeys[0], TranscriptJson.Options); } /// @@ -353,10 +350,7 @@ private TResult UnderLock(AgentSession session, Func(AgentSession session, Func _gates.GetValue(session, static _ => new CallGate()); - /// What one call holds outside its state bag: its lock, and its queue of store writes. + /// What one call holds outside its state bag: its lock, its transcript, and its queue of store writes. private sealed class CallGate { /// Gets the lock every read and every change of this call'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 or sets the tail of this call's store writes. It never faults. public Task Writes { get; set; } = Task.CompletedTask; diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs new file mode 100644 index 00000000..64fc9a8a --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallSessionGraphStateTests.cs @@ -0,0 +1,168 @@ +using System.Text.Json; +using AgentCore.Application.Calls; +using AgentCore.Application.Calls.Memory; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; +using AgentCore.TestSupport; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +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. +/// A graph row without one still runs every turn fresh, exactly as before. +/// +public sealed class CallSessionGraphStateTests +{ + private const string TodosYaml = + """ + apiVersion: agentcore/v1 + name: graph-todos + agents: + items: + - { id: adder, instructions: "track todos", todos: true, model: { ref: adder } } + - { id: echo, instructions: "echo back", model: { ref: echo } } + graph: + pattern: sequential + agents: [ adder, echo ] + """; + + private const string PlainYaml = + """ + apiVersion: agentcore/v1 + name: graph-plain + agents: + items: + - { id: first, instructions: "one", model: { ref: first } } + - { id: second, instructions: "two", model: { ref: second } } + graph: + pattern: sequential + agents: [ first, second ] + """; + + [Fact] + public async Task SecondTurn_AdderRequestCarriesTheRestoredTodo_AndNoRenderedHistory() + { + InMemoryCallStore 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"); + + await session.RunTurnAsync("track this", TestContext.Current.CancellationToken); + var turn1Calls = 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]; + Assert.Contains(run2, message => message.Text.Contains("buy milk", StringComparison.Ordinal)); + + // …and the resumed conversation already carries what came before, so the turn + // renders no history of its own. Rendered plus resumed would deliver it twice. + Assert.DoesNotContain(run2, message => message.Text.Contains(TurnMessages.HistoryPreamble, StringComparison.Ordinal)); + } + + [Fact] + public async Task ResumeFromTheSameStore_AdderRequestCarriesTheRestoredTodo() + { + InMemoryCallStore 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"); + await first.RunTurnAsync("track this", TestContext.Current.CancellationToken); + + var second = factory.Create("call-1"); + await second.RunTurnAsync("anything new?", TestContext.Current.CancellationToken); + + var resumed = adderRequests.Requests[^1]; + Assert.Contains(resumed, message => message.Text.Contains("buy milk", StringComparison.Ordinal)); + } + + [Fact] + public async Task NoHarnessSwitch_AfterATurn_Store0HoldsNeitherBlobNorProviders() + { + InMemoryCallStore store = new(); + var factory = Build( + PlainYaml, + store, + new ScriptedToolCallingChatClient() { FinalText = "one" }, + new ScriptedToolCallingChatClient() { FinalText = "two" }); + var session = factory.Create("call-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); + Assert.NotNull(record?.State); + Assert.Null(record.State.WorkflowState); + Assert.Empty(record.State.Providers); + } + + [Fact] + public async Task TodosSwitch_AfterATurn_Store0HoldsTheBlobAndNoPickedKeys() + { + InMemoryCallStore 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"); + + await session.RunTurnAsync("track this", TestContext.Current.CancellationToken); + + var record = await store.GetAsync("call-1", TestContext.Current.CancellationToken); + Assert.NotNull(record?.State); + Assert.NotNull(record.State.WorkflowState); + Assert.Empty(record.State.Providers); + } + + [Fact] + public async Task PickedProvidersWithoutABlob_AreIgnored_AdderStartsFresh() + { + InMemoryCallStore 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() + { + Providers = new Dictionary(StringComparer.Ordinal) + { + [new TodoProvider().StateKeys[0]] = JsonDocument.Parse( + """{"items":[{"id":1,"title":"buy milk","isComplete":false}],"nextId":2}""").RootElement, + }, + }; + + var session = factory.Create("call-1", fabricated); + await session.RunTurnAsync("anything new?", TestContext.Current.CancellationToken); + + Assert.DoesNotContain( + adderRequests.Requests[0], + message => message.Text.Contains("buy milk", StringComparison.Ordinal)); + } + + private static CallSessionFactory Build(string yaml, ICallStore store, IChatClient first, IChatClient second) + { + var document = ConfigurationLoader.LoadYaml(yaml); + RoutingChatClientFactory chatClients = new(first); + chatClients.Route("echo", second); + chatClients.Route("second", second); + var compiled = ConfigurationCompiler.Compile( + document, + new AgentCompilationContext(chatClients) { CallStore = store }); + + return new CallSessionFactory(compiled, new GuardEvaluator(compiled.Configuration.Guards)); + } +} diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderStateBagTests.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderStateBagTests.cs deleted file mode 100644 index 52edb171..00000000 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderStateBagTests.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.Text.Json; -using System.Text.Json.Nodes; -using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Transcript; -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; -using Xunit; - -namespace AgentCore.Application.Tests.Transcript; - -/// -/// Pins that reads its transcript back out of the session's -/// state bag under , not AIJsonUtilities.DefaultOptions. -/// strips every before a message reaches -/// , so the provider can no longer write one into the bag itself — -/// but a transcript written before that change, or by some other writer, still can carry one, and -/// nothing else in the suite would catch the provider quietly losing the options that let it come back. -/// -public sealed class AgentCoreChatHistoryProviderStateBagTests -{ - private const string CallId = "call-1"; - private const string StateKey = "AgentCoreChatHistoryProvider"; - - /// - /// Seeds a session's state bag directly with a transcript carrying a — - /// standing in for one written before started stripping, or by a - /// writer other than this provider — then drives the provider's own read path over it. This is the - /// regression this test exists to catch: revert the provider's constructor from - /// back to AIJsonUtilities.DefaultOptions and this throws, - /// because that options set has no converter for the "agentcore.render" discriminator. - /// - [Fact] - public void Read_ATranscriptWrittenWithARenderContent_ComesBackIntact() - { - // Arrange - var seed = new AgentSessionStateBag(); - seed.SetValue(StateKey, TranscriptWithARenderContent(out var data), TranscriptJson.Options); - - // Round-tripped through Serialize/Deserialize so the bag holds raw JSON, the way a session - // loaded from storage would: a same-process SetValue keeps the CLR object and never touches - // these options at all, which would let this test pass no matter what the provider is wired to. - var session = new StubSession(AgentSessionStateBag.Deserialize(seed.Serialize())); - var provider = new AgentCoreChatHistoryProvider(new RecordingCallStore()); - - // Act - var read = provider.Read(session); - - // Assert - var render = Assert.Single(Assert.Single(read).Contents.OfType()); - Assert.Equal("order-card", render.Name); - Assert.Equal("order-41", render.RenderId); - Assert.True(JsonNode.DeepEquals(JsonNode.Parse(data.GetRawText()), JsonNode.Parse(render.Data.GetRawText()))); - } - - /// - /// A drawing carried on a stored message is unreadable under the options the provider used before - /// this fix: AIJsonUtilities.DefaultOptions has no converter for the "agentcore.render" - /// discriminator, so deserializing it throws rather than quietly dropping the drawing. - /// - [Fact] - public void DefaultOptions_ReadingARenderContent_ThrowsInsteadOfDroppingIt() - { - // Arrange - var bag = new AgentSessionStateBag(); - bag.SetValue(StateKey, TranscriptWithARenderContent(out _), TranscriptJson.Options); - var deserialized = AgentSessionStateBag.Deserialize(bag.Serialize()); - - // Act & Assert - var exception = Assert.Throws( - () => deserialized.TryGetValue(StateKey, out _, AIJsonUtilities.DefaultOptions)); - Assert.Contains("agentcore.render", exception.Message, StringComparison.Ordinal); - } - - /// - /// Builds a transcript carrying a directly, bypassing - /// : that strips the before it - /// reaches , which is exactly what these tests need to get - /// past to exercise the read side. - /// - private static CallTranscript TranscriptWithARenderContent(out JsonElement data) - { - data = JsonSerializer.SerializeToElement(new { widget = "gauge" }); - - var transcript = new CallTranscript { CallId = CallId }; - transcript.Messages.Add(new CallTranscript.StoredMessage - { - Ordinal = 0, - TurnIndex = 0, - Message = new ChatMessage(ChatRole.Assistant, - [ - new FunctionResultContent("call-1", new { status = "shipped" }), - new RenderContent { Name = "order-card", RenderId = "order-41", Data = data }, - ]), - }); - - return transcript; - } - - private sealed class StubSession(AgentSessionStateBag bag) : AgentSession(bag); -} diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs index 6c6df84d..3eac06d5 100644 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTestSupport.cs @@ -17,14 +17,12 @@ internal static class AgentCoreChatHistoryProviderTestSupport internal const string CallId = "call-1"; /// - /// The key the call's transcript is filed under in . Changing - /// it orphans the state of any session already persisted under the old one. + /// The provider's MAF-default state key: its own type name. The transcript no longer files + /// under it — or anywhere in the bag — and a change still renames what the collision checks + /// compare, so it stays pinned here rather than inlined. /// internal const string StateKey = "AgentCoreChatHistoryProvider"; - /// The converters the provider files the transcript with. - internal static JsonSerializerOptions StateOptions => AIJsonUtilities.DefaultOptions; - /// /// 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 @@ -54,13 +52,6 @@ internal static void AppendTurn( [new ChatMessage(ChatRole.User, said), new ChatMessage(ChatRole.Assistant, replied)]); } - /// Reads one session's transcript straight out of its state bag, past the provider. - internal static CallTranscript TranscriptIn(AgentSession session) - { - Assert.True(session.StateBag.TryGetValue(StateKey, out var transcript, StateOptions)); - Assert.NotNull(transcript); - return transcript; - } internal static async Task> ProvideAsync( AgentCoreChatHistoryProvider provider, AgentSession session) diff --git a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs index eb641c26..4c823c4d 100644 --- a/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/AgentCoreChatHistoryProviderTests.cs @@ -162,11 +162,12 @@ public async Task ProvideChatHistory_TwoConcurrentSessions_DoNotMix() /// /// The framework validates this set at agent construction and again on every run, and refuses a - /// collision. The value is also the name a persisted session's state is filed under, so a change - /// here is a silent data loss rather than a rename. + /// collision. The value is MAF's default — the provider's own type name — and nothing files + /// under it anymore, but a change still renames what the collision checks compare, so it stays + /// pinned rather than inlined. /// [Fact] - public void StateKeys_IsTheSingleKeyTheTranscriptIsFiledUnder() + public void StateKeys_IsTheSingleProviderTypeNameKey() { // Arrange var provider = new AgentCoreChatHistoryProvider(); @@ -176,7 +177,7 @@ public void StateKeys_IsTheSingleKeyTheTranscriptIsFiledUnder() } [Fact] - public async Task AppendTurn_PutsTheTranscriptInTheSessionStateBagUnderTheProviderKey() + public async Task AppendTurn_LeavesTheSessionStateBagEmpty() { // Arrange var (provider, _, session) = await NewCall(); @@ -185,18 +186,16 @@ public async Task AppendTurn_PutsTheTranscriptInTheSessionStateBagUnderTheProvid AppendTurn(provider, session, turnIndex: 0, "order 41?", "it ships Friday"); // Assert - Assert.True(session.StateBag.TryGetValue(StateKey, out var transcript, StateOptions)); - Assert.NotNull(transcript); - Assert.Equal(CallId, transcript.CallId); - Assert.Equal(["order 41?", "it ships Friday"], transcript.Read().Select(message => message.Text)); + Assert.Equal(0, session.StateBag.Count); + Assert.Equal(["order 41?", "it ships Friday"], provider.Read(session).Select(message => message.Text)); } /// - /// The provider is one object shared by every call, so the same key on two sessions must reach - /// two transcripts. A key resolved against the provider rather than the session would merge them. + /// The provider is one object shared by every call, 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_EachHoldsItsOwnTranscriptUnderThatKey() + public void AppendTurn_TwoSessions_EachHoldsItsOwnTranscript() { // Arrange var provider = new AgentCoreChatHistoryProvider(new RecordingCallStore()); @@ -210,8 +209,8 @@ public void AppendTurn_TwoSessions_EachHoldsItsOwnTranscriptUnderThatKey() AppendTurn(provider, second, turnIndex: 0, "b said", "b heard"); // Assert - Assert.Equal(["a said", "a heard"], TranscriptIn(first).Read().Select(message => message.Text)); - Assert.Equal(["b said", "b heard"], TranscriptIn(second).Read().Select(message => message.Text)); + Assert.Equal(["a said", "a heard"], provider.Read(first).Select(message => message.Text)); + Assert.Equal(["b said", "b heard"], provider.Read(second).Select(message => message.Text)); } [Fact] From 685b82db27a96647d4fbd53cc4d0f19c07e01b96 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 19:16:08 -0600 Subject: [PATCH 17/32] refactor: use agent harness and remove async local implementation --- sonar-project.properties | 1 + .../Compilation/AgentDelegationTool.cs | 86 +- .../Compilation/AgentHarnessProviders.cs | 50 +- .../Validation/ConfigurationValidator.cs | 15 +- .../Knowledge/FacetFilterProvider.cs | 11 +- .../Knowledge/FacetFilteredSearch.cs | 77 +- .../Knowledge/KnowledgePrefetchProvider.cs | 63 + .../Knowledge/KnowledgeProbe.cs | 40 +- .../Knowledge/KnowledgeProviderFactory.cs | 172 +- .../Knowledge/KnowledgeSearch.cs | 205 +++ .../Knowledge/KnowledgeSearchRecord.cs | 10 +- .../Knowledge/StateKnowledgeScope.cs | 14 +- .../Knowledge/ToolFacetScope.cs | 42 - .../Ports/IConversationPort.cs | 29 +- .../Ports/IKnowledgeRetrievalPort.cs | 2 + .../Ports/IKnowledgeStoreAdapter.cs | 4 +- .../PublicAPI.Unshipped.txt | 13 +- .../AuditingFunctionInvokingChatClient.cs | 150 +- .../Runtime/CallRenderScope.cs | 13 - .../Runtime/CallSession.cs | 1509 ++--------------- .../CallSession/CallInterruptionTracker.cs | 172 ++ .../CallSession/CallSessionLifetime.cs | 79 + .../CallSession/CallSessionStateStore.cs | 172 ++ .../CallSession/CallTranscriptLedger.cs | 181 ++ .../Runtime/CallSession/CallTurn.cs | 27 + .../Runtime/CallSession/CallTurnCompletion.cs | 394 +++++ .../Runtime/CallSession/CallTurnRunner.cs | 313 ++++ .../Runtime/CallSession/CallTurnStream.cs | 158 ++ .../Runtime/CallSession/CallTurnWriters.cs | 78 + .../Runtime/CallSourceScope.cs | 11 - .../Runtime/CallStateScope.cs | 37 +- .../Runtime/Clarifications.cs | 12 +- .../Runtime/DelegatedAgentRun.cs | 61 + .../Runtime/Harness/CallFilesProvider.cs | 70 + .../Harness/CallScopedAgentFileStore.cs | 38 - .../Harness/CallShellEnvironmentProvider.cs | 3 +- .../Runtime/Harness/CallShellProvider.cs | 3 +- .../Runtime/KnowledgeScopeScope.cs | 22 - .../Runtime/ModelFacingChatClient.cs | 49 +- .../Runtime/OuterToolCall.cs | 39 - .../Runtime/ToolCallScopes.cs | 25 +- .../Runtime/ToolFailureScope.cs | 42 - .../Runtime/Turn/TurnAmbients.cs | 147 -- .../Runtime/Turn/TurnContextProvider.cs | 5 +- .../Runtime/Turn/TurnContextScope.cs | 69 - .../Runtime/Turn/TurnRegistry.cs | 33 + .../Runtime/Turn/TurnRenders.cs | 52 +- .../Runtime/Turn/TurnResults.cs | 49 + .../Runtime/Turn/TurnSources.cs | 52 +- .../Runtime/TurnInvocation.cs | 85 + .../Tools/Binding/ToolParameterBindings.cs | 37 + .../Tools/Binding/TypedBindingTool.cs | 5 +- .../Tools/Drawing/DrawingAgentDefinition.cs | 4 +- .../Tools/Drawing/PresentTool.cs | 19 +- .../Tools/Shipped/IShippedAgentDefinition.cs | 4 +- .../Tools/Shipped/ShippedAgentBuilder.cs | 39 +- .../VectorData/Qdrant/QdrantKnowledgeStore.cs | 13 +- .../Llm/OpenAI/OpenAiChatClientAdapter.cs | 2 +- .../Tools/Mcp/McpTool.cs | 47 +- .../ClarificationWiringBindingTests.cs | 112 +- .../ConfigurationCompilerModelFacingTests.cs | 23 +- .../Compilation/FilesCompilationTests.cs | 3 +- .../KnowledgeProviderBindingTests.cs | 12 +- .../Compilation/MemoryCompilationTests.cs | 2 +- .../Knowledge/FacetFilterTests.cs | 25 +- .../Fakes/RecordingKnowledgeStoreAdapter.cs | 1 + .../Knowledge/Fakes/StubKnowledgePort.cs | 23 +- .../Knowledge/KnowledgeProbeTests.cs | 370 ++-- .../KnowledgeProviderFactoryTests.cs | 217 ++- .../Knowledge/StateKnowledgeScopeTests.cs | 20 +- ...ctionInvokingChatClientErrorPolicyTests.cs | 35 +- ...ngFunctionInvokingChatClientRenderTests.cs | 134 +- ...ingFunctionInvokingChatClientStripTests.cs | 138 +- .../Runtime/CallSessionProbeTests.cs | 6 +- .../Runtime/DelegatedToolsTests.cs | 19 - .../Runtime/Harness/CallFilesProviderTests.cs | 102 ++ .../Harness/CallScopedAgentFileStoreTests.cs | 50 - .../Runtime/KnowledgeScopeScopeTests.cs | 54 - .../KnowledgeScopeThroughCallSessionTests.cs | 126 +- .../Runtime/Turn/TurnAmbientsTestScope.cs | 38 - .../Runtime/Turn/TurnContextProviderTests.cs | 10 +- .../Runtime/Turn/TurnResultsTests.cs | 19 +- .../Runtime/Turn/TurnSourcesTests.cs | 30 +- ...RenderScopeTests.cs => TurnScreenTests.cs} | 91 +- .../Tools/DrawingAgentTests.cs | 47 +- .../Tools/PresentToolTests.cs | 46 +- .../Tools/ShippedAgentBuilderTests.cs | 17 +- .../Tools/TypedBindingToolTests.cs | 32 + .../Transcript/CallSessionTranscriptTests.cs | 22 +- .../Transcript/InnerAgentTranscriptTests.cs | 6 +- .../Call/CallTurnArbiterTests.cs | 4 + .../DependencyInjection/AddAgentCoreTests.cs | 4 +- .../AmbiguityStartupTests.cs | 3 +- .../KnowledgeLoggingThroughBootTests.cs | 5 +- .../KnowledgeScopeArgumentOrderTests.cs | 3 +- .../KnowledgeStartupTests.cs | 3 +- .../Endpoints/DrawingWireTests.cs | 18 +- .../Endpoints/SourceWireTests.cs | 13 +- tests/AgentCore.Evals/GoldenSetEvalTests.cs | 2 +- .../Qdrant/AmbiguityIntegrationTests.cs | 79 +- .../Qdrant/DirectLinkLookupTests.cs | 4 +- .../VectorData/Qdrant/ForeignSchemaTests.cs | 27 +- .../Qdrant/QdrantKnowledgeAdapterTests.cs | 3 +- .../Qdrant/QdrantKnowledgeStoreTests.cs | 79 +- .../Qdrant/QdrantWildcardScopeTests.cs | 42 +- .../Qdrant/ScoreFloorOnPrefetchTests.cs | 14 +- .../Qdrant/StoreNamingNeutralityTests.cs | 31 +- .../Qdrant/WildcardScopeIntegrationTests.cs | 38 +- .../Tools/Fakes/ControllableMcpServer.cs | 49 +- .../Tools/McpServerSessionTests.cs | 26 + .../TextSearchProviderInternals.cs | 58 - 111 files changed, 4097 insertions(+), 3392 deletions(-) create mode 100644 sonar-project.properties create mode 100644 src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs create mode 100644 src/AgentCore.Application/Knowledge/KnowledgeSearch.cs delete mode 100644 src/AgentCore.Application/Knowledge/ToolFacetScope.cs delete mode 100644 src/AgentCore.Application/Runtime/CallRenderScope.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallSessionStateStore.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTurn.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs create mode 100644 src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs delete mode 100644 src/AgentCore.Application/Runtime/CallSourceScope.cs create mode 100644 src/AgentCore.Application/Runtime/DelegatedAgentRun.cs create mode 100644 src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs delete mode 100644 src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs delete mode 100644 src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs delete mode 100644 src/AgentCore.Application/Runtime/OuterToolCall.cs delete mode 100644 src/AgentCore.Application/Runtime/ToolFailureScope.cs delete mode 100644 src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs delete mode 100644 src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs create mode 100644 src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs create mode 100644 src/AgentCore.Application/Runtime/TurnInvocation.cs create mode 100644 src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs create mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs delete mode 100644 tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs delete mode 100644 tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeScopeTests.cs delete mode 100644 tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs rename tests/AgentCore.Application.Tests/Runtime/{CallRenderScopeTests.cs => TurnScreenTests.cs} (61%) delete mode 100644 tests/AgentCore.TestSupport/TextSearchProviderInternals.cs diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 00000000..1d3a723d --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1 @@ +sonar.projectKey=agentcore diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs index 03daff39..7cff6a59 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; using AgentCore.Application.Tools; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; @@ -23,35 +24,57 @@ internal static AIFunction Create(ToolConfiguration tool, AIAgent inner) { // The document names the function and describes it, because the calling model reads both to // decide when to delegate. Without a description it falls back to the inner agent's own. + // AsAIFunction is the schema donor only — the wrapper below runs the agent directly, so + // its name, description and parameters stay exactly what the model was built against. var function = inner.AsAIFunction(new AIFunctionFactoryOptions { Name = tool.Id, Description = tool.Description ?? inner.Description, }); - return tool.Parameters is { } parameters - ? new DeclaredSchemaFunction(function, parameters) - : function; + return new DeclaredSchemaFunction(function, tool.Parameters, tool.Id, inner); } /// - /// Advertises the parameters: the document declares, over a function that takes one string. + /// Advertises the parameters: the document declares, over a function that takes one + /// string — or the inner function as-is when the document declares none — and runs the + /// inner agent directly instead of the framework's delegation machinery, so the nested run + /// carries the turn on its own options like every other run. /// private sealed class DeclaredSchemaFunction : DelegatingAIFunction { private readonly JsonElement _schema; - private readonly string _argument; - internal DeclaredSchemaFunction(AIFunction inner, JsonNode parameters) + private readonly string? _argument; + + private readonly string _toolId; + + private readonly AIAgent _inner; + + internal DeclaredSchemaFunction(AIFunction inner, JsonNode? parameters, string toolId, AIAgent innerAgent) : base(inner) { - using var document = JsonDocument.Parse(parameters.ToJsonString()); - _schema = document.RootElement.Clone(); + ArgumentNullException.ThrowIfNull(toolId); - _argument = FirstProperty(inner.JsonSchema) ?? DefaultArgument; + _toolId = toolId; + _inner = innerAgent ?? throw new ArgumentNullException(nameof(innerAgent)); + + if (parameters is null) + { + _schema = inner.JsonSchema; + _argument = null; + } + else + { + using var document = JsonDocument.Parse(parameters.ToJsonString()); + + _schema = document.RootElement.Clone(); + _argument = FirstProperty(inner.JsonSchema) ?? DefaultArgument; + } } - public override JsonElement JsonSchema => _schema; + public override JsonElement JsonSchema + => _schema; protected override ValueTask InvokeCoreAsync( AIFunctionArguments arguments, @@ -59,21 +82,41 @@ internal DeclaredSchemaFunction(AIFunction inner, JsonNode parameters) { ArgumentNullException.ThrowIfNull(arguments); - var payload = ToolArgumentJson.ToJsonObject(arguments); + var parent = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var turn) && turn is TurnInvocation p + ? p + : null; - AIFunctionArguments forwarded = new(new Dictionary(StringComparer.Ordinal) - { - [_argument] = payload.ToJsonString(), - }) - { - Services = arguments.Services, - Context = arguments.Context, - }; + // Schemaless the donor advertises one query string; declared, the payload the + // document shaped. Either way the nested agent reads words, not arguments. + string query = _argument is null + && arguments.TryGetValue(DefaultArgument, out var bare) + && BareText(bare) is { } text + ? text + : ToolArgumentJson.ToJsonObject(arguments).ToJsonString(); + + // Decided here where the parent turn is in hand: the nested run neither latches + // the holder (K42) nor records, and only the run under this tool is offered its + // tools. Without a turn the nested run is bare, as before. + var nested = parent is not null + ? parent with { Clarifications = null, Nested = true } + : null; + + var offered = parent?.ToolsFor == _toolId ? parent?.Tools : null; - return InnerFunction.InvokeAsync(forwarded, cancellationToken); + return DelegatedAgentRun.RunAsync(_inner, query, nested, offered, cancellationToken); } - /// Reads the name of the first declared property of one JSON Schema object. + private static string? BareText(object? value) + => value switch + { + string text => text, + JsonElement { ValueKind: JsonValueKind.String } element => element.GetString(), + _ => null, + }; + + /// + /// Reads the name of the first declared property of one JSON Schema object. + /// private static string? FirstProperty(JsonElement schema) { if (schema.ValueKind is not JsonValueKind.Object @@ -90,5 +133,6 @@ internal DeclaredSchemaFunction(AIFunction inner, JsonNode parameters) return null; } + } } diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index 79b66c34..c1c3649e 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -38,7 +38,7 @@ 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 — CallScopedAgentFileStore + /// "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 /// how to use the tools, is unchanged. /// @@ -55,7 +55,9 @@ internal static class AgentHarnessProviders + "- To change part of a file, find the line numbers with `file_access_grep`, read the range around them\n" + " with `file_access_read_lines`, then edit with `file_access_replace_lines`. Reading the whole file\n" + " first is rarely necessary."; + #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. /// The provider list under construction. /// The agents.defaults section, or . @@ -110,6 +112,7 @@ public static void Add( } } #pragma warning restore MAAI001 + #pragma warning disable MAAI001 // The loop family is evaluation-only in Microsoft.Agents.AI 1.21.0. /// @@ -147,6 +150,7 @@ public static AIAgent ApplyLoop(AIAgent agent, AgentDefaults? defaults, AgentCon { var untilPointer = ConfigurationError.AppendPointer( ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "loop"), "until"), index); + var until = loop.Until[index]; if (until.Todos is not null) @@ -181,13 +185,15 @@ public static AIAgent ApplyLoop(AIAgent agent, AgentDefaults? defaults, AgentCon // Every iteration's text reaches the stream; there are no per-iteration entries (decision 14). return new LoopAgent(agent, evaluators, new LoopAgentOptions { MaxIterations = loop.MaxRounds }); } + #pragma warning restore MAAI001 +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. + /// /// The state keys of the harness providers among — never the /// history provider's key, which is the transcript and belongs to store 1. /// -#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. internal static IReadOnlySet StateKeysOf(IEnumerable providers) { HashSet keys = new(StringComparer.Ordinal); @@ -207,11 +213,15 @@ 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) + AgentConfiguration item, + string pointer, + Func resolve) { if (item.Background.Contains(item.Id, StringComparer.Ordinal)) { @@ -226,6 +236,7 @@ private static BackgroundAgentsProvider BuildBackgroundProvider( { var childPointer = ConfigurationError.AppendPointer( ConfigurationError.AppendPointer(pointer, "background"), index); + var childId = item.Background[index]; children.Add(resolve(childId) @@ -250,6 +261,7 @@ private static BackgroundAgentsProvider BuildBackgroundProvider( $"the agent '{item.Id}' declares background: children whose names collide: {exception.Message}"); } } + #pragma warning restore MAAI001 private static FileMemoryProvider BuildMemoryProvider( @@ -266,12 +278,14 @@ private static FileMemoryProvider BuildMemoryProvider( try { + #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. return new FileMemoryProvider( new FileSystemAgentFileStore(root), InitializeWorkingFolder, new FileMemoryProviderOptions { Instructions = MemoryInstructions }); #pragma warning restore MAAI001 + } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { @@ -287,8 +301,12 @@ private static FileMemoryProvider BuildMemoryProvider( } #pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. - private static FileAccessProvider BuildFilesProvider( - AgentConfiguration item, AgentFilesConfiguration files, AgentCompilationContext context, string pointer) + + private static CallFilesProvider BuildFilesProvider( + AgentConfiguration item, + AgentFilesConfiguration files, + AgentCompilationContext context, + string pointer) { if (context.WorkspaceRoot is null) { @@ -299,8 +317,8 @@ private static FileAccessProvider BuildFilesProvider( + "the folder, or remove the files: block."); } - return new FileAccessProvider( - new CallScopedAgentFileStore(), + return new CallFilesProvider( + context.WorkspaceRoot, new FileAccessProviderOptions { DisableWriteTools = !files.Write, @@ -309,10 +327,13 @@ private static FileAccessProvider BuildFilesProvider( Instructions = FilesInstructions, }); } + #pragma warning restore MAAI001 private static CallShellOptions BuildShellOptions( - AgentConfiguration item, ShellConfiguration shell, AgentCompilationContext context, string pointer) + AgentConfiguration item, + ShellConfiguration shell, + AgentCompilationContext context, string pointer) { if (context.WorkspaceRoot is null) { @@ -324,13 +345,16 @@ private static CallShellOptions BuildShellOptions( } 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) + 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 @@ -369,23 +393,25 @@ private static bool IsValidRegex(string pattern) } } +#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. + /// /// 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. /// -#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. private static FileMemoryState InitializeWorkingFolder(AgentSession? session) { - if (TurnAmbients.Current?.CallId is not { } callId) + if (TurnRegistry.For(session)?.CallId is not { } callId) { throw new InvalidOperationException( "A memory: block's FileMemoryProvider needs the running call's id, and no turn is " - + "open on this flow of execution. The provider's working folder is bound only while " + + "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."); } return new FileMemoryState { WorkingFolder = callId }; } + #pragma warning restore MAAI001 } diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index ed9e20ff..ceff6c2e 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -28,6 +28,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); if (toolErrors.Count == 0) @@ -218,6 +219,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar for (var index = 0; index < items.Count; index++) { var agent = items[index]; + AddUnknownModel( agent.Model, ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Pointer.Agent(index), "model"), "ref"), @@ -227,6 +229,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar for (var child = 0; child < agent.Background.Count; child++) { var childId = agent.Background[child]; + if (!names.Agents.Contains(childId)) { errors.Add(Reference( @@ -247,6 +250,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar 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( @@ -258,6 +262,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar { var transition = stage.To[exit]; var pointer = Pointer.Transition(index, exit); + if (!names.Stages.Contains(transition.Stage)) { errors.Add(Reference( @@ -299,6 +304,7 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar { var edge = graph.Edges[index]; var pointer = Pointer.Edge(index); + if (!names.Nodes.Contains(edge.From)) { errors.Add(Reference( @@ -386,6 +392,7 @@ private static void CheckSkillReferences( 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])) @@ -535,7 +542,7 @@ private static void CheckKnowledgeScopeSlots( } // A wildcard without fromState is a supported shape: the deployment resolves its own facets - // and opens them as the host ambient, which the store still widens. See + // 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) { @@ -879,10 +886,12 @@ private static void CheckExclusivity(AgentCoreConfiguration configuration, List< { 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(index, exit); + exits.Add(new SiblingExit( DescribeExit(transition.When, "exit", transition.Stage), transition.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"), @@ -915,6 +924,7 @@ private static void CheckExclusivity(AgentCoreConfiguration configuration, List< 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(pair.index); @@ -1024,6 +1034,7 @@ private static void CheckGraphWellFormedness(AgentCoreConfiguration configuratio var outgoing = new HashSet(StringComparer.Ordinal); var incoming = new HashSet(StringComparer.Ordinal); + foreach (var edge in graph.Edges) { outgoing.Add(edge.From); @@ -1080,10 +1091,12 @@ private static void CheckDelegationCycles(AgentCoreConfiguration configuration, // 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)) diff --git a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs index 4535de6b..0e40630a 100644 --- a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs +++ b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs @@ -10,14 +10,17 @@ namespace AgentCore.Application.Knowledge; /// internal sealed class FacetFilterProvider( AIContextProvider innerProvider, - IReadOnlyList facets) + IReadOnlyList? facets, + KnowledgeSearch.Core core) : AIContextProvider { private readonly AIContextProvider _inner = innerProvider ?? throw new ArgumentNullException(nameof(innerProvider)); - private readonly IReadOnlyList _facets = facets - ?? throw new ArgumentNullException(nameof(facets)); + private readonly IReadOnlyList? _facets = facets; + + private readonly KnowledgeSearch.Core _core = core + ?? throw new ArgumentNullException(nameof(core)); /// public override IReadOnlyList StateKeys => _inner.StateKeys; @@ -48,7 +51,7 @@ protected override async ValueTask InvokingCoreAsync( foreach (var tool in tools) { wrapped.Add(tool is AIFunction function - ? new FacetFilteredSearch(function, _facets) + ? new FacetFilteredSearch(function, _facets, _core) : tool); } diff --git a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs index a738efe5..73cbbafd 100644 --- a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs +++ b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs @@ -1,8 +1,10 @@ using System.Text.Json; using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime; using Microsoft.Extensions.AI; +using Microsoft.Agents.AI; namespace AgentCore.Application.Knowledge; @@ -11,24 +13,31 @@ namespace AgentCore.Application.Knowledge; /// internal sealed class FacetFilteredSearch : DelegatingAIFunction { - private readonly IReadOnlyList _facets; + private readonly IReadOnlyList? _facets; + + private readonly KnowledgeSearch.Core _core; private readonly JsonElement _schema; /// Wraps one search function. - /// The function the framework built. - /// What scope.filterable declared, in document order. + /// The function the framework built: the schema donor, never invoked. + /// What scope.filterable declared, in document order — or null when it declared none. + /// The search bound to this agent's store and wiring. /// A required argument is . internal FacetFilteredSearch( AIFunction innerFunction, - IReadOnlyList facets) + IReadOnlyList? facets, + KnowledgeSearch.Core core) : base(innerFunction) { ArgumentNullException.ThrowIfNull(innerFunction); - ArgumentNullException.ThrowIfNull(facets); + ArgumentNullException.ThrowIfNull(core); _facets = facets; - _schema = FacetFilterSchema.Extend(innerFunction.JsonSchema, facets); + _core = core; + _schema = facets is { Count: > 0 } + ? FacetFilterSchema.Extend(innerFunction.JsonSchema, facets) + : innerFunction.JsonSchema; } /// @@ -40,35 +49,55 @@ internal FacetFilteredSearch( { ArgumentNullException.ThrowIfNull(arguments); - var named = FacetFilterReader.Read(arguments, _facets); + var named = _facets is { Count: > 0 } + ? FacetFilterReader.Read(arguments, _facets) + : null; + + var turn = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var filed) && filed is TurnInvocation invocation + ? invocation + : null; + + // The donor's own declaration names the question: the model was built against it. + var question = FirstQueryArgument(InnerFunction.JsonSchema) is { } name + && arguments.TryGetValue(name, out var asked) + ? QueryText(asked) + : null; + + if (question is null) + { + throw new InvalidOperationException( + "The knowledge search was called without a search question, so there is nothing to look up."); + } - using var scope = named.Count > 0 ? ToolFacetScope.Open(named) : null; + IReadOnlyList results = + await _core(question, named?.Count > 0 ? named : null, turn, cancellationToken).ConfigureAwait(false); - return await base.InvokeCoreAsync(Forwarded(arguments), cancellationToken).ConfigureAwait(false); + return results; } - /// The arguments without the one this wrapper owns. - private static AIFunctionArguments Forwarded(AIFunctionArguments arguments) + /// Reads the donor's question argument name off its own schema. + private static string? FirstQueryArgument(JsonElement schema) { - if (!arguments.ContainsKey(FacetFilterSchema.ArgumentName)) + if (schema.ValueKind is not JsonValueKind.Object + || !schema.TryGetProperty("properties", out var properties) + || properties.ValueKind is not JsonValueKind.Object) { - return arguments; + return null; } - Dictionary kept = new(StringComparer.Ordinal); - - foreach (var (name, value) in arguments) + foreach (var property in properties.EnumerateObject()) { - if (!string.Equals(name, FacetFilterSchema.ArgumentName, StringComparison.Ordinal)) - { - kept[name] = value; - } + return property.Name; } - return new AIFunctionArguments(kept) + return null; + } + + private static string? QueryText(object? value) + => value switch { - Services = arguments.Services, - Context = arguments.Context, + string text => text, + JsonElement { ValueKind: JsonValueKind.String } element => element.GetString(), + _ => null, }; - } } diff --git a/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs new file mode 100644 index 00000000..2f7d6542 --- /dev/null +++ b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs @@ -0,0 +1,63 @@ +using Microsoft.Agents.AI; +using Microsoft.Extensions.Logging; +using AgentCore.Application.Runtime.Turn; + +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 +// 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. +internal sealed class KnowledgePrefetchProvider( + AIContextProvider template, + TextSearchProviderOptions options, + ILoggerFactory? loggers, + KnowledgeSearch.Core core) + : AIContextProvider +{ + private readonly AIContextProvider _template = template + ?? throw new ArgumentNullException(nameof(template)); + + private readonly TextSearchProviderOptions _options = options + ?? throw new ArgumentNullException(nameof(options)); + + private readonly ILoggerFactory? _loggers = loggers; + + private readonly KnowledgeSearch.Core _core = core + ?? throw new ArgumentNullException(nameof(core)); + + /// + public override IReadOnlyList StateKeys => _template.StateKeys; + + /// + public override object? GetService(Type serviceType, object? serviceKey = null) + { + ArgumentNullException.ThrowIfNull(serviceType); + + return serviceType.IsInstanceOfType(this) && serviceKey is null + ? this + : _template.GetService(serviceType, serviceKey); + } + + /// + protected override async ValueTask InvokingCoreAsync( + InvokingContext context, CancellationToken cancellationToken) + { + var turn = TurnRegistry.For(context.Session); + + AIContextProvider inner = new TextSearchProvider( + async (query, token) => + (IEnumerable)await _core(query, null, turn, token).ConfigureAwait(false), + _options, + _loggers); + + return await inner.InvokingAsync(context, cancellationToken).ConfigureAwait(false); + } + + /// + protected override ValueTask InvokedCoreAsync( + InvokedContext context, CancellationToken cancellationToken) + => _template.InvokedAsync(context, cancellationToken); +} diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs index 1827760a..41619bee 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs @@ -5,7 +5,6 @@ using AgentCore.Application.Diagnostics; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Knowledge; using Microsoft.Agents.AI; using Microsoft.Extensions.Logging; @@ -24,6 +23,8 @@ 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. + /// 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. @@ -33,12 +34,15 @@ internal static class KnowledgeProbe KnowledgeScope scope, string agent, string query, + Clarifications? clarifications, + bool carriesHistory, ILogger logger, CancellationToken cancellationToken) { - // K42: a nested tool call strips the holder from the ambient, so a delegated run's own search - // cannot latch, count or record — but a scoped run still owes the caller the notice. - if (TurnAmbients.Current?.Clarifications is not { } clarifications) + // 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)]; } @@ -84,28 +88,26 @@ 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 var deadline = - CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); + using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(ambiguity.ProbeDeadlineSeconds)); + + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); IReadOnlyList probeCards; + try { - using var narrowed = KnowledgeScopeScope.Open(WithoutFacet(scope, facet)); - + var narrowedScope = WithoutFacet(scope, facet); var started = Stopwatch.GetTimestamp(); - probeCards = await port.SearchAsync(query, deadline.Token).ConfigureAwait(false); + + probeCards = await port.SearchAsync(query, narrowedScope, deadline.Token).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Debug)) { - // Filed while the narrowed scope is still open, so the record names the scope this - // second store call actually ran under. Without it an operator sizing store load - // sees one record per turn for two calls. var record = KnowledgeSearchRecord.Of( agent, knowledge, query, + narrowedScope, probeCards, Stopwatch.GetElapsedTime(started).TotalMilliseconds, failure: null).ForLog(); @@ -132,7 +134,7 @@ internal static class KnowledgeProbe return Publish(probe, KnowledgeNotices.Empty); } - return Name(probeCards, template, ambiguity, wiring, wildcardValue, facet, agent, logger, clarifications, probe); + return Name(probeCards, template, ambiguity, wiring, wildcardValue, facet, agent, logger, clarifications, carriesHistory, probe); } finally { @@ -172,6 +174,7 @@ internal static class KnowledgeProbe string agent, ILogger logger, Clarifications clarifications, + bool carriesHistory, Clarifications.Probe probe) { // §8 step 5: the value at the facet's payload path is a string or a list of strings alike — @@ -202,11 +205,12 @@ internal static class KnowledgeProbe // message. var wouldName = Clarifications.LastNamed.For(union, 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. - var carriesHistory = TurnAmbients.Current?.Context?.CarriesHistory ?? false; + // out, but the record of what was named — which arms K21's tie-break — does not. The flag + // arrives as a parameter because the probe runs inside a search delegate that is never + // handed a session to compare. // 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 diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs index 79423574..b479e81a 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs @@ -1,11 +1,6 @@ -using System.Diagnostics; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Diagnostics; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; -using AgentCore.Application.State; -using AgentCore.Domain.Knowledge; using Microsoft.Agents.AI; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -17,11 +12,6 @@ namespace AgentCore.Application.Knowledge; /// internal static class KnowledgeProviderFactory { - /// - /// The scope an agent that declares scoped: false searches under. - /// - private static readonly KnowledgeScope WholeCorpus = - new() { Facets = new Dictionary(StringComparer.Ordinal) }; /// Builds the provider one agent binds. /// The store every agent shares. @@ -31,8 +21,8 @@ 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 no - /// ambient carries down here. + /// sink is not, because AuditEvent requires a call id and a sequence number that this + /// seam doesn't carry down here. /// /// The document's providers.knowledge.scope block, or . /// The provider to hang on that agent. @@ -65,156 +55,24 @@ internal static AIContextProvider Create( RecentMessageMemoryLimit = 4, }; - AIContextProvider provider = new TextSearchProvider(SearchAsync, options, loggers); + KnowledgeSearch.Core core = KnowledgeSearch.Bind(port, knowledge, agent, citations, logger); - return knowledge.Mode == KnowledgeMode.Tool && scope?.Filterable is { Count: > 0 } filterable - ? new FacetFilterProvider(provider, filterable) - : provider; + // The template's own delegate never runs: tool-mode searches go through the + // invocation-bound wrapper, prefetch through per-invocation providers. It fails + // loudly if either path ever leaks through. + AIContextProvider template = new TextSearchProvider(UnreachableSearch, options, loggers); - async Task> SearchAsync( - string query, CancellationToken cancellationToken) + if (knowledge.Mode != KnowledgeMode.Tool) { - // An ambient with no facets filters nothing, so it is the absent ambient 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. - if (knowledge.Scoped && KnowledgeScopeScope.Current is not { Facets.Count: > 0 }) - { - return [KnowledgeNotices.Of(KnowledgeNotices.NoScope)]; - } - - var composed = knowledge.Scoped ? KnowledgeScopeScope.Current! : WholeCorpus; - - var (narrowed, byTool) = ToolFacetOverlay.Apply(composed, ToolFacetScope.Current); - - var started = Stopwatch.GetTimestamp(); - - double? searched = null; - - try - { - var under = narrowed; - var (cards, latency) = await Under(narrowed).ConfigureAwait(false); - searched = latency; - - if (cards.Count == 0 && byTool) - { - under = composed; - (cards, _) = await Under(composed).ConfigureAwait(false); - } - - using var tail = KnowledgeScopeScope.Open(under); - - if (cards.Count == 0 - && knowledge.Mode == KnowledgeMode.Tool - && under.Facets.Count > 0) - { - return await KnowledgeProbe - .RunAsync(port, knowledge, under, agent, query, logger, cancellationToken) - .ConfigureAwait(false); - } - - var shown = Kept(cards, knowledge); - Cite(shown, knowledge, citations); - - return Map(shown, knowledge, citations); - } - catch (Exception failure) when (!KnowledgeCancellation.ByCaller(failure, cancellationToken)) - { - var latency = searched ?? Stopwatch.GetElapsedTime(started).TotalMilliseconds; - var record = KnowledgeSearchRecord - .Of(agent, knowledge, query, [], latency, failure) - .ForLog(); - - Log.KnowledgeRetrievalFailed(logger, agent, record, failure); - - return [KnowledgeNotices.Of(KnowledgeNotices.Unreachable)]; - } - - async Task<(IReadOnlyList Cards, double LatencyMs)> Under(KnowledgeScope open) - { - using var held = KnowledgeScopeScope.Open(open); - - var cards = await port.SearchAsync(query, cancellationToken).ConfigureAwait(false); - - var latency = Stopwatch.GetElapsedTime(started).TotalMilliseconds; - - if (logger.IsEnabled(LogLevel.Debug)) - { - var record = KnowledgeSearchRecord - .Of(agent, knowledge, query, cards, latency, failure: null) - .ForLog(); - - Log.KnowledgeRetrieved(logger, agent, cards.Count, record); - } - - return (cards, latency); - } + return new KnowledgePrefetchProvider(template, options, loggers, core); } - } - /// Cites what this search read, for the caller's screen. - /// The cards the agent is actually shown, after cuts the search down to the agent's limit: — not everything the store returned. - /// The agent's resolved knowledge: block. - /// The wording providers.knowledge.citation named. - private static void Cite( - IReadOnlyList cards, - ResolvedKnowledge knowledge, - IKnowledgeCitationFormatter citations) - { - if (!knowledge.Citations || CallSourceScope.Current is not { } port) - { - return; - } - - foreach (var card in cards) - { - if (KnowledgeSourceMapper.ToSource(card, citations) is { } source) - { - port.Publish(source); - } - } - } - - /// Cuts one search down to the agent's limit:. - /// What the store returned, best first, links last. - /// The agent's resolved knowledge: block. - /// The cards this agent is shown. - private static List Kept(IReadOnlyList cards, ResolvedKnowledge knowledge) - { - List kept = []; - var ranked = 0; - - foreach (var card in cards) - { - if (!card.ViaLink && ranked++ >= knowledge.Limit) - { - continue; - } - - kept.Add(card); - } - - return kept; + return new FacetFilterProvider(template, scope?.Filterable, core); } - /// Maps the cards this agent is shown into what the framework injects. - /// The cards already cut down to the agent's limit:. - /// The agent's resolved knowledge: block. - /// The wording each card's source label is written in. - /// The results the framework injects. - private static List Map( - IReadOnlyList cards, - ResolvedKnowledge knowledge, - IKnowledgeCitationFormatter citations) - { - List mapped = []; - - foreach (var card in cards) - { - mapped.Add(KnowledgeCardMapper.ToResult(card, knowledge.Citations, citations)); - } - - return mapped; - } + private static Task> UnreachableSearch( + string query, CancellationToken cancellationToken) + => Task.FromException>( + new InvalidOperationException( + "A knowledge search ran outside its turn. Searches run through the turn's own provider or tool.")); } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs b/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs new file mode 100644 index 00000000..4d4f66a5 --- /dev/null +++ b/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs @@ -0,0 +1,205 @@ +using System.Diagnostics; +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Diagnostics; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; +using AgentCore.Domain.Knowledge; +using Microsoft.Agents.AI; +using Microsoft.Extensions.Logging; + +namespace AgentCore.Application.Knowledge; + +// One search against the store with everything the turn hands it, as explicit values: the +// scope to read under, the tool-call facets to overlay, and the turn's own probe, history +// flag and citation port. The framework invokes the search in two shapes — a tool call +// carrying arguments, and a prefetch carrying only a session — and both bind those shapes +// to these values before calling here, so this core never reads the flow. +internal static class KnowledgeSearch +{ + /// Searches with an explicit scope, facets and turn. + internal delegate Task> Core( + string query, + IReadOnlyDictionary? facets, + TurnInvocation? turn, + CancellationToken cancellationToken); + + /// The scope an agent that declares scoped: false searches under. + internal static readonly KnowledgeScope WholeCorpus = + 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) + { + 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); + } + + private static async Task> RunAsync( + IKnowledgeRetrievalPort port, + ResolvedKnowledge knowledge, + string agent, + string query, + IReadOnlyDictionary? facets, + TurnInvocation? turn, + IKnowledgeCitationFormatter citations, + ILogger logger, + CancellationToken cancellationToken) + { + // 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 + // turn — a framework-driven sub-run (graph node, background child) the loop never + // invoked — searches the whole corpus unscoped and names NoScope scoped: loud, never + // a leak. + var composed = knowledge.Scoped ? turn?.Knowledge : WholeCorpus; + + if (knowledge.Scoped && composed is not { Facets.Count: > 0 }) + { + return [KnowledgeNotices.Of(KnowledgeNotices.NoScope)]; + } + + var scope = composed ?? WholeCorpus; + + var (narrowed, byTool) = ToolFacetOverlay.Apply(scope, facets); + + var started = Stopwatch.GetTimestamp(); + + double? searched = null; + var under = narrowed; + + try + { + var (cards, latency) = await Under(narrowed).ConfigureAwait(false); + searched = latency; + + if (cards.Count == 0 && byTool) + { + under = scope; + (cards, _) = await Under(scope).ConfigureAwait(false); + } + + if (cards.Count == 0 + && knowledge.Mode == KnowledgeMode.Tool + && under.Facets.Count > 0) + { + return await KnowledgeProbe + .RunAsync(port, knowledge, under, agent, query, turn?.Clarifications, turn?.CarriesHistory ?? false, logger, cancellationToken) + .ConfigureAwait(false); + } + + var shown = Kept(cards, knowledge); + Cite(shown, knowledge, citations, turn?.Sources); + + return Map(shown, knowledge, citations); + } + catch (Exception failure) when (!KnowledgeCancellation.ByCaller(failure, cancellationToken)) + { + var latency = searched ?? Stopwatch.GetElapsedTime(started).TotalMilliseconds; + var record = KnowledgeSearchRecord + .Of(agent, knowledge, query, under, [], latency, failure) + .ForLog(); + + Log.KnowledgeRetrievalFailed(logger, agent, record, failure); + + return [KnowledgeNotices.Of(KnowledgeNotices.Unreachable)]; + } + + async Task<(IReadOnlyList Cards, double LatencyMs)> Under(KnowledgeScope open) + { + var cards = await port.SearchAsync(query, open, cancellationToken).ConfigureAwait(false); + + var latency = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + + if (logger.IsEnabled(LogLevel.Debug)) + { + var record = KnowledgeSearchRecord + .Of(agent, knowledge, query, open, cards, latency, failure: null) + .ForLog(); + + Log.KnowledgeRetrieved(logger, agent, cards.Count, record); + } + + return (cards, latency); + } + } + + /// Cuts one search down to the agent's limit:. + /// What the store returned, best first, links last. + /// The agent's resolved knowledge: block. + /// The cards this agent is shown. + private static List Kept(IReadOnlyList cards, ResolvedKnowledge knowledge) + { + List kept = []; + var ranked = 0; + + foreach (var card in cards) + { + if (!card.ViaLink && ranked++ >= knowledge.Limit) + { + continue; + } + + kept.Add(card); + } + + return kept; + } + + /// Cites what this search read, for the caller's screen. + /// The cards the agent is actually shown, after cuts the search down to the agent's limit: — not everything the store returned. + /// The agent's resolved knowledge: block. + /// The wording providers.knowledge.citation named. + /// What the turn cites into, or outside a turn. + private static void Cite( + IReadOnlyList cards, + ResolvedKnowledge knowledge, + IKnowledgeCitationFormatter citations, + TurnSources? port) + { + if (!knowledge.Citations || port is null) + { + return; + } + + foreach (var card in cards) + { + if (KnowledgeSourceMapper.ToSource(card, citations) is { } source) + { + port.Publish(source); + } + } + } + + /// Maps the cards this agent is shown into what the framework injects. + /// The cards already cut down to the agent's limit:. + /// The agent's resolved knowledge: block. + /// The wording each card's source label is written in. + /// The results the framework injects. + private static List Map( + IReadOnlyList cards, + ResolvedKnowledge knowledge, + IKnowledgeCitationFormatter citations) + { + List mapped = []; + + foreach (var card in cards) + { + mapped.Add(KnowledgeCardMapper.ToResult(card, knowledge.Citations, citations)); + } + + return mapped; + } +} diff --git a/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs index f1bc3f14..14b177ed 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs @@ -1,5 +1,4 @@ using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Runtime; using AgentCore.Domain.Knowledge; namespace AgentCore.Application.Knowledge; @@ -13,19 +12,16 @@ internal static class KnowledgeSearchRecord /// The id of the agent that asked. /// The agent's resolved knowledge: block. /// The search text the framework composed. + /// The scope the store call ran under. /// What the store returned, or empty when it threw. /// How long that one store call took, in milliseconds. /// What the port threw, or when it answered. /// The record. - /// - /// The scope comes from the live ambient, so a caller has to build this while the scope the call - /// ran under is still open. The probe's second search opens a narrowed scope of its own, and its - /// record is meant to name that one rather than the scope the main search used. - /// internal static KnowledgeAuditRecord Of( string agent, ResolvedKnowledge knowledge, string query, + KnowledgeScope? scope, IReadOnlyList cards, double latencyMs, Exception? failure) @@ -34,7 +30,7 @@ internal static KnowledgeAuditRecord Of( agent, knowledge.Mode, query, - KnowledgeScopeScope.Current, + scope, cards, latencyMs, failure); diff --git a/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs b/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs index d4ea3092..1d689d66 100644 --- a/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs +++ b/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs @@ -10,13 +10,13 @@ namespace AgentCore.Application.Knowledge; /// internal static class StateKnowledgeScope { - /// Composes the turn's scope from the host's ambient and the call's state. + /// 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. /// The document's providers.knowledge.scope block, or null. - /// What the host opened for this turn, or null when it opened nothing. - /// The scope, or unchanged when this document composes none. + /// What the host set for this call, or null when it set nothing. + /// The scope, or unchanged when this document composes none. internal static KnowledgeScope? Compose( - StateDocument state, KnowledgeScopeConfiguration? scope, KnowledgeScope? ambient) + StateDocument state, KnowledgeScopeConfiguration? scope, KnowledgeScope? hostScope) { ArgumentNullException.ThrowIfNull(state); @@ -26,15 +26,15 @@ internal static class StateKnowledgeScope // scope — including its absence, which still fails closed — is what the turn sees. if (scope?.Wildcard is not { } wildcard || scope.FromState.Count == 0) { - return ambient; + return hostScope; } Dictionary facets = new(StringComparer.Ordinal); Dictionary origins = new(StringComparer.Ordinal); - if (ambient is not null) + if (hostScope is not null) { - foreach (var (key, value) in ambient.Facets) + foreach (var (key, value) in hostScope.Facets) { facets[key] = value; origins[key] = KnowledgeFacetOrigin.Host; diff --git a/src/AgentCore.Application/Knowledge/ToolFacetScope.cs b/src/AgentCore.Application/Knowledge/ToolFacetScope.cs deleted file mode 100644 index d46fa58e..00000000 --- a/src/AgentCore.Application/Knowledge/ToolFacetScope.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace AgentCore.Application.Knowledge; - -/// -/// Carries the facets a search tool's argument named down to the search itself. -/// -internal static class ToolFacetScope -{ - private static readonly AsyncLocal?> Named = new(); - - /// Gets what a tool argument named on this flow, or when none did. - internal static IReadOnlyDictionary? Current => Named.Value; - - /// Opens one set of named facets over this flow. - /// The facet key to stored value. - /// A handle that puts back what was open before. - /// is . - internal static IDisposable Open(IReadOnlyDictionary facets) - { - ArgumentNullException.ThrowIfNull(facets); - - var before = Named.Value; - Named.Value = facets; - - return new Handle(before); - } - - private sealed class Handle(IReadOnlyDictionary? before) : IDisposable - { - private bool _closed; - - public void Dispose() - { - if (_closed) - { - return; - } - - _closed = true; - Named.Value = before; - } - } -} diff --git a/src/AgentCore.Application/Ports/IConversationPort.cs b/src/AgentCore.Application/Ports/IConversationPort.cs index 2cc2afa7..8f6fbd09 100644 --- a/src/AgentCore.Application/Ports/IConversationPort.cs +++ b/src/AgentCore.Application/Ports/IConversationPort.cs @@ -1,4 +1,5 @@ using AgentCore.Domain; +using AgentCore.Domain.Knowledge; using Microsoft.Extensions.AI; namespace AgentCore.Application.Ports; @@ -6,30 +7,6 @@ namespace AgentCore.Application.Ports; /// /// The inbound seam of one call: start or continue a turn, stream the reply, cancel it. /// -/// -/// -/// Decision D4 puts one inbound port in front of the turn loop, and section 7 names it. Two adapters -/// drive it. The Telnyx Conversation Relay shim drives it first, and the -/// /v1/chat/completions SSE endpoint drives it second. Both read the same contract, so D8 -/// holds: the core never learns a vendor frame schema. -/// -/// -/// The relay frames themselves stay in the adapter. RelayFrame and RelayToken of -/// section 7.1 are a wire format, and nothing of that shape appears here. The shim reads a -/// prompt frame and calls ; it reads an interrupt -/// frame and calls ; it writes each update back as one RelayToken. -/// -/// -/// Cancelling has two shapes, because the two adapters mean different things by it. The SSE endpoint -/// cancels with the token when the client disconnects, and the turn simply stops. The relay cancels -/// with when the caller speaks over the reply, and the turn ends with a -/// record of what the caller heard. A token carries no record, so barge-in needs its own call. -/// -/// -/// One port serves one call, and one call runs one turn at a time. A second turn started while one -/// runs throws rather than corrupting the state of the call. -/// -/// public interface IConversationPort { /// Gets the id of the call. @@ -41,6 +18,10 @@ public interface IConversationPort /// Gets whether the call 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. + KnowledgeScope? Scope { get; set; } + /// Gets the turn that finished last, or before the first turn ends. TurnResult? LastTurn { get; } diff --git a/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs b/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs index 10b3c043..ef8988c1 100644 --- a/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs +++ b/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs @@ -16,9 +16,11 @@ public interface IKnowledgeRetrievalPort /// Finds the cards that answer one query. /// What the caller asked, in their own words. /// Cancels the search. + /// What the caller may see, or when the caller is unscoped. /// The cards, best first. It is empty when nothing clears the score floor. ValueTask> SearchAsync( string query, + KnowledgeScope? scope = null, CancellationToken cancellationToken = default); /// Asks this store for a capability it may also serve. diff --git a/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs b/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs index 67ef2d4e..c66821f2 100644 --- a/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs +++ b/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs @@ -24,8 +24,8 @@ public interface IKnowledgeStoreAdapter : IVendorAdapter /// /// /// Whether every agent reading this store declares scoped: true. The store is shared - /// across every agent that reads it, so an adapter that fails closed with no ambient - /// KnowledgeScope open is only correct when ALL of them want scoping -- one store cannot + /// across every agent that reads it, so an adapter that fails closed with no + /// KnowledgeScope passed is only correct when ALL of them want scoping -- one store cannot /// enforce a scope for one agent while staying open for another. A mixed deployment passes /// here, and the per-agent gate then lives in the caller instead of the /// store. diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index d49ba3c7..6fdff2d0 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -1127,6 +1127,8 @@ AgentCore.Application.Ports.IConversationPort.RunTurnAsync(string! userInput, Sy AgentCore.Application.Ports.IConversationPort.RunTurnMessageAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! AgentCore.Application.Ports.IConversationPort.RunTurnMessageStreamingAsync(Microsoft.Extensions.AI.ChatMessage! userInput, System.Threading.CancellationToken cancellationToken) -> System.Collections.Generic.IAsyncEnumerable! AgentCore.Application.Ports.IConversationPort.RunTurnStreamingAsync(string! userInput, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! +AgentCore.Application.Ports.IConversationPort.Scope.get -> AgentCore.Domain.Knowledge.KnowledgeScope? +AgentCore.Application.Ports.IConversationPort.Scope.set -> void AgentCore.Application.Ports.IConversationPort.Stage.get -> string! AgentCore.Application.Ports.IEmbeddingGeneratorAdapter AgentCore.Application.Ports.IEmbeddingGeneratorAdapter.CreateGeneratorAsync(AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!>!> @@ -1136,7 +1138,7 @@ AgentCore.Application.Ports.IKnowledgeFacetReadPort AgentCore.Application.Ports.IKnowledgeFacetReadPort.ReadByFacetAsync(string! path, string! value, int limit, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Ports.IKnowledgeRetrievalPort AgentCore.Application.Ports.IKnowledgeRetrievalPort.GetService(System.Type! serviceType, object? serviceKey = null) -> object? -AgentCore.Application.Ports.IKnowledgeRetrievalPort.SearchAsync(string! query, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> +AgentCore.Application.Ports.IKnowledgeRetrievalPort.SearchAsync(string! query, AgentCore.Domain.Knowledge.KnowledgeScope? scope = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Ports.IKnowledgeStoreAdapter AgentCore.Application.Ports.IKnowledgeStoreAdapter.CanScope.get -> bool AgentCore.Application.Ports.IKnowledgeStoreAdapter.CanServeSearch.get -> bool @@ -1211,7 +1213,6 @@ AgentCore.Application.Runtime.CallEventKind.TranscriptWriteFailed = 10 -> AgentC 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.CallRenderScope AgentCore.Application.Runtime.CallSession AgentCore.Application.Runtime.CallSession.CallId.get -> string! AgentCore.Application.Runtime.CallSession.Compiled.get -> AgentCore.Application.Configuration.Compilation.CompiledAgent! @@ -1230,6 +1231,8 @@ AgentCore.Application.Runtime.CallSession.RunTurnMessageStreamingAsync(Microsoft 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! @@ -1240,7 +1243,6 @@ 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.CallSourceScope AgentCore.Application.Runtime.CallStateScope AgentCore.Application.Runtime.CallTurnOrigin AgentCore.Application.Runtime.CallTurnOrigin.$() -> AgentCore.Application.Runtime.CallTurnOrigin! @@ -1253,7 +1255,6 @@ 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.KnowledgeScopeScope AgentCore.Application.Secrets.KnownSecrets AgentCore.Application.Secrets.ResolvedSecrets AgentCore.Application.Secrets.ResolvedSecrets.Contains(string! name) -> bool @@ -1983,15 +1984,11 @@ static AgentCore.Application.Providers.VendorSeam.operator ==(AgentCore.Applicat 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.CallRenderScope.Current.get -> AgentCore.Application.Ports.IRenderPort? 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.CallSourceScope.Current.get -> AgentCore.Application.Ports.ISourcePort? static AgentCore.Application.Runtime.CallStateScope.Enter(AgentCore.Application.State.StateDocument! state) -> System.IDisposable! static AgentCore.Application.Runtime.CallStateScope.Snapshot() -> System.Collections.Generic.IReadOnlyDictionary! 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.KnowledgeScopeScope.Current.get -> AgentCore.Domain.Knowledge.KnowledgeScope? -static AgentCore.Application.Runtime.KnowledgeScopeScope.Open(AgentCore.Domain.Knowledge.KnowledgeScope! scope) -> System.IDisposable! static AgentCore.Application.Secrets.ResolvedSecrets.Create(System.Collections.Generic.IEnumerable>! secrets) -> AgentCore.Application.Secrets.ResolvedSecrets! static AgentCore.Application.Secrets.ResolvedSecrets.Empty.get -> AgentCore.Application.Secrets.ResolvedSecrets! static AgentCore.Application.Secrets.ResolvedSecrets.ResolveAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort! resolver, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs index bc5892c0..9bbc4e76 100644 --- a/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs +++ b/src/AgentCore.Application/Runtime/AuditingFunctionInvokingChatClient.cs @@ -1,12 +1,30 @@ using System.Net.Sockets; using System.Security.Authentication; -using AgentCore.Application.Runtime.Turn; -using AgentCore.Application.Tools; using AgentCore.Domain.Audit; +using AgentCore.Application.Tools; using Microsoft.Extensions.AI; +using System.Collections.Concurrent; +using AgentCore.Application.Runtime.Turn; namespace AgentCore.Application.Runtime; +/// One tool call that did not run to completion, as the function-invocation loop saw it. +internal sealed record ToolFailure +{ + /// Gets the name the MODEL called. + + public required string ToolName { get; init; } + + /// Gets the id the model gave this one call. + public required string ToolCallId { get; init; } + + /// Gets which of the two ways a tool call fails this one was. + public required ToolFailureKind Kind { get; init; } + + /// Gets what went wrong, in one sentence. It never holds a secret value. + public required string Message { get; init; } +} + /// /// The function-invocation loop of Microsoft.Extensions.AI, with every tool call that did not /// run to completion reported to the call that made it, and the tool error policy applied to every @@ -14,6 +32,14 @@ namespace AgentCore.Application.Runtime; /// internal sealed class AuditingFunctionInvokingChatClient : FunctionInvokingChatClient { + // Drain state per open tool call, keyed by the model's own call id. The round that ends a + // turn never reaches CreateResponseMessages, so a final round's entries are swept at turn + // end through Release; every other entry is consumed where it drains. + private readonly ConcurrentDictionary _drains = new(StringComparer.Ordinal); + + private sealed record Drain( + TurnRenders? Renders, TurnSources? Sources, Action? OnToolFailure, bool Nested); + /// Creates the client. /// The model this loop sends its rounds to. internal AuditingFunctionInvokingChatClient(IChatClient innerClient) @@ -21,6 +47,18 @@ internal AuditingFunctionInvokingChatClient(IChatClient innerClient) { } + /// Drops drain state for calls whose round never drained, at turn end. + /// Every tool call id the turn recorded. + internal void Release(IReadOnlyList callIds) + { + ArgumentNullException.ThrowIfNull(callIds); + + foreach (var callId in callIds) + { + _drains.TryRemove(callId, out _); + } + } + /// /// Runs one tool, turns a fault the model can answer into the error result it reads, and reports /// and rethrows a fault beyond the model. @@ -31,14 +69,38 @@ internal AuditingFunctionInvokingChatClient(IChatClient innerClient) { ArgumentNullException.ThrowIfNull(context); - using var outerCall = OuterToolCall.Enter(context.CallContent.CallId, out var nested); + var callId = context.CallContent.CallId; + + // The turn arrives on the run's own options — filed there by the loop for the outer + // run and by the delegating bridge for a nested one, one value per run, so concurrent + // runs never share it. A call with no turn runs bare, exactly as the null branch did + // before. Nested runs arrive already stripped per K42 with the outermost call id kept, + // so nothing here recomputes either. + TurnInvocation? invocation = null; + bool nested = false; + + if (context.Options?.AdditionalProperties?.TryGetValue(TurnInvocation.ArgumentsKey, out var top) == true + && top is TurnInvocation own) + { + invocation = own with { OuterCallId = own.OuterCallId ?? callId }; + nested = own.Nested; + } - // A delegated run must not touch the caller's Clarifications: it would burn the turn's probe - // and record a lastNamed from a note the caller never heard (K42). The knowledge search - // itself is a tool call, so the strip is conditional on being nested rather than unconditional - // — an unconditional strip would blind the caller's own search too. - using IDisposable? strippedClarifications = nested - ? TurnAmbients.Amend(ambients => ambients with { Clarifications = null }) + if (invocation is not null) + { + // 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); + 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; try @@ -47,7 +109,7 @@ internal AuditingFunctionInvokingChatClient(IChatClient innerClient) if (!nested) { - TurnAmbients.Current?.Results?.Record(context.Function.Name, result); + invocation?.Results?.Record(context.Function.Name, result); } return result; @@ -59,7 +121,7 @@ internal AuditingFunctionInvokingChatClient(IChatClient innerClient) } catch (Exception failure) when (!IsCallerCancellation(failure, cancellationToken)) { - ToolFailureScope.Report(new ToolFailure + invocation?.OnToolFailure?.Invoke(new ToolFailure { ToolName = context.CallContent.Name, ToolCallId = context.CallContent.CallId, @@ -69,6 +131,13 @@ internal AuditingFunctionInvokingChatClient(IChatClient innerClient) 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. @@ -114,46 +183,8 @@ private static bool IsCallerCancellation(Exception failure, CancellationToken ca /// protected override IList CreateResponseMessages(ReadOnlySpan results) { - foreach (FunctionInvocationResult result in results) - { - // Only NotFound. An exception was already reported where it was thrown, and the round - // that ends the turn never reaches this method at all. See the remarks on this class. - if (result.Status != FunctionInvocationStatus.NotFound) - { - continue; - } - - ToolFailureScope.Report(new ToolFailure - { - ToolName = result.CallContent.Name, - ToolCallId = result.CallContent.CallId, - Kind = ToolFailureKind.Undeclared, - Message = $"the model called '{result.CallContent.Name}', and no such tool is declared.", - }); - } - var messages = base.CreateResponseMessages(results); - // A nested loop's own InvokeFunctionAsync opens a no-op OuterToolCall scope (outermost - // wins), so the outer scope is still open for every round the nested loop runs, and only - // closes once the outer call that started it returns. A non-null Current here therefore - // means this round belongs to that nested loop, not to the call the caller's own transcript - // holds: draining here risks a nested tool call whose id happens to match the outer one, - // which would attach the drawing to a message that never reaches the caller. Only the round - // that runs with no OuterToolCall scope left open — the outermost loop's own — may drain. - if (OuterToolCall.Current is not null) - { - return messages; - } - - var renders = TurnAmbients.Current?.Renders; - var sources = TurnAmbients.Current?.Sources; - - if (renders is null && sources is null) - { - return messages; - } - foreach (var message in messages) { // Materialised before the loop below adds to the very list this reads: Contents is a @@ -161,14 +192,21 @@ protected override IList CreateResponseMessages(ReadOnlySpan().Select(r => r.CallId).ToList()) { - foreach (var drawn in renders?.TakeFor(callId) ?? []) - { - message.Contents.Add(drawn); - } - - foreach (var cited in sources?.TakeFor(callId) ?? []) + // 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) { - message.Contents.Add(cited); + foreach (var drawn in drain.Renders?.TakeFor(callId) ?? []) + { + message.Contents.Add(drawn); + } + + foreach (var cited in drain.Sources?.TakeFor(callId) ?? []) + { + message.Contents.Add(cited); + } } } } diff --git a/src/AgentCore.Application/Runtime/CallRenderScope.cs b/src/AgentCore.Application/Runtime/CallRenderScope.cs deleted file mode 100644 index ddf7fae3..00000000 --- a/src/AgentCore.Application/Runtime/CallRenderScope.cs +++ /dev/null @@ -1,13 +0,0 @@ -using AgentCore.Application.Ports; -using AgentCore.Application.Runtime.Turn; - -namespace AgentCore.Application.Runtime; - -/// -/// The screen of the call that runs on this flow of execution. -/// -public static class CallRenderScope -{ - /// The screen of the call that runs now, or when it has none. - public static IRenderPort? Current => TurnAmbients.Current?.Screen; -} diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index e99ae94b..ae395d04 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -1,23 +1,17 @@ -using System.Diagnostics; -using System.Globalization; using System.Runtime.CompilerServices; using System.Text.Json; using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Diagnostics; -using AgentCore.Application.Knowledge; using AgentCore.Application.Policy; using AgentCore.Application.Ports; using AgentCore.Application.Runtime.Harness; -using AgentCore.Application.Runtime.Turn; using AgentCore.Application.State; -using AgentCore.Application.Tools; using AgentCore.Application.Transcript; using AgentCore.Domain; -using AgentCore.Domain.Audit; using AgentCore.Domain.Knowledge; +using AgentCore.Domain.Audit; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; using Microsoft.Extensions.Logging; @@ -63,7 +57,7 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable /// /// How long the work after the reply may take before it is abandoned. /// - private static readonly TimeSpan TurnCompletionTimeout = TimeSpan.FromSeconds(5); + internal static readonly TimeSpan TurnCompletionTimeout = TimeSpan.FromSeconds(5); private readonly CompiledAgent _compiled; @@ -104,12 +98,10 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private CancellationTokenSource? _runCancellation; - private Interruption? _interruption; + private CallInterruptionTracker.Interruption? _interruption; private Guid? _amendableEventId; - private int _running; - private CallSessionState? _checkpoint; private readonly Clarifications _clarifications = new(); @@ -118,23 +110,64 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private readonly CallShells? _shells; - // The background release runs once per call: both DisposeAsync and the turn-end path below - // reach it, and a second release would re-cancel children that already went away. - private int _backgroundReleased; + // 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 + // moved, so every commit protocol is byte-identical to the single-file shape. + internal StagePolicy? Policy => _policy; + + internal StateExtractor? Extractor => _extractor; + + internal CounterStateWriter Counters => _counters; + + internal TimeProvider Time => _time; + + internal CallEventChain Events => _events; + + internal DateTimeOffset StartedAt => _startedAt; + + internal AgentCoreChatHistoryProvider History => _history; + + internal bool SessionCarriesHistory => _sessionCarriesHistory; + + internal ILogger Logger => _logger; + + internal Lock InterruptLock => _interruptLock; + + internal CallShells? Shells => _shells; + + internal CallWorkspace? WorkspaceRoot => _workspace; + + internal AgentSession? AgentSession { get => _agentSession; set => _agentSession = value; } + + internal AgentSession? GraphSession { get => _graphSession; set => _graphSession = value; } + + internal JsonElement? GraphBlob { get => _graphBlob; set => _graphBlob = value; } + + internal CancellationTokenSource? RunCancellation { get => _runCancellation; set => _runCancellation = value; } + + internal CallInterruptionTracker.Interruption? Interruption { get => _interruption; set => _interruption = value; } + + internal Guid? AmendableEventId { get => _amendableEventId; set => _amendableEventId = value; } + + internal CallSessionState? Checkpoint { get => _checkpoint; set => _checkpoint = value; } + + internal Clarifications Clarifications => _clarifications; - // Whether the running turn has already handed the host something to speak. One rule for both - // run shapes: a run that has handed the host nothing cannot be the turn the caller was hearing, - // so a barge-in in that window belongs to the turn that finished before it. A streaming turn - // raises this at its first piece of content; a turn that never streams hands the host nothing - // until it returns, so it never raises it and is never cut in flight. It is dropped twice: - // once in CompleteTurnAsync's commit lock, the moment the turn's own record exists for a late - // barge-in to amend, and again in EndRun, which is the only clear a turn that never reached - // that commit gets. - private volatile bool _runIsAudible; + internal CallTurnRunner Runner { get; } - private (string ToolId, IReadOnlyList Tools)? _delegatedTools; + internal CallTurnStream Stream { get; } - private bool _hasScreen; + internal CallTurnCompletion Completion { get; } + + internal CallTurnWriters Writers { get; } + + internal CallInterruptionTracker Interruptions { get; } + + internal CallTranscriptLedger Ledger { get; } + + internal CallSessionStateStore States { get; } + + internal CallSessionLifetime Lifetime { get; } /// /// Creates the session of one call. @@ -202,6 +235,15 @@ internal CallSession( // spoken to, and then ended through EndCall write a call.ended with no call.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); } /// @@ -223,52 +265,57 @@ internal CallSession( /// /// Gets whether the call reached a terminal stage. A document with no policy never does. /// - public bool IsComplete { get; private set; } + public bool IsComplete { get; internal set; } /// /// Gets the state of this call. 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 + /// 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. /// public IReadOnlyList Transcript - => Session() is { } session ? _history.Read(session) : []; + => Ledger.Session() is { } session ? _history.Read(session) : []; /// /// Gets the turn that finished last, or before the first turn ends. /// - public TurnResult? LastTurn { get; private set; } + public TurnResult? LastTurn { get; internal set; } /// /// Gets the name the last written message was stored under, for a caller to hang an edit off. /// - public string? LastReplyMessageId { get; private set; } + public string? LastReplyMessageId { get; internal set; } /// /// Gets the compiled agent this session runs. Every call shares it. /// public CompiledAgent Compiled => _compiled; + /// + /// Whether this call 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. /// - /// The kind: agent tool whose delegated runs are offered these. - /// The tools. An empty list offers nothing, exactly as never calling this does. - /// An argument is . public void SetDelegatedTools(string delegatingToolId, IReadOnlyList tools) - { - ArgumentNullException.ThrowIfNull(delegatingToolId); - ArgumentNullException.ThrowIfNull(tools); - - _delegatedTools = (delegatingToolId, tools); - } + => Runner.SetDelegatedTools(delegatingToolId, tools); /// /// Gives this call the screen its tools draw on, or takes it away. /// - public void SetHasScreen(bool hasScreen) => _hasScreen = hasScreen; + public void SetHasScreen(bool hasScreen) => Runner.SetHasScreen(hasScreen); /// /// Runs one turn end to end, and returns what it did. @@ -279,105 +326,33 @@ public Task RunTurnAsync(string userInput, CancellationToken cancell /// /// Runs one turn end to end from a message the caller built, and returns what it did. /// - /// What the caller said or answered: words, an approval answer, or both. - /// Cancels the turn. public Task RunTurnMessageAsync(ChatMessage userInput, CancellationToken cancellationToken) => RunTurnMessageAtOriginAsync(userInput, origin: null, cancellationToken); /// /// Runs one turn that knows where it sits in the conversation the caller can see. /// - /// What the caller said. - /// - /// Where these words hang, or for a caller that does not track its - /// messages by name. See : supplying it is what lets a caller send an - /// earlier message again and have the answers to the old one withdrawn. - /// - /// Cancels the turn. - public async Task RunTurnAtOriginAsync( + public Task RunTurnAtOriginAsync( string userInput, CallTurnOrigin? origin, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(userInput); - return await RunTurnCoreAsync(new ChatMessage(ChatRole.User, userInput), origin, cancellationToken) - .ConfigureAwait(false); + return Runner.RunTurnCoreAsync(new ChatMessage(ChatRole.User, userInput), origin, cancellationToken); } /// /// Runs one turn from a message the caller built, that knows where it sits in the conversation /// the caller can see. /// - /// What the caller said or answered: words, an approval answer, or both. - /// - /// Where these words hang, or for a caller that does not track its - /// messages by name. See , which this mirrors. - /// - /// Cancels the turn. - public async Task RunTurnMessageAtOriginAsync( + public Task RunTurnMessageAtOriginAsync( ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userInput); - return await RunTurnCoreAsync(userInput, origin, cancellationToken).ConfigureAwait(false); - } - - /// 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. - /// Cancels the turn. - /// What the turn did. - private async Task RunTurnCoreAsync( - ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) - { - var session = await OpenSessionAsync(cancellationToken).ConfigureAwait(false); - - var turn = BeginTurn(userInput, session, origin); - - var cancellation = StartRun(cancellationToken); - - try - { - using var ambients = EnterAmbients(turn); - - AgentResponse response; - string? toolFault = null; - - try - { - // Interrupt never cancels this token: the turn is not audible, so a barge-in takes - // the amendment path against the turn that finished last. Only the host's own token - // cancels this run, and that cancellation propagates. - response = await turn.Agent - .RunAsync( - turn.Request, - await RunSessionAsync(turn, cancellation.Token).ConfigureAwait(false), - options: null, - cancellationToken: cancellation.Token) - .ConfigureAwait(false); - } - catch (Exception exception) when (exception is not OperationCanceledException) - { - // Section 8.7, sixth row. The run throws, the turn ends, and the call lives. - toolFault = exception.Message; - response = new AgentResponse(); - } - - // 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 CompleteTurnAsync(turn, response, toolFault, ReadDisposition(response), cancellationToken) - .ConfigureAwait(false); - } - finally - { - EndRun(cancellation); - turn.Activity?.Dispose(); - } + return Runner.RunTurnCoreAsync(userInput, origin, cancellationToken); } /// Runs one turn and streams the reply as it arrives. - /// What the caller said. - /// Cancels the model calls. /// 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 @@ -388,8 +363,6 @@ public IAsyncEnumerable RunTurnStreamingAsync( => RunTurnStreamingAtOriginAsync(userInput, origin: null, cancellationToken); /// Runs one turn from a message the caller built and streams the reply as it arrives. - /// What the caller said or answered: words, an approval answer, or both. - /// Cancels the model calls. /// 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 @@ -400,33 +373,12 @@ public IAsyncEnumerable RunTurnMessageStreamingAsync( => RunTurnMessageStreamingAtOriginAsync(userInput, origin: null, cancellationToken); /// Builds the answer message for one queued approval request of this call. - /// 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 - /// answer re-enters through on this same call — an answer - /// another call built is dropped in silence, so callers must match them. - /// public ChatMessage? TryCreateApprovalAnswer(string requestId, bool approved) - { - ArgumentException.ThrowIfNullOrEmpty(requestId); - - return Session() is { } session - ? PendingApprovalQueue.AnswerFor(session.StateBag.Serialize(), requestId, approved) - : null; - } + => Ledger.TryCreateApprovalAnswer(requestId, approved); /// /// Runs one streaming turn that knows where it sits in the conversation the caller can see. /// - /// What the caller said. - /// - /// Where these words hang, or for a caller that does not track its - /// messages by name. See , which this mirrors. - /// - /// Cancels the model calls. - /// The reply, one update at a time. Every update carries content. public async IAsyncEnumerable RunTurnStreamingAtOriginAsync( string userInput, CallTurnOrigin? origin, @@ -434,7 +386,7 @@ public async IAsyncEnumerable RunTurnStreamingAtOriginAsync( { ArgumentNullException.ThrowIfNull(userInput); - await foreach (var update in RunTurnStreamingCoreAsync( + await foreach (var update in Stream.RunTurnStreamingCoreAsync( new ChatMessage(ChatRole.User, userInput), origin, cancellationToken).ConfigureAwait(false)) { yield return update; @@ -445,13 +397,6 @@ public async IAsyncEnumerable RunTurnStreamingAtOriginAsync( /// Runs one streaming turn from a message the caller built, that knows where it sits in the /// conversation the caller can see. /// - /// What the caller said or answered: words, an approval answer, or both. - /// - /// Where these words hang, or for a caller that does not track its - /// messages by name. See , which this mirrors. - /// - /// Cancels the model calls. - /// The reply, one update at a time. Every update carries content. public async IAsyncEnumerable RunTurnMessageStreamingAtOriginAsync( ChatMessage userInput, CallTurnOrigin? origin, @@ -459,335 +404,34 @@ public async IAsyncEnumerable RunTurnMessageStreamingAtOrigi { ArgumentNullException.ThrowIfNull(userInput); - await foreach (var update in RunTurnStreamingCoreAsync(userInput, origin, cancellationToken).ConfigureAwait(false)) + await foreach (var update in Stream.RunTurnStreamingCoreAsync(userInput, origin, cancellationToken).ConfigureAwait(false)) { yield return update; } } - /// Streams 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. - /// Cancels the model calls. - /// The reply, one update at a time. - private async IAsyncEnumerable RunTurnStreamingCoreAsync( - ChatMessage userInput, - CallTurnOrigin? origin, - [EnumeratorCancellation] CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(userInput); - - var session = await OpenSessionAsync(cancellationToken).ConfigureAwait(false); - - var turn = BeginTurn(userInput, session, origin); - - // A streaming turn becomes audible only once it hands the host its first piece of content. - // Until then nothing of it has reached the caller, and a barge-in belongs elsewhere. - var cancellation = StartRun(cancellationToken); - try - { - List updates = []; - string? toolFault = null; - - // This scope covers opening the run's session and building the stream, and reaches no - // round: an async iterator restores its caller's execution context at every yield. - using var opening = EnterAmbients(turn); - - var stream = ScopedEnumerator.Over( - turn.Agent - .RunStreamingAsync( - turn.Request, - await RunSessionAsync(turn, cancellation.Token).ConfigureAwait(false), - options: null, - cancellationToken: cancellation.Token) - .GetAsyncEnumerator(cancellation.Token), - () => EnterAmbients(turn)); - - try - { - while (true) - { - AgentResponseUpdate update; - - // The enumeration itself sits in its own try, because a method that yields takes - // no catch clause around the yield. - try - { - if (!await stream.MoveNextAsync().ConfigureAwait(false)) - { - break; - } - - update = stream.Current; - } - catch (OperationCanceledException) when (CurrentInterruption() is not null) - { - // The caller spoke over the reply, and the relay already reported how much of - // it played. Nothing here estimates that value: see item 6c. - break; - } - catch (Exception exception) when (exception is not OperationCanceledException) - { - // Section 8.7, sixth row. - toolFault = exception.Message; - break; - } - - updates.Add(update); - - var content = update.AsChatResponseUpdate(); - if (TurnMessages.CarriesContent(content) && Speaks(update)) - { - // Marked before the yield, not after it: an async iterator only resumes past - // a yield once the host comes back for the next update, and by then the host - // has already queued this piece for the caller. - _runIsAudible = true; - - // The host speaks this, so it leaves the seam as fast as the model produced it. - yield return content; - } - } - } - finally - { - await stream.DisposeAsync().ConfigureAwait(false); - } - - // CompleteTurnAsync publishes LastTurn itself. See the same note in RunTurnAsync. The - // disposition comes off the raw updates and never off the folded response: update-level - // properties do not survive streaming coalescing. - _ = await CompleteTurnAsync( - turn, updates.ToAgentResponse(), toolFault, ReadDisposition(updates), cancellationToken) - .ConfigureAwait(false); - } - finally - { - EndRun(cancellation); - turn.Activity?.Dispose(); - } - } - /// /// Ends the running turn where the caller cut the reply off. /// - /// The text the caller actually heard. - /// How much of the reply played, as the relay reported it. - /// - /// Whether the turn running now is the turn the caller was hearing. An adapter that tracks which - /// turn's output actually reached the vendor answers that question itself and says so here; - /// sends the frame straight to the amendment path, whatever the running - /// turn has produced. The default is , which leaves the decision to this - /// session alone, and that is the right answer for a caller that speaks over a reply it is - /// itself streaming. - /// - /// - /// when this call 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. - /// - /// - /// is negative. - /// public bool Interrupt( string utteranceUntilInterrupt, TimeSpan durationUntilInterrupt, bool cutsRunningTurn = true) - { - ArgumentNullException.ThrowIfNull(utteranceUntilInterrupt); - ArgumentOutOfRangeException.ThrowIfLessThan(durationUntilInterrupt, TimeSpan.Zero); - - lock (_interruptLock) - { - // Both conditions, and in this order. The adapter's answer only ever removes the - // in-flight path: an adapter that knows the caller was hearing an earlier turn skips it - // outright, and one that says nothing leaves this session's own audibility test to - // decide. - if (cutsRunningTurn && _runCancellation is { } cancellation && _runIsAudible) - { - _interruption = new Interruption(utteranceUntilInterrupt, durationUntilInterrupt); - cancellation.Cancel(); - return true; - } - - return AmendLastTurn(new Interruption(utteranceUntilInterrupt, durationUntilInterrupt)); - } - } + => Interruptions.Interrupt(utteranceUntilInterrupt, durationUntilInterrupt, cutsRunningTurn); /// Closes the call, and writes the last event of its chain. - /// Why the call ended, as one member of the closed set. - /// - /// when this call wrote the event, and when the - /// call had already ended. - /// - /// - /// is not a member of the closed set. - /// - public bool EndCall(CallEndReason reason) - { - // The event is written before the flag moves. A value outside the closed set therefore ends - // no call and writes nothing. - var wrote = _events.EndCall(reason, _time.GetUtcNow()); - 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. - /// - private void DeleteWorkspace() => _workspace?.Delete(_logger); - - /// - /// 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 - /// only the turn-end path and tear it down. - /// - private ValueTask DisposeShellsAsync() => _shells?.DisposeAsync() ?? ValueTask.CompletedTask; + public bool EndCall(CallEndReason reason) => Lifetime.EndCall(reason); /// /// Disposes this call's background sessions and shell executors. Idempotent: a session already /// disposed, or one that never had either, disposes nothing. /// - public async ValueTask DisposeAsync() - { - await ReleaseBackgroundSessionsAsync().ConfigureAwait(false); - await DisposeShellsAsync().ConfigureAwait(false); - } + public ValueTask DisposeAsync() => Lifetime.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 - /// children. Release precedes the shells: a child cancelled here may be inside a shell tool. - /// - private async ValueTask ReleaseBackgroundSessionsAsync() - { - if (Interlocked.Exchange(ref _backgroundReleased, 1) == 1 - || _compiled.BackgroundProviders.Count == 0 - || Session() is not { } session) - { - return; - } - - await BackgroundSessionRelease.ReleaseAsync( - _compiled.BackgroundProviders, session, CallId, _logger, CancellationToken.None).ConfigureAwait(false); - } - - /// - /// 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. - /// - /// The session of this call. - /// Cancels the reads. - private async ValueTask ResyncTranscriptAsync(AgentSession opened, CancellationToken cancellationToken) - { - await _history.DrainAsync(opened).ConfigureAwait(false); - - try - { - var refreshed = await _compiled.CallStore.GetAsync(CallId, cancellationToken).ConfigureAwait(false) - ?? throw new InvalidOperationException( - $"Store 0 holds no call '{CallId}' for its own session to resync against."); - - if (refreshed.NextOrdinal == _history.NextOrdinal(opened)) - { - return; - } - - var rows = await _compiled.CallStore.ReadAsync(CallId, cancellationToken).ConfigureAwait(false); - - _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. - catch (Exception exception) when (exception is not OperationCanceledException) -#pragma warning restore CA1031 - { - Log.TranscriptResyncFailed(_logger, CallId, State.TurnIndex, exception); - _events.RaiseFailedTranscriptResync(State.TurnIndex, exception); - } - } - - /// - /// Opens the session of this call, once, and re-syncs it with store 0 before handing it to every - /// later turn. + /// Waits for every store 1 write this call has queued. /// - /// Cancels the open. - /// The session. - private async ValueTask OpenSessionAsync(CancellationToken cancellationToken) - { - if (Session() is { } opened) - { - await ResyncTranscriptAsync(opened, cancellationToken).ConfigureAwait(false); - return opened; - } - - var record = await _compiled.CallStore.CreateAsync(CallId, cancellationToken).ConfigureAwait(false); - - CallSessionState? checkpoint; - lock (_interruptLock) - { - checkpoint = _checkpoint; - } - - // One restore point for both sources, and store 0 outranks the host's checkpoint outright - // 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. - var stored = record.State ?? checkpoint; - - AgentSession session; - if (_sessionCarriesHistory) - { - session = stored is { Version: CallSessionState.CurrentVersion, Providers.Count: > 0 } - ? await _compiled.TurnAgent.DeserializeSessionAsync( - HarnessSessionState.Wrap(stored.Providers), cancellationToken: cancellationToken).ConfigureAwait(false) - : await _compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); - } - else - { - session = new CallHistorySession(); - - // 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 - // participant's provider state from its checkpoints whenever a turn runs on it. - if (ReusesGraphSession) - { - _graphSession = stored is { Version: CallSessionState.CurrentVersion, WorkflowState: { } blob } - ? await _compiled.TurnAgent.DeserializeSessionAsync(blob, cancellationToken: cancellationToken).ConfigureAwait(false) - : await _compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); - } - } - - IReadOnlyList spoken = record.LastMessageAt is null - ? [] - : await _compiled.CallStore.ReadAsync(CallId, cancellationToken).ConfigureAwait(false); - - lock (_interruptLock) - { - if (_agentSession is null) - { - _agentSession = session; - - State.TurnIndex = _history.BeginCall( - session, - CallId, - spoken, - _events.RaiseDroppedTranscriptWrite, - new TranscriptMarks(record.NextOrdinal, stored?.NextTurnIndex ?? 0)); - - // After the constructor, never inside it. The const writer has already run by now, - // so a slot a previous session filled lands on top of the const default rather than - // under it — and the record it is read from only exists after an async store read. - if (stored is { } s) - { - Restore(s); - } - } - - return _agentSession; - } - } + public Task FlushTranscriptAsync() => Ledger.FlushTranscriptAsync(); /// /// Reads the state this call would resume from, as it stands right now. The provider state is @@ -795,961 +439,8 @@ private async ValueTask OpenSessionAsync(CancellationToken cancell /// 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() - { - lock (_interruptLock) - { - if (_agentSession is null && _checkpoint is { } held) - { - // Handed back by reference, where the branch below deep-clones through - // WrittenSlots(). Deliberate, and not the asymmetry it looks like: this value is the - // host's own object, arriving from Resume and going straight back out to the only - // caller that can reach this branch — the seam, which serializes it and drops it. A - // clone would defend the host against itself, and cost a copy of the slots to do it. - return held; - } - } - - return new() - { - Stage = State.Stage, - IsComplete = IsComplete, - Slots = State.WrittenSlots(), - - // The turn index this call has reached, which is already the NEXT one by the time the - // commit reads it. - NextTurnIndex = State.TurnIndex, - - Clarifications = _clarifications.Spent(), - - Providers = HarnessSessionState.Capture(_agentSession, _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. - WorkflowState = _graphBlob, - }; - } + internal CallSessionState Snapshot() => States.Snapshot(); /// Names the state this call resumes from when store 0 holds none of its own. - internal void Resume(CallSessionState stored) - { - ArgumentNullException.ThrowIfNull(stored); - - // One lock over the check and the write. The guard exists to catch a late hand-off, and a - // guard that read the session under the lock and then wrote the field outside it would be - // racing the very reader — OpenSessionAsync at the top of this file — that it guards. - lock (_interruptLock) - { - if (_agentSession is not null) - { - throw new InvalidOperationException( - $"The call '{CallId}' has already run a turn, and a call resumes only as its " - + "first turn opens it. Hand the state to the factory that builds the session " - + "instead."); - } - - _checkpoint = stored; - } - } - - /// Puts back what a previous session of this call had, as far as the document still allows. - private void Restore(CallSessionState stored) - { - if (stored.Version != CallSessionState.CurrentVersion) - { - Dropped($"the stored state is version {stored.Version} and this build writes {CallSessionState.CurrentVersion}."); - return; - } - - string? refusedStage = null; - - if (_policy is null) - { - // A document with no policy: has no stage machine and no stage to hold, so the only - // stored stage it can honour is no stage at all. An id from a build that still declared - // policy: would otherwise land in the reserved stage slot, where the guards and the - // audit chain read it as though a machine were holding it. - if (stored.Stage.Length > 0) - { - refusedStage = $"the document declares no policy, so the stage '{stored.Stage}' has nowhere to go."; - } - } - else if (!_policy.Declares(stored.Stage)) - { - refusedStage = $"the document no longer declares the stage '{stored.Stage}'."; - } - - if (refusedStage is null) - { - // 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 - // then report a stage it was not actually running in. - _policy?.RestoreStage(stored.Stage); - 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 - // turn away — the one outcome this whole method exists to avoid. - IsComplete = stored.IsComplete; - } - else - { - Dropped(refusedStage); - } - - // Before the slots, and unconditionally: the ask budget is per call, 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. - _clarifications.RestoreSpent(stored.Clarifications); - - foreach (var slot in stored.Slots) - { - 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 - // 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. - Dropped($"the slot '{slot.Key}' is reserved, and a reserved slot is never restored."); - continue; - } - - if (State.TryWrite(slot.Key, slot.Value?.DeepClone())) - { - continue; - } - - // TryWrite answers false for two kinds of reason that cost an operator different things - // to fix — a slot the document no longer declares, and a value its type or enum: gate - // now refuses — so the reason says which one happened rather than making them guess. - Dropped( - State.Configuration.State.ContainsKey(slot.Key) - ? $"the slot '{slot.Key}' no longer takes the value it was stored with." - : $"the document no longer declares the slot '{slot.Key}'."); - } - - void Dropped(string reason) => _events.RaiseDiagnostic( - CallEventKind.StateRestorePartial, - _time.GetUtcNow(), - turnIndex: null, - payload: new Dictionary(StringComparer.Ordinal) - { - [CallEventPayloadKeys.Reason] = reason, - }); - } - - /// - /// Whether this call 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. - /// - private bool ReusesGraphSession => !_sessionCarriesHistory && _compiled.HarnessStateKeys.Count > 0; - - /// - /// Reads the session one run is handed. - /// - /// 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. - private async ValueTask RunSessionAsync(Turn turn, CancellationToken cancellationToken) - { - if (_sessionCarriesHistory) - { - return turn.Session; - } - - if (ReusesGraphSession) - { - return _graphSession ??= await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); - } - - return await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); - } - - /// - /// Opens the ambients this turn runs under. - /// - /// The turn about to run. - /// The scope. Disposing it closes every ambient it opened. - private IDisposable EnterAmbients(Turn turn) - => TurnAmbients.Enter( - CallId, - State, - turn.Renders, - turn.Sources, - turn.Results, - failure => _events.RaiseToolFailure(turn.Index, failure), - TurnContextOf(turn), - turn.Knowledge, - _clarifications, - Workspace, - _shells); - - /// - /// Reads what one turn adds to its own model invocation. - /// - /// The turn about to run. - /// The context merges into the request. - private TurnContext TurnContextOf(Turn turn) - => new() - { - Session = turn.Session, - Instructions = turn.Reminder, - Tools = _delegatedTools?.Tools, - ToolsFor = _delegatedTools?.ToolId, - CarriesHistory = _sessionCarriesHistory, - }; - - /// - /// Reads the session of this call, or null before its first turn opened one. - /// - /// The session. - private AgentSession? Session() - { - lock (_interruptLock) - { - return _agentSession; - } - } - - /// - /// Waits for every store 1 write this call has queued. - /// - /// A task that completes when the words of the call are durable. - public async Task FlushTranscriptAsync() - { - if (Session() is { } session) - { - await _history.DrainAsync(session).ConfigureAwait(false); - } - } - - /// - /// Picks the agent, withdraws whatever this turn replaces, builds the model input, and takes the - /// turn. - /// - /// What the caller said or answered: words, an approval answer, or both. - /// The session of this call. - /// Where the turn hangs, or null for a caller that does not say. - /// Everything the rest of the turn needs. - private Turn BeginTurn(ChatMessage userInput, AgentSession session, CallTurnOrigin? origin = null) - { - if (IsComplete) - { - throw new InvalidOperationException( - $"The call '{CallId}' reached the terminal stage '{Stage}', so it runs no further turn."); - } - - var agent = ResolveAgent(); - - // One session runs one turn at a time. The state document takes no lock, so a second turn - // that overlapped the first would corrupt it rather than fail. - if (Interlocked.Exchange(ref _running, 1) == 1) - { - throw new InvalidOperationException( - $"A turn of the call '{CallId}' is still running. One call runs one turn at a time."); - } - - Activity? activity = null; - try - { - // After both guards: a turn refused as terminal or already-running must not drop the - // probe latch out from under the turn actually in flight. Runs exactly once here, and - // never in EnterAmbients, which reopens per streaming step and would drop the latch - // several times inside one streaming turn. - _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. - // 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 - // index in the chain is worse than a gap in it. - WithdrawSuperseded(session, origin); - - // The reminder rides a request that happens anyway, and it rides exactly one, as a message - // the framework appends for that invocation and stores nowhere. It reads the state document - // and never the transcript. Only a document with a policy: has a stage that waits on a slot. - var reminder = _policy is null ? null : UnfilledSlotReminder.Build(State, _policy.CurrentStage); - ChatMessage spoken = userInput; - - // The framework has never heard of a turn, so the turn loop names this one before the run. - _history.BeginTurn(session, State.TurnIndex); - - // Rows 1 and 2 read the call 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 - // still recognises. Neither shape puts the caller's message in store 1 yet: the turn - // writes what it said and what it heard together, when it commits, so the run that is - // about to read the history does not find its own prompt already in it. - List request = _sessionCarriesHistory || ReusesGraphSession - ? [spoken] - : TurnMessages.GraphHistory(_history.Read(session)) is { } rendered ? [rendered, spoken] : [spoken]; - - // One turn is one span. The call 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(CallId, State.TurnIndex, State.Stage); - var knowledge = StateKnowledgeScope.Compose( - State, _compiled.Configuration.Providers?.Knowledge?.Scope, KnowledgeScopeScope.Current); - - if (knowledge is { Origins.Count: > 0 }) - { - Log.KnowledgeScopeComposed(_logger, CallId, State.TurnIndex, knowledge.Origins); - } - - return new Turn( - agent, - session, - request, - spoken, - reminder, - State.Stage, - State.TurnIndex, - activity, - _time.GetTimestamp(), - _hasScreen ? new TurnRenders() : null, - new TurnSources(), - new TurnResults(), - knowledge, - origin?.MessageId); - } - catch - { - // 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. - activity?.Dispose(); - Volatile.Write(ref _running, 0); - throw; - } - } - - /// Takes back everything the call said after the message this turn hangs off. - private void WithdrawSuperseded(AgentSession session, CallTurnOrigin? origin) - { - if (origin is not { NamesParent: true } - || _history.TruncateFrom(session, origin.ParentMessageId) is not { } withdrawn) - { - return; - } - - // Without this, lastNamed would survive a withdrawal that deleted the very turns it recorded, - // and silence the probe forever about a question the caller edited away. The ask counter is - // deliberately untouched here: what the caller heard, they still heard, and clearing it - // would let the withdrawn segment buy a fresh maxAsks budget. - _clarifications.Withdraw(); - - // The turn index the event is filed under is the one about to run; the payload is what says - // which turns it replaced. The rows of those turns are already deleted, so nothing else in - // any store can answer that afterwards. - _ = _events.Raise( - CallEventKind.TurnSuperseded, - _time.GetUtcNow(), - State.TurnIndex, - payload: new Dictionary(StringComparer.Ordinal) - { - [AuditPayloadKeys.WithdrewFromTurnIndex] = - withdrawn.First.ToString(CultureInfo.InvariantCulture), - [AuditPayloadKeys.WithdrewThroughTurnIndex] = - withdrawn.Last.ToString(CultureInfo.InvariantCulture), - }); - } - - /// - /// Opens the window in which reaches this turn. - /// - /// The token of the host. - /// The source the run reads. The caller ends it with . - private CancellationTokenSource StartRun(CancellationToken cancellationToken) - { - CancellationTokenSource cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - lock (_interruptLock) - { - _interruption = null; - _runCancellation = cancellation; - _runIsAudible = false; - } - - return cancellation; - } - - /// - /// Closes the window, and frees the session for the next turn. - /// - /// The source returned. - private void EndRun(CancellationTokenSource cancellation) - { - // The field drops first. A frame that arrives now meets no source to cancel, so it reaches - // the amendment path rather than a disposed one. - lock (_interruptLock) - { - _runCancellation = null; - _runIsAudible = false; - } - - cancellation.Dispose(); - Volatile.Write(ref _running, 0); - } - - /// - /// Records a barge-in against the turn that finished last, and corrects its record. - /// - /// What the relay reported: the heard text and the played duration. - /// - /// when the turn was amended, and when there was - /// no turn to amend. - /// - private bool AmendLastTurn(Interruption cut) - { - // The chain has already closed, so nothing may be appended behind call.ended. - if (_events.HasEnded - || _amendableEventId is not { } completedEventId - || LastTurn is not { InterruptedAfter: null } finished - || Session() is not { } session) - { - return false; - } - - var heard = cut.HeardText.Trim(); - - // Store 1 keeps the reply row and rewrites its words, rather than replacing the turn's - // messages. The turn it corrects ran to its end, so every tool call it made is already - // paired and there is nothing unfinished to strip out. - // - // The cut always lands today: a turn is amendable only when it completed with words, and a - // turn that completed with words left a reply row holding them. The answer is still read, - // because the row below names a HASH of those words — a chain that proves words store 1 - // does not hold proves nothing, so no cut means no amendment. - if (!_history.TruncateLastReply(session, heard, cut.PlayedDuration)) - { - return false; - } - - LastTurn = finished with { ReplyText = heard, InterruptedAfter = cut.PlayedDuration }; - - _events.RaiseReplyInterrupted( - finished.TurnIndex, _time.GetUtcNow(), completedEventId, heard, cut.PlayedDuration); - - return true; - } - - /// Reads the interruption the relay reported for the running turn. - /// The record, or when the caller did not interrupt. - private Interruption? CurrentInterruption() - { - lock (_interruptLock) - { - return _interruption; - } - } - - /// Reads whether the caller hears the node that produced one update. - /// One update of the run. - /// when the host should speak it. - private bool Speaks(AgentResponseUpdate update) - => _compiled.SpokenBy is not { } spoken - || (update.AuthorName is { } author && spoken.Contains(author)) - || update.AdditionalProperties?.Contains() is true; - - /// Runs every writer, then lets the machine pick the stage of the next turn. - /// The turn that just spoke. - /// What the agent answered. - /// - /// The message of the fault that threw out of the run, or when nothing - /// threw. Section 8.7, row six. - /// - /// Cancels the extractor call. - /// The finished turn. - /// - /// What and reported about - /// this turn, or when neither layer marked it. A flagged turn skips the - /// extractor: the words moderation flagged are its only input, and a slot filled from them would - /// carry the flagged content into the state document and into every later prompt. Everything else - /// about a refused turn is ordinary, so the refusal enters the transcript, the stage machine - /// advances, and turn.completed proves the refusal under - /// . - /// - private async Task CompleteTurnAsync( - Turn turn, - AgentResponse response, - string? toolFault, - TurnDisposition? disposition, - CancellationToken cancellationToken) - { - var interruption = CurrentInterruption(); - - // The moderation facts of this turn, raised before the turn's own events so the flag still - // takes the lower ordinal. The verdict is known before the model runs, which is the one rule - // that separates prompt.flagged from reply.interrupted: it amends nothing. - var refused = disposition?.Moderation is ModerationOutcome.Flagged; - _events.RaiseModeration(turn.Index, disposition); - - // 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. - toolFault ??= disposition is { Fallback: FallbackCause.Faulted, FallbackReason: { } caught } - ? caught - : null; - var reply = SpokenReply.From(response.Messages); - var spokenReply = reply; - TimeSpan? interruptedAfter = null; - string? failure = toolFault is null ? null : 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. - var approvals = ApprovalRequestsOf(response); - - if (interruption is { } cut) - { - // Item 6a. The record holds the text the caller heard, not the text the model produced. - // A trailing space is not speech, so it is trimmed: pipecat pins the same rule in its - // aggregator test, where the model sent "Hello " and the record holds "Hello". - reply = cut.HeardText.Trim(); - interruptedAfter = cut.PlayedDuration; - } - else if (approvals.Count == 0 && (failure is not null - || 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 - // failure even though nothing threw. - failure ??= EmptyReplyReason; - reply = _compiled.Configuration.FallbackReply; - spokenReply = reply; - } - - // Section 8.7, last row, raised once for the turn. It is diagnostic only, so it takes no - // ordinal and no row records it; the turn.completed event of this same turn carries the - // fallback the caller actually heard. The tool fault of row six is raised in - // WriteTurnEvents instead, because the chain stores that one and its row is stamped with - // the same endedAt every other event of the turn carries. - if (toolFault is null && failure is not null) - { - _events.RaiseDiagnostic(CallEventKind.EmptyReply, _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. - // 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; - - // 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 (_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]; - } - } - - // The per-turn writers run from here, in the order the constructor documents: tool results - // first. - ApplyToolResults(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; - - // 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) - { - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - deadline.CancelAfter(TurnCompletionTimeout); - try - { - extractionFailure = await ExtractAsync(turn, response, deadline.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) - { - extractionFailure = 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 - // because the line an operator reads is the same one the turn loop used to write itself. - _events.RaiseDiagnostic( - CallEventKind.ExtractionFailed, - _time.GetUtcNow(), - turn.Index, - payload: new Dictionary(StringComparer.Ordinal) - { - [CallEventPayloadKeys.Reason] = extractionFailure, - }); - } - - // 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 = _time.GetUtcNow(); - State.TurnIndex++; - State.CallDurationSeconds = (endedAt - _startedAt).TotalSeconds; - - // The counters write last. - _counters.Apply(State); - - var stageAfter = turn.StageBefore; - if (_policy is not null) - { - stageAfter = _policy.Advance(State.Snapshot()); - State.Stage = stageAfter; - IsComplete = _policy.IsTerminal; - } - - TurnResult result = new( - CallId, - turn.Index, - turn.StageBefore, - stageAfter, - reply, - 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 (ReusesGraphSession && _graphSession is { } shared) - { - _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 (_interruptLock) - { - // What the caller said and what the caller heard, written together. - if (_sessionCarriesHistory) - { - LastReplyMessageId = _history.AppendTurn( - turn.Session, [turn.Spoken, .. written], 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. - LastReplyMessageId = _history.AppendCallerFacingTurn( - turn.Session, turn.Spoken, heard, 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 = _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. - _amendableEventId = interruptedAfter is null ? completedEventId : null; - 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 - && _interruption is { } late - && AmendLastTurn(late) - && 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. - _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. - _runCancellation = null; - _runIsAudible = false; - } - - AgentCoreTelemetry.EndTurn( - turn.Activity, - _time.GetElapsedTime(turn.StartedAt), - Outcome(failure, interruptedAfter), - stageAfter, - failure); - - if (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. - _events.EndCall(CallEndReason.AgentCompleted, endedAt, stageAfter); - } - - if (IsComplete || _events.HasEnded) - { - // Children before shells: a cancelled child may be inside a shell tool the next line - // tears down. - await 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 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. - DeleteWorkspace(); - } - - return result; - } - - /// Reads the closed outcome value of one finished turn. - /// The section 8.7 reason, or . - /// The played duration, or . - /// One of the three values the metric attribute takes. - private static string Outcome(string? failure, TimeSpan? interruptedAfter) => (failure, interruptedAfter) switch - { - (not null, _) => AgentCoreTelemetry.OutcomeFailed, - (_, not null) => AgentCoreTelemetry.OutcomeInterrupted, - _ => AgentCoreTelemetry.OutcomeCompleted, - }; - - /// Reads the approval requests one finished turn still waits on. - /// What the agent answered. - /// One entry per request content, oldest first; empty when the turn asked nothing. - private static List ApprovalRequestsOf(AgentResponse response) - { - List approvals = []; - foreach (var request in response.Messages - .SelectMany(message => message.Contents) - .OfType()) - { - if (request.ToolCall is not FunctionCallContent call) - { - continue; - } - - approvals.Add(new PendingApproval( - request.RequestId, - call.Name, - JsonSerializer.SerializeToElement( - call.Arguments ?? new Dictionary(StringComparer.Ordinal)))); - } - - return approvals; - } - - /// Reads what the turn layers reported about one finished turn. - /// What the agent answered. - /// The disposition, or when no layer marked the turn. - private static TurnDisposition? ReadDisposition(AgentResponse response) - => response.AdditionalProperties is { } properties - && properties.TryGetValue(out var disposition) - ? disposition - : null; - - /// Reads what the turn layers reported across the updates of one streaming turn. - /// Every update the run produced, in order, before the seam filtered them. - /// The disposition, or when no update carried one. - private static TurnDisposition? ReadDisposition(List updates) - { - TurnDisposition? found = null; - foreach (var update in updates) - { - if (update.AdditionalProperties is { } properties - && properties.TryGetValue(out var disposition)) - { - found = disposition; - } - } - - return found; - } - - /// Runs the extractor against the finished turn. - /// The turn that just spoke. - /// What the agent answered. - /// Cancels the model call. - /// The reason the extractor produced nothing, or . - private async Task ExtractAsync(Turn turn, AgentResponse response, CancellationToken cancellationToken) - { - if (_extractor is null || _compiled.Configuration.Extractor is not { When: ExtractorTrigger.AfterReply }) - { - return null; - } - - // 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 - // 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]; - if (Transcript.LastOrDefault(message => message.Role == ChatRole.Assistant && message.Text.Length > 0) is { } asked) - { - finished.Insert(0, asked); - } - - // A failed extraction never drops the turn. The result carries the reason instead. - var result = await _extractor.ExtractAsync(State, finished, _clarifications, cancellationToken) - .ConfigureAwait(false); - return result.Failure; - } - - /// Fills every tool-written slot from the tool results of one turn. - /// The messages the agent produced, oldest first. - private void ApplyToolResults(IEnumerable messages) - { - // The name a call carries is the declared tool id, because the compile table names every - // function after the tools: entry it built. - ToolCallNames names = new(); - - foreach (var message in messages) - { - foreach (var content in message.Contents) - { - switch (content) - { - case FunctionCallContent call: - names.Called(call); - break; - - case FunctionResultContent result when names.Of(result) is { } toolId: - ToolStateWriter.Apply(State, toolId, ToolResultJson.ToNode(result.Result)); - break; - - default: - break; - } - } - } - } - - /// Picks the agent that speaks this turn. - /// The agent. - private AIAgent ResolveAgent() - { - if (_policy is null) - { - // Row 1, row 3, and row 4 of the compile table. One entry agent answers every turn. - return _compiled.TurnAgent; - } - - if (_policy.CurrentAgentId is not { Length: > 0 } - || _compiled.TurnAgentForStage(_policy.Stage) is not { } agent) - { - throw new InvalidOperationException( - $"The stage '{_policy.Stage}' of the call '{CallId}' names no agent, so no turn can run."); - } - - return agent; - } - - /// Everything one turn carries from its start to its end. - /// The agent the stage names. - /// The session of the call. Store 1 lives in it. - /// The messages the run reads. - /// What the caller said. - /// The <system-reminder> this one invocation carries, or null. - /// The stage the turn spoke in. - /// The zero-based index of the turn. - /// The span of this turn, or when nothing listens. - /// The timestamp the duration is measured from. - /// - /// What this turn draws into, or when it has no screen. Built once per - /// turn for the same reason is: reopens its - /// scope on every step of a streaming turn, and a fresh collector each time would lose whatever - /// an earlier step drew before a later step could attach it to a message. - /// - /// - /// What this turn cites into. Built once per turn for the same reason is, - /// and never null: a call with no screen still answers from documents. - /// - /// - /// What this turn's tools answer into, so a drawing script can read the rows. Built once per - /// turn: a later turn's rows are not this turn's. - /// - /// - /// What this turn may see of the knowledge base. Built once per turn for the same reason - /// is, and additionally because a scope that changed between two updates - /// of one streaming turn would search two different corpora for one answer. - /// - /// - /// What the caller calls the message it sent, or when it named none. The - /// append stamps it on the row so a later edit has something to anchor on. - /// - private sealed record Turn( - AIAgent Agent, - AgentSession Session, - List Request, - ChatMessage Spoken, - string? Reminder, - string StageBefore, - int Index, - Activity? Activity, - long StartedAt, - TurnRenders? Renders, - TurnSources Sources, - TurnResults Results, - KnowledgeScope? Knowledge, - string? MessageId); - - /// The session a graph row's call holds, so store 1 has somewhere to live. - private sealed class CallHistorySession : AgentSession; - - /// What the relay reported when the caller spoke over the reply. - /// The text the caller actually heard. - /// How much of the reply played, at 1 ms. - private sealed record Interruption(string HeardText, TimeSpan PlayedDuration); + internal void Resume(CallSessionState stored) => States.Resume(stored); } diff --git a/src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs b/src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs new file mode 100644 index 00000000..3e68a71a --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallInterruptionTracker.cs @@ -0,0 +1,172 @@ +namespace AgentCore.Application.Runtime; + +internal sealed class CallInterruptionTracker +{ + private readonly CallSession _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. + private int _running; + + // Whether the running turn has already handed the host something to speak. One rule for both + // run shapes: a run that has handed the host nothing cannot be the turn the caller was hearing. + private volatile bool _runIsAudible; + + /// + /// Whether the running turn has handed the host something to speak. + /// + internal bool RunIsAudible { get => _runIsAudible; set => _runIsAudible = value; } + + internal CallInterruptionTracker(CallSession session) + { + ArgumentNullException.ThrowIfNull(session); + _session = session; + } + + /// + /// Ends the running turn where the caller cut the reply off. + /// + /// The text the caller actually heard. + /// How much of the reply played, as the relay reported it. + /// + /// Whether the turn running now is the turn the caller was hearing. An adapter that tracks which + /// turn's output actually reached the vendor answers that question itself and says so here; + /// sends the frame straight to the amendment path, whatever the running + /// turn has produced. The default is , which leaves the decision to this + /// session alone, and that is the right answer for a caller that speaks over a reply it is + /// itself streaming. + /// + /// + /// when this call 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. + /// + /// + /// is negative. + /// + internal bool Interrupt( + string utteranceUntilInterrupt, + TimeSpan durationUntilInterrupt, + bool cutsRunningTurn = true) + { + ArgumentNullException.ThrowIfNull(utteranceUntilInterrupt); + ArgumentOutOfRangeException.ThrowIfLessThan(durationUntilInterrupt, TimeSpan.Zero); + + lock (_session.InterruptLock) + { + // Both conditions, and in this order. The adapter's answer only ever removes the + // in-flight path: an adapter that knows the caller was hearing an earlier turn skips it + // outright, and one that says nothing leaves this session's own audibility test to + // decide. + if (cutsRunningTurn && _session.RunCancellation is { } cancellation && RunIsAudible) + { + _session.Interruption = new Interruption(utteranceUntilInterrupt, durationUntilInterrupt); + cancellation.Cancel(); + return true; + } + + return AmendLastTurn(new Interruption(utteranceUntilInterrupt, durationUntilInterrupt)); + } + } + + /// + /// Opens the window in which reaches this turn. + /// + /// The token of the host. + /// The source the run reads. The caller ends it with . + internal CancellationTokenSource StartRun(CancellationToken cancellationToken) + { + CancellationTokenSource cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + lock (_session.InterruptLock) + { + _session.Interruption = null; + _session.RunCancellation = cancellation; + _runIsAudible = false; + } + + return cancellation; + } + + /// Takes the turn slot, unless a turn of this call is still running. + /// when another turn holds the slot. + internal bool TryEnterTurn() => Interlocked.Exchange(ref _running, 1) == 0; + + /// Frees the turn slot after a turn refused to start left it taken. + internal void ReleaseTurn() => Volatile.Write(ref _running, 0); + + /// + /// Closes the window, and frees the session for the next turn. + /// + /// The source returned. + internal void EndRun(CancellationTokenSource cancellation) + { + // The field drops first. A frame that arrives now meets no source to cancel, so it reaches + // the amendment path rather than a disposed one. + lock (_session.InterruptLock) + { + _session.RunCancellation = null; + _runIsAudible = false; + } + + cancellation.Dispose(); + Volatile.Write(ref _running, 0); + } + + /// + /// Records a barge-in against the turn that finished last, and corrects its record. + /// + /// What the relay reported: the heard text and the played duration. + /// + /// when the turn was amended, and when there was + /// no turn to amend. + /// + internal bool AmendLastTurn(Interruption cut) + { + // The chain has already closed, so nothing may be appended behind call.ended. + if (_session.Events.HasEnded + || _session.AmendableEventId is not { } completedEventId + || _session.LastTurn is not { InterruptedAfter: null } finished + || _session.Ledger.Session() is not { } session) + { + return false; + } + + var heard = cut.HeardText.Trim(); + + // Store 1 keeps the reply row and rewrites its words, rather than replacing the turn's + // messages. The turn it corrects ran to its end, so every tool call it made is already + // paired and there is nothing unfinished to strip out. + // + // The cut always lands today: a turn is amendable only when it completed with words, and a + // turn that completed with words left a reply row holding them. The answer is still read, + // because the row below names a HASH of those words — a chain that proves words store 1 + // does not hold proves nothing, so no cut means no amendment. + if (!_session.History.TruncateLastReply(session, heard, cut.PlayedDuration)) + { + return false; + } + + _session.LastTurn = finished with { ReplyText = heard, InterruptedAfter = cut.PlayedDuration }; + + _session.Events.RaiseReplyInterrupted( + finished.TurnIndex, _session.Time.GetUtcNow(), completedEventId, heard, cut.PlayedDuration); + + return true; + } + + /// Reads the interruption the relay reported for the running turn. + /// The record, or when the caller did not interrupt. + internal Interruption? CurrentInterruption() + { + lock (_session.InterruptLock) + { + return _session.Interruption; + } + } + + /// What the relay reported when the caller spoke over the reply. + /// The text the caller actually heard. + /// How much of the reply played, at 1 ms. + internal sealed record Interruption(string HeardText, TimeSpan PlayedDuration); +} diff --git a/src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs b/src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs new file mode 100644 index 00000000..14c06e03 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallSessionLifetime.cs @@ -0,0 +1,79 @@ +using AgentCore.Application.Runtime.Harness; +using AgentCore.Domain.Audit; + +namespace AgentCore.Application.Runtime; + +internal sealed class CallSessionLifetime +{ + private readonly CallSession _session; + + // The background release runs once per call: 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) + { + 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. + /// + /// when this call wrote the event, and when the + /// call had already ended. + /// + /// + /// is not a member of the closed set. + /// + internal bool EndCall(CallEndReason 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()); + _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. + /// + internal void DeleteWorkspace() => _session.WorkspaceRoot?.Delete(_session.Logger); + + /// + /// Disposes this call's background sessions and shell executors. Idempotent: a session already + /// disposed, or one that never had either, disposes nothing. + /// + internal async ValueTask DisposeAsync() + { + await ReleaseBackgroundSessionsAsync().ConfigureAwait(false); + await DisposeShellsAsync().ConfigureAwait(false); + } + + /// + /// 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 + /// children. Release precedes the shells: a child cancelled here may be inside a shell tool. + /// + internal async ValueTask ReleaseBackgroundSessionsAsync() + { + if (Interlocked.Exchange(ref _backgroundReleased, 1) == 1 + || _session.Compiled.BackgroundProviders.Count == 0 + || _session.Ledger.Session() is not { } session) + { + return; + } + + await BackgroundSessionRelease.ReleaseAsync( + _session.Compiled.BackgroundProviders, session, _session.CallId, _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 + /// 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/CallSession/CallSessionStateStore.cs new file mode 100644 index 00000000..2039ac27 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallSessionStateStore.cs @@ -0,0 +1,172 @@ +using AgentCore.Application.Calls; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Harness; + +namespace AgentCore.Application.Runtime; + +// The persistable half of the session (LangGraph checkpoint seam): restoring a previous +// session's stage, slots, and ask budget onto the live document, as far as the compiled +// document still allows. Never throws a call away over a stale blob — every refusal lands as +// a diagnostic and the call runs on what restored. +internal sealed class CallSessionStateStore +{ + private readonly CallSession _session; + + internal CallSessionStateStore(CallSession 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) + { + if (stored.Version != CallSessionState.CurrentVersion) + { + Dropped($"the stored state is version {stored.Version} and this build writes {CallSessionState.CurrentVersion}."); + return; + } + + string? refusedStage = null; + + if (_session.Policy is null) + { + // A document with no policy: has no stage machine and no stage to hold, so the only + // stored stage it can honour is no stage at all. An id from a build that still declared + // policy: would otherwise land in the reserved stage slot, where the guards and the + // audit chain read it as though a machine were holding it. + if (stored.Stage.Length > 0) + { + refusedStage = $"the document declares no policy, so the stage '{stored.Stage}' has nowhere to go."; + } + } + else if (!_session.Policy.Declares(stored.Stage)) + { + refusedStage = $"the document no longer declares the stage '{stored.Stage}'."; + } + + if (refusedStage is null) + { + // 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 + // 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 + // turn away — the one outcome this whole method exists to avoid. + _session.IsComplete = stored.IsComplete; + } + else + { + Dropped(refusedStage); + } + + // Before the slots, and unconditionally: the ask budget is per call, 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); + + foreach (var slot in stored.Slots) + { + 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 + // 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. + Dropped($"the slot '{slot.Key}' is reserved, and a reserved slot is never restored."); + continue; + } + + if (_session.State.TryWrite(slot.Key, slot.Value?.DeepClone())) + { + continue; + } + + // TryWrite answers false for two kinds of reason that cost an operator different things + // to fix — a slot the document no longer declares, and a value its type or enum: gate + // now refuses — so the reason says which one happened rather than making them guess. + Dropped( + _session.State.Configuration.State.ContainsKey(slot.Key) + ? $"the slot '{slot.Key}' no longer takes the value it was stored with." + : $"the document no longer declares the slot '{slot.Key}'."); + } + + void Dropped(string reason) => _session.Events.RaiseDiagnostic( + CallEventKind.StateRestorePartial, + _session.Time.GetUtcNow(), + turnIndex: null, + payload: new Dictionary(StringComparer.Ordinal) + { + [CallEventPayloadKeys.Reason] = reason, + }); + } + + /// + /// Reads the state this call 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() + { + lock (_session.InterruptLock) + { + if (_session.AgentSession is null && _session.Checkpoint is { } held) + { + // Handed back by reference, where the branch below deep-clones through + // WrittenSlots(). Deliberate, and not the asymmetry it looks like: this value is the + // host's own object, arriving from Resume and going straight back out to the only + // caller that can reach this branch — the seam, which serializes it and drops it. A + // clone would defend the host against itself, and cost a copy of the slots to do it. + return held; + } + } + + return new() + { + Stage = _session.State.Stage, + IsComplete = _session.IsComplete, + Slots = _session.State.WrittenSlots(), + + // The turn index this call has reached, which is already the NEXT one by the time the + // commit reads it. + NextTurnIndex = _session.State.TurnIndex, + + Clarifications = _session.Clarifications.Spent(), + + 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. + WorkflowState = _session.GraphBlob, + }; + } + + /// Names the state this call resumes from when store 0 holds none of its own. + internal void Resume(CallSessionState stored) + { + ArgumentNullException.ThrowIfNull(stored); + + // One lock over the check and the write. The guard exists to catch a late hand-off, and a + // guard that read the session under the lock and then wrote the field outside it would be + // racing the very reader — OpenSessionAsync at the top of this file — that it guards. + lock (_session.InterruptLock) + { + 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 " + + "first turn opens it. Hand the state to the factory that builds the session " + + "instead."); + } + + _session.Checkpoint = stored; + } + } +} + diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs b/src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs new file mode 100644 index 00000000..b9ff8009 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTranscriptLedger.cs @@ -0,0 +1,181 @@ +using AgentCore.Application.Calls; +using AgentCore.Application.Diagnostics; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Transcript; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +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 +{ + private readonly CallSession _session; + + internal CallTranscriptLedger(CallSession 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 + /// later turn. + /// + /// Cancels the open. + /// The session. + internal async ValueTask OpenSessionAsync(CancellationToken cancellationToken) + { + if (Session() is { } opened) + { + await ResyncTranscriptAsync(opened, cancellationToken).ConfigureAwait(false); + return opened; + } + + var record = await _session.Compiled.CallStore.CreateAsync(_session.CallId, cancellationToken).ConfigureAwait(false); + + CallSessionState? checkpoint; + lock (_session.InterruptLock) + { + checkpoint = _session.Checkpoint; + } + + // One restore point for both sources, and store 0 outranks the host's checkpoint outright + // 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. + var stored = record.State ?? checkpoint; + + AgentSession session; + if (_session.SessionCarriesHistory) + { + session = stored is { Version: CallSessionState.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(); + + // 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 + // 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 } + ? await _session.Compiled.TurnAgent.DeserializeSessionAsync(blob, cancellationToken: cancellationToken).ConfigureAwait(false) + : await _session.Compiled.TurnAgent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + } + + IReadOnlyList spoken = record.LastMessageAt is null + ? [] + : await _session.Compiled.CallStore.ReadAsync(_session.CallId, cancellationToken).ConfigureAwait(false); + + lock (_session.InterruptLock) + { + if (_session.AgentSession is null) + { + _session.AgentSession = session; + + _session.State.TurnIndex = _session.History.BeginCall( + session, + _session.CallId, + spoken, + _session.Events.RaiseDroppedTranscriptWrite, + new TranscriptMarks(record.NextOrdinal, stored?.NextTurnIndex ?? 0)); + + // After the constructor, never inside it. The const writer has already run by now, + // so a slot a previous session filled lands on top of the const default rather than + // under it — and the record it is read from only exists after an async store read. + if (stored is { } s) + { + _session.States.Restore(s); + } + } + + return _session.AgentSession; + } + } + + /// + /// 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. + /// + /// The session of this call. + /// Cancels the reads. + private async ValueTask ResyncTranscriptAsync(AgentSession opened, CancellationToken cancellationToken) + { + await _session.History.DrainAsync(opened).ConfigureAwait(false); + + try + { + var refreshed = await _session.Compiled.CallStore.GetAsync(_session.CallId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException( + $"Store 0 holds no call '{_session.CallId}' 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); + + _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. + catch (Exception exception) when (exception is not OperationCanceledException) +#pragma warning restore CA1031 + { + Log.TranscriptResyncFailed(_session.Logger, _session.CallId, _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. + /// + /// The session. + internal AgentSession? Session() + { + lock (_session.InterruptLock) + { + return _session.AgentSession; + } + } + + /// + /// Waits for every store 1 write this call has queued. + /// + /// A task that completes when the words of the call are durable. + internal async Task FlushTranscriptAsync() + { + if (Session() is { } session) + { + await _session.History.DrainAsync(session).ConfigureAwait(false); + } + } + + /// Builds the answer message for one queued approval request of this call. + /// 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. + /// + internal ChatMessage? TryCreateApprovalAnswer(string requestId, bool approved) + { + ArgumentException.ThrowIfNullOrEmpty(requestId); + + return Session() is { } session + ? PendingApprovalQueue.AnswerFor(session.StateBag.Serialize(), requestId, approved) + : null; + } + + /// The session a graph row's call holds, so store 1 has somewhere to live. + private sealed class CallHistorySession : AgentSession; +} diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurn.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurn.cs new file mode 100644 index 00000000..a94f74c2 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurn.cs @@ -0,0 +1,27 @@ +using System.Diagnostics; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Domain.Knowledge; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +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 +// 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( + AIAgent Agent, + AgentSession Session, + List Request, + ChatMessage Spoken, + string? Reminder, + string StageBefore, + int Index, + Activity? Activity, + long StartedAt, + TurnRenders? Renders, + TurnSources Sources, + TurnResults Results, + KnowledgeScope? Knowledge, + string? MessageId); diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs new file mode 100644 index 00000000..db4a1fd0 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs @@ -0,0 +1,394 @@ +using System.Text.Json; +using AgentCore.Application.Diagnostics; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Domain; +using AgentCore.Domain.Audit; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +internal sealed class CallTurnCompletion +{ + private readonly CallSession _session; + + internal CallTurnCompletion(CallSession session) + { + ArgumentNullException.ThrowIfNull(session); + _session = session; + } + + /// Runs every writer, then lets the machine pick the stage of the next turn. + /// The turn that just spoke. + /// What the agent answered. + /// + /// The message of the fault that threw out of the run, or when nothing + /// threw. Section 8.7, row six. + /// + /// Cancels the extractor call. + /// The finished turn. + /// + /// What and reported about + /// this turn, or when neither layer marked it. A flagged turn skips the + /// extractor: the words moderation flagged are its only input, and a slot filled from them would + /// carry the flagged content into the state document and into every later prompt. Everything else + /// about a refused turn is ordinary, so the refusal enters the transcript, the stage machine + /// advances, and turn.completed proves the refusal under + /// . + /// + internal async Task CompleteTurnAsync( + CallTurn turn, + AgentResponse response, + string? toolFault, + TurnDisposition? disposition, + CancellationToken cancellationToken) + { + // Sweep drain state for tool calls whose round never reached the client's drain: the + // round that ends a turn attaches nothing, so turn-scoped records would otherwise + // leave entries sitting on the shared clients. + turn.Results.Sweep(); + + // Calls the model named that no tool answered never reach the invoking client, so no + // per-call state names them. The turn's own record does: every id the model gave minus + // every id a tool ran under. Reported here, at the same turn end that sweeps the drain. + ReportUndeclaredToolCalls(turn, response); + + var interruption = _session.Interruptions.CurrentInterruption(); + + // The moderation facts of this turn, raised before the turn's own events so the flag still + // takes the lower ordinal. The verdict is known before the model runs, which is the one rule + // that separates prompt.flagged from reply.interrupted: it amends nothing. + var refused = disposition?.Moderation is ModerationOutcome.Flagged; + _session.Events.RaiseModeration(turn.Index, disposition); + + // 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. + toolFault ??= disposition is { Fallback: FallbackCause.Faulted, FallbackReason: { } caught } + ? caught + : 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. + var approvals = ApprovalRequestsOf(response); + + if (interruption is { } cut) + { + // Item 6a. The record holds the text the caller heard, not the text the model produced. + // A trailing space is not speech, so it is trimmed: pipecat pins the same rule in its + // aggregator test, where the model sent "Hello " and the record holds "Hello". + reply = cut.HeardText.Trim(); + interruptedAfter = cut.PlayedDuration; + } + else if (approvals.Count == 0 && (failure is not null + || 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 + // failure even though nothing threw. + failure ??= CallSession.EmptyReplyReason; + reply = _session.Compiled.Configuration.FallbackReply; + spokenReply = reply; + } + + // Section 8.7, last row, raised once for the turn. It is diagnostic only, so it takes no + // ordinal and no row records it; the turn.completed event of this same turn carries the + // fallback the caller actually heard. The tool fault of row six is raised in + // WriteTurnEvents instead, because the chain stores that one and its row is stamped with + // 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); + } + + // 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. + // 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; + + // 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) + { + 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]; + } + } + + // The per-turn writers run from here, in the order the constructor documents: tool results + // first. + _session.Writers.ApplyToolResults(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; + + // 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) + { + 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; + } + } + + 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 + // because the line an operator reads is the same one the turn loop used to write itself. + _session.Events.RaiseDiagnostic( + CallEventKind.ExtractionFailed, + _session.Time.GetUtcNow(), + turn.Index, + payload: new Dictionary(StringComparer.Ordinal) + { + [CallEventPayloadKeys.Reason] = extractionFailure, + }); + } + + // 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); + } + + if (_session.IsComplete || _session.Events.HasEnded) + { + // 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 result; + } + + /// Reads the closed outcome value of one finished turn. + /// The section 8.7 reason, or . + /// The played duration, or . + /// One of the three values the metric attribute takes. + private static string Outcome(string? failure, TimeSpan? interruptedAfter) => (failure, interruptedAfter) switch + { + (not null, _) => AgentCoreTelemetry.OutcomeFailed, + (_, not null) => AgentCoreTelemetry.OutcomeInterrupted, + _ => AgentCoreTelemetry.OutcomeCompleted, + }; + + /// Reads the approval requests one finished turn still waits on. + /// What the agent answered. + /// One entry per request content, oldest first; empty when the turn asked nothing. + private static List ApprovalRequestsOf(AgentResponse response) + { + List approvals = []; + foreach (var request in response.Messages + .SelectMany(message => message.Contents) + .OfType()) + { + if (request.ToolCall is not FunctionCallContent call) + { + continue; + } + + approvals.Add(new PendingApproval( + request.RequestId, + call.Name, + JsonSerializer.SerializeToElement( + call.Arguments ?? new Dictionary(StringComparer.Ordinal)))); + } + + return approvals; + } + + /// 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) + { + var invoked = new HashSet(turn.Results.CallIds, StringComparer.Ordinal); + + foreach (var call in response.Messages + .SelectMany(message => message.Contents) + .OfType()) + { + if (!invoked.Contains(call.CallId)) + { + _session.Events.RaiseToolFailure(turn.Index, new ToolFailure + { + ToolName = call.Name, + ToolCallId = call.CallId, + Kind = ToolFailureKind.Undeclared, + Message = $"the model called '{call.Name}', and no such tool is declared.", + }); + } + } + } +} diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs new file mode 100644 index 00000000..0d9fb78d --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs @@ -0,0 +1,313 @@ +using System.Diagnostics; +using System.Globalization; +using AgentCore.Application.Diagnostics; +using AgentCore.Application.Knowledge; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.State; +using AgentCore.Domain; +using AgentCore.Domain.Audit; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +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 +{ + private readonly CallSession _session; + + private (string ToolId, IReadOnlyList Tools)? _delegatedTools; + + private bool _hasScreen; + + internal CallTurnRunner(CallSession session) + { + ArgumentNullException.ThrowIfNull(session); + _session = session; + } + + /// + /// Gives the runs this call 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. + /// An argument is . + internal void SetDelegatedTools(string delegatingToolId, IReadOnlyList tools) + { + ArgumentNullException.ThrowIfNull(delegatingToolId); + ArgumentNullException.ThrowIfNull(tools); + + _delegatedTools = (delegatingToolId, tools); + } + + /// + /// Gives this call the screen its tools draw on, or takes it away. + /// + internal void SetHasScreen(bool hasScreen) => _hasScreen = hasScreen; + + /// 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. + /// Cancels the turn. + /// What the turn did. + internal async Task RunTurnCoreAsync( + ChatMessage userInput, CallTurnOrigin? origin, CancellationToken cancellationToken) + { + var session = await _session.Ledger.OpenSessionAsync(cancellationToken).ConfigureAwait(false); + + var turn = BeginTurn(userInput, session, origin); + + var cancellation = _session.Interruptions.StartRun(cancellationToken); + + try + { + using var ambients = EnterAmbients(turn); + // The turn travels on the run's own options from here to the invoking client, one + // value per turn, and in the session-keyed registry from here to the providers — + // keyed by the session the run actually gets, which a graph row re-creates per turn. + var invocation = TurnInvocationOf(turn); + var runSession = await RunSessionAsync(turn, cancellation.Token).ConfigureAwait(false); + TurnRegistry.Set(runSession, invocation); + + AgentResponse response; + string? toolFault = null; + + try + { + // Interrupt never cancels this token: the turn is not audible, so a barge-in takes + // the amendment path against the turn that finished last. Only the host's own token + // cancels this run, and that cancellation propagates. + response = await turn.Agent + .RunAsync( + turn.Request, + runSession, + invocation.RunOptions(), + cancellationToken: cancellation.Token) + .ConfigureAwait(false); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + // Section 8.7, sixth row. The run throws, the turn ends, and the call lives. + toolFault = exception.Message; + response = new AgentResponse(); + } + + // 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) + .ConfigureAwait(false); + } + finally + { + _session.Interruptions.EndRun(cancellation); + turn.Activity?.Dispose(); + } + } + + /// + /// Picks the agent, withdraws whatever this turn replaces, builds the model input, and takes the + /// turn. + /// + /// What the caller said or answered: words, an approval answer, or both. + /// The session of this call. + /// 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) + { + if (_session.IsComplete) + { + throw new InvalidOperationException( + $"The call '{_session.CallId}' reached the terminal stage '{_session.Stage}', so it runs no further turn."); + } + + var agent = ResolveAgent(); + + // One session runs one turn at a time. The state document takes no lock, so a second turn + // that overlapped the first would corrupt it rather than fail. + 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."); + } + + Activity? activity = null; + try + { + // After both guards: a turn refused as terminal or already-running must not drop the + // probe latch out from under the turn actually in flight. Runs exactly once here, and + // never in EnterAmbients, which reopens per streaming step and would drop the latch + // several times 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. + // 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 + // index in the chain is worse than a gap in it. + WithdrawSuperseded(session, origin); + + // The reminder rides a request that happens anyway, and it rides exactly one, as a message + // the framework appends for that invocation and stores nowhere. It reads the state document + // and never the transcript. Only a document with a policy: has a stage that waits on a slot. + var reminder = _session.Policy is null ? null : UnfilledSlotReminder.Build(_session.State, _session.Policy.CurrentStage); + ChatMessage spoken = userInput; + + // 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 + // 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 + // still recognises. Neither shape puts the caller's message in store 1 yet: the turn + // writes what it said and what it heard together, when it commits, so the run that is + // about to read the history does not find its own prompt already in it. + List request = _session.SessionCarriesHistory || _session.ReusesGraphSession + ? [spoken] + : TurnMessages.GraphHistory(_session.History.Read(session)) is { } rendered ? [rendered, spoken] : [spoken]; + + // One turn is one span. The call 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); + 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); + } + + return new CallTurn( + agent, + session, + request, + spoken, + reminder, + _session.State.Stage, + _session.State.TurnIndex, + activity, + _session.Time.GetTimestamp(), + _hasScreen ? new TurnRenders() : null, + new TurnSources(), + new TurnResults(), + knowledge, + origin?.MessageId); + } + catch + { + // 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. + 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) + { + if (origin is not { NamesParent: true } + || _session.History.TruncateFrom(session, origin.ParentMessageId) is not { } withdrawn) + { + return; + } + + // Without this, lastNamed would survive a withdrawal that deleted the very turns it recorded, + // and silence the probe forever about a question the caller edited away. The ask counter is + // deliberately untouched here: what the caller heard, they still heard, and clearing it + // would let the withdrawn segment buy a fresh maxAsks budget. + _session.Clarifications.Withdraw(); + + // The turn index the event is filed under is the one about to run; the payload is what says + // 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, + _session.Time.GetUtcNow(), + _session.State.TurnIndex, + payload: new Dictionary(StringComparer.Ordinal) + { + [AuditPayloadKeys.WithdrewFromTurnIndex] = + withdrawn.First.ToString(CultureInfo.InvariantCulture), + [AuditPayloadKeys.WithdrewThroughTurnIndex] = + withdrawn.Last.ToString(CultureInfo.InvariantCulture), + }); + } + + /// Picks the agent that speaks this turn. + /// The agent. + internal AIAgent ResolveAgent() + { + if (_session.Policy is null) + { + // Row 1, row 3, and row 4 of the compile table. One entry agent answers every turn. + return _session.Compiled.TurnAgent; + } + + if (_session.Policy.CurrentAgentId is not { Length: > 0 } + || _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."); + } + + return agent; + } + + /// + /// Reads the session one run is handed. + /// + /// 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) + { + if (_session.SessionCarriesHistory) + { + return turn.Session; + } + + if (_session.ReusesGraphSession) + { + return _session.GraphSession ??= await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + + return await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Opens the state scope this turn runs under, so guarded graph edges read this call. + /// + /// The turn about to run. + /// The scope. Disposing it closes the state scope. + internal IDisposable EnterAmbients(CallTurn turn) => CallStateScope.Enter(_session.State); + + /// 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) + => new() + { + CallId = _session.CallId, + TurnIndex = turn.Index, + Stage = turn.StageBefore, + Instructions = turn.Reminder, + Workspace = _session.Workspace, + Shells = _session.Shells, + Knowledge = turn.Knowledge, + Clarifications = _session.Clarifications, + CarriesHistory = _session.SessionCarriesHistory, + Screen = turn.Renders, + Sources = turn.Sources, + Renders = turn.Renders, + Results = turn.Results, + OnToolFailure = failure => _session.Events.RaiseToolFailure(turn.Index, failure), + Tools = _delegatedTools?.Tools, + ToolsFor = _delegatedTools?.ToolId, + }; +} diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs new file mode 100644 index 00000000..42f53653 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs @@ -0,0 +1,158 @@ +using System.Runtime.CompilerServices; +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +internal sealed class CallTurnStream +{ + private readonly CallSession _session; + + internal CallTurnStream(CallSession session) + { + ArgumentNullException.ThrowIfNull(session); + _session = session; + } + + /// Streams 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. + /// Cancels the model calls. + /// The reply, one update at a time. + internal async IAsyncEnumerable RunTurnStreamingCoreAsync( + ChatMessage userInput, + CallTurnOrigin? origin, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(userInput); + + var session = await _session.Ledger.OpenSessionAsync(cancellationToken).ConfigureAwait(false); + + var turn = _session.Runner.BeginTurn(userInput, session, origin); + + // A streaming turn becomes audible only once it hands the host its first piece of content. + // Until then nothing of it has reached the caller, and a barge-in belongs elsewhere. + var cancellation = _session.Interruptions.StartRun(cancellationToken); + try + { + List updates = []; + string? toolFault = null; + + // This scope covers opening the run's session and building the stream, and reaches no + // round: an async iterator restores its caller's execution context at every yield. + using var opening = _session.Runner.EnterAmbients(turn); + + var invocation = _session.Runner.TurnInvocationOf(turn); + var runSession = await _session.Runner.RunSessionAsync(turn, cancellation.Token).ConfigureAwait(false); + TurnRegistry.Set(runSession, invocation); + + var stream = ScopedEnumerator.Over( + turn.Agent + .RunStreamingAsync( + turn.Request, + runSession, + invocation.RunOptions(), + cancellationToken: cancellation.Token) + .GetAsyncEnumerator(cancellation.Token), + () => _session.Runner.EnterAmbients(turn)); + + try + { + while (true) + { + AgentResponseUpdate update; + + // The enumeration itself sits in its own try, because a method that yields takes + // no catch clause around the yield. + try + { + if (!await stream.MoveNextAsync().ConfigureAwait(false)) + { + break; + } + + update = stream.Current; + } + catch (OperationCanceledException) when (_session.Interruptions.CurrentInterruption() is not null) + { + // The caller spoke over the reply, and the relay already reported how much of + // it played. Nothing here estimates that value: see item 6c. + break; + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + // Section 8.7, sixth row. + toolFault = exception.Message; + break; + } + + updates.Add(update); + + var content = update.AsChatResponseUpdate(); + if (TurnMessages.CarriesContent(content) && Speaks(update)) + { + // Marked before the yield, not after it: an async iterator only resumes past + // a yield once the host comes back for the next update, and by then the host + // has already queued this piece for the caller. + _session.Interruptions.RunIsAudible = true; + + // The host speaks this, so it leaves the seam as fast as the model produced it. + yield return content; + } + } + } + finally + { + await stream.DisposeAsync().ConfigureAwait(false); + } + + // CompleteTurnAsync publishes LastTurn itself. See the same note in RunTurnAsync. The + // disposition comes off the raw updates and never off the folded response: update-level + // properties do not survive streaming coalescing. + _ = await _session.Completion.CompleteTurnAsync( + turn, updates.ToAgentResponse(), toolFault, ReadDisposition(updates), cancellationToken) + .ConfigureAwait(false); + } + finally + { + _session.Interruptions.EndRun(cancellation); + turn.Activity?.Dispose(); + } + } + + /// Reads whether the caller hears the node that produced one update. + /// One update of the run. + /// when the host should speak it. + internal bool Speaks(AgentResponseUpdate update) + => _session.Compiled.SpokenBy is not { } spoken + || (update.AuthorName is { } author && spoken.Contains(author)) + || update.AdditionalProperties?.Contains() is true; + + /// Reads what the turn layers reported about one finished turn. + /// What the agent answered. + /// The disposition, or when no layer marked the turn. + internal static TurnDisposition? ReadDisposition(AgentResponse response) + => response.AdditionalProperties is { } properties + && properties.TryGetValue(out var disposition) + ? disposition + : null; + + /// Reads what the turn layers reported across the updates of one streaming turn. + /// Every update the run produced, in order, before the seam filtered them. + /// The disposition, or when no update carried one. + internal static TurnDisposition? ReadDisposition(List updates) + { + TurnDisposition? found = null; + foreach (var update in updates) + { + if (update.AdditionalProperties is { } properties + && properties.TryGetValue(out var disposition)) + { + found = disposition; + } + } + + return found; + } +} diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs new file mode 100644 index 00000000..a94948c2 --- /dev/null +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnWriters.cs @@ -0,0 +1,78 @@ +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.State; +using AgentCore.Application.Tools; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +internal sealed class CallTurnWriters +{ + private readonly CallSession _session; + + internal CallTurnWriters(CallSession session) + { + ArgumentNullException.ThrowIfNull(session); + _session = session; + } + + /// Runs the extractor against the finished turn. + /// The turn that just spoke. + /// 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) + { + if (_session.Extractor is null || _session.Compiled.Configuration.Extractor is not { When: ExtractorTrigger.AfterReply }) + { + return null; + } + + // 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 + // 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]; + if (_session.Transcript.LastOrDefault(message => message.Role == ChatRole.Assistant && message.Text.Length > 0) is { } asked) + { + finished.Insert(0, asked); + } + + // A failed extraction never drops the turn. The result carries the reason instead. + var result = await _session.Extractor.ExtractAsync(_session.State, finished, _session.Clarifications, cancellationToken) + .ConfigureAwait(false); + + return result.Failure; + } + + /// Fills every tool-written slot from the tool results of one turn. + /// The messages the agent produced, oldest first. + internal void ApplyToolResults(IEnumerable messages) + { + // The name a call carries is the declared tool id, because the compile table names every + // function after the tools: entry it built. + ToolCallNames names = new(); + + foreach (var message in messages) + { + foreach (var content in message.Contents) + { + switch (content) + { + case FunctionCallContent call: + names.Called(call); + break; + + case FunctionResultContent result when names.Of(result) is { } toolId: + ToolStateWriter.Apply(_session.State, toolId, ToolResultJson.ToNode(result.Result)); + break; + + default: + break; + } + } + } + } +} diff --git a/src/AgentCore.Application/Runtime/CallSourceScope.cs b/src/AgentCore.Application/Runtime/CallSourceScope.cs deleted file mode 100644 index 063fafbb..00000000 --- a/src/AgentCore.Application/Runtime/CallSourceScope.cs +++ /dev/null @@ -1,11 +0,0 @@ -using AgentCore.Application.Ports; -using AgentCore.Application.Runtime.Turn; - -namespace AgentCore.Application.Runtime; - -/// Where a producer cites a source for the call that runs now. -public static class CallSourceScope -{ - /// The sources of the call that runs now, or when none is open. - public static ISourcePort? Current => TurnAmbients.Current?.Sources; -} diff --git a/src/AgentCore.Application/Runtime/CallStateScope.cs b/src/AgentCore.Application/Runtime/CallStateScope.cs index fa6fee9b..0f5c5d17 100644 --- a/src/AgentCore.Application/Runtime/CallStateScope.cs +++ b/src/AgentCore.Application/Runtime/CallStateScope.cs @@ -1,14 +1,18 @@ using System.Text.Json.Nodes; -using AgentCore.Application.Runtime.Turn; using AgentCore.Application.State; namespace AgentCore.Application.Runtime; /// -/// The state of the call that runs on this flow of execution. +/// The state of the call that runs on this flow of execution. An explicit open/close seam with +/// its own carrier: the loop opens the turn's document around every run, and a sessionless +/// graph opens its own around the run instead. Nothing reads the turn through this except the +/// guarded edges it was made for. /// public static class CallStateScope { + private static readonly AsyncLocal Flow = new(); + /// The message throws with when no scope is open. internal const string NoScopeMessage = "A guarded graph edge asked for the state of the running call, and no call scope is open on " @@ -20,13 +24,15 @@ public static class CallStateScope /// Opens the scope of one call over this flow of execution. /// The state of the call that runs now. - /// The scope. Disposing it puts back the state that was ambient before. + /// The scope. Disposing it puts back the state that was open before. /// is . public static IDisposable Enter(StateDocument state) { ArgumentNullException.ThrowIfNull(state); - return TurnAmbients.Amend(ambients => ambients with { State = state }); + var previous = Flow.Value; + Flow.Value = state; + return new Scope(previous); } /// Takes the snapshot a guarded graph edge reads. @@ -36,5 +42,26 @@ public static IDisposable Enter(StateDocument state) /// scope. /// public static IReadOnlyDictionary Snapshot() - => (TurnAmbients.Current?.State ?? throw new InvalidOperationException(NoScopeMessage)).Snapshot(); + => (Flow.Value ?? throw new InvalidOperationException(NoScopeMessage)).Snapshot(); + + /// One open scope. Disposing it puts back what was open before. + private sealed class Scope : IDisposable + { + private readonly StateDocument? _previous; + + private bool _closed; + + public Scope(StateDocument? previous) => _previous = previous; + + public void Dispose() + { + if (_closed) + { + return; + } + + _closed = true; + Flow.Value = _previous; + } + } } diff --git a/src/AgentCore.Application/Runtime/Clarifications.cs b/src/AgentCore.Application/Runtime/Clarifications.cs index 01eee47f..16c4bac3 100644 --- a/src/AgentCore.Application/Runtime/Clarifications.cs +++ b/src/AgentCore.Application/Runtime/Clarifications.cs @@ -1,5 +1,4 @@ using AgentCore.Application.Calls; -using AgentCore.Application.Runtime.Turn; using Microsoft.Agents.AI; namespace AgentCore.Application.Runtime; @@ -8,15 +7,6 @@ namespace AgentCore.Application.Runtime; /// One call'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). /// -/// -/// Constructed once by and put on as the same -/// instance every turn, so a value the extractor path writes is read back by the factory's probe and -/// vice versa. A graph: pattern: concurrent row runs several participants against this same -/// instance at once, so every read and every write takes — there is no member on -/// this type that touches a field without it. Reads go through and writes through -/// , each taking the lock once for the whole snapshot or transition, so a -/// concurrent participant can never observe a slot half way through §8's compound updates. -/// internal sealed class Clarifications { private readonly Lock _gate = new(); @@ -102,7 +92,7 @@ internal Probe ClaimProbe() /// /// /// Must run exactly once per turn, from CallSession.BeginTurn and nowhere else. - /// CallSession.EnterAmbients reopens its ambient scope once per streaming step. + /// CallSession.EnterAmbients reopens its state scope once per streaming step. /// internal void BeginTurn() { diff --git a/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs b/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs new file mode 100644 index 00000000..13f47a40 --- /dev/null +++ b/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs @@ -0,0 +1,61 @@ +using Microsoft.Agents.AI; +using System.Text.Json; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +// Runs one delegated agent directly — the same RunAsync every other run goes through — +// instead of the framework's agent-as-function machinery, which builds the nested run's +// options where no caller can file the turn. The bridge files the nested turn and the +// tools this delegation is offered on the nested run's own options, exactly like the +// loop does for the outer run. One nested run, one fresh session: concurrent delegations +// never share one. +internal static class DelegatedAgentRun +{ + /// Runs one inner agent for one delegating tool call. + /// The agent being delegated to. + /// What the outer agent asked, in words. + /// The parent turn, stripped per K42 — or null outside a turn. + /// The tools this delegation is offered, or null for none. + /// Cancels the run. + /// What the inner agent answered, as the outer agent reads it. + internal static async ValueTask RunAsync( + AIAgent inner, + string query, + TurnInvocation? nested, + IReadOnlyList? tools, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(query); + + var session = await inner.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + + ChatOptions chat = new() + { + AdditionalProperties = new AdditionalPropertiesDictionary(), + }; + + if (nested is not null) + { + chat.AdditionalProperties[TurnInvocation.ArgumentsKey] = nested; + } + + if (tools is { Count: > 0 }) + { + chat.Tools = [.. tools]; + } + + var response = await inner.RunAsync( + [new ChatMessage(ChatRole.User, query)], + session, + new ChatClientAgentRunOptions(chat), + cancellationToken).ConfigureAwait(false); + + // Marshaled like the framework's own agent-as-function result: the outer loop reads + // words either way, but callers pin the JsonElement shape. + return response.Text is { } text + ? JsonSerializer.SerializeToElement(text) + : null; + } +} diff --git a/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs new file mode 100644 index 00000000..24913c29 --- /dev/null +++ b/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs @@ -0,0 +1,70 @@ +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; + +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 +// 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 +{ + private const string NoTurnMessage = + "A files: tool runs only while a turn runs through a CallSession with a workspace root bound."; + + private readonly FileAccessProvider _template; + + private readonly FileAccessProviderOptions _options; + + public CallFilesProvider(string root, FileAccessProviderOptions options) + { + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(options); + + _options = options; + _template = new FileAccessProvider(new FileSystemAgentFileStore(root), options); + } + + /// + public override IReadOnlyList StateKeys => _template.StateKeys; + + /// + public override object? GetService(Type serviceType, object? serviceKey = null) + { + ArgumentNullException.ThrowIfNull(serviceType); + + return serviceType.IsInstanceOfType(this) && serviceKey is null + ? this + : _template.GetService(serviceType, serviceKey); + } + + /// + protected override async ValueTask InvokingCoreAsync( + InvokingContext context, CancellationToken cancellationToken) + { + var workspace = TurnRegistry.For(context.Session)?.Workspace + ?? throw new InvalidOperationException(NoTurnMessage); + + // Not using-declared on purpose: the tools this returns run after this method does, + // and disposing the provider would dispose the store out from under them. The store + // holds a path, not handles, so ordinary collection reclaims it. + FileAccessProvider inner = new(new FileSystemAgentFileStore(workspace), _options); + + return await inner.InvokingAsync(context, cancellationToken).ConfigureAwait(false); + } + + /// + protected override ValueTask InvokedCoreAsync( + InvokedContext context, CancellationToken cancellationToken) + => _template.InvokedAsync(context, cancellationToken); + + /// + public void Dispose() => _template.Dispose(); +} + +#pragma warning restore MAAI001 diff --git a/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs b/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs deleted file mode 100644 index 4571c058..00000000 --- a/src/AgentCore.Application/Runtime/Harness/CallScopedAgentFileStore.cs +++ /dev/null @@ -1,38 +0,0 @@ -using AgentCore.Application.Runtime.Turn; -using Microsoft.Agents.AI; - -namespace AgentCore.Application.Runtime.Harness; - -/// -/// The store behind an agent's files: block. One instance serves every call: each operation -/// resolves the running call's workspace folder off and forwards to a -/// fresh rooted there. -/// -#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0. -internal sealed class CallScopedAgentFileStore : AgentFileStore -{ - private const string NoTurnMessage = - "A files: tool runs only while a turn runs through a CallSession with a workspace root bound."; - - private static FileSystemAgentFileStore Inner() => - new(TurnAmbients.Current?.Workspace ?? throw new InvalidOperationException(NoTurnMessage)); - - public override Task WriteAsync(string path, string content, CancellationToken cancellationToken = default) => - Inner().WriteAsync(path, content, cancellationToken); - - public override Task ReadAsync(string path, CancellationToken cancellationToken = default) => - Inner().ReadAsync(path, cancellationToken); - - public override Task DeleteAsync(string path, CancellationToken cancellationToken = default) => - Inner().DeleteAsync(path, cancellationToken); - - public override Task> ListChildrenAsync(string directory, CancellationToken cancellationToken = default) => - Inner().ListChildrenAsync(directory, cancellationToken); - - public override Task FileExistsAsync(string path, CancellationToken cancellationToken = default) => - Inner().FileExistsAsync(path, cancellationToken); - - public override Task CreateDirectoryAsync(string path, CancellationToken cancellationToken = default) => - Inner().CreateDirectoryAsync(path, cancellationToken); -} -#pragma warning restore MAAI001 diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs index 5f184b42..9c7f017c 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShellEnvironmentProvider.cs @@ -26,7 +26,8 @@ public CallShellEnvironmentProvider(CallShellOptions options) protected override async ValueTask ProvideAIContextAsync( InvokingContext context, CancellationToken cancellationToken = default) { - var shells = TurnAmbients.Current?.Shells ?? throw new InvalidOperationException(NoTurnMessage); + var shells = TurnRegistry.For(context.Session)?.Shells + ?? throw new InvalidOperationException(NoTurnMessage); var snapshot = await shells.GetEnvironmentAsync(_options, cancellationToken).ConfigureAwait(false); diff --git a/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs index 23616190..b062ad4e 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallShellProvider.cs @@ -25,7 +25,8 @@ public CallShellProvider(CallShellOptions options) protected override ValueTask ProvideAIContextAsync( InvokingContext context, CancellationToken cancellationToken = default) { - var shells = TurnAmbients.Current?.Shells ?? throw new InvalidOperationException(NoTurnMessage); + var shells = TurnRegistry.For(context.Session)?.Shells + ?? throw new InvalidOperationException(NoTurnMessage); return new ValueTask(new AIContext { diff --git a/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs b/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs deleted file mode 100644 index 17a17ebc..00000000 --- a/src/AgentCore.Application/Runtime/KnowledgeScopeScope.cs +++ /dev/null @@ -1,22 +0,0 @@ -using AgentCore.Application.Runtime.Turn; -using AgentCore.Domain.Knowledge; - -namespace AgentCore.Application.Runtime; - -/// Opens the knowledge scope of one turn over this flow of execution. -public static class KnowledgeScopeScope -{ - /// Gets the scope open on this flow, or when none is. - public static KnowledgeScope? Current => TurnAmbients.Current?.Knowledge; - - /// Opens one scope over this flow. - /// What the turn may see. - /// The scope. Disposing it puts back what was ambient before. - /// is . - public static IDisposable Open(KnowledgeScope scope) - { - ArgumentNullException.ThrowIfNull(scope); - - return TurnAmbients.Amend(ambients => ambients with { Knowledge = scope }); - } -} diff --git a/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs b/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs index 7022b67e..6d7e08f0 100644 --- a/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs +++ b/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs @@ -1,3 +1,4 @@ +using System.Runtime.CompilerServices; using AgentCore.Application.Transcript; using Microsoft.Extensions.AI; @@ -6,14 +7,52 @@ namespace AgentCore.Application.Runtime; /// Takes what only the caller can use out of the history before the model sees it. internal sealed class ModelFacingChatClient(IChatClient inner) : DelegatingChatClient(inner) { - public override Task GetResponseAsync( + public override async Task GetResponseAsync( IEnumerable messages, ChatOptions? options = null, CancellationToken ct = default) - => base.GetResponseAsync(Strip(messages), options, ct); + { + using var _ = KeyHider.Hide(options); + return await base.GetResponseAsync(Strip(messages), options, ct).ConfigureAwait(false); + } - public override IAsyncEnumerable GetStreamingResponseAsync( - IEnumerable messages, ChatOptions? options = null, CancellationToken ct = default) - => base.GetStreamingResponseAsync(Strip(messages), options, ct); + public override async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + ChatOptions? options = null, + [EnumeratorCancellation] CancellationToken ct = default) + { + using var _ = KeyHider.Hide(options); + await foreach (var update in base.GetStreamingResponseAsync(Strip(messages), options, ct).ConfigureAwait(false)) + { + yield return update; + } + } private static IEnumerable Strip(IEnumerable messages) => messages.Select(static message => message.WithoutHostContent()); + + // The loop files the turn on the run's own options for the invoking client above; the + // vendor below must never see it. Hidden in place around the inner call and restored + // after: the options object belongs to this one run, and cloning it would drop vendor + // fields this layer knows nothing about. + private sealed class KeyHider : IDisposable + { + private readonly ChatOptions? _options; + private readonly object? _held; + private readonly bool _took; + + private KeyHider(ChatOptions? options) + { + _options = options; + _took = options?.AdditionalProperties?.Remove(TurnInvocation.ArgumentsKey, out _held) ?? false; + } + + public static KeyHider Hide(ChatOptions? options) => new(options); + + public void Dispose() + { + if (_took && _options?.AdditionalProperties is { } kept) + { + kept[TurnInvocation.ArgumentsKey] = _held; + } + } + } } diff --git a/src/AgentCore.Application/Runtime/OuterToolCall.cs b/src/AgentCore.Application/Runtime/OuterToolCall.cs deleted file mode 100644 index 00b45201..00000000 --- a/src/AgentCore.Application/Runtime/OuterToolCall.cs +++ /dev/null @@ -1,39 +0,0 @@ -using AgentCore.Application.Runtime.Turn; - -namespace AgentCore.Application.Runtime; - -/// -/// The outermost tool call open on this flow of execution. -/// -internal static class OuterToolCall -{ - /// The id of the outermost tool call open on this flow, or when none is. - internal static string? Current => TurnAmbients.Current?.OuterCallId; - - /// Opens the scope of one tool call over this flow of execution. - /// The id of the tool call being opened. - /// - /// Whether a tool call was already open on this flow, so this one runs inside it. Reported from - /// here rather than read separately by the caller, because the outermost call is what owns the - /// ambient and a caller that read after this method would always see one. - /// - /// The scope. Disposing it puts back what was ambient before. - internal static IDisposable Enter(string callId, out bool nested) - { - ArgumentNullException.ThrowIfNull(callId); - - nested = Current is not null; - - return nested ? NoOpScope.Instance : TurnAmbients.Amend(ambients => ambients with { OuterCallId = callId }); - } - - /// A scope that puts nothing back, because it never changed anything. - private sealed class NoOpScope : IDisposable - { - internal static readonly NoOpScope Instance = new(); - - public void Dispose() - { - } - } -} diff --git a/src/AgentCore.Application/Runtime/ToolCallScopes.cs b/src/AgentCore.Application/Runtime/ToolCallScopes.cs index 6d63ddf0..2e593e62 100644 --- a/src/AgentCore.Application/Runtime/ToolCallScopes.cs +++ b/src/AgentCore.Application/Runtime/ToolCallScopes.cs @@ -1,33 +1,24 @@ -using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools; namespace AgentCore.Application.Runtime; -/// -/// The of the turn running on this flow of execution. -/// +// The of one turn, built from the invocation the call runs under. internal static class ToolCallScopes { - /// The message throws with when no turn is open. + /// 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."; - /// Builds the scope of the call and turn running on this flow. + /// Builds the scope of the call and turn one invocation belongs to. + /// The turn the tool call runs under. /// The scope. - /// - /// No turn is open on this flow of execution. The message names the fault and says what opens one. - /// - internal static ToolCallScope Current() + /// is . + internal static ToolCallScope From(TurnInvocation invocation) { - var ambients = TurnAmbients.Current; + ArgumentNullException.ThrowIfNull(invocation); - if (ambients?.CallId is not { } callId || ambients.State is not { } state) - { - throw new InvalidOperationException(NoTurnMessage); - } - - return new ToolCallScope(callId, state.TurnIndex, state.Stage, ambients.Workspace); + return new ToolCallScope(invocation.CallId, invocation.TurnIndex, invocation.Stage, invocation.Workspace); } } diff --git a/src/AgentCore.Application/Runtime/ToolFailureScope.cs b/src/AgentCore.Application/Runtime/ToolFailureScope.cs deleted file mode 100644 index eb555db9..00000000 --- a/src/AgentCore.Application/Runtime/ToolFailureScope.cs +++ /dev/null @@ -1,42 +0,0 @@ -using AgentCore.Application.Runtime.Turn; -using AgentCore.Domain.Audit; - -namespace AgentCore.Application.Runtime; - -/// One tool call that did not run to completion, as the function-invocation loop saw it. -internal sealed record ToolFailure -{ - /// Gets the name the MODEL called. - - public required string ToolName { get; init; } - - /// Gets the id the model gave this one call. - public required string ToolCallId { get; init; } - - /// Gets which of the two ways a tool call fails this one was. - public required ToolFailureKind Kind { get; init; } - - /// Gets what went wrong, in one sentence. It never holds a secret value. - public required string Message { get; init; } -} - -/// -/// Where a tool failure is reported on this flow of execution. -/// -internal static class ToolFailureScope -{ - /// Opens the scope of one turn over this flow of execution. - /// What to do with each failure. It is called on the framework's tool flow. - /// The scope. Disposing it puts back the listener that was ambient before. - /// is . - internal static IDisposable Enter(Action listener) - { - ArgumentNullException.ThrowIfNull(listener); - - return TurnAmbients.Amend(ambients => ambients with { OnToolFailure = listener }); - } - - /// Reports one tool failure to the call running on this flow of execution. - /// What did not run to completion. - internal static void Report(ToolFailure failure) => TurnAmbients.Current?.OnToolFailure?.Invoke(failure); -} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs b/src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs deleted file mode 100644 index da5fe994..00000000 --- a/src/AgentCore.Application/Runtime/Turn/TurnAmbients.cs +++ /dev/null @@ -1,147 +0,0 @@ -using AgentCore.Application.Ports; -using AgentCore.Application.Runtime.Harness; -using AgentCore.Application.State; -using AgentCore.Domain.Knowledge; - -namespace AgentCore.Application.Runtime.Turn; - -/// -/// Everything one turn makes ambient, carried as a single value on the flow of execution. -/// -internal sealed record TurnAmbients -{ - private static readonly TurnAmbients None = new(); - - private static readonly AsyncLocal Ambient = new(); - - /// Gets what is ambient on this flow, or when nothing is open. - internal static TurnAmbients? Current => Ambient.Value; - - /// Gets the id of the call the turn belongs to. - public string? CallId { get; init; } - - /// Gets the state document the call reads and writes. - public StateDocument? State { get; init; } - - /// Gets the screen this call draws on, or when it has none. - public IRenderPort? Screen { get; init; } - - /// Gets what a turn has drawn and not yet attached to a message, or when this call has no screen. - public TurnRenders? Renders { get; init; } - - /// Gets what a turn has cited and not yet attached to a message. - public TurnSources? Sources { get; init; } - - /// Gets what the turn's tools answered, for a script to read, or . - public TurnResults? Results { get; init; } - - /// Gets what to do with a tool failure the run reports. - public Action? OnToolFailure { get; init; } - - /// Gets the turn the tools are running inside. - public TurnContext? Context { get; init; } - - /// Gets the id of the outermost tool call open on this flow, or when none is. - public string? OuterCallId { get; init; } - - /// Gets what the turn may see of the knowledge base, or . - public KnowledgeScope? Knowledge { get; init; } - - /// Gets the call's ambiguity holder (K36), or inside a nested tool call (K42). - public Clarifications? Clarifications { get; init; } - - /// Gets the folder this call owns on disk, or when the host bound no workspace root. - public string? Workspace { get; init; } - - /// Gets this call's shell executors, or when the call has no workspace. - public CallShells? Shells { get; init; } - - /// Opens what a turn owns, and carries every other ambient through unchanged. - /// The id of the call the turn belongs to. - /// The state document the call reads and writes. - /// What this turn draws into, or when it has no screen. - /// What this turn cites into. Never null: a call with no screen still has sources. - /// What this turn's tools answer into. - /// What to do with a tool failure the run reports. - /// The turn the tools are running inside. - /// What this turn may see of the knowledge base, or when the document composes none. - /// The call's ambiguity holder. - /// The folder this call owns on disk, or when the host bound no workspace root. - /// This call's shell executors, or when the call has no workspace. - internal static IDisposable Enter( - string callId, - StateDocument state, - TurnRenders? renders, - TurnSources sources, - TurnResults results, - Action onToolFailure, - TurnContext context, - KnowledgeScope? knowledge, - Clarifications clarifications, - string? workspace, - CallShells? shells) - { - ArgumentNullException.ThrowIfNull(callId); - ArgumentNullException.ThrowIfNull(state); - ArgumentNullException.ThrowIfNull(sources); - ArgumentNullException.ThrowIfNull(results); - ArgumentNullException.ThrowIfNull(onToolFailure); - ArgumentNullException.ThrowIfNull(context); - ArgumentNullException.ThrowIfNull(clarifications); - - var current = Ambient.Value ?? None; - - return Push(current with - { - CallId = callId, - State = state, - Screen = renders, - Renders = renders, - Sources = sources, - Results = results, - OnToolFailure = onToolFailure, - Context = context, - Knowledge = knowledge ?? current.Knowledge, - Clarifications = clarifications, - Workspace = workspace, - Shells = shells, - }); - } - - /// Opens one changed ambient over this flow, leaving the rest as they are. - internal static IDisposable Amend(Func change) - { - ArgumentNullException.ThrowIfNull(change); - - return Push(change(Ambient.Value ?? None)); - } - - private static Scope Push(TurnAmbients next) - { - var previous = Ambient.Value; - Ambient.Value = next; - return new Scope(previous); - } - - /// One open scope. Disposing it puts back what was ambient before. - private sealed class Scope : IDisposable - { - private readonly TurnAmbients? _previous; - - private bool _closed; - - public Scope(TurnAmbients? previous) => _previous = previous; - - public void Dispose() - { - if (_closed) - { - // A second dispose must not put an older value back over a newer scope. - return; - } - - _closed = true; - Ambient.Value = _previous; - } - } -} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs b/src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs index a98d69e3..363b5eea 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnContextProvider.cs @@ -14,16 +14,13 @@ protected override ValueTask ProvideAIContextAsync( { ArgumentNullException.ThrowIfNull(context); - var instructions = TurnContextScope.For(context.Session)?.Instructions; - - var tools = TurnContextScope.ToolsFor(FunctionInvokingChatClient.CurrentContext?.Function.Name); + var instructions = TurnRegistry.For(context.Session)?.Instructions; return new(new AIContext { Messages = string.IsNullOrEmpty(instructions) ? null : [new ChatMessage(ChatRole.System, instructions)], - Tools = tools, }); } } diff --git a/src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs b/src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs deleted file mode 100644 index c7408109..00000000 --- a/src/AgentCore.Application/Runtime/Turn/TurnContextScope.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Runtime.Turn; - -/// -/// What one turn adds to the model invocation, on top of what the compiled agent already carries. -/// -internal sealed record TurnContext -{ - /// Gets the session the turn runs on. The context applies to a run on that session alone. - public required AgentSession Session { get; init; } - - /// Gets the instructions for this one invocation, or for none. - public string? Instructions { get; init; } - - /// Gets the tools a delegated run of this call is offered, or for none. - public IReadOnlyList? Tools { get; init; } - - /// Gets the id of the delegating tool are meant for. - public string? ToolsFor { get; init; } - - /// - /// Gets whether this row's session carries the caller's own history — true on rows 1 and 2, false - /// on a graph row. §8 step 6 reads this to decide whether the probe may record what it named - /// (K39, drawn for the record rather than for the message): the probe runs inside a search - /// delegate that is never handed a session to compare, unlike 's - /// ReferenceEquals guard, so it reads this flag off the ambient instead. - /// - public bool CarriesHistory { get; init; } -} - -/// -/// The turn whose per-invocation context runs on this flow of execution. -/// -internal static class TurnContextScope -{ - /// Opens the context of one turn over this flow of execution. - /// What this turn adds to its own model invocation. - /// The scope. Disposing it puts back the context that was ambient before. - /// is . - internal static IDisposable Enter(TurnContext context) - { - ArgumentNullException.ThrowIfNull(context); - - return TurnAmbients.Amend(ambients => ambients with { Context = context }); - } - - /// Reads the context of the turn a run on one session belongs to. - /// The session the framework is about to run on. - /// The context, or when this run is not that turn's own. - internal static TurnContext? For(AgentSession? session) - => TurnAmbients.Current?.Context is { } context && ReferenceEquals(context.Session, session) - ? context - : null; - - /// Reads the tools offered to a run delegated through one tool of this call. - /// - /// The tool whose invocation this run sits under, or when it sits under - /// none — which is every run the caller's own agent makes. - /// - /// The tools, or when this run is offered none. - internal static IReadOnlyList? ToolsFor(string? delegatingToolId) - => delegatingToolId is not null - && TurnAmbients.Current?.Context is { Tools: { Count: > 0 } tools, ToolsFor: { } gate } - && string.Equals(gate, delegatingToolId, StringComparison.Ordinal) - ? tools - : null; -} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs b/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs new file mode 100644 index 00000000..5685d9ec --- /dev/null +++ b/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs @@ -0,0 +1,33 @@ +using System.Runtime.CompilerServices; +using Microsoft.Agents.AI; + +namespace AgentCore.Application.Runtime.Turn; + +// The turn running on one session, keyed by the session the framework hands providers — +// the MAF AgentSession.StateBag shape, but live: the bag serializes and a turn holds +// sessions and tools, so the table carries what the bag cannot. The loop files the turn +// under the session the run actually gets (a graph row re-creates its own per turn); +// providers read it back off the session their InvokingContext carries. Weak keys: an +// entry dies with its session, and each turn overwrites the last, so nothing here leaks +// or crosses turns. +internal static class TurnRegistry +{ + private static readonly ConditionalWeakTable Turns = new(); + + /// Files the turn running on one session. + /// The session the run actually gets. + /// What that run may see and cite. + internal static void Set(AgentSession session, TurnInvocation turn) + { + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(turn); + + Turns.Remove(session); + Turns.Add(session, turn); + } + + /// Reads the turn a run on one session belongs to, or null when it is not ours. + /// The session the framework is about to run on. + internal static TurnInvocation? For(AgentSession? session) + => session is not null && Turns.TryGetValue(session, out var turn) ? turn : null; +} diff --git a/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs b/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs index b9889944..1a64cae3 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnRenders.cs @@ -10,6 +10,56 @@ internal sealed class TurnRenders : 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) @@ -18,7 +68,7 @@ public void Publish(string name, string renderId, object data, bool transient = ArgumentNullException.ThrowIfNull(renderId); ArgumentNullException.ThrowIfNull(data); - if (transient || OuterToolCall.Current is not { } callId) + if (transient || _outerCallId is not { } callId) { return; } diff --git a/src/AgentCore.Application/Runtime/Turn/TurnResults.cs b/src/AgentCore.Application/Runtime/Turn/TurnResults.cs index b78920bd..606518a5 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnResults.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnResults.cs @@ -20,6 +20,10 @@ internal sealed class TurnResults private readonly List _order = []; + private readonly HashSet _callIds = new(StringComparer.Ordinal); + + private readonly List>> _sweeps = []; + /// The tools that answered something structured, in first-answer order. internal IReadOnlyList Tools { @@ -56,6 +60,51 @@ internal void Record(string tool, object? result) answers.Add(node); } } + + /// Keeps one tool call's id and its client's drain sweep, so turn end can sweep drain state for calls whose round never drained. + /// The id the model gave this one call. + /// Drops that client's entries for the turn's ids. + internal void NoteCall(string callId, Action> sweep) + { + ArgumentNullException.ThrowIfNull(callId); + ArgumentNullException.ThrowIfNull(sweep); + + lock (_gate) + { + _callIds.Add(callId); + _sweeps.Add(sweep); + } + } + + /// Sweeps every recorded client's drain state for this turn's call ids. + internal void Sweep() + { + IReadOnlyList callIds; + List>> sweeps; + + lock (_gate) + { + callIds = [.. _callIds]; + sweeps = [.. _sweeps]; + } + + foreach (var sweep in sweeps) + { + sweep(callIds); + } + } + + /// Every tool call id the turn recorded, in no particular order. + internal IReadOnlyList CallIds + { + get + { + lock (_gate) + { + return [.. _callIds]; + } + } + } /// The latest answer of one tool, or . /// The tool's declared id. diff --git a/src/AgentCore.Application/Runtime/Turn/TurnSources.cs b/src/AgentCore.Application/Runtime/Turn/TurnSources.cs index eeb50df7..1235fb9e 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnSources.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnSources.cs @@ -10,13 +10,63 @@ internal sealed class TurnSources : 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 (OuterToolCall.Current is not { } callId) + if (_outerCallId is not { } callId) { return; } diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs new file mode 100644 index 00000000..3431cd8a --- /dev/null +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -0,0 +1,85 @@ +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; +using AgentCore.Domain.Knowledge; +using Microsoft.Extensions.AI; +using Microsoft.Agents.AI; + +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 +// 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. + 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 zero-based index of the turn now running. + public required int TurnIndex { get; init; } + + /// Gets the stage the machine holds. Empty when the document declares no policy. + public required string Stage { get; init; } + + /// Gets the folder this call owns on disk, or . + public string? Workspace { get; init; } + + /// Gets this call's shell executors, or . + public CallShells? 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. + public Clarifications? Clarifications { get; init; } + + /// Gets the instructions for this one invocation, or for none. + public string? Instructions { 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. + public IRenderPort? Screen { get; init; } + + /// Gets what the turn cites into. Never on a loop-built turn. + public TurnSources? Sources { get; init; } + + /// Gets what the turn draws into, or when it has no screen. + public TurnRenders? Renders { get; init; } + + /// Gets what the turn's tools answer into. Never on a loop-built turn. + public TurnResults? Results { get; init; } + + /// Gets the tools a delegated run of this call is offered, or for none. + public IReadOnlyList? Tools { get; init; } + + /// Gets the id of the delegating tool are meant for. + public string? ToolsFor { get; init; } + + /// Gets what to do with a tool failure the run reports. + public Action? OnToolFailure { get; init; } + + /// Gets the outermost tool call open on this flow, stamped by the invoking client, + /// or before the first tool call. + public string? OuterCallId { get; init; } + + /// Gets whether this turn runs nested inside another tool call. A nested turn neither latches the holder nor records. + public bool Nested { get; init; } + + /// Builds the per-run options carrying this turn to the invoking client. + internal ChatClientAgentRunOptions RunOptions() + { + ChatOptions chat = new() + { + AdditionalProperties = new AdditionalPropertiesDictionary { [ArgumentsKey] = this }, + }; + + return new ChatClientAgentRunOptions(chat); + } +} diff --git a/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs b/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs new file mode 100644 index 00000000..c92d1aab --- /dev/null +++ b/src/AgentCore.Application/Tools/Binding/ToolParameterBindings.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using AgentCore.Application.Runtime; +using Microsoft.Extensions.AI; + +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. +internal static class ToolParameterBindings +{ + /// Binds one runtime-filled parameter, or answers for the model's own. + internal static AIFunctionFactoryOptions.ParameterBindingOptions For(ParameterInfo parameter) + { + ArgumentNullException.ThrowIfNull(parameter); + + var type = parameter.ParameterType; + return type == typeof(ToolCallScope) || type == typeof(TurnInvocation) + ? new() { ExcludeFromSchema = true, BindParameter = (_, args) => Bind(type, args) } + : default; + } + + 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; + + if (type == typeof(TurnInvocation)) + { + return invocation; + } + + return invocation is not null + ? ToolCallScopes.From(invocation) + : throw new InvalidOperationException(ToolCallScopes.NoTurnMessage); + } +} diff --git a/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs b/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs index 39571483..c36cb2d1 100644 --- a/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs +++ b/src/AgentCore.Application/Tools/Binding/TypedBindingTool.cs @@ -1,6 +1,5 @@ using System.Text.Json; using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime; using Microsoft.Extensions.AI; namespace AgentCore.Application.Tools.Binding; @@ -18,9 +17,7 @@ internal TypedBindingTool(ToolConfiguration tool, Delegate method) { Name = tool.Id, Description = tool.Description, - ConfigureParameterBinding = parameter => parameter.ParameterType == typeof(ToolCallScope) - ? new() { ExcludeFromSchema = true, BindParameter = static (_, _) => ToolCallScopes.Current() } - : default, + ConfigureParameterBinding = ToolParameterBindings.For, }); /// diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs b/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs index 154a26e9..94905c64 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingAgentDefinition.cs @@ -41,8 +41,8 @@ public IReadOnlyList InnerTools(ToolConfiguration tool, BuiltinToolPorts /// The drawing model cannot see the conversation, and it must not see the rows either: they go /// to its script. What it gets is the request and, after it, the shape of each answer. /// - public string Compose(string query) - => DrawingData.Describe(TurnAmbients.Current?.Results) is { } data + public string Compose(string query, TurnResults? results) + => DrawingData.Describe(results) is { } data ? query + "\n\n" + data : query; } diff --git a/src/AgentCore.Application/Tools/Drawing/PresentTool.cs b/src/AgentCore.Application/Tools/Drawing/PresentTool.cs index c3a874f7..78b845d0 100644 --- a/src/AgentCore.Application/Tools/Drawing/PresentTool.cs +++ b/src/AgentCore.Application/Tools/Drawing/PresentTool.cs @@ -4,6 +4,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Scripting; +using AgentCore.Application.Tools.Binding; using Microsoft.Extensions.AI; namespace AgentCore.Application.Tools.Drawing; @@ -33,26 +34,28 @@ internal static AIFunction Create(string toolId, IScriptRunnerPort scripts) return AIFunctionFactory.Create( async ([Description("JavaScript: the body of a function that reads `data` and returns the tree to draw.")] string code, + TurnInvocation? turn, CancellationToken cancellationToken) - => await PublishAsync(toolId, scripts, code, cancellationToken).ConfigureAwait(false), + => await PublishAsync(toolId, scripts, code, turn, cancellationToken).ConfigureAwait(false), new AIFunctionFactoryOptions { Name = Name, Description = "Run code that builds one tree for the caller and draw it. Call this once.", ExcludeResultSchema = true, + ConfigureParameterBinding = ToolParameterBindings.For, }); } private static async ValueTask PublishAsync( - string toolId, IScriptRunnerPort scripts, string code, CancellationToken cancellationToken) + string toolId, IScriptRunnerPort scripts, string code, TurnInvocation? turn, CancellationToken cancellationToken) { - if (CallRenderScope.Current is not { } screen) + if (turn?.Screen is not { } screen) { return ToolErrorResult.Create( toolId, "this call has no screen, so nothing can be drawn on it. Say it in words instead."); } - var data = TurnAmbients.Current?.Results?.Data() ?? new JsonObject { [TurnResults.AllKey] = new JsonObject() }; + var data = turn?.Results?.Data() ?? new JsonObject { [TurnResults.AllKey] = new JsonObject() }; var run = await scripts.RunAsync(new ScriptRequest(code, data) { Emit = Name }, cancellationToken).ConfigureAwait(false); if (run.Error is { } error) @@ -80,10 +83,10 @@ private static async ValueTask PublishAsync( // The outer tool call is stable across every retry the drawing agent's own tool loop // makes for this one call, so a rejected tree followed by an accepted one replaces the - // drawing rather than leaving both behind. The ?? toolId fallback only matters to a port - // with no rule against an absent outer call: the shipped TurnRenders discards a publish - // with none open regardless of the id, so in production this key is never read back. - screen.Publish(RendererName, OuterToolCall.Current ?? toolId, node); + // drawing rather than leaving both behind. The ?? toolId fallback only matters outside + // a turn: the shipped collectors discard a publish with none open regardless of the id, + // so in production this key is never read back. + screen.Publish(RendererName, turn?.OuterCallId ?? toolId, node); return new JsonObject { ["drew"] = receipt }; } diff --git a/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs b/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs index a205e4b0..86b2b951 100644 --- a/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs +++ b/src/AgentCore.Application/Tools/Shipped/IShippedAgentDefinition.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools.Builtin; using Microsoft.Extensions.AI; @@ -32,6 +33,7 @@ internal interface IShippedAgentDefinition : IToolDefinition /// Builds the request this agent reads from what the outer agent wrote. /// The outer agent's one string. + /// What this turn's tools answered, or outside a turn. /// The request. Most agents hand the string through unchanged. - string Compose(string query); + string Compose(string query, TurnResults? results); } diff --git a/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs b/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs index 30464497..43953aa2 100644 --- a/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs +++ b/src/AgentCore.Application/Tools/Shipped/ShippedAgentBuilder.cs @@ -1,6 +1,7 @@ using System.Text.Json; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Registry; using Microsoft.Agents.AI; @@ -61,7 +62,9 @@ internal static AIFunction Build( Description = described.Description!, ExcludeResultSchema = true, }), - definition), + definition, + tool.Id, + agent), tool.Id, rounds); } @@ -75,30 +78,44 @@ private sealed class ComposedRequest : DelegatingAIFunction private const string QueryParameter = "query"; private readonly IShippedAgentDefinition _definition; + private readonly string _toolId; + private readonly AIAgent _inner; - internal ComposedRequest(AIFunction inner, IShippedAgentDefinition definition) + internal ComposedRequest(AIFunction inner, IShippedAgentDefinition definition, string toolId, AIAgent innerAgent) : base(inner) { _definition = definition; + _toolId = toolId ?? throw new ArgumentNullException(nameof(toolId)); + _inner = innerAgent ?? throw new ArgumentNullException(nameof(innerAgent)); } protected override ValueTask InvokeCoreAsync( AIFunctionArguments arguments, CancellationToken cancellationToken) { - if (arguments.TryGetValue(QueryParameter, out var value) && Text(value) is { } query) + if (!arguments.TryGetValue(QueryParameter, out var value) || Text(value) is not { } query) { - var composed = new AIFunctionArguments(new Dictionary(arguments, StringComparer.Ordinal)) - { - Services = arguments.Services, - Context = arguments.Context, - }; - composed[QueryParameter] = _definition.Compose(query); - return InnerFunction.InvokeAsync(composed, cancellationToken); + throw new InvalidOperationException( + $"'{_toolId}' was called without a '{QueryParameter}' string, so there is no request to compose."); } - return InnerFunction.InvokeAsync(arguments, cancellationToken); + var parent = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var turn) && turn is TurnInvocation p + ? p + : null; + + var composed = _definition.Compose(query, TurnResultsOf(arguments)); + var nested = parent is not null + ? parent with { Clarifications = null, Nested = true } + : null; + var offered = parent?.ToolsFor == _toolId ? parent?.Tools : null; + + return DelegatedAgentRun.RunAsync(_inner, composed, nested, offered, cancellationToken); } + /// Reads what this turn's tools answered out of one call's arguments. + private static TurnResults? TurnResultsOf(AIFunctionArguments arguments) + => arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var filed) + ? (filed as TurnInvocation)?.Results + : null; private static string? Text(object? value) => value switch diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs index a803c854..22bf82aa 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs @@ -2,7 +2,6 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; using AgentCore.Domain.Knowledge; using Google.Protobuf.Collections; using Microsoft.Extensions.AI; @@ -75,24 +74,22 @@ public QdrantKnowledgeStore( /// public void Dispose() => (_channel as IDisposable)?.Dispose(); - /// public async ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); - var scope = KnowledgeScopeScope.Current; if (_options.Scoped) { // Two different host bugs, so two different messages. An empty facet map filters - // nothing, which is the same leak as no ambient at all: a host that reads a customer + // nothing, which is the same leak as no scope at all: a host that reads a customer // record with no product on it builds one without noticing. if (scope is null) { throw new InvalidOperationException( - "This deployment declares scoped: true and no KnowledgeScope is open on this turn. " - + "An unscoped search serves every customer every card, so it fails instead. Open the " - + "scope before the call, or set scoped: false on the agent."); + "This deployment declares scoped: true and the search arrived without a KnowledgeScope. " + + "An unscoped search serves every customer every card, so it fails instead. Pass the " + + "scope to SearchAsync, or set scoped: false on the agent."); } if (scope.Facets.Count == 0) diff --git a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs index 58a5a204..6dee0bea 100644 --- a/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs +++ b/src/AgentCore.Infrastructure/Llm/OpenAI/OpenAiChatClientAdapter.cs @@ -1,5 +1,5 @@ // The reasoning-effort type is marked for evaluation by the SDK (OPENAI001). It is pinned at -// OpenAI 2.12.0 and covered by OpenAiReasoningEffortTests, which fail loudly if a bump moves it. +// OpenAI 2.13.0 and covered by OpenAiReasoningEffortTests, which fail loudly if a bump moves it. #pragma warning disable OPENAI001 using System.ClientModel; diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs index cfbbc84f..595a0974 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs @@ -4,6 +4,11 @@ using Microsoft.Extensions.AI; using ModelContextProtocol.Protocol; +// 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. + namespace AgentCore.Infrastructure.Tools.Mcp; /// @@ -17,6 +22,8 @@ internal sealed class McpTool : AIFunction private readonly string _id; + private readonly HashSet? _declared; + /// Creates the tool. /// The server this tool is called on. /// The tool as the server described it when the session opened. @@ -30,6 +37,28 @@ public McpTool(McpServerSession session, McpToolDescriptor descriptor, string id _session = session; _descriptor = descriptor; _id = id; + _declared = DeclaredProperties(descriptor.JsonSchema); + } + + /// Reads the property names one tool schema declares, if it declares any. + /// The schema the server listed for this tool. + /// The names, or when the schema names none. + private static HashSet? DeclaredProperties(JsonElement schema) + { + if (schema.ValueKind is not JsonValueKind.Object + || !schema.TryGetProperty("properties", out var properties) + || properties.ValueKind is not JsonValueKind.Object) + { + return null; + } + + HashSet names = new(StringComparer.Ordinal); + foreach (var property in properties.EnumerateObject()) + { + names.Add(property.Name); + } + + return names; } /// @@ -49,7 +78,23 @@ public McpTool(McpServerSession session, McpToolDescriptor descriptor, string id try { - var answer = await _session.CallAsync(_descriptor.Name, arguments, cancellationToken) + // The model is built against this schema, so anything outside it is harness + // residue rather than model intent: the filed turn carries delegates no JSON + // writer can hold. A schema that names no properties keeps the old passthrough. + var outgoing = arguments; + if (_declared is not null) + { + outgoing = new AIFunctionArguments(); + foreach (var entry in arguments) + { + if (_declared.Contains(entry.Key)) + { + outgoing[entry.Key] = entry.Value; + } + } + } + + var answer = await _session.CallAsync(_descriptor.Name, outgoing, cancellationToken) .ConfigureAwait(false); return Unwrap(answer); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs index 361d15be..96b57c47 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ClarificationWiringBindingTests.cs @@ -1,13 +1,14 @@ +using System.Text.Json; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; -using AgentCore.Application.Tests.Runtime.Turn; using AgentCore.Domain.Knowledge; -using AgentCore.TestSupport; using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; using Xunit; namespace AgentCore.Application.Tests.Configuration.Compilation; @@ -17,12 +18,6 @@ namespace AgentCore.Application.Tests.Configuration.Compilation; /// bound search. The wiring is document-level and the knowledge: block is per agent, so the /// compiler is the only place the two meet. /// -/// -/// KnowledgeProbeTests hand-builds its ResolvedKnowledge and so proves only that the -/// probe reads what it is given. These tests compile a real document, so a compiler that composed -/// the block and then handed the probe an unwired one fails here — where it would otherwise ship -/// green and degrade every deployment's probe to the "holds nothing" notice. -/// public sealed class ClarificationWiringBindingTests { private const string ModelDescription = "The model, as printed on the machine."; @@ -69,10 +64,16 @@ public async Task TheDocumentsAmbiguityWiring_ReachesTheAgentsOwnBoundSearch() // carries across: drop any of ambiguity, wildcard.value, wildcard.facets, scope.template or // fromState on the way, and this note collapses into the bare "holds nothing" notice. var port = new ScopedFakePort(); - using var clarifications = TurnAmbientsTestScope.WithClarifications(new Clarifications()); - using var scope = KnowledgeScopeScope.Open(Scope(model: "*", audience: "everyone")); + var turn = new TurnInvocation + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Knowledge = Scope(model: "*", audience: "everyone"), + Clarifications = new Clarifications(), + }; - var note = await SearchAsync(CompileTheSearchProvider(port), "belt slipping"); + var note = await SearchAsync(CompileTheSearchProvider(port), "belt slipping", turn); Assert.Contains("It could be: e33, f63", note, StringComparison.Ordinal); Assert.Equal(2, port.Calls); @@ -84,16 +85,22 @@ public async Task TheSlotsOwnDescription_ReachesTheNoteTheProbeWrites() // The description lives under state:, not under providers.knowledge, so it reaches the probe // only because the compiler joined the two. Losing it degrades the ask to the bare slot name. var port = new ScopedFakePort(); - using var clarifications = TurnAmbientsTestScope.WithClarifications(new Clarifications()); - using var scope = KnowledgeScopeScope.Open(Scope(model: "*", audience: "everyone")); + var turn = new TurnInvocation + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Knowledge = Scope(model: "*", audience: "everyone"), + Clarifications = new Clarifications(), + }; - var note = await SearchAsync(CompileTheSearchProvider(port), "belt slipping"); + var note = await SearchAsync(CompileTheSearchProvider(port), "belt slipping", turn); Assert.Contains(ModelDescription, note, StringComparison.Ordinal); Assert.DoesNotContain("known: model ", note, StringComparison.Ordinal); } - private static TextSearchProvider CompileTheSearchProvider(IKnowledgeRetrievalPort port) + private static FacetFilterProvider CompileTheSearchProvider(IKnowledgeRetrievalPort port) { using SequencedChatClient reply = new("hello there."); @@ -101,7 +108,7 @@ private static TextSearchProvider CompileTheSearchProvider(IKnowledgeRetrievalPo ConfigurationLoader.LoadYaml(WiredYaml), new AgentCompilationContext(new FakeChatClientFactory(reply)) { Knowledge = port }); - return Assert.Single(Providers(compiled.Agents["only"]).OfType()); + return Assert.Single(Providers(compiled.Agents["only"]).OfType()); } private static IEnumerable Providers(AIAgent agent) @@ -123,10 +130,71 @@ private static KnowledgeScope Scope(string model, string audience) }; /// The one notice the bound search returned, as text. - private static async Task SearchAsync(TextSearchProvider provider, string query) - => Assert.Single( - await TextSearchProviderInternals.SearchAsync( - provider, query, TestContext.Current.CancellationToken).ConfigureAwait(false)).Text; + private static async Task SearchAsync(AIContextProvider provider, string query, TurnInvocation turn) + { + StubSession session = new(); + var context = await provider.InvokingAsync( + 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) + { + ["userQuestion"] = query, + [TurnInvocation.ArgumentsKey] = turn, + }), + TestContext.Current.CancellationToken).ConfigureAwait(false) + as IReadOnlyList; + return Assert.Single(results!).Text; + } + + /// Runs the provider the way the framework runs it, over one caller message. + private static AIContextProvider.InvokingContext Invoking(string text, AgentSession session) + { +#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. + return new( + StubAgent.Instance, + session, + new AIContext { Messages = [new ChatMessage(ChatRole.User, text)] }); +#pragma warning restore MAAI001 + } + + private sealed class StubSession : AgentSession; + + /// Stands in for the agent the framework names on a context. Nothing here runs it. + private sealed class StubAgent : AIAgent + { + public static StubAgent Instance { get; } = new(); + + protected override ValueTask CreateSessionCoreAsync( + CancellationToken cancellationToken = default) + => new(new StubSession()); + + protected override ValueTask SerializeSessionCoreAsync( + AgentSession session, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override ValueTask DeserializeSessionCoreAsync( + JsonElement serializedState, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } /// /// A store that answers nothing while model is still in the scope, and names two models @@ -137,11 +205,11 @@ private sealed class ScopedFakePort : IKnowledgeRetrievalPort internal int Calls { get; private set; } public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { Calls++; - var facets = KnowledgeScopeScope.Current?.Facets; + var facets = scope?.Facets; if (facets is null || facets.ContainsKey("model")) { return new([]); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs index 3ef67799..616c3aca 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/ConfigurationCompilerModelFacingTests.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools.Binding; using AgentCore.Application.Transcript; using AgentCore.TestSupport; using Microsoft.Extensions.AI; @@ -33,7 +34,8 @@ public sealed class ConfigurationCompilerModelFacingTests [Fact] public async Task TheSecondRoundOfACompiledAgent_NeverForwardsARenderContentTheFirstRoundsToolAttached() { - using var scope = TurnAmbients.Amend(ambients => ambients with { Renders = new TurnRenders() }); + TurnRenders renders = new(); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Renders = renders }; RequestCapturingChatClient recorder = new(new ToolCallingChatClient("done.")); var document = ConfigurationLoader.LoadYaml(Yaml); @@ -47,7 +49,12 @@ public async Task TheSecondRoundOfACompiledAgent_NeverForwardsARenderContentTheF TestContext.Current.CancellationToken), }); - await compiled.Agent.RunAsync("draw me a card", cancellationToken: TestContext.Current.CancellationToken); + var session = await compiled.Agent.CreateSessionAsync(TestContext.Current.CancellationToken); + await compiled.Agent.RunAsync( + [new ChatMessage(ChatRole.User, "draw me a card")], + session, + turn.RunOptions(), + TestContext.Current.CancellationToken); Assert.Equal(2, recorder.Requests.Count); Assert.DoesNotContain( @@ -57,11 +64,15 @@ public async Task TheSecondRoundOfACompiledAgent_NeverForwardsARenderContentTheF private static AIFunction DrawCard() => AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - TurnAmbients.Current?.Renders?.Publish("card", "card-1", new { text = "hi" }); + turn!.Renders!.Publish("card", "card-1", new { text = "hi" }); return "drawn."; }, - "draw_card", - "Draw a card for the caller."); + new AIFunctionFactoryOptions + { + Name = "draw_card", + Description = "Draw a card for the caller.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); } diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs index d8b74f56..ba0527ba 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/FilesCompilationTests.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; using AgentCore.Domain.Audit; @@ -83,7 +84,7 @@ 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 FileAccessProvider); + Assert.Contains(Providers(agent), provider => provider is CallFilesProvider); var factory = BuildFactory(FilesYaml, _root, reply); var session = factory.Create("call-1"); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs index de7a8fc0..dff3ef5d 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/KnowledgeProviderBindingTests.cs @@ -1,8 +1,8 @@ -using AgentCore.TestSupport; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Ports; using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Knowledge; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Knowledge.Fakes; using AgentCore.Application.Tests.Runtime; @@ -80,7 +80,7 @@ public void AnAgentWithAKnowledgeBlock_CarriesBothProviders() var agent = CompileOne(KnowledgeYaml, new StubKnowledgePort([])); Assert.Contains(Providers(agent), provider => provider is TurnContextProvider); - Assert.Contains(Providers(agent), provider => provider is TextSearchProvider); + Assert.Contains(Providers(agent), provider => provider is KnowledgePrefetchProvider); } [Fact] @@ -88,7 +88,7 @@ public void AnAgentWithNoKnowledgeBlock_CarriesOnlyTheTurnProvider() { var agent = CompileOne(NoKnowledgeYaml, new StubKnowledgePort([])); - Assert.DoesNotContain(Providers(agent), provider => provider is TextSearchProvider); + Assert.DoesNotContain(Providers(agent), provider => provider is FacetFilterProvider or KnowledgePrefetchProvider); } [Fact] @@ -103,8 +103,8 @@ public void OnlyTheAgentThatDeclaredTheBlock_Retrieves() Knowledge = new StubKnowledgePort([]), }); - Assert.Contains(Providers(compiled.Agents["reader"]), provider => provider is TextSearchProvider); - Assert.DoesNotContain(Providers(compiled.Agents["quiet"]), provider => provider is TextSearchProvider); + Assert.Contains(Providers(compiled.Agents["reader"]), provider => provider is FacetFilterProvider); + Assert.DoesNotContain(Providers(compiled.Agents["quiet"]), provider => provider is FacetFilterProvider or KnowledgePrefetchProvider); } [Fact] @@ -122,7 +122,7 @@ public async Task TheAgentsOwnSettings_ReachTheProviderThatWasBound() }); var reader = compiled.Agents["reader"]; - var provider = Assert.Single(Providers(reader).OfType()); + var provider = Assert.Single(Providers(reader).OfType()); #pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. AIContextProvider.InvokingContext context = new(reader, null, new AIContext()); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs index a407e70c..fbe97555 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/MemoryCompilationTests.cs @@ -104,7 +104,7 @@ public async Task Compile_MemoryWorkspaceWithARoot_GetsAFileMemoryProviderAndThe var session = factory.Create("call-1"); // A turn must be open for the FileMemoryProvider's state initializer to read the call id off - // TurnAmbients, so the tool list is read through a real call rather than agent.RunAsync + // the session, so the tool list is read through a real call rather than agent.RunAsync // directly, unlike the todos/mode providers in HarnessCompilationTests. await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs index 82352a69..30956825 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs @@ -4,6 +4,7 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; using AgentCore.Application.Tests.Knowledge.Fakes; using AgentCore.Domain.Knowledge; using AgentCore.TestSupport; @@ -188,10 +189,10 @@ public async Task Filters_ClearNoCardAndNothingElseDoesEither_StaysEmpty() [Fact] public async Task Filters_AreNamedInTheRecordAnOperatorDebugsFrom() { - // The record reads the LIVE scope ambient, so it has to be written while the search's own - // scope is still open. Built a line later, it names whatever the turn composed instead -- - // and the one thing an operator opens this record to see, which facet narrowed the search - // that found nothing, is exactly the part that goes missing. + // The record is written while the search's own scope is still the composed one. Built a + // line later, it names whatever the turn composed instead -- and the one thing an operator + // opens this record to see, which facet narrowed the search that found nothing, is exactly + // the part that goes missing. RecordingLoggerFactory loggers = new(); var tool = await SearchToolAsync(new StubKnowledgePort([Card("a")]), Declared, loggers: loggers); @@ -221,7 +222,7 @@ private static async Task SearchToolAsync( var context = await provider.InvokingAsync( new AIContextProvider.InvokingContext( StubAgent.Instance, - null, + new StubSession(), new AIContext { Messages = [new ChatMessage(ChatRole.User, "hello")] }), TestContext.Current.CancellationToken); #pragma warning restore MAAI001 @@ -241,12 +242,20 @@ private static async Task CallAsync( ["key"] = filter.Key, ["value"] = filter.Value, })), + [TurnInvocation.ArgumentsKey] = new TurnInvocation + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Knowledge = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) }, + }, }; - var answer = await tool.InvokeAsync( - new AIFunctionArguments(arguments), TestContext.Current.CancellationToken); + var results = await tool.InvokeAsync( + new AIFunctionArguments(arguments), TestContext.Current.CancellationToken) + as IReadOnlyList; - return answer?.ToString() ?? string.Empty; + return results is null ? string.Empty : string.Join("\n", results.Select(result => result.Text)); } private sealed class StubSession : AgentSession; diff --git a/tests/AgentCore.Application.Tests/Knowledge/Fakes/RecordingKnowledgeStoreAdapter.cs b/tests/AgentCore.Application.Tests/Knowledge/Fakes/RecordingKnowledgeStoreAdapter.cs index 199d3ea2..751c25b1 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/Fakes/RecordingKnowledgeStoreAdapter.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/Fakes/RecordingKnowledgeStoreAdapter.cs @@ -66,6 +66,7 @@ internal sealed class FakeKnowledgeStore : IKnowledgeRetrievalPort { public ValueTask> SearchAsync( string query, + KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => ValueTask.FromResult>([]); } diff --git a/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs b/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs index e7c91c00..b48ca318 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/Fakes/StubKnowledgePort.cs @@ -1,7 +1,6 @@ using System.Diagnostics; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Knowledge; namespace AgentCore.Application.Tests.Knowledge.Fakes; @@ -20,25 +19,24 @@ public StubKnowledgePort(IReadOnlyList cards) /// Gets how many searches reached this store. public int Calls { get; private set; } - /// Gets the scope ambient on the flow when the last search arrived, or . + /// Gets the scope the last search was handed, or when none ran. /// - /// Read here rather than in the test body on purpose: the real store reads the ambient at exactly - /// this point, deep inside the provider's delegate and several awaits below wherever the host - /// opened it. A test that reads it anywhere else proves something easier. + /// Read here rather than in the test body on purpose: the real store reads the passed scope at + /// exactly this point, deep inside the provider's delegate. A test that reads it anywhere else + /// proves something easier. /// public KnowledgeScope? ScopeAtTheStore { get; private set; } - /// Gets the ambient on the flow when the last search arrived. - /// Read at the same point as , for the same reason. + /// Always : the store is handed a scope, never the turn's holder. public Clarifications? ClarificationsAtTheStore { get; private set; } public ValueTask> SearchAsync( string query, + KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { LastQuery = query; - ScopeAtTheStore = KnowledgeScopeScope.Current; - ClarificationsAtTheStore = TurnAmbients.Current?.Clarifications; + ScopeAtTheStore = scope; Calls++; return ValueTask.FromResult(_cards); } @@ -54,6 +52,7 @@ public ThrowingKnowledgePort(Exception failure) public ValueTask> SearchAsync( string query, + KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => throw _failure; } @@ -83,6 +82,7 @@ public HangingKnowledgePort(TimeSpan deadline) public async ValueTask> SearchAsync( string query, + KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -95,7 +95,7 @@ public async ValueTask> SearchAsync( } /// -/// A store that filters the way the real one does: it folds the ambient scope's facets into its answer. +/// A store that filters the way the real one does: it folds the passed scope's facets into its answer. /// /// /// ignores the scope, so it can prove which scope arrived but never @@ -115,9 +115,10 @@ public ScopeFilteringKnowledgePort( public ValueTask> SearchAsync( string query, + KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { - var wanted = KnowledgeScopeScope.Current?.Facets ?? NoFacets; + var wanted = scope?.Facets ?? NoFacets; IReadOnlyList hits = [ diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs index 35ddaa5d..efd3b3f2 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs @@ -1,6 +1,7 @@ using AgentCore.Application.Configuration.Parsing; using System.Diagnostics; using System.Reflection; +using System.Text.Json; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; @@ -22,12 +23,12 @@ namespace AgentCore.Application.Tests.Knowledge; /// one wildcard-filled facet, re-searching, and naming the values it finds. /// /// -/// Every test drives KnowledgeProviderFactory's own search delegate directly, the same way +/// Every test drives the search tool KnowledgeProviderFactory offers, the same way /// KnowledgeProviderFactoryTests does, rather than through CallSession: the probe reads -/// only the ambient (, , -/// ) and the resolved knowledge: block, so opening 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. +/// 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. /// public sealed class KnowledgeProbeTests { @@ -39,10 +40,9 @@ public sealed class KnowledgeProbeTests public async Task Step1_MainSearchReturnedCards_TheProbeNeverRuns() { var port = new ProbeFakePort((_, _) => Task.FromResult>([Card("a")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Contains(results, r => r.Text == "card a"); Assert.Equal(1, port.Calls); @@ -54,10 +54,10 @@ public async Task Step2_UnscopedAgentsEmptySearch_ReturnsAnEmptyList() // Acceptance: "an unscoped agent's empty search returns an empty list." The probe and the // "holds nothing" notice are for a scoped agent only (K19). var port = new ProbeFakePort((_, _) => Task.FromResult>([])); - using var clarifications = OpenClarifications(); + var turn = TurnOf(null, new Clarifications()); var results = await InvokeSearchAsync( - Provider(port, Resolved(["applies_to"], scoped: false)), "e33"); + Provider(port, Resolved(["applies_to"], scoped: false)), "e33", turn); Assert.Empty(results); Assert.Equal(1, port.Calls); @@ -69,11 +69,10 @@ public async Task NoAmbiguityConfigured_StaysByteIdenticalToTheWildcardPlan() // K19: with no ambiguity: (and so no wildcard, no template) configured, behaviour is // byte-identical to the wildcard plan's own "holds nothing" notice — no second search. var port = new ProbeFakePort((_, _) => Task.FromResult>([])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); var plain = new ResolvedKnowledge(KnowledgeMode.Tool, 5, Citations: false, Scoped: true); - var results = await InvokeSearchAsync(Provider(port, plain), "e33"); + var results = await InvokeSearchAsync(Provider(port, plain), "e33", turn); Assert.Contains(results, r => r.Text.Contains("holds nothing", StringComparison.Ordinal)); Assert.Equal(1, port.Calls); @@ -86,10 +85,9 @@ public async Task Step3_SingleFacetScope_IsUndroppable() { // K33: dropping the scope's only facet would open it empty, which a scoped store refuses. var port = new ProbeFakePort((_, _) => Task.FromResult>([])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to")); + var turn = TurnOf(FullScope("applies_to"), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Contains(results, r => r.Text.Contains("holds nothing", StringComparison.Ordinal)); // Only the main search ran. The probe never opened a second, narrowed scope. @@ -100,11 +98,10 @@ public async Task Step3_SingleFacetScope_IsUndroppable() public async Task Step3_MaxAsksZero_DropsNoFacet_AndEmitsW11sNotice() { var port = new ProbeFakePort((_, _) => Task.FromResult>([])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("brand", "applies_to")); + var turn = TurnOf(FullScope("brand", "applies_to"), new Clarifications()); var knowledge = Resolved(["brand", "applies_to"], ambiguity: new KnowledgeAmbiguityConfiguration { MaxAsks = 0 }); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); Assert.Single(results); Assert.Contains("holds nothing", results[0].Text, StringComparison.Ordinal); @@ -119,11 +116,10 @@ public async Task Step3_FacetAtItsAskCap_IsSkipped_AndTheNextDroppableFacetIsTri var clarificationsObject = new Clarifications(); clarificationsObject.Update("brand", s => s.ProbeAsks = 2); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("brand", "applies_to")); + var turn = TurnOf(FullScope("brand", "applies_to"), clarificationsObject); var knowledge = Resolved(["brand", "applies_to"]); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); Assert.Contains(results, r => r.Text.Contains("ct900", StringComparison.Ordinal)); // brand was skipped, not touched: it stays exactly where the test seeded it. @@ -137,13 +133,12 @@ public async Task Step4_DropsTheFirstDroppableFacet_InFromStateDeclarationOrder( var port = new ProbeFakePort((facets, _) => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "brand")); + var turn = TurnOf(FullScope("applies_to", "brand"), new Clarifications()); // fromState declares applies_to before brand, so applies_to is tried first even though both // are equally droppable. var knowledge = Resolved(["applies_to", "brand"]); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); Assert.Contains(results, r => r.Text.Contains("ct900", StringComparison.Ordinal)); } @@ -159,12 +154,10 @@ public async Task Steps5And6_FindsCandidates_RecordsWhatItNamedAndEmitsTheNote() : [CardWithFacet("a", "applies_to", "ct900"), CardWithFacet("b", "applies_to", "ct900ent")])); var clarificationsObject = new Clarifications(); - using var clarifications = OpenClarifications(clarificationsObject); - using var carries = TurnAmbientsTestScope.WithCarriesHistory(true); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject, carriesHistory: true); var knowledge = Resolved(["applies_to"], slotDescriptions: Descriptions(("applies_to", Description))); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); Assert.Equal( ClarificationText.Note(Description, ["ct900", "ct900ent"], KnowledgeAmbiguityConfiguration.DefaultMaxCandidates), @@ -186,10 +179,9 @@ public async Task Step5_ReadsAListShapedFacetValue_NotJustAString() ? [] : [CardWithFacetList("a", "applies_to", ["ct900", "ct900ent"])])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); var text = Assert.Single(results).Text; Assert.Contains("ct900", text, StringComparison.Ordinal); @@ -205,11 +197,10 @@ public async Task Step5_WalksANestedTemplatePath() ? [] : [CardWithFacet("a", "applies_to", "ct900", template)])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); var results = await InvokeSearchAsync( - Provider(port, Resolved(["applies_to"], template: template)), "e33"); + Provider(port, Resolved(["applies_to"], template: template)), "e33", turn); Assert.Contains("ct900", Assert.Single(results).Text, StringComparison.Ordinal); } @@ -222,10 +213,9 @@ public async Task K6_TheWildcardValueItselfIsDiscardedFromTheCandidates() ? [] : [CardWithFacet("a", "applies_to", "*"), CardWithFacet("b", "applies_to", "ct900")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); var text = Assert.Single(results).Text; Assert.Contains("ct900", text, StringComparison.Ordinal); @@ -240,12 +230,11 @@ public async Task K24_OneCardIsNeverASpread() var port = new ProbeFakePort((facets, _) => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); var results = await InvokeSearchAsync( Provider(port, Resolved(["applies_to"], slotDescriptions: Descriptions(("applies_to", Description)))), - "e33"); + "e33", turn); Assert.Equal( ClarificationText.Note(Description, ["ct900"], KnowledgeAmbiguityConfiguration.DefaultMaxCandidates), @@ -263,12 +252,11 @@ public async Task MoreThanMaxCandidates_NamesNone() ? [] : [.. many.Select((value, i) => CardWithFacet($"c{i}", "applies_to", value))])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); var knowledge = Resolved( ["applies_to"], ambiguity: new KnowledgeAmbiguityConfiguration { MaxCandidates = 6 }); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); var text = Assert.Single(results).Text; Assert.DoesNotContain("holds nothing", text, StringComparison.Ordinal); @@ -290,10 +278,9 @@ public async Task K34_ARepeatedIdenticalCandidateSet_EmitsHoldsNothing() clarificationsObject.Update( "applies_to", s => s.LastNamed = Clarifications.LastNamed.Of(new HashSet(["ct900", "ct900ent"], StringComparer.Ordinal))); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Contains("holds nothing", Assert.Single(results).Text, StringComparison.Ordinal); @@ -306,10 +293,9 @@ public async Task ZeroCandidatesFound_EmitsHoldsNothing() { var port = new ProbeFakePort((_, _) => Task.FromResult>([])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Contains("holds nothing", Assert.Single(results).Text, StringComparison.Ordinal); } @@ -323,11 +309,9 @@ public async Task K39_AGraphDocumentsProbe_EmitsItsNote_AndRecordsNoLastNamed() facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); var clarificationsObject = new Clarifications(); - using var clarifications = OpenClarifications(clarificationsObject); - using var carries = TurnAmbientsTestScope.WithCarriesHistory(false); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject, carriesHistory: false); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Contains("ct900", Assert.Single(results).Text, StringComparison.Ordinal); @@ -339,13 +323,13 @@ public async Task K39_AGraphDocumentsProbe_EmitsItsNote_AndRecordsNoLastNamed() // K42: no holder, no probe -- but the notice is still owed to a scoped run. [Fact] - public async Task K42_NoHolderOnTheAmbient_TheProbeDoesNotSearch_ButStillEmitsTheNotice() + public async Task K42_NoHolderOnTheTurn_TheProbeDoesNotSearch_ButStillEmitsTheNotice() { var port = new ProbeFakePort((_, _) => Task.FromResult>([])); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), null); - // No Clarifications opened on the ambient at all -- the K42 strip inside a nested tool call. - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + // No Clarifications on the turn at all -- the K42 strip inside a nested tool call. + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Contains("holds nothing", Assert.Single(results).Text, StringComparison.Ordinal); Assert.Equal(1, port.Calls); @@ -356,7 +340,7 @@ public async Task K42_ASubAgentThatSearchesFirst_WritesNoLastNamed_AndTheCallers { // Acceptance: "a sub-agent that searches first writes no lastNamed, and the caller's own // search still counts." Simulates exactly what AuditingFunctionInvokingChatClient. - // InvokeFunctionAsync does for a NESTED tool call: it strips Clarifications from the ambient, + // InvokeFunctionAsync does for a NESTED tool call: it strips Clarifications from the turn, // leaving the outer call id in place. var port = new ProbeFakePort((facets, _) => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); @@ -365,25 +349,18 @@ public async Task K42_ASubAgentThatSearchesFirst_WritesNoLastNamed_AndTheCallers var knowledge = Resolved(["applies_to"]); var provider = Provider(port, knowledge); - using (OpenClarifications(clarificationsObject)) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - { - IReadOnlyList nested; - using (TurnAmbients.Amend(a => a with { Clarifications = null })) - { - nested = await InvokeSearchAsync(provider, "the sub-agent's own question"); - } + var scope = FullScope("applies_to", "other"); + var nested = await InvokeSearchAsync(provider, "the sub-agent's own question", TurnOf(scope, null)); - Assert.Contains("holds nothing", Assert.Single(nested).Text, StringComparison.Ordinal); - Assert.Equal(0, clarificationsObject.Read("applies_to").ProbeAsks); - // Only the sub-agent's own main search ran; its own probe search never reached the port. - Assert.Equal(1, port.Calls); + Assert.Contains("holds nothing", Assert.Single(nested).Text, StringComparison.Ordinal); + Assert.Equal(0, clarificationsObject.Read("applies_to").ProbeAsks); + // Only the sub-agent's own main search ran; its own probe search never reached the port. + Assert.Equal(1, port.Calls); - var callers = await InvokeSearchAsync(provider, "the caller's own question"); + var callers = await InvokeSearchAsync(provider, "the caller's own question", TurnOf(scope, clarificationsObject)); - Assert.Contains("ct900", Assert.Single(callers).Text, StringComparison.Ordinal); - Assert.Equal(1, clarificationsObject.Read("applies_to").ProbeAsks); - } + Assert.Contains("ct900", Assert.Single(callers).Text, StringComparison.Ordinal); + Assert.Equal(1, clarificationsObject.Read("applies_to").ProbeAsks); } // K25: every notice this design emits carries the reserved source name, and none is citable. @@ -392,21 +369,15 @@ public async Task K42_ASubAgentThatSearchesFirst_WritesNoLastNamed_AndTheCallers public async Task EveryOutcome_CarriesTheReservedSourceName() { var holdsNothing = new ProbeFakePort((_, _) => Task.FromResult>([])); - using (OpenClarifications()) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - { - var results = await InvokeSearchAsync(Provider(holdsNothing, Resolved(["applies_to"])), "e33"); - Assert.All(results, r => Assert.Equal(KnowledgeNotices.SourceName, r.SourceName)); - } + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); + var results = await InvokeSearchAsync(Provider(holdsNothing, Resolved(["applies_to"])), "e33", turn); + Assert.All(results, r => Assert.Equal(KnowledgeNotices.SourceName, r.SourceName)); var named = new ProbeFakePort((facets, _) => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - using (OpenClarifications()) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - { - var results = await InvokeSearchAsync(Provider(named, Resolved(["applies_to"])), "e33"); - Assert.All(results, r => Assert.Equal(KnowledgeNotices.SourceName, r.SourceName)); - } + var secondTurn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); + var second = await InvokeSearchAsync(Provider(named, Resolved(["applies_to"])), "e33", secondTurn); + Assert.All(second, r => Assert.Equal(KnowledgeNotices.SourceName, r.SourceName)); } [Fact] @@ -422,12 +393,10 @@ public async Task K23_AProbeSpread_PublishesNoSources() var provider = Provider(port, Resolved(["applies_to"], citations: true)); TurnSources sources = new(); - using (OpenClarifications()) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - using (TurnAmbientsTestScope.WithSources(sources)) - using (TurnAmbientsTestScope.WithOuterCall("call-1")) + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications(), sources: sources); + using (sources.BeginOuterCall("call-1")) { - await InvokeSearchAsync(provider, "e33"); + await InvokeSearchAsync(provider, "e33", turn); } Assert.Empty(sources.TakeFor("call-1")); @@ -445,12 +414,11 @@ public async Task Probe_SecondSearchThrows_EmitsHoldsNothing_AndLogsItsOwnFailur : throw boom); RecordingLoggerFactory loggers = new(); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); var provider = KnowledgeProviderFactory.Create( port, Resolved(["applies_to"]), "agent-under-test", new SourceLocatorCitationFormatter(), loggers); - var results = await InvokeSearchAsync(provider, "e33"); + var results = await InvokeSearchAsync(provider, "e33", turn); Assert.Contains("holds nothing", Assert.Single(results).Text, StringComparison.Ordinal); Assert.DoesNotContain("unreachable", Assert.Single(results).Text, StringComparison.OrdinalIgnoreCase); @@ -480,13 +448,12 @@ public async Task Probe_SecondSearchTimesOut_IsTreatedAsAFailure_NeverAsUnreacha }); var clarificationsObject = new Clarifications(); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); var knowledge = Resolved( ["applies_to"], ambiguity: new KnowledgeAmbiguityConfiguration { ProbeDeadlineSeconds = 1, ProbeWaitMarginSeconds = 1 }); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); Assert.Contains("holds nothing", Assert.Single(results).Text, StringComparison.Ordinal); @@ -506,16 +473,13 @@ public async Task K43_ThreeSearchCallsInOneTurn_RunOneProbe_AndIncrementOnce() var clarificationsObject = new Clarifications(); var provider = Provider(port, Resolved(["applies_to"])); - using (OpenClarifications(clarificationsObject)) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - { - var first = await InvokeSearchAsync(provider, "e33"); - var second = await InvokeSearchAsync(provider, "e33 again"); - var third = await InvokeSearchAsync(provider, "e33 once more"); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); + var first = await InvokeSearchAsync(provider, "e33", turn); + var second = await InvokeSearchAsync(provider, "e33 again", turn); + var third = await InvokeSearchAsync(provider, "e33 once more", turn); - Assert.Same(first[0], second[0]); - Assert.Same(first[0], third[0]); - } + Assert.Same(first[0], second[0]); + 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. @@ -529,14 +493,12 @@ public async Task K43_TwoCalls_TheFirstEmittedHoldsNothing_TheSecondReplaysTheSa var port = new ProbeFakePort((_, _) => Task.FromResult>([])); var provider = Provider(port, Resolved(["applies_to"])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); - - var first = await InvokeSearchAsync(provider, "e33"); - var second = await InvokeSearchAsync(provider, "e33 again"); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); + var first = await InvokeSearchAsync(provider, "e33", turn); + var second = await InvokeSearchAsync(provider, "e33 again", turn); - // InvokeSearchAsync itself materialises a fresh list with ToList(), so the replay proof is on - // the element the two lists share, not on the wrapper InvokeSearchAsync just allocated. + // Each search returns the turn's own probe payload, so the replay proof is on the element + // the two lists share, not on the lists themselves. Assert.Same(first[0], second[0]); } @@ -557,11 +519,9 @@ public async Task K43_TwoCalls_TheFirstProbeThrows_TheSecondReplaysHoldsNothing( var provider = Provider(port, Resolved(["applies_to"])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); - - var first = await InvokeSearchAsync(provider, "e33"); - var second = await InvokeSearchAsync(provider, "e33 again"); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); + var first = await InvokeSearchAsync(provider, "e33", turn); + var second = await InvokeSearchAsync(provider, "e33 again", turn); Assert.Equal(1, thrown); Assert.Same(first[0], second[0]); @@ -589,10 +549,9 @@ public async Task K43_ACancelledProbe_RollsBackTheIncrement_FailsThePayload_AndK var clarificationsObject = new Clarifications(); var provider = Provider(port, Resolved(["applies_to"])); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); - var winner = InvokeSearchWithCallerTokenAsync(provider, "e33", caller.Token); + var winner = InvokeSearchWithCallerTokenAsync(provider, "e33", turn, caller.Token); await probeStarted.Task.WaitAsync(TestContext.Current.CancellationToken); await caller.CancelAsync(); @@ -650,17 +609,16 @@ public async Task K43_ACancelledProbe_WakesAGenuinelyWaitingLoser_RatherThanLett ambiguity: new KnowledgeAmbiguityConfiguration { ProbeDeadlineSeconds = 1, ProbeWaitMarginSeconds = 1 }); var provider = Provider(port, knowledge); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); - var winner = InvokeSearchWithCallerTokenAsync(provider, "e33", caller.Token); + var winner = InvokeSearchWithCallerTokenAsync(provider, "e33", turn, caller.Token); // Only reached after the claim, the increment, and the narrowed scope's own search have // all already run, so the loser below is guaranteed to lose the race, not win it. await probeStarted.Task.WaitAsync(TestContext.Current.CancellationToken); var stopwatch = Stopwatch.StartNew(); - var loser = InvokeSearchAsync(provider, "e33 from a second caller"); + var loser = InvokeSearchAsync(provider, "e33 from a second caller", turn); await caller.CancelAsync(); @@ -701,21 +659,13 @@ public async Task K43_ProbeThatThrowsEveryTurn_StillAdvancesProbeAsks() var clarificationsObject = new Clarifications(); var provider = Provider(port, Resolved(["applies_to"])); - using (OpenClarifications(clarificationsObject)) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - { - await InvokeSearchAsync(provider, "turn one"); - } + await InvokeSearchAsync(provider, "turn one", TurnOf(FullScope("applies_to", "other"), clarificationsObject)); Assert.Equal(1, clarificationsObject.Read("applies_to").ProbeAsks); clarificationsObject.BeginTurn(); - using (OpenClarifications(clarificationsObject)) - using (KnowledgeScopeScope.Open(FullScope("applies_to", "other"))) - { - await InvokeSearchAsync(provider, "turn two"); - } + await InvokeSearchAsync(provider, "turn two", TurnOf(FullScope("applies_to", "other"), clarificationsObject)); Assert.Equal(2, clarificationsObject.Read("applies_to").ProbeAsks); Assert.Equal(2, attempts); @@ -735,13 +685,12 @@ public async Task Loser_WaitExpiresBeforeAnyOutcomeIsPublished_EmitsHoldsNothing var clarificationsObject = new Clarifications(); Assert.True(clarificationsObject.ClaimProbe().Won); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); var knowledge = Resolved( ["applies_to"], ambiguity: new KnowledgeAmbiguityConfiguration { ProbeDeadlineSeconds = 0, ProbeWaitMarginSeconds = 0 }); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); + var results = await InvokeSearchAsync(Provider(port, knowledge), "e33", turn); var text = Assert.Single(results).Text; Assert.Contains("holds nothing", text, StringComparison.Ordinal); @@ -779,18 +728,17 @@ public void ResolvedKnowledge_TheAmbiguityMembers_RoundTripThroughInit() [Fact] public async Task Step3_HostPinnedTheWildcardValue_IsNotDropped() { - // A host that opens a facet on the wildcard literal is saying "every value of it", not "I did + // A host that pins a facet to the wildcard literal is saying "every value of it", not "I did // not know". Origins is where that difference is recorded, so the value alone cannot decide // droppability: widening here would overrule the host rather than recover a lost value. var port = new ProbeFakePort(facets => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(ScopeWithOrigins( + var turn = TurnOf(ScopeWithOrigins( ("brand", "acme", KnowledgeFacetOrigin.Host), - ("applies_to", "*", KnowledgeFacetOrigin.Host))); + ("applies_to", "*", KnowledgeFacetOrigin.Host)), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Single(results); Assert.Contains("holds nothing", results[0].Text, StringComparison.Ordinal); @@ -805,12 +753,11 @@ public async Task Step3_OriginsRecordTheWildcardFilledIt_SoTheFacetIsDropped() var port = new ProbeFakePort(facets => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(ScopeWithOrigins( + var turn = TurnOf(ScopeWithOrigins( ("brand", "acme", KnowledgeFacetOrigin.Host), - ("applies_to", "*", KnowledgeFacetOrigin.Wildcard))); + ("applies_to", "*", KnowledgeFacetOrigin.Wildcard)), new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Single(results); Assert.Contains("ct900", results[0].Text, StringComparison.Ordinal); @@ -834,10 +781,9 @@ public async Task Step4_TheNarrowedScopeKeepsTheCallersOwnComparer() ["applies_to"] = "*", }; - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(new KnowledgeScope { Facets = facets }); + var turn = TurnOf(new KnowledgeScope { Facets = facets }, new Clarifications()); - var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33"); + var results = await InvokeSearchAsync(Provider(port, Resolved(["applies_to"])), "e33", turn); Assert.Single(results); Assert.Contains("ct900", results[0].Text, StringComparison.Ordinal); @@ -875,14 +821,13 @@ public async Task Step4_TheDeadlineFiredBeforeTheCallerHungUp_KeepsTheAskCharged }); var clarificationsObject = new Clarifications(); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); var knowledge = Resolved( ["applies_to"], ambiguity: new KnowledgeAmbiguityConfiguration { ProbeDeadlineSeconds = 1 }); - var results = await InvokeSearchWithCallerTokenAsync(Provider(port, knowledge), "e33", caller.Token); + var results = await InvokeSearchWithCallerTokenAsync(Provider(port, knowledge), "e33", turn, caller.Token); Assert.Single(results); Assert.Contains("holds nothing", results[0].Text, StringComparison.Ordinal); @@ -900,14 +845,13 @@ public async Task AThrowBetweenTheProbeSearchAndThePublish_StillResolvesTheLatch facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); var clarificationsObject = new Clarifications(); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), clarificationsObject); using ThrowingLoggerFactory loggers = new(ProbeRanEventId); var provider = KnowledgeProviderFactory.Create( port, Resolved(["applies_to"]), "agent-under-test", new SourceLocatorCitationFormatter(), loggers); - var results = await InvokeSearchAsync(provider, "e33"); + var results = await InvokeSearchAsync(provider, "e33", turn); Assert.Single(results); Assert.Contains("unreachable", results[0].Text, StringComparison.Ordinal); @@ -929,14 +873,13 @@ public async Task TheProbesOwnSearchIsRecorded_SoAnOperatorSeesBothStoreCalls() var port = new ProbeFakePort(facets => Task.FromResult>( facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - using var clarifications = OpenClarifications(); - using var scope = KnowledgeScopeScope.Open(FullScope("applies_to", "other")); + var turn = TurnOf(FullScope("applies_to", "other"), new Clarifications()); using CountingLoggerFactory loggers = new(RetrievedEventId); var provider = KnowledgeProviderFactory.Create( port, Resolved(["applies_to"]), "agent-under-test", new SourceLocatorCitationFormatter(), loggers); - var results = await InvokeSearchAsync(provider, "e33"); + var results = await InvokeSearchAsync(provider, "e33", turn); Assert.Contains("ct900", results[0].Text, StringComparison.Ordinal); Assert.Equal(port.Calls, loggers.Count); @@ -1062,8 +1005,20 @@ private static AIContextProvider Provider(IKnowledgeRetrievalPort port, Resolved => KnowledgeProviderFactory.Create( port, knowledge, "agent-under-test", new SourceLocatorCitationFormatter(), loggers: null); - private static IDisposable OpenClarifications(Clarifications? clarifications = null) - => TurnAmbientsTestScope.WithClarifications(clarifications ?? new Clarifications()); + private static TurnInvocation TurnOf( + KnowledgeScope? scope, + Clarifications? clarifications = null, + bool carriesHistory = false, + TurnSources? sources = null) => new() + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Knowledge = scope, + Clarifications = clarifications, + CarriesHistory = carriesHistory, + Sources = sources, + }; private static ResolvedKnowledge Resolved( IReadOnlyList fromState, @@ -1145,30 +1100,89 @@ private static KnowledgeCard CardWithFacetList(string id, string facetKey, IRead } /// - /// Calls the factory's own search delegate directly, exactly as KnowledgeProviderFactoryTests - /// does. + /// Invokes the search tool the provider offers, the way the model would: the turn rides along + /// as an argument, carrying the scope and the clarifications the search runs under. /// private static Task> InvokeSearchAsync( - AIContextProvider provider, string query) - => RunSearchDelegateAsync(provider, query, TestContext.Current.CancellationToken); + AIContextProvider provider, string query, TurnInvocation turn) + => InvokeSearchWithCallerTokenAsync(provider, query, turn, TestContext.Current.CancellationToken); /// - /// The cancellation row's own entry point: here is the + /// The cancellation row's own entry point: here is the /// 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. + /// only caller. Named apart from + /// so a deliberately non-TestContext token at this one call site does not read as a mistake. /// - private static Task> InvokeSearchWithCallerTokenAsync( - AIContextProvider provider, string query, CancellationToken callerToken) - => RunSearchDelegateAsync(provider, query, callerToken); + private static async Task> InvokeSearchWithCallerTokenAsync( + AIContextProvider provider, string query, TurnInvocation turn, CancellationToken callerToken) + { + StubSession session = new(); + var context = await provider.InvokingAsync( + 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) + { + ["userQuestion"] = query, + [TurnInvocation.ArgumentsKey] = turn, + }), + callerToken).ConfigureAwait(false) + as IReadOnlyList; + return results!; + } + + /// Runs the provider the way the framework runs it, over one caller message. + private static AIContextProvider.InvokingContext Invoking(string text, AgentSession session) + { +#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. + return new( + StubAgent.Instance, + session, + new AIContext { Messages = [new ChatMessage(ChatRole.User, text)] }); +#pragma warning restore MAAI001 + } - private static Task> RunSearchDelegateAsync( - AIContextProvider provider, string query, CancellationToken cancellationToken) - => TextSearchProviderInternals.SearchAsync(provider, query, cancellationToken); + private sealed class StubSession : AgentSession; + + /// Stands in for the agent the framework names on a context. Nothing here runs it. + private sealed class StubAgent : AIAgent + { + public static StubAgent Instance { get; } = new(); + + protected override ValueTask CreateSessionCoreAsync( + CancellationToken cancellationToken = default) + => new(new StubSession()); + + protected override ValueTask SerializeSessionCoreAsync( + AgentSession session, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override ValueTask DeserializeSessionCoreAsync( + JsonElement serializedState, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } /// - /// A knowledge store whose answer is a function of the live scope's facets, so one instance can + /// A knowledge store whose answer is a function of the passed scope's facets, so one instance can /// stand in for both the main search (full scope) and the probe's own second search (narrowed). /// private sealed class ProbeFakePort : IKnowledgeRetrievalPort @@ -1187,10 +1201,10 @@ internal ProbeFakePort( internal int Calls { get; private set; } public async ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { Calls++; - var facets = KnowledgeScopeScope.Current?.Facets ?? new Dictionary(StringComparer.Ordinal); + var facets = scope?.Facets ?? new Dictionary(StringComparer.Ordinal); return await _answer(facets, cancellationToken).ConfigureAwait(false); } } diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs index 051968db..04b6ab21 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs @@ -34,8 +34,7 @@ public async Task Create_PrefetchMode_RetrievesBeforeTheModelIsCalled() var port = new StubKnowledgePort([Card("a"), Card("b")]); var provider = Provider(port, Resolved(KnowledgeMode.Prefetch)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); Assert.Null(context.Tools); Assert.Equal("the screen says e33", port.LastQuery); @@ -50,7 +49,7 @@ public async Task Create_ToolMode_OffersASearchToolInstead() var provider = Provider(port, Resolved(KnowledgeMode.Tool)); var context = await provider.InvokingAsync( - Invoking("hello"), TestContext.Current.CancellationToken); + Invoking("hello", new StubSession()), TestContext.Current.CancellationToken); Assert.NotNull(context.Tools); Assert.Single(context.Tools); @@ -67,8 +66,7 @@ public async Task Create_PortThrows_InjectsANoticeAndDoesNotFailTheTurn() new ThrowingKnowledgePort(new InvalidOperationException("qdrant is down")), Resolved(KnowledgeMode.Prefetch)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); var text = Merged(context); Assert.Contains("knowledge base", text, StringComparison.OrdinalIgnoreCase); @@ -93,8 +91,7 @@ public async Task Create_TheStoresOwnDeadlineFires_InjectsTheNoticeAndWritesTheC new SourceLocatorCitationFormatter(), loggers); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); var text = Merged(context); Assert.Contains("unreachable", text, StringComparison.OrdinalIgnoreCase); @@ -126,10 +123,13 @@ public async Task Create_TheCallerCancels_IsNotDressedUpAsARetrievalFailure() caller.CancelAfter(TimeSpan.FromMilliseconds(20)); + StubSession callerSession = new(); + TurnRegistry.Set(callerSession, PrefetchTurn()); + // The framework swallows whatever escapes the delegate, so "propagated" is read off what did // NOT happen: no notice, and neither the success row nor the failure row. A delegate that // returned normally would have written row 11, and one that took the failure path row 12. - var context = await provider.InvokingAsync(Invoking("the screen says e33"), caller.Token); + var context = await provider.InvokingAsync(Invoking("the screen says e33", callerSession), caller.Token); Assert.DoesNotContain("unreachable", Merged(context), StringComparison.OrdinalIgnoreCase); Assert.Empty(loggers.Of(11)); @@ -144,8 +144,7 @@ public async Task Create_PortReturnsNothing_InjectsNothing() var provider = Provider( new StubKnowledgePort([]), Resolved(KnowledgeMode.Prefetch)); - var context = await provider.InvokingAsync( - Invoking("hello"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "hello", PrefetchTurn(), new StubSession()); Assert.Equal(["hello"], Texts(context)); } @@ -159,8 +158,7 @@ public async Task Create_ScopedAgentWithNoAmbientScope_NeverReachesThePort() var provider = Provider( port, Resolved(KnowledgeMode.Prefetch, scoped: true)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); Assert.Equal(0, port.Calls); Assert.DoesNotContain("card a", Merged(context), StringComparison.Ordinal); @@ -173,12 +171,11 @@ public async Task Create_ScopedAgentWithAnEmptyScope_NeverReachesThePort() { // An ambient with no facets filters nothing, so it is the absent ambient wearing a hat. var port = new StubKnowledgePort([Card("a"), Card("b")]); - using var open = KnowledgeScopeScope.Open(new KnowledgeScope { Facets = new Dictionary() }); + var scope = new KnowledgeScope { Facets = new Dictionary() }; var provider = Provider( port, Resolved(KnowledgeMode.Prefetch, scoped: true)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(scope), new StubSession()); Assert.Equal(0, port.Calls); Assert.Contains("no scope is open", Merged(context), StringComparison.OrdinalIgnoreCase); @@ -188,13 +185,11 @@ public async Task Create_ScopedAgentWithAnEmptyScope_NeverReachesThePort() public async Task Create_ScopedAgentWithAScopeOpen_Searches() { var port = new StubKnowledgePort([Card("a")]); - using var open = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }); + var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; var provider = Provider( port, Resolved(KnowledgeMode.Prefetch, scoped: true)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(scope), new StubSession()); Assert.Equal(1, port.Calls); Assert.Contains("card a", Merged(context), StringComparison.Ordinal); @@ -209,8 +204,7 @@ public async Task Create_UnscopedAgentWithNoAmbientScope_StillSearches() var provider = Provider( port, Resolved(KnowledgeMode.Prefetch, scoped: false)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); Assert.Equal(1, port.Calls); Assert.Contains("card a", Merged(context), StringComparison.Ordinal); @@ -220,20 +214,18 @@ 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 opens ct900 for the whole call, and the analyst -- which the + // requires a scope, so the host sets ct900 for the whole call, and the analyst -- which the // same document says "searches every product on purpose" -- was silently filtered to ct900 - // with it. The store folds whatever ambient it finds into the filter, so the ambient has to - // stop here. + // 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. var port = new ScopeFilteringKnowledgePort( (Card("ct900"), Facets("ct900")), (Card("ent"), Facets("ct900ent"))); - using var host = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }); + var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; var provider = Provider(port, Resolved(KnowledgeMode.Prefetch, scoped: false)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(scope), new StubSession()); // The card OUTSIDE the host's facet is the whole point: an unscoped agent sees it. Assert.Contains("card ent", Merged(context), StringComparison.Ordinal); @@ -246,12 +238,10 @@ public async Task Create_UnscopedAgent_ReachesTheStoreUnderAnEmptyScopeRatherTha // The mechanism behind the fact above, asserted where the store reads it. An empty facet map // adds no filter condition, so this is a whole-corpus read and not a differently-shaped one. var port = new StubKnowledgePort([Card("a")]); - - using var host = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }); + var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; var provider = Provider(port, Resolved(KnowledgeMode.Prefetch, scoped: false)); - await provider.InvokingAsync(Invoking("the screen says e33"), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(scope), new StubSession()); Assert.NotNull(port.ScopeAtTheStore); Assert.Empty(port.ScopeAtTheStore.Facets); @@ -260,15 +250,13 @@ public async Task Create_UnscopedAgent_ReachesTheStoreUnderAnEmptyScopeRatherTha [Fact] public async Task Create_ScopedAgent_ReachesTheStoreUnderTheHostsOwnScope() { - // The counterpart. Taking the ambient away from the unscoped agent must not take it away from - // the scoped one, which is the agent the ambient exists for. + // The counterpart. Taking the scope away from the unscoped agent must not take it away from + // the scoped one, which is the agent the scope exists for. var port = new StubKnowledgePort([Card("a")]); var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - using var host = KnowledgeScopeScope.Open(scope); - var provider = Provider(port, Resolved(KnowledgeMode.Prefetch, scoped: true)); - await provider.InvokingAsync(Invoking("the screen says e33"), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(scope), new StubSession()); Assert.Same(scope, port.ScopeAtTheStore); } @@ -277,17 +265,19 @@ public async Task Create_ScopedAgent_ReachesTheStoreUnderTheHostsOwnScope() public async Task Create_UnscopedAgent_PutsTheHostsScopeBackAfterTheSearch() { // The empty scope covers one port call and nothing else. Leaking it would silently unscope the - // scoped agent that runs next on the same flow -- the very leak this whole design fails closed - // against, arriving from the inside. + // scoped agent that runs next -- the very leak this whole design fails closed against, + // arriving from the inside. var port = new StubKnowledgePort([Card("a")]); var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - using var host = KnowledgeScopeScope.Open(scope); - var provider = Provider(port, Resolved(KnowledgeMode.Prefetch, scoped: false)); - await provider.InvokingAsync(Invoking("the screen says e33"), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); + + // The empty scope covered that one search only: a scoped turn still resolves the host's scope. + var scoped = Provider(port, Resolved(KnowledgeMode.Prefetch, scoped: true)); + await InvokePrefetchAsync(scoped, "the screen says e33", PrefetchTurn(scope), new StubSession()); - Assert.Same(scope, KnowledgeScopeScope.Current); + Assert.Same(scope, port.ScopeAtTheStore); } [Fact] @@ -300,7 +290,7 @@ public async Task Create_ASearchThatAnswered_WritesTheRetrievalRecord() var provider = KnowledgeProviderFactory.Create( port, Resolved(KnowledgeMode.Prefetch), "analyst", new SourceLocatorCitationFormatter(), loggers); - await provider.InvokingAsync(Invoking("the screen says e33"), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); var line = Assert.Single(loggers.Of(11)); Assert.Equal("analyst", line.Field("Agent")); @@ -325,7 +315,7 @@ public async Task Create_ASearchThatThrew_WritesTheCauseTheModelNeverSees() var provider = KnowledgeProviderFactory.Create( new ThrowingKnowledgePort(down), Resolved(KnowledgeMode.Prefetch), "resolver", new SourceLocatorCitationFormatter(), loggers); - await provider.InvokingAsync(Invoking("the screen says e33"), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(), new StubSession()); var line = Assert.Single(loggers.Of(12)); Assert.Equal(LogLevel.Error, line.Level); @@ -357,7 +347,7 @@ public async Task Create_NeitherLoggedRow_CarriesWhatTheCallerSaid() var answered = KnowledgeProviderFactory.Create( new StubKnowledgePort([Card("a")]), Resolved(KnowledgeMode.Prefetch), "analyst", new SourceLocatorCitationFormatter(), loggers); - await answered.InvokingAsync(Invoking(spoken), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(answered, spoken, PrefetchTurn(), new StubSession()); var threw = KnowledgeProviderFactory.Create( new ThrowingKnowledgePort(new InvalidOperationException("qdrant is down")), @@ -365,7 +355,7 @@ public async Task Create_NeitherLoggedRow_CarriesWhatTheCallerSaid() "resolver", new SourceLocatorCitationFormatter(), loggers); - await threw.InvokingAsync(Invoking(spoken), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(threw, spoken, PrefetchTurn(), new StubSession()); // Both rows were written -- a test that logged nothing would pass the assertions below // vacuously, and this is exactly the fact that must not pass vacuously. @@ -399,7 +389,7 @@ public async Task Create_TheLoggedRow_CarriesTheQuerysLengthInstead() var provider = KnowledgeProviderFactory.Create( new StubKnowledgePort([Card("a")]), Resolved(KnowledgeMode.Prefetch), "analyst", new SourceLocatorCitationFormatter(), loggers); - await provider.InvokingAsync(Invoking(spoken), TestContext.Current.CancellationToken); + await InvokePrefetchAsync(provider, spoken, PrefetchTurn(), new StubSession()); var view = Assert.Single(loggers.Of(11)).Field("Record"); Assert.NotNull(view); @@ -421,8 +411,8 @@ public async Task Create_MoreCardsThanTheAgentAsksFor_KeepsTheBestFew( var provider = Provider( port, Resolved(KnowledgeMode.Prefetch, limit: limit)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync( + provider, "the screen says e33", PrefetchTurn(), new StubSession()); var text = Merged(context); Assert.Contains("card a", text, StringComparison.Ordinal); @@ -442,8 +432,8 @@ public async Task Create_TheLimit_CountsRankedCardsAndLetsALinkedOneRideAlong() var provider = Provider( port, Resolved(KnowledgeMode.Prefetch, limit: 2)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync( + provider, "the screen says e33", PrefetchTurn(), new StubSession()); var text = Merged(context); Assert.Contains("card a", text, StringComparison.Ordinal); @@ -460,8 +450,8 @@ public async Task Create_CitationsOff_AsksForNoCitationAtAll() var provider = Provider( new StubKnowledgePort([Card("a")]), Resolved(KnowledgeMode.Prefetch, citations: false)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync( + provider, "the screen says e33", PrefetchTurn(), new StubSession()); var text = Merged(context); Assert.DoesNotContain("Include citations", text, StringComparison.Ordinal); @@ -474,8 +464,8 @@ public async Task Create_CitationsOn_NamesTheSourceAndForbidsAnInventedLink() var provider = Provider( new StubKnowledgePort([Card("a")]), Resolved(KnowledgeMode.Prefetch, citations: true)); - var context = await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + var context = await InvokePrefetchAsync( + provider, "the screen says e33", PrefetchTurn(), new StubSession()); var text = Merged(context); Assert.Contains("ct900-om, p.27", text, StringComparison.Ordinal); @@ -486,7 +476,7 @@ public async Task Create_CitationsOn_NamesTheSourceAndForbidsAnInventedLink() [Fact] public async Task Create_CitationsOn_PublishesASourceForEachCardShown() { - // Task 5 fix round 1, Finding 1. Nothing in this suite drove CallSourceScope.Current to a + // Task 5 fix round 1, Finding 1. Nothing in this suite drove the sources port to a // non-null value for a citing search before this test, so the body of the publish loop had // never executed. A collector plus an outer call, both open around the same InvokingAsync // the other tests already drive, is what proves the wiring rather than just reading it. @@ -495,11 +485,12 @@ public async Task Create_CitationsOn_PublishesASourceForEachCardShown() TurnSources sources = new(); - using (TurnAmbientsTestScope.WithSources(sources)) - using (TurnAmbientsTestScope.WithOuterCall("call-1")) + StubSession session = new(); + TurnRegistry.Set(session, PrefetchTurn(sources: sources)); + using (sources.BeginOuterCall("call-1")) { await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + Invoking("the screen says e33", session), TestContext.Current.CancellationToken); } var cited = sources.TakeFor("call-1"); @@ -521,11 +512,12 @@ public async Task Create_CitationsOff_PublishesNothing() TurnSources sources = new(); - using (TurnAmbientsTestScope.WithSources(sources)) - using (TurnAmbientsTestScope.WithOuterCall("call-1")) + StubSession session = new(); + TurnRegistry.Set(session, PrefetchTurn(sources: sources)); + using (sources.BeginOuterCall("call-1")) { await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + Invoking("the screen says e33", session), TestContext.Current.CancellationToken); } Assert.Empty(sources.TakeFor("call-1")); @@ -542,11 +534,12 @@ public async Task Create_MoreCardsThanTheLimit_CitesOnlyTheCardsTheModelIsShown( TurnSources sources = new(); - using (TurnAmbientsTestScope.WithSources(sources)) - using (TurnAmbientsTestScope.WithOuterCall("call-1")) + StubSession session = new(); + TurnRegistry.Set(session, PrefetchTurn(sources: sources)); + using (sources.BeginOuterCall("call-1")) { await provider.InvokingAsync( - Invoking("the screen says e33"), TestContext.Current.CancellationToken); + Invoking("the screen says e33", session), TestContext.Current.CancellationToken); } var cited = sources.TakeFor("call-1"); @@ -563,11 +556,13 @@ public async Task Create_WhatAnEarlierProviderInjected_IsNotPartOfTheQuery() // a query, and a search over them retrieves the wrong cards. var port = new StubKnowledgePort([]); var provider = Provider(port, Resolved(KnowledgeMode.Prefetch)); + StubSession session = new(); + TurnRegistry.Set(session, PrefetchTurn()); #pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. AIContextProvider.InvokingContext context = new( StubAgent.Instance, - session: null, + session, new AIContext { Messages = @@ -594,7 +589,7 @@ public async Task Create_ASecondTurn_SearchesWithWhatTheCallerSaidBefore() StubSession session = new(); var provider = Provider(port, Resolved(KnowledgeMode.Prefetch)); - + TurnRegistry.Set(session, PrefetchTurn()); await provider.InvokingAsync( Invoking("the screen says e33", session), TestContext.Current.CancellationToken); await provider.InvokedAsync( @@ -610,10 +605,9 @@ await provider.InvokingAsync( public async Task Search_ToolModeWithNoResults_InjectsTheEmptyNotice() { var provider = Provider(new StubKnowledgePort([]), Resolved(KnowledgeMode.Tool, scoped: true)); - using var open = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }); + var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - var results = await InvokeSearchAsync(provider, "f63 error e03"); + var results = await InvokeSearchAsync(provider, "f63 error e03", ToolTurn(scope)); Assert.Contains(results, r => r.Text.Contains("holds nothing", StringComparison.Ordinal)); } @@ -623,9 +617,9 @@ public async Task Search_PrefetchModeWithNoResults_InjectsNothing() { var provider = Provider(new StubKnowledgePort([]), Resolved(KnowledgeMode.Prefetch)); - var results = await InvokeSearchAsync(provider, "hello"); + var context = await InvokePrefetchAsync(provider, "hello", PrefetchTurn(), new StubSession()); - Assert.Empty(results); + Assert.Equal(["hello"], Texts(context)); } [Fact] @@ -635,12 +629,11 @@ public async Task Search_ScopedPrefetchModeWithNoResults_InjectsNothing() // clears the Facets.Count > 0 half, so only the KnowledgeMode.Tool clause keeps a prefetch // agent's empty search silent. var provider = Provider(new StubKnowledgePort([]), Resolved(KnowledgeMode.Prefetch, scoped: true)); - using var open = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }); + var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - var results = await InvokeSearchAsync(provider, "the screen says e33"); + var context = await InvokePrefetchAsync(provider, "the screen says e33", PrefetchTurn(scope), new StubSession()); - Assert.Empty(results); + Assert.Equal(["the screen says e33"], Texts(context)); } [Fact] @@ -650,7 +643,7 @@ public async Task Search_UnscopedToolModeWithNoResults_InjectsNothing() // byte-identical to an unscoped one: an empty list, no notice. var provider = Provider(new StubKnowledgePort([]), Resolved(KnowledgeMode.Tool, scoped: false)); - var results = await InvokeSearchAsync(provider, "f63 error e03"); + var results = await InvokeSearchAsync(provider, "f63 error e03", ToolTurn()); Assert.Empty(results); } @@ -660,10 +653,9 @@ public async Task Search_EveryNotice_CarriesTheReservedSourceName() { // A notice must never be citable as a card, and the reserved source name is what stops it. var provider = Provider(new StubKnowledgePort([]), Resolved(KnowledgeMode.Tool, scoped: true)); - using var open = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }); + var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - var results = await InvokeSearchAsync(provider, "f63 error e03"); + var results = await InvokeSearchAsync(provider, "f63 error e03", ToolTurn(scope)); Assert.All(results, r => Assert.Equal("agentcore:notice", r.SourceName)); } @@ -674,7 +666,7 @@ public async Task Search_ToolModeThatThrows_StillSaysUnreachable() var provider = Provider( new ThrowingKnowledgePort(new InvalidOperationException("boom")), Resolved(KnowledgeMode.Tool)); - var results = await InvokeSearchAsync(provider, "f63"); + var results = await InvokeSearchAsync(provider, "f63", ToolTurn()); Assert.Contains(results, r => r.Text.Contains("unreachable", StringComparison.Ordinal)); } @@ -683,24 +675,63 @@ public async Task Search_ToolModeThatThrows_StillSaysUnreachable() /// The store the provider searches. /// The agent's resolved knowledge: block. /// The provider. + private static TurnInvocation PrefetchTurn(KnowledgeScope? scope = null, TurnSources? sources = null) => new() + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Knowledge = scope, + Sources = sources, + }; + + private static TurnInvocation ToolTurn( + KnowledgeScope? scope = null, Clarifications? clarifications = null, TurnSources? sources = null) => new() + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Knowledge = scope, + Clarifications = clarifications ?? new Clarifications(), + Sources = sources, + }; + + private static async Task InvokePrefetchAsync( + AIContextProvider provider, string text, TurnInvocation turn, AgentSession session) + { + TurnRegistry.Set(session, turn); + return await provider.InvokingAsync( + Invoking(text, session), TestContext.Current.CancellationToken).ConfigureAwait(false); + } + private static AIContextProvider Provider(IKnowledgeRetrievalPort port, ResolvedKnowledge knowledge) => KnowledgeProviderFactory.Create( port, knowledge, "agent-under-test", new SourceLocatorCitationFormatter(), loggers: null); /// - /// Calls the factory's own search delegate directly, rather than through - /// . The guard under test reads - /// itself, so it behaves identically whether the framework - /// would have called the delegate before the model (prefetch) or handed it to the model as a - /// tool -- TextSearchProvider only decides which of those two happens, and in tool mode - /// never calls the delegate on its own. + /// Invokes the search tool the provider offers, the way the model would: the turn rides along + /// as an argument, carrying the scope and the clarifications the search runs under. /// /// The provider built. /// The search text. - /// What the delegate returned. - private static Task> InvokeSearchAsync( - AIContextProvider provider, string query) - => TextSearchProviderInternals.SearchAsync(provider, query, TestContext.Current.CancellationToken); + /// The turn the search runs under. + /// What the search returned. + private static async Task> InvokeSearchAsync( + AIContextProvider provider, string query, TurnInvocation turn) + { + StubSession session = new(); + var context = await provider.InvokingAsync( + 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) + { + ["userQuestion"] = query, + [TurnInvocation.ArgumentsKey] = turn, + }), + TestContext.Current.CancellationToken).ConfigureAwait(false) + as IReadOnlyList; + return results!; + } /// Every message text of a returned context, in one string. private static string Merged(AIContext context) @@ -734,7 +765,7 @@ private static KnowledgeCard Linked(string id) => Card(id) with { Score = null, ViaLink = true }; /// Runs the provider the way the framework runs it, over one caller message. - private static AIContextProvider.InvokingContext Invoking(string text, AgentSession? session = null) + private static AIContextProvider.InvokingContext Invoking(string text, AgentSession session) { #pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. return new( diff --git a/tests/AgentCore.Application.Tests/Knowledge/StateKnowledgeScopeTests.cs b/tests/AgentCore.Application.Tests/Knowledge/StateKnowledgeScopeTests.cs index ef9725ea..e4c6ea5d 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/StateKnowledgeScopeTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/StateKnowledgeScopeTests.cs @@ -40,7 +40,7 @@ private static StateDocument Document() [Fact] public void Compose_NothingKnown_IsAllWildcard() { - var scope = StateKnowledgeScope.Compose(Document(), Configured, ambient: null); + var scope = StateKnowledgeScope.Compose(Document(), Configured, hostScope: null); Assert.Equal("*", scope!.Facets["brand"]); Assert.Equal("*", scope.Facets["applies_to"]); @@ -52,7 +52,7 @@ public void Compose_BrandKnown_LeavesTheMachineWildcard() var state = Document(); state.TryWrite("brand", JsonValue.Create("sole")); - var scope = StateKnowledgeScope.Compose(state, Configured, ambient: null); + var scope = StateKnowledgeScope.Compose(state, Configured, hostScope: null); Assert.Equal("sole", scope!.Facets["brand"]); Assert.Equal("*", scope.Facets["applies_to"]); @@ -63,35 +63,35 @@ public void Compose_HostAlreadySetTheKey_DoesNotOverwriteIt() { var state = Document(); state.TryWrite("brand", JsonValue.Create("sole")); - KnowledgeScope ambient = new() + KnowledgeScope host = new() { Facets = new Dictionary(StringComparer.Ordinal) { ["brand"] = "spirit" }, }; - var scope = StateKnowledgeScope.Compose(state, Configured, ambient); + var scope = StateKnowledgeScope.Compose(state, Configured, host); Assert.Equal("spirit", scope!.Facets["brand"]); } [Fact] - public void Compose_NoFromState_ReturnsTheAmbientInstance() + public void Compose_NoFromState_ReturnsTheHostInstance() { - KnowledgeScope ambient = new() + KnowledgeScope host = new() { Facets = new Dictionary(StringComparer.Ordinal) { ["brand"] = "sole" }, }; var scope = StateKnowledgeScope.Compose( - Document(), Configured with { FromState = [] }, ambient); + Document(), Configured with { FromState = [] }, host); - Assert.Same(ambient, scope); + Assert.Same(host, scope); } [Fact] - public void Compose_NoWildcard_ReturnsTheAmbientInstance() + public void Compose_NoWildcard_ReturnsNull() { var scope = StateKnowledgeScope.Compose( - Document(), Configured with { Wildcard = null }, ambient: null); + Document(), Configured with { Wildcard = null }, hostScope: null); Assert.Null(scope); } diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs index 971d363a..55dd3110 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs @@ -52,16 +52,16 @@ public async Task AFaultTheModelCanAnswer_BecomesTheErrorResultTheModelReads() // --------------------------------------------------------------------------------------- // 4. Reporting must not change: an answerable fault never leaves the tool as an exception, - // so it must never reach ToolFailureScope.Report. + // so it must never reach the turn's failure listener. // --------------------------------------------------------------------------------------- [Fact] public async Task AFaultTheModelCanAnswer_IsNeverReported() { List reported = []; - using var scope = ToolFailureScope.Enter(failure => reported.Add(failure)); + var turn = new TurnInvocation { CallId = "call", 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); + await RunSingleRoundAsync(tool, TestContext.Current.CancellationToken, turn: turn); Assert.Empty(reported); } @@ -109,11 +109,11 @@ public async Task AFaultTheModelCannotAnswer_KeepsItsOriginalStack() public async Task AFaultTheModelCannotAnswer_IsReportedOnceForEveryPropagatingRound() { List reported = []; - using var scope = ToolFailureScope.Enter(failure => reported.Add(failure)); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", OnToolFailure = failure => reported.Add(failure) }; var failure = new TimeoutException("the endpoint did not answer."); var tool = new ThrowingDeclaredTool(LookupOrder, failure); - await RunUntilTheBudgetThrowsAsync(tool, TestContext.Current.CancellationToken); + await RunUntilTheBudgetThrowsAsync(tool, TestContext.Current.CancellationToken, turn); // MaximumConsecutiveErrorsPerRequest is 3, so the 4th round is the one that spends the // budget, and all four reached this middleware and were reported before they propagated. @@ -128,7 +128,7 @@ public async Task AFaultTheModelCannotAnswer_IsReportedOnceForEveryPropagatingRo public async Task ACallerThatHungUp_PassesTheCancellationThroughUnreported() { List reported = []; - using var scope = ToolFailureScope.Enter(failure => reported.Add(failure)); + var turn = new TurnInvocation { CallId = "call", 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 @@ -136,7 +136,11 @@ public async Task ACallerThatHungUp_PassesTheCancellationThroughUnreported() var tool = new CancelingDeclaredTool(LookupOrder, source); LoopingToolCallingChatClient inner = new(); using AuditingFunctionInvokingChatClient client = new(inner); - ChatOptions options = new() { Tools = [tool] }; + ChatOptions options = new() + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; await Assert.ThrowsAnyAsync(() => client.GetResponseAsync( @@ -205,18 +209,19 @@ public async Task ARealBindingTool_GetsTheSameErrorResultThroughTheRealMiddlewar /// The arguments the fake model fills, or for none — enough for a tool /// that validates its own arguments before it ever reaches its adapter. /// - /// - /// calls the one offered tool once and then answers with - /// text, which keeps the round finite regardless of what the tool call returns. - /// private static async Task RunSingleRoundAsync( AIFunction tool, CancellationToken cancellationToken, - Dictionary? arguments = null) + Dictionary? arguments = null, + TurnInvocation? turn = null) { ToolCallingChatClient inner = new("the loop continues.", arguments); using AuditingFunctionInvokingChatClient client = new(inner); ChatOptions options = new() { Tools = [tool] }; + if (turn is not null) + { + options.AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }; + } await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "where is my order")], @@ -235,11 +240,15 @@ [new ChatMessage(ChatRole.User, "where is my order")], /// never stops calling the tool, so a fault that /// propagates on every round spends the budget on the fourth. /// - private static async Task RunUntilTheBudgetThrowsAsync(AIFunction tool, CancellationToken cancellationToken) + private static async Task RunUntilTheBudgetThrowsAsync(AIFunction tool, CancellationToken cancellationToken, TurnInvocation? turn = null) { LoopingToolCallingChatClient inner = new(); using AuditingFunctionInvokingChatClient client = new(inner); ChatOptions options = new() { Tools = [tool] }; + if (turn is not null) + { + options.AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }; + } return await Assert.ThrowsAnyAsync(() => client.GetResponseAsync( diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs index 9453c000..4d01969d 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientRenderTests.cs @@ -2,6 +2,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tools.Builtin; using AgentCore.Application.Tools.Drawing; using AgentCore.Application.Tools.Shipped; @@ -47,11 +48,15 @@ public async Task AStreamingTurnThatDrawsOnce_AttachesOneRenderContentAfterTheFu { var tool = DrawOnceTool(); TurnRenders renders = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = renders, Renders = renders }; ToolCallingChatClient inner = new("the loop continues."); using AuditingFunctionInvokingChatClient client = new(inner); - ChatOptions options = new() { Tools = [tool] }; + ChatOptions options = new() + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; List updates = []; await foreach (var update in client.GetStreamingResponseAsync( @@ -77,21 +82,29 @@ [new ChatMessage(ChatRole.User, "draw it")], options, TestContext.Current.Cancel public async Task PublishingTheSameRenderIdTwice_ReplacesTheEarlierOneInPlace() { var tool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - CallRenderScope.Current!.Publish("generative-ui", "chart-1", new { title = "loading" }); - CallRenderScope.Current!.Publish("generative-ui", "chart-1", new { title = "final" }); + turn!.Screen!.Publish("generative-ui", "chart-1", new { title = "loading" }); + turn!.Screen!.Publish("generative-ui", "chart-1", new { title = "final" }); return "drew."; }, - "build_chart", - "Draw a chart for the caller."); + new AIFunctionFactoryOptions + { + Name = "build_chart", + Description = "Draw a chart for the caller.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); TurnRenders renders = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = renders, Renders = renders }; ToolCallingChatClient inner = new("the loop continues."); using AuditingFunctionInvokingChatClient client = new(inner); - ChatOptions options = new() { Tools = [tool] }; + ChatOptions options = new() + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; var response = await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "draw it")], options, TestContext.Current.CancellationToken); @@ -114,20 +127,28 @@ public async Task PublishingTheSameRenderIdTwice_ReplacesTheEarlierOneInPlace() public async Task ATransientPublish_LeavesNoRenderContentAnywhere() { var tool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - CallRenderScope.Current!.Publish("generative-ui", "chart-1", new { title = "peek" }, transient: true); + turn!.Screen!.Publish("generative-ui", "chart-1", new { title = "peek" }, transient: true); return "drew."; }, - "build_chart", - "Draw a chart for the caller."); + new AIFunctionFactoryOptions + { + Name = "build_chart", + Description = "Draw a chart for the caller.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); TurnRenders renders = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = renders, Renders = renders }; ToolCallingChatClient inner = new("the loop continues."); using AuditingFunctionInvokingChatClient client = new(inner); - ChatOptions options = new() { Tools = [tool] }; + ChatOptions options = new() + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; var response = await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "draw it")], options, TestContext.Current.CancellationToken); @@ -140,7 +161,7 @@ public async Task ATransientPublish_LeavesNoRenderContentAnywhere() // --------------------------------------------------------------------------------------- // The outer call id wins. A drawing made inside the nested drawing agent attaches to the // OUTER draw tool-result message, and not to the inner present call, which never reaches - // the caller's own transcript at all. This is the guard for OuterToolCall's outermost-wins + // the caller's own transcript at all. This is the guard for the outermost-wins // rule. // --------------------------------------------------------------------------------------- [Fact] @@ -152,12 +173,16 @@ public async Task ADrawingMadeInsideTheNestedDrawingAgent_AttachesToTheOuterDraw new BuiltinToolPorts(new RecordingChatClientFactory(new PresentCallingChatClient(Card)), new FakeScriptRunner())); TurnRenders renders = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = renders, Renders = renders }; ToolCallingChatClient outer = new( "done.", new Dictionary(StringComparer.Ordinal) { ["query"] = "draw a card" }); using AuditingFunctionInvokingChatClient client = new(outer); - ChatOptions options = new() { Tools = [drawTool] }; + ChatOptions options = new() + { + Tools = [drawTool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; var response = await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "draw a card")], options, TestContext.Current.CancellationToken); @@ -179,36 +204,55 @@ public async Task ADrawingMadeInsideTheNestedDrawingAgent_AttachesToTheOuterDraw public async Task ANestedLoopWhoseOwnCallIdMatchesTheOuterOne_DoesNotStealTheDrawing() { var innerTool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - CallRenderScope.Current!.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); + turn!.Screen!.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); return "drew it."; }, - "inner_tool", - "Draws for the caller."); + new AIFunctionFactoryOptions + { + Name = "inner_tool", + Description = "Draws for the caller.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); var outerTool = AIFunctionFactory.Create( - async () => + async (TurnInvocation? turn) => { // ToolCallingChatClient always hands out the same fixed call id, so running one as // the model behind a NESTED loop reproduces a vendor whose id scheme collides with // the outer call's own id, without needing a bespoke fake to force it. ToolCallingChatClient innerModel = new("nested done."); using AuditingFunctionInvokingChatClient innerClient = new(innerModel); - ChatOptions innerOptions = new() { Tools = [innerTool] }; + ChatOptions innerOptions = new() + { + Tools = [innerTool], + AdditionalProperties = new AdditionalPropertiesDictionary + { + [TurnInvocation.ArgumentsKey] = turn! with { Nested = true, Clarifications = null }, + }, + }; await innerClient.GetResponseAsync( [new ChatMessage(ChatRole.User, "draw")], innerOptions, TestContext.Current.CancellationToken); return "outer done."; }, - "outer_tool", - "Runs a nested loop."); + new AIFunctionFactoryOptions + { + Name = "outer_tool", + Description = "Runs a nested loop.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); TurnRenders renders = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = renders, Renders = renders }; ToolCallingChatClient outerModel = new("done."); using AuditingFunctionInvokingChatClient outerClient = new(outerModel); - ChatOptions outerOptions = new() { Tools = [outerTool] }; + ChatOptions outerOptions = new() + { + Tools = [outerTool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; var response = await outerClient.GetResponseAsync( [new ChatMessage(ChatRole.User, "go")], outerOptions, TestContext.Current.CancellationToken); @@ -228,23 +272,31 @@ await innerClient.GetResponseAsync( public async Task PublishingUnderAnEarlierRenderId_KeepsItsOriginalPosition() { var tool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - var screen = CallRenderScope.Current!; + var screen = turn!.Screen!; screen.Publish("generative-ui", "a", new { title = "first" }); screen.Publish("generative-ui", "b", new { title = "second" }); screen.Publish("generative-ui", "a", new { title = "first-revised" }); return "drew."; }, - "build_chart", - "Draw a chart for the caller."); + new AIFunctionFactoryOptions + { + Name = "build_chart", + Description = "Draw a chart for the caller.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); TurnRenders renders = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = renders, Renders = renders }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = renders, Renders = renders }; ToolCallingChatClient inner = new("the loop continues."); using AuditingFunctionInvokingChatClient client = new(inner); - ChatOptions options = new() { Tools = [tool] }; + ChatOptions options = new() + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; var response = await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "draw it")], options, TestContext.Current.CancellationToken); @@ -276,7 +328,7 @@ public async Task PublishingUnderAnEarlierRenderId_KeepsItsOriginalPosition() public void TakeFor_ReturnsDistinctRenderIds_InPublishOrder() { TurnRenders renders = new(); - using var outer = OuterToolCall.Enter("call_1", out _); + using var outer = renders.BeginOuterCall("call_1"); renders.Publish("generative-ui", "b", new { title = "second" }); renders.Publish("generative-ui", "a", new { title = "first" }); @@ -292,11 +344,15 @@ public void TakeFor_ReturnsDistinctRenderIds_InPublishOrder() /// A tool that draws once, unconditionally, and answers with words. private static AIFunction DrawOnceTool() => AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - CallRenderScope.Current!.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); + turn!.Screen!.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); return "drew a chart."; }, - "build_chart", - "Draw a chart for the caller."); + new AIFunctionFactoryOptions + { + Name = "build_chart", + Description = "Draw a chart for the caller.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); } diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs index 8d334ec5..82058d3b 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientStripTests.cs @@ -2,7 +2,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Knowledge.Fakes; using AgentCore.Domain.Knowledge; @@ -12,17 +12,17 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// K42's strip: removes -/// from the ambient for the duration of a nested -/// tool call, and leaves it alone on the outermost one. +/// K42's strip: hands a +/// nested tool call the turn with its stripped, and hands the +/// outermost call the whole turn. /// /// /// The first two facts drive directly, the same way -/// does, with the ambient hand-rolled -/// through . The third drives a real turn, -/// because that is the only place that proves CallSession.EnterAmbients actually threads its -/// own Clarifications instance through — a fact the first two cannot see, since they open the -/// ambient by hand. +/// does, with the turn filed +/// on the call'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. /// public sealed class AuditingFunctionInvokingChatClientStripTests { @@ -33,19 +33,27 @@ public async Task TheCallersOwnToolCall_SeesTheHolder() Clarifications? seen = null; var tool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - seen = TurnAmbients.Current?.Clarifications; + seen = turn?.Clarifications; return "done."; }, - "search_tool", - "Reads the ambient."); + new AIFunctionFactoryOptions + { + Name = "search_tool", + Description = "Reads the turn.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); - using var scope = TurnAmbients.Amend(ambients => ambients with { Clarifications = clarifications }); + var invocation = TurnOf(clarifications); ToolCallingChatClient inner = new("the loop continues."); using AuditingFunctionInvokingChatClient client = new(inner); - ChatOptions options = new() { Tools = [tool] }; + ChatOptions options = new() + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = invocation }, + }; await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "search")], options, TestContext.Current.CancellationToken); @@ -56,7 +64,7 @@ await client.GetResponseAsync( [Fact] public async Task ANestedToolCall_HasNoHolder_WhileTheOuterCallStillDoes() { - // The outer tool's own invocation reads the ambient before starting the nested loop, and the + // The outer tool's own invocation reads the filed turn before starting the nested loop, and the // inner tool reads it from inside that nested loop's own InvokeFunctionAsync. The two reads // must disagree: K42's strip is conditional on being nested, not on being any tool call at // all, or it would blind the caller's own search too. @@ -65,35 +73,54 @@ public async Task ANestedToolCall_HasNoHolder_WhileTheOuterCallStillDoes() Clarifications? seenNested = null; var innerTool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - seenNested = TurnAmbients.Current?.Clarifications; + seenNested = turn?.Clarifications; return "inner done."; }, - "inner_tool", - "Reads the ambient from inside a nested loop."); + new AIFunctionFactoryOptions + { + Name = "inner_tool", + Description = "Reads the turn from inside a nested loop.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); var outerTool = AIFunctionFactory.Create( - async () => + async (TurnInvocation? outerTurn) => { - seenOutside = TurnAmbients.Current?.Clarifications; + seenOutside = outerTurn?.Clarifications; ToolCallingChatClient innerModel = new("nested done."); using AuditingFunctionInvokingChatClient innerClient = new(innerModel); - ChatOptions innerOptions = new() { Tools = [innerTool] }; + ChatOptions innerOptions = new() + { + Tools = [innerTool], + AdditionalProperties = new AdditionalPropertiesDictionary + { + [TurnInvocation.ArgumentsKey] = outerTurn! with { Nested = true, Clarifications = null }, + }, + }; await innerClient.GetResponseAsync( [new ChatMessage(ChatRole.User, "go")], innerOptions, TestContext.Current.CancellationToken); return "outer done."; }, - "outer_tool", - "Runs a nested loop."); + new AIFunctionFactoryOptions + { + Name = "outer_tool", + Description = "Runs a nested loop.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); - using var scope = TurnAmbients.Amend(ambients => ambients with { Clarifications = clarifications }); + var invocation = TurnOf(clarifications); ToolCallingChatClient outerModel = new("done."); using AuditingFunctionInvokingChatClient outerClient = new(outerModel); - ChatOptions outerOptions = new() { Tools = [outerTool] }; + ChatOptions outerOptions = new() + { + Tools = [outerTool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = invocation }, + }; await outerClient.GetResponseAsync( [new ChatMessage(ChatRole.User, "go")], outerOptions, TestContext.Current.CancellationToken); @@ -102,10 +129,18 @@ await outerClient.GetResponseAsync( Assert.Null(seenNested); } + private static TurnInvocation TurnOf(Clarifications clarifications) => new() + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Clarifications = clarifications, + }; + // ------------------------------------------------------------------------------------------- - // The wiring fact: a real CallSession turn opens its own Clarifications and threads it through - // EnterAmbients, so the model's own (outermost) knowledge search sees it, exactly as the two - // hand-rolled facts above predict once CallSession is actually driving. + // The wiring fact: a real CallSession 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. // ------------------------------------------------------------------------------------------- [Fact] public async Task RunTurnAsync_AToolModeKnowledgeSearch_SeesTheHolder() @@ -113,18 +148,43 @@ public async Task RunTurnAsync_AToolModeKnowledgeSearch_SeesTheHolder() const string yaml = """ apiVersion: agentcore/v1 name: clarifications-through-callsession + state: + applies_to: + type: string + writer: extractor + description: "The model, as printed on the machine." + enum: [CT900, CT900ENT] + brand: + type: string + writer: extractor + description: "The brand of the caller's machine." + enum: [sole, spirit] + extractor: + model: { ref: fill } + when: after_reply + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + knowledge: + kind: qdrant + collection: kb + fields: { body: text } + scope: + template: "{key}" + fromState: [applies_to, brand] + wildcard: { value: "*", facets: [applies_to, brand] } + ambiguity: { maxCandidates: 6, maxAsks: 2 } agents: + defaults: + model: { ref: reply } items: - id: only - instructions: "answer the caller" - knowledge: { mode: tool, scoped: false } - policy: - initial: greeting - stages: - - { id: greeting, agent: only } + knowledge: { mode: tool, scoped: true } """; - var port = new StubKnowledgePort([Card("a")]); + var port = new StubKnowledgePort([]); var compiled = ConfigurationCompiler.Compile( ConfigurationLoader.LoadYaml(yaml), @@ -141,8 +201,8 @@ public async Task RunTurnAsync_AToolModeKnowledgeSearch_SeesTheHolder() await session.RunTurnAsync("what is it", TestContext.Current.CancellationToken); - Assert.Equal(1, port.Calls); - Assert.NotNull(port.ClarificationsAtTheStore); + Assert.Equal(2, port.Calls); + Assert.Equal(1, session.Clarifications.Read("applies_to").ProbeAsks); } private static KnowledgeCard Card(string id) diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs index e0581d27..4b641359 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs @@ -2,10 +2,8 @@ using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.Tests.Fakes; using AgentCore.Domain.Knowledge; using AgentCore.TestSupport; using Microsoft.Extensions.AI; @@ -112,9 +110,9 @@ private sealed class ThrowingOnNarrowedScopePort : IKnowledgeRetrievalPort internal ThrowingOnNarrowedScopePort(Action onNarrowedCall) => _onNarrowedCall = onNarrowedCall; public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { - if (KnowledgeScopeScope.Current?.Facets.Count == 2) + if (scope is { Facets.Count: 2 }) { return ValueTask.FromResult>([]); } diff --git a/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs b/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs index 7e7ed803..e6715f13 100644 --- a/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/DelegatedToolsTests.cs @@ -3,7 +3,6 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using Microsoft.Extensions.AI; using Xunit; @@ -114,23 +113,6 @@ public async Task TheSecondCallOfSetDelegatedTools_ReplacesTheFirst() Assert.DoesNotContain("build_ui", specialist.Offered.Select(tool => tool.Name)); } - [Fact] - public void ARunUnderNoDelegation_IsOfferedNothing() - { - // This is the outer agent's own run, where FunctionInvokingChatClient.CurrentContext is null. - // The id gate shuts it out for nothing, so no session check is needed to keep the tool in. - using var scope = TurnContextScope.Enter(new TurnContext - { - Session = new StubSession(), - Tools = [DrawTool], - ToolsFor = "ask_specialist", - }); - - Assert.Null(TurnContextScope.ToolsFor(null)); - Assert.Null(TurnContextScope.ToolsFor("something_else")); - Assert.Equal([DrawTool], TurnContextScope.ToolsFor("ask_specialist")); - } - [Fact] public void SetDelegatedTools_RefusesNulls() { @@ -163,5 +145,4 @@ private static (CallSession Session, ToolCallingChatClient Greeter, ToolCallingC return (session, greeter, specialist); } - private sealed class StubSession : Microsoft.Agents.AI.AgentSession; } diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs new file mode 100644 index 00000000..041b7510 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/Harness/CallFilesProviderTests.cs @@ -0,0 +1,102 @@ +using System.Text.Json; + +using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Harness; +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Xunit; + +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 +/// workspace of the turn filed for the invoking session, and refuses to serve any when no turn +/// is filed. +/// +public sealed class CallFilesProviderTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"call-files-{Guid.NewGuid():N}"); + + public CallFilesProviderTests() => Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Fact] + public async Task InvokingAsync_WithASessionFiledTurn_ServesFileTools() + { + using CallFilesProvider provider = new(_root, Options()); + StubSession session = new(); + TurnRegistry.Set( + session, + new TurnInvocation { CallId = "call-1", TurnIndex = 0, Stage = "", Workspace = _root }); + + var context = await provider.InvokingAsync( + Invoking(session), TestContext.Current.CancellationToken); + + Assert.NotNull(context.Tools); + Assert.NotEmpty(context.Tools); + } + + [Fact] + public async Task InvokingAsync_WithoutATurn_ThrowsInvalidOperationException() + { + using CallFilesProvider provider = new(_root, Options()); + + var exception = await Assert.ThrowsAsync( + () => provider.InvokingAsync( + Invoking(new StubSession()), TestContext.Current.CancellationToken).AsTask()); + + Assert.Contains("files: tool", exception.Message, StringComparison.Ordinal); + } + + private static FileAccessProviderOptions Options() => new() + { + DisableReadOnlyToolApproval = true, + DisableWriteToolApproval = true, + }; + + private static AIContextProvider.InvokingContext Invoking(AgentSession session) => new( + StubAgent.Instance, + session, + new AIContext { Messages = [new ChatMessage(ChatRole.User, "list my files")] }); + + private sealed class StubSession : AgentSession; + + private sealed class StubAgent : AIAgent + { + public static StubAgent Instance { get; } = new(); + + protected override ValueTask CreateSessionCoreAsync( + CancellationToken cancellationToken = default) + => new(new StubSession()); + + protected override ValueTask SerializeSessionCoreAsync( + AgentSession session, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override ValueTask DeserializeSessionCoreAsync( + JsonElement serializedState, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs b/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs deleted file mode 100644 index d279dd66..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/Harness/CallScopedAgentFileStoreTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Harness; -using AgentCore.Application.Runtime.Turn; -using AgentCore.Application.Tests.Runtime.Turn; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime.Harness; - -/// -/// as a unit: it resolves the running call's workspace off -/// at each operation, with no root and no cache of its own. -/// -public sealed class CallScopedAgentFileStoreTests -{ - [Fact] - public async Task NoAmbientWorkspace_ReadAsyncThrowsInvalidOperationException() - { - var store = new CallScopedAgentFileStore(); - - var exception = await Assert.ThrowsAsync( - () => store.ReadAsync("out.txt", TestContext.Current.CancellationToken)); - - Assert.Contains("files: tool", exception.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task AmbientWorkspaceOpen_WriteThenReadRoundTrips_UnderThatWorkspace() - { - var workspace = Directory.CreateTempSubdirectory("call-scoped-file-store-").FullName; - try - { - var store = new CallScopedAgentFileStore(); - - using (TurnAmbientsTestScope.WithWorkspace(workspace)) - { - await store.WriteAsync("out.txt", "hello", TestContext.Current.CancellationToken); - var read = await store.ReadAsync("out.txt", TestContext.Current.CancellationToken); - - Assert.Equal("hello", read); - } - - Assert.Equal("hello", await File.ReadAllTextAsync( - Path.Combine(workspace, "out.txt"), TestContext.Current.CancellationToken)); - } - finally - { - Directory.Delete(workspace, recursive: true); - } - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeScopeTests.cs b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeScopeTests.cs deleted file mode 100644 index d6ac4fef..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeScopeTests.cs +++ /dev/null @@ -1,54 +0,0 @@ -using AgentCore.Application.Runtime; -using AgentCore.Domain.Knowledge; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -public sealed class KnowledgeScopeScopeTests -{ - [Fact] - public void Current_NoScopeOpen_IsNull() => Assert.Null(KnowledgeScopeScope.Current); - - [Fact] - public void Current_InsideAnOpenScope_IsThatScope() - { - var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - - using (KnowledgeScopeScope.Open(scope)) - { - Assert.Same(scope, KnowledgeScopeScope.Current); - } - - Assert.Null(KnowledgeScopeScope.Current); - } - - [Fact] - public async Task Current_AcrossAnAwait_SurvivesInsideTheScope() - { - var scope = new KnowledgeScope { Facets = new Dictionary { ["model"] = "ct900" } }; - - using (KnowledgeScopeScope.Open(scope)) - { - await Task.Yield(); - Assert.Same(scope, KnowledgeScopeScope.Current); - } - } - - [Fact] - public async Task Current_ConcurrentTurns_DoNotSeeEachOther() - { - using var barrier = new Barrier(8); - - var seen = await Task.WhenAll(Enumerable.Range(0, 8).Select(i => Task.Run(() => - { - var mine = new KnowledgeScope { Facets = new Dictionary { ["model"] = $"m{i}" } }; - using (KnowledgeScopeScope.Open(mine)) - { - barrier.SignalAndWait(); - return KnowledgeScopeScope.Current!.Facets["model"]; - } - }))); - - Assert.Equal(Enumerable.Range(0, 8).Select(i => $"m{i}"), seen); - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs index 690d78c9..e91b862a 100644 --- a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs @@ -1,4 +1,3 @@ -using System.Runtime.CompilerServices; using System.Text.Json.Nodes; using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Compilation; @@ -14,21 +13,20 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// The one wiring a host can actually write: open a knowledge scope, run a turn, and have the scope -/// still be there when the retrieval delegate reads it. +/// The one wiring a host can actually write: set a knowledge scope on the session, run a turn, +/// and have the scope still be there when the retrieval delegate reads it. /// /// /// -/// Every other test of the scope opens it and reads it back on the same flow, with no turn loop in -/// between, and every one of them passed while the feature was wired shut: TurnAmbients.Enter -/// pushed a fresh record carrying only the four ambients the turn loop owns, so the fifth — the one -/// the HOST opens — was erased before the first model call and again on every streaming step. The -/// defect lives in the interaction, so the test has to run the interaction. +/// Every other test of the scope sets it and reads it back without a turn loop in between, and +/// every one of them passed while the feature was wired shut: the loop built its turn without the +/// session's scope, so the store never saw it. The defect lives in the interaction, so the test +/// has to run the interaction. /// /// /// The agent here is scoped: true, which makes the erasure visible twice over: the provider's -/// own gate refuses to call the store at all with no scope open, so a broken carry-through shows up -/// as a store nobody searched as well as an ambient nobody could read. +/// own gate refuses to call the store at all with no scope set, so a broken carry-through shows up +/// as a store nobody searched as well as a scope nobody could read. /// /// public sealed class KnowledgeScopeThroughCallSessionTests @@ -100,10 +98,8 @@ public async Task RunTurnAsync_UnderAHostScope_TheStoreStillSeesThatScope() var session = Build(reply, port).Create("call-1"); var scope = Scope(); - using (KnowledgeScopeScope.Open(scope)) - { - await session.RunTurnAsync("the screen says e33", TestContext.Current.CancellationToken); - } + session.Scope = scope; + await session.RunTurnAsync("the screen says e33", TestContext.Current.CancellationToken); Assert.Equal(1, port.Calls); Assert.Same(scope, port.ScopeAtTheStore); @@ -120,13 +116,11 @@ public async Task RunTurnStreamingAsync_UnderAHostScope_TheStoreStillSeesThatSco var session = Build(reply, port).Create("call-2"); var scope = Scope(); - using (KnowledgeScopeScope.Open(scope)) + session.Scope = scope; + await foreach (var update in session + .RunTurnStreamingAsync("the screen says e33", TestContext.Current.CancellationToken)) { - await foreach (var update in session - .RunTurnStreamingAsync("the screen says e33", TestContext.Current.CancellationToken)) - { - Assert.NotNull(update); - } + Assert.NotNull(update); } Assert.Equal(1, port.Calls); @@ -157,14 +151,10 @@ public async Task RunTurnAsync_AfterTheTurn_PutsBackWhatTheHostHadOpen() var session = Build(reply, port).Create("call-4"); var scope = Scope(); - using (KnowledgeScopeScope.Open(scope)) - { - await session.RunTurnAsync("the screen says e33", TestContext.Current.CancellationToken); - - Assert.Same(scope, KnowledgeScopeScope.Current); - } + session.Scope = scope; + await session.RunTurnAsync("the screen says e33", TestContext.Current.CancellationToken); - Assert.Null(KnowledgeScopeScope.Current); + Assert.Same(scope, session.Scope); } [Fact] @@ -217,88 +207,22 @@ public async Task Scope_NothingKnown_IsAllWildcard() } [Fact] - public async Task Scope_StreamingTurn_IsTheSameOnFirstAndLastUpdate() + public async Task Scope_StreamingTurn_ComposesTheSameScope() { - // _port.ScopeAtTheStore is written exactly once, by the single prefetch search "mode: - // prefetch" runs before the model call — reading it after every streamed update proves - // nothing about later re-entries, because the field never changes again no matter what a - // later EnterAmbients call composes. ScopeSamplingChatClient instead reads the ambient from - // inside its own fragment loop, which ScopedEnumerator re-enters through EnterAmbients on - // every streaming step, so each sample reflects exactly what that step's own scope held. - using ScopeSamplingChatClient reply = new("hello ", "there."); + // The streaming path drives the turn through its own entry point, so it needs its own + // fact rather than an argument from the single-shot one: the scope the store sees must + // match what a non-streaming turn composes. + using SequencedChatClient reply = new("hello there."); var session = FreshSession(reply); - await foreach (var _ in session.RunTurnStreamingAsync("hello", TestContext.Current.CancellationToken)) + await foreach (var _ in session.RunTurnStreamingAsync("what are your opening hours?", TestContext.Current.CancellationToken)) { } - Assert.True(reply.Samples.Count >= 2, "the fake reply must yield at least two fragments, or this never observes a re-entry."); - Assert.All(reply.Samples, sample => Assert.Same(reply.Samples[0], sample)); - Assert.Same(reply.Samples[0], _port.ScopeAtTheStore); + Assert.Equal("*", _port.ScopeAtTheStore!.Facets["brand"]); + Assert.Equal("*", _port.ScopeAtTheStore.Facets["applies_to"]); } - /// - /// A model that streams fragments one at a time and records the knowledge ambient immediately - /// before each is yielded. Unlike , which only proves the seam - /// drops empty updates, this proves what the ambient holds from inside a fragment's own scope — - /// which a field the store's stub sets once cannot, because it never changes again regardless of - /// how many more times EnterAmbients runs afterward. - /// - private sealed class ScopeSamplingChatClient : IChatClient - { - private readonly string[] _fragments; - - public ScopeSamplingChatClient(params string[] fragments) => _fragments = fragments; - - /// Gets the ambient scope read immediately before each fragment was yielded, in order. - public List Samples { get; } = []; - - public async IAsyncEnumerable GetStreamingResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(messages); - await Task.Yield(); - - var responseId = Guid.NewGuid().ToString("N"); - - foreach (var fragment in _fragments) - { - Samples.Add(KnowledgeScopeScope.Current); - yield return new ChatResponseUpdate(ChatRole.Assistant, fragment) - { - ResponseId = responseId, - MessageId = responseId, - }; - } - } - - 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) - { - ArgumentNullException.ThrowIfNull(serviceType); - return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; - } - - public void Dispose() - { - } - } private static CallSessionFactory Build(IChatClient reply, StubKnowledgePort port, string yaml = Yaml) { diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs deleted file mode 100644 index 701cd748..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnAmbientsTestScope.cs +++ /dev/null @@ -1,38 +0,0 @@ -using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Turn; -using Microsoft.Agents.AI; - -namespace AgentCore.Application.Tests.Runtime.Turn; - -/// -/// Opens one ambient at a time, so a collector can be tested without standing up a whole call. -/// -internal static class TurnAmbientsTestScope -{ - /// Opens a source collector over this flow. - internal static IDisposable WithSources(TurnSources sources) - => TurnAmbients.Amend(ambients => ambients with { Sources = sources }); - - /// Opens an outer tool call over this flow. - internal static IDisposable WithOuterCall(string callId) => OuterToolCall.Enter(callId, out _); - - /// Opens the call's ambiguity holder over this flow, the way CallSession does. - internal static IDisposable WithClarifications(Clarifications clarifications) - => TurnAmbients.Amend(ambients => ambients with { Clarifications = clarifications }); - - /// Opens the call's workspace folder over this flow, the way CallSession does. - internal static IDisposable WithWorkspace(string? workspace) - => TurnAmbients.Amend(ambients => ambients with { Workspace = workspace }); - - /// - /// Opens a turn context whose is - /// — true for a row 1 or 2 turn, false for a graph row's own participant invocation (K39). - /// - internal static IDisposable WithCarriesHistory(bool carriesHistory) - => TurnAmbients.Amend(ambients => ambients with - { - Context = new TurnContext { Session = new StubSession(), CarriesHistory = carriesHistory }, - }); - - private sealed class StubSession : AgentSession; -} diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs index b99aa67d..674fa3a6 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnContextProviderTests.cs @@ -20,9 +20,9 @@ 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 on the flow of execution instead, and it applies what it finds -/// only to a run on the session that turn opened. 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. +/// nothing per call. 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. @@ -83,7 +83,7 @@ public sealed class TurnContextProviderTests public async Task TheProvider_HandsTheTurnsInstructionsToARunOnTheCallsSession() { StubSession session = new(); - using var scope = TurnContextScope.Enter(new TurnContext { Session = session, Instructions = "ask for the model" }); + TurnRegistry.Set(session, new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Instructions = "ask for the model" }); var context = await InvokeAsync(session); @@ -101,7 +101,7 @@ public async Task TheProvider_HandsNothingToARunOnAnotherSession() { StubSession call = new(); StubSession delegated = new(); - using var scope = TurnContextScope.Enter(new TurnContext { Session = call, Instructions = "ask for the model" }); + TurnRegistry.Set(call, new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Instructions = "ask for the model" }); var context = await InvokeAsync(delegated); diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs index eaed832d..ddebd420 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs @@ -98,10 +98,10 @@ public void AnUnstructuredResult_IsNotRecorded(object? result) public async Task AnOutermostToolCall_IsRecordedUnderTheToolsName() { TurnResults results = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Results = results }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Results = results }; var tool = AIFunctionFactory.Create(() => Orders, "lookup_orders"); - await Run(tool); + await Run(tool, turn); Assert.Equal(["lookup_orders"], results.Tools); Assert.Equal(Orders.ToJsonString(), results.Data()["lookup_orders"]!.ToJsonString()); @@ -112,29 +112,34 @@ public async Task AToolCallNestedInsideAnother_IsNotRecorded() { // The outer model never saw a nested result, so it cannot ask to draw it. TurnResults results = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Results = results }); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Results = results }; var inner = AIFunctionFactory.Create(() => Orders, "inner_lookup"); var outer = AIFunctionFactory.Create( async () => { - await Run(inner); + await Run(inner, turn with { Nested = true, Clarifications = null }); return JsonNode.Parse("""{"outer":true}"""); }, "delegate"); - await Run(outer); + await Run(outer, turn); Assert.Equal(["delegate"], results.Tools); } - private static async Task Run(AIFunction tool) + private static async Task Run(AIFunction tool, TurnInvocation turn) { ToolCallingChatClient model = new("done."); using AuditingFunctionInvokingChatClient client = new(model); + var options = new ChatOptions + { + Tools = [tool], + AdditionalProperties = new AdditionalPropertiesDictionary { [TurnInvocation.ArgumentsKey] = turn }, + }; await client.GetResponseAsync( [new ChatMessage(ChatRole.User, "go")], - new ChatOptions { Tools = [tool] }, + options, TestContext.Current.CancellationToken); } } diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs index 66197e19..a5c9c474 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnSourcesTests.cs @@ -1,4 +1,3 @@ -using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Domain.Sources; using Xunit; @@ -19,7 +18,7 @@ public void Publish_UnderACall_IsTakenByThatCall() { TurnSources sources = new(); - using (OpenCall("call-1")) + using (OpenCall(sources, "call-1")) { sources.Publish(Reference("card-1")); } @@ -49,7 +48,7 @@ public void Publish_TheSameIdTwice_IsShownOnce() // are noise, and the second publish is the fresher one. TurnSources sources = new(); - using (OpenCall("call-1")) + using (OpenCall(sources, "call-1")) { sources.Publish(Reference("card-1") with { Title = "first" }); sources.Publish(Reference("card-1") with { Title = "second" }); @@ -64,7 +63,7 @@ public void TakeFor_TakesOnlyOnce() { TurnSources sources = new(); - using (OpenCall("call-1")) + using (OpenCall(sources, "call-1")) { sources.Publish(Reference("card-1")); } @@ -81,12 +80,12 @@ public void Publish_UnderTwoDifferentCalls_StampsEachSourceWithItsOwnCallId() // whichever call happens to be findable on that shared message afterward. TurnSources sources = new(); - using (OpenCall("call-1")) + using (OpenCall(sources, "call-1")) { sources.Publish(Reference("card-1")); } - using (OpenCall("call-2")) + using (OpenCall(sources, "call-2")) { sources.Publish(Reference("card-2")); } @@ -100,24 +99,7 @@ public void Publish_UnderTwoDifferentCalls_StampsEachSourceWithItsOwnCallId() Assert.Equal("card-2", fromCallTwo.Source.SourceId); } - [Fact] - public void CallSourceScope_IsWhatAProducerPublishesThrough() - { - TurnSources sources = new(); - - Assert.Null(CallSourceScope.Current); - - using (TurnAmbientsTestScope.WithSources(sources)) - using (OpenCall("call-1")) - { - Assert.NotNull(CallSourceScope.Current); - CallSourceScope.Current!.Publish(Reference("card-1")); - } - - Assert.Single(sources.TakeFor("call-1")); - } - - private static IDisposable OpenCall(string callId) => TurnAmbientsTestScope.WithOuterCall(callId); + private static IDisposable OpenCall(TurnSources sources, string callId) => sources.BeginOuterCall(callId); private static SourceReference Reference(string id) => new() { diff --git a/tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs b/tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs similarity index 61% rename from tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs rename to tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs index d19e62cb..53020696 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallRenderScopeTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/TurnScreenTests.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; +using AgentCore.Application.Tools.Binding; using AgentCore.TestSupport; using Microsoft.Extensions.AI; using Xunit; @@ -12,22 +13,11 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// The screen of one call, found by a tool that was compiled once for the whole process. +/// The turn reaches its tools: the screen the loop builds arriving at the tool that draws. /// -/// -/// -/// A tool that draws cannot hold the screen it draws on: the compiled agent is a process singleton -/// and the screen belongs to one call. It reads the ambient scope instead, exactly as a guarded -/// graph edge reads . -/// -/// -/// Every test here runs offline: no network call and no API key. -/// -/// -public sealed class CallRenderScopeTests +public sealed class TurnScreenTests { - private const string DelegationYaml = - """ + private const string DelegationYaml = """ apiVersion: agentcore/v1 name: render-scope tools: @@ -44,50 +34,6 @@ public sealed class CallRenderScopeTests - { id: greeting, agent: greeter, terminal: true } """; - [Fact] - public void WithNoScopeOpen_TheScreenIsNullRatherThanAThrow() - { - // Unlike CallStateScope, which throws. A guarded edge that quietly became unconditional is a - // silent failure; a call that genuinely has no screen — the telephone — is not. - Assert.Null(CallRenderScope.Current); - } - - [Fact] - public void ClosingAScope_PutsBackTheOneThatWasOpenBefore() - { - RecordingRenderPort outer = new(); - RecordingRenderPort inner = new(); - - using (TurnAmbients.Amend(ambients => ambients with { Screen = outer })) - { - Assert.Same(outer, CallRenderScope.Current); - - using (TurnAmbients.Amend(ambients => ambients with { Screen = inner })) - { - Assert.Same(inner, CallRenderScope.Current); - } - - Assert.Same(outer, CallRenderScope.Current); - } - - Assert.Null(CallRenderScope.Current); - } - - [Fact] - public void DisposingTwice_DoesNotPutAnOlderScreenOverANewerScope() - { - RecordingRenderPort first = new(); - RecordingRenderPort second = new(); - - var scope = TurnAmbients.Amend(ambients => ambients with { Screen = first }); - scope.Dispose(); - - using var later = TurnAmbients.Amend(ambients => ambients with { Screen = second }); - scope.Dispose(); - - Assert.Same(second, CallRenderScope.Current); - } - [Fact] public async Task ATurnThatDoesNotStream_ShowsItsToolsTheScreen() { @@ -95,12 +41,11 @@ public async Task ATurnThatDoesNotStream_ShowsItsToolsTheScreen() await session.RunTurnAsync("hi", TestContext.Current.CancellationToken); - // The screen a tool finds must be the SAME recorder TurnAmbients.Renders holds, not merely + // The screen a tool finds must be the SAME recorder the turn draws into, not merely // some TurnRenders or other: a regression that handed the tool a different instance would - // still draw, and would still lose the drawing, since CreateResponseMessages drains Renders - // and not whatever the tool happened to see. + // still draw, and would still lose the drawing, since the drain reads the turn's own. Assert.IsType(probe.Seen); - Assert.Same(probe.AmbientRenders, probe.Seen); + Assert.Same(probe.TurnRenders, probe.Seen); } [Fact] @@ -117,7 +62,7 @@ public async Task ATurnThatStreams_ShowsItsToolsTheScreenToo() } Assert.IsType(probe.Seen); - Assert.Same(probe.AmbientRenders, probe.Seen); + Assert.Same(probe.TurnRenders, probe.Seen); } [Fact] @@ -177,20 +122,24 @@ private static (CallSession Session, ScreenProbe Probe) NewCall(bool withScreen return (session, probe); } - /// A tool that reports the screen and the ambient recorder it found, from wherever it ran. + /// A tool that reports the screen and the recorder it found, from wherever it ran. private sealed class ScreenProbe { public ScreenProbe() => Tool = AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { Ran = true; - Seen = CallRenderScope.Current; - AmbientRenders = TurnAmbients.Current?.Renders; + Seen = turn?.Screen; + TurnRenders = turn?.Renders; return "drawn."; }, - "build_ui", - "Draw something on the caller's screen."); + new AIFunctionFactoryOptions + { + Name = "build_ui", + Description = "Draw something on the caller's screen.", + ConfigureParameterBinding = ToolParameterBindings.For, + }); public AIFunction Tool { get; } @@ -198,7 +147,7 @@ public ScreenProbe() public IRenderPort? Seen { get; private set; } - /// What held at the same moment was read. - public TurnRenders? AmbientRenders { get; private set; } + /// What the turn drew into at the same moment was read. + public TurnRenders? TurnRenders { get; private set; } } } diff --git a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs index cc0f841d..ed91e526 100644 --- a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; @@ -85,13 +86,13 @@ public void TheAdvertisedSchema_IsATinyFractionOfTheShippedOne() public async Task ADrawingAgent_ThatCallsPresentWithAValidTree_PublishesToTheScreen() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); var function = Build(new RecordingChatClientFactory(new PresentCallingChatClient(Card))); - var result = await function.InvokeAsync( - new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }), - TestContext.Current.CancellationToken); + var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }); + arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, }; + + var result = await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); var published = Assert.Single(screen.Published); Assert.Equal(PresentTool.RendererName, published.Name); @@ -105,11 +106,9 @@ public async Task ADrawingAgent_ThatCallsPresentWithAValidTree_PublishesToTheScr public async Task ATreeTheValidatorRejects_ComesBackAsAnErrorAndTheAgentDrawsTheNextOne() { // The whole reason the hand-rolled retry loop could be deleted. Nothing in C# notices the - // bad tree: present answers a section 8.7 error, the agent reads it, and asks again. RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Draw("""{ "$type": "Wombat" }""", Card); + var result = await Draw(screen, """{ "$type": "Wombat" }""", Card); var published = Assert.Single(screen.Published); Assert.Equal("Card", ((JsonObject)published.Data)["$type"]!.GetValue()); @@ -127,12 +126,10 @@ public async Task ATreeTheValidatorRejects_ComesBackAsAnErrorAndTheAgentDrawsThe public async Task TheDefaultRoundCap_AllowsThreeTriesAndNoFourth(int rejected, bool drawn) { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); string[] trees = [.. Enumerable.Repeat("""{ "$type": "Wombat" }""", rejected), Card]; - await Draw(trees); - + await Draw(screen, trees); Assert.Equal(drawn, screen.Published.Count == 1); } @@ -143,9 +140,8 @@ public async Task ADrawingAgentThatSpendsEveryRound_AnswersASection87ErrorAndNot // holds only the tool call it refused to invoke, so the text is "". Handed that, the calling // agent would tell the caller their drawing is on screen. RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Draw("""{ "$type": "Wombat" }""", """{ "$type": "Wombat" }""", """{ "$type": "Wombat" }""", Card); + var result = await Draw(screen, """{ "$type": "Wombat" }""", """{ "$type": "Wombat" }""", """{ "$type": "Wombat" }""", Card); Assert.Empty(screen.Published); @@ -205,13 +201,14 @@ public async Task TheDrawingModel_IsToldWhatThisTurnsToolsAnswered_AfterTheReque RecordingRenderPort screen = new(); TurnResults results = new(); results.Record("lookup_orders", JsonNode.Parse("""[{"id":"SO-1","total":5},{"id":"SO-2","total":7}]""")!); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = results }); PresentCallingChatClient model = new(Card); var function = Build(new RecordingChatClientFactory(model)); - await function.InvokeAsync( - new AIFunctionArguments(new Dictionary { ["query"] = "a table of the lookup_orders result" }), - TestContext.Current.CancellationToken); + + var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "a table of the lookup_orders result" }); + arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, Results = results, }; + + await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); var prompt = model.Prompts[0]; Assert.StartsWith("a table of the lookup_orders result", prompt, StringComparison.Ordinal); @@ -223,13 +220,14 @@ await function.InvokeAsync( public async Task WithNothingAnswered_TheRequestGoesThroughUntouched() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = new TurnResults() }); PresentCallingChatClient model = new(Card); var function = Build(new RecordingChatClientFactory(model)); - await function.InvokeAsync( - new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }), - TestContext.Current.CancellationToken); + + var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }); + arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, Results = new TurnResults(), }; + + await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); Assert.Equal("draw a card", model.Prompts[0]); } @@ -286,16 +284,17 @@ public void TheVocabulary_TeachesEveryComponentTheValidatorAllows() } /// Runs the drawing agent the document declares over one script of trees. - private static async Task Draw(params string[] trees) + private static async Task Draw(RecordingRenderPort screen, params string[] trees) { var registration = await Provide( Declaration, new RecordingChatClientFactory(new PresentCallingChatClient(trees))); var function = Assert.IsAssignableFrom(registration.Materialise()); - return await function.InvokeAsync( - new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }), - TestContext.Current.CancellationToken); + var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }); + arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, }; + + return await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); } private static AIFunction Build(RecordingChatClientFactory factory) diff --git a/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs b/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs index 116f34c4..9ce2597f 100644 --- a/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/PresentToolTests.cs @@ -1,5 +1,7 @@ using System.Text.Json; using System.Text.Json.Nodes; +using AgentCore.Application.Ports; +using AgentCore.Application.Runtime; using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; @@ -25,11 +27,10 @@ public sealed class PresentToolTests public async Task Present_AValidTree_PublishesItAndReturnsTheReceipt() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); var result = await Invoke(Tool(), """ { "$type": "Card", "children": [{ "$type": "Text", "children": ["hi"] }] } - """); + """, screen); Assert.Equal(PresentTool.RendererName, Assert.Single(screen.Published).Name); Assert.False(result.ContainsKey(ToolErrorResult.ErrorProperty)); @@ -39,9 +40,8 @@ public async Task Present_AValidTree_PublishesItAndReturnsTheReceipt() public async Task Present_AnUnknownComponent_ReturnsAnErrorAndDrawsNothing() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(Tool(), """{ "$type": "Wombat" }"""); + var result = await Invoke(Tool(), """{ "$type": "Wombat" }""", screen); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -51,7 +51,7 @@ public async Task Present_AnUnknownComponent_ReturnsAnErrorAndDrawsNothing() [Fact] public async Task Present_NoScreen_ReturnsAnError() { - var result = await Invoke(Tool(), """{ "$type": "Card" }"""); + var result = await Invoke(Tool(), """{ "$type": "Card" }""", null); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); } @@ -60,9 +60,8 @@ public async Task Present_NoScreen_ReturnsAnError() public async Task Present_ATreeThatIsNotAnObject_ReturnsAnErrorAndDrawsNothing() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(Tool(), "[1, 2, 3]"); + var result = await Invoke(Tool(), "[1, 2, 3]", screen); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -71,7 +70,7 @@ public async Task Present_ATreeThatIsNotAnObject_ReturnsAnErrorAndDrawsNothing() [Fact] public async Task Present_NamesTheDeclaredToolInTheErrorResult() { - var result = await Invoke(Tool(), """{ "$type": "Wombat" }"""); + var result = await Invoke(Tool(), """{ "$type": "Wombat" }""", null); Assert.Equal("draw", result[ToolErrorResult.ToolProperty]!.GetValue()); } @@ -80,9 +79,8 @@ public async Task Present_NamesTheDeclaredToolInTheErrorResult() public async Task Present_ANumericType_ReturnsAnActionableErrorAndDrawsNothing() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(Tool(), """{ "$type": 123 }"""); + var result = await Invoke(Tool(), """{ "$type": 123 }""", screen); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -95,11 +93,10 @@ public async Task Present_ANumericType_ReturnsAnActionableErrorAndDrawsNothing() public async Task Present_ANonStringActionType_ReturnsAnActionableErrorAndDrawsNothing() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); var result = await Invoke( Tool(), - """{ "$type": "Button", "label": "Yes", "$action": { "type": 42 } }"""); + """{ "$type": "Button", "label": "Yes", "$action": { "type": 42 } }""", screen); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -118,10 +115,9 @@ public async Task Present_ANonStringActionType_ReturnsAnActionableErrorAndDrawsN public async Task Present_ANonStringActionTypeUnderAReservedKey_FinishesWithoutThrowing() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); var result = await Invoke( - Tool(), """{ "$type": "Card", "$key": { "$action": { "type": 42 } } }"""); + Tool(), """{ "$type": "Card", "$key": { "$action": { "type": 42 } } }""", screen); // The validator accepts this tree, so the tool must finish it: one publish, one receipt, and // no button named off a type that is not a string. What must never happen again is the @@ -135,9 +131,8 @@ public async Task Present_ANonStringActionTypeUnderAReservedKey_FinishesWithoutT public async Task Present_AScriptThatFails_ReturnsItsErrorAndAsksForAnotherTry() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(Tool(), "throw: data.orders is undefined"); + var result = await Invoke(Tool(), "throw: data.orders is undefined", screen); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -150,9 +145,8 @@ public async Task Present_AScriptThatFails_ReturnsItsErrorAndAsksForAnotherTry() public async Task Present_AScriptThatReturnsNothing_ReturnsAnErrorAndDrawsNothing() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen }); - var result = await Invoke(Tool(), "null"); + var result = await Invoke(Tool(), "null", screen); Assert.Empty(screen.Published); Assert.True(result[ToolErrorResult.ErrorProperty]!.GetValue()); @@ -165,10 +159,9 @@ public async Task TheScript_SeesThisTurnsToolResultsAsData_AndMayCallPresentItse RecordingRenderPort screen = new(); TurnResults results = new(); results.Record("lookup_orders", JsonNode.Parse("""[{"id":"SO-1"}]""")!); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = results }); FakeScriptRunner runner = new(); - await Invoke(PresentTool.Create("draw", runner), """{ "$type": "Text", "value": "hi" }"""); + await Invoke(PresentTool.Create("draw", runner), """{ "$type": "Text", "value": "hi" }""", screen, results); var request = Assert.Single(runner.Requests); Assert.Equal("""[{"id":"SO-1"}]""", request.Data["lookup_orders"]!.ToJsonString()); @@ -180,10 +173,9 @@ public async Task TheScript_SeesThisTurnsToolResultsAsData_AndMayCallPresentItse public async Task WithNoToolResultsThisTurn_TheScriptStillSeesAnEmptyData() { RecordingRenderPort screen = new(); - using var scope = TurnAmbients.Amend(ambients => ambients with { Screen = screen, Results = null }); FakeScriptRunner runner = new(); - await Invoke(PresentTool.Create("draw", runner), """{ "$type": "Text", "value": "hi" }"""); + await Invoke(PresentTool.Create("draw", runner), """{ "$type": "Text", "value": "hi" }""", screen); var data = Assert.IsType(Assert.Single(runner.Requests).Data); Assert.Empty(data[TurnResults.AllKey]!.AsObject()); @@ -201,11 +193,19 @@ public void TheTool_AdvertisesNoResultSchema() private static AIFunction Tool() => PresentTool.Create("draw", new FakeScriptRunner()); /// Calls the tool with one script and reads the result as a node tree. - private static async Task Invoke(AIFunction tool, string code) + private static async Task Invoke(AIFunction tool, string code, IRenderPort? screen, TurnResults? results = null) { var arguments = new AIFunctionArguments { ["code"] = code, + [TurnInvocation.ArgumentsKey] = new TurnInvocation + { + CallId = "call", + TurnIndex = 0, + Stage = "", + Screen = screen, + Results = results, + }, }; var result = await tool.InvokeAsync(arguments, TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs b/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs index 9bbeef8c..5e75bdae 100644 --- a/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/ShippedAgentBuilderTests.cs @@ -3,6 +3,7 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; +using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Runtime; using AgentCore.Application.Tools; using AgentCore.Application.Tools.Builtin; @@ -226,9 +227,9 @@ await function.InvokeAsync( /// /// The other half of section 8.7. A fault naming a dependency that is not there must still /// propagate, so the outer agent's error budget counts it and the turn can end on the fallback - /// line. It must also be reported: a plain loop never calls - /// at all, so before this an inner tool could take the - /// knowledge store down mid-call and the audit chain would hold nothing about it. + /// line. It must also be reported: a plain loop never invokes the turn's failure listener at + /// all, so before this an inner tool could take the knowledge store down mid-call and the + /// audit chain would hold nothing about it. /// [Fact] public async Task Build_AnInnerToolThrowsAFaultBeyondTheModel_ItIsReportedAndPropagates() @@ -246,11 +247,15 @@ public async Task Build_AnInnerToolThrowsAFaultBeyondTheModel_ItIsReportedAndPro new BuiltinToolPorts(new RecordingChatClientFactory(new LoopingToolCallingChatClient()))); List reported = []; - using var scope = ToolFailureScope.Enter(reported.Add); + var turn = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", OnToolFailure = reported.Add }; await Assert.ThrowsAsync( () => function.InvokeAsync( - new AIFunctionArguments(new Dictionary { ["query"] = "go" }), + new AIFunctionArguments(new Dictionary + { + ["query"] = "go", + [TurnInvocation.ArgumentsKey] = turn, + }), TestContext.Current.CancellationToken).AsTask()); Assert.Contains(reported, failure => failure.ToolName == "loop_tool"); @@ -285,6 +290,6 @@ public FakeDefinition(string? missingPort = null, IReadOnlyList? innerTo public string? MissingPort(BuiltinToolPorts ports) => _missingPort; - public string Compose(string query) => query; + public string Compose(string query, TurnResults? results) => query; } } diff --git a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs index cf2d61ac..a9373450 100644 --- a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs @@ -206,6 +206,38 @@ await tool.InvokeAsync( Assert.Equal(ToolCallScopes.NoTurnMessage, thrown.Message); } + /// A tool call carrying the turn in its arguments binds the scope off no flow at all. + [Fact] + public async Task AToolCallScopeParameterWithTheTurnFiled_BindsWithoutAFlow() + { + ToolCallScope? captured = null; + var tool = await CreateAsync((string reason, ToolCallScope scope) => + { + captured = scope; + return reason; + }); + + var result = await tool.InvokeAsync( + new AIFunctionArguments + { + ["reason"] = "the caller wants a person", + [TurnInvocation.ArgumentsKey] = new TurnInvocation + { + CallId = "call-9", + TurnIndex = 4, + Stage = "handling", + Workspace = "ws", + }, + }, + TestContext.Current.CancellationToken); + + Assert.Equal("the caller wants a person", $"{result}"); + Assert.Equal("call-9", captured!.CallId); + Assert.Equal(4, captured.TurnIndex); + Assert.Equal("handling", captured.Stage); + Assert.Equal("ws", captured.Workspace); + } + /// The error policy of section 8.7 keys off , not off the delegate. [Fact] public async Task ATypedBinding_IsStillADeclaredTool() diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs index 72cfd3fd..ce58a2b0 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs @@ -5,9 +5,9 @@ using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.Runtime.Turn; using AgentCore.Application.Tests.Fakes; using AgentCore.Application.Tests.Runtime; +using AgentCore.Application.Tools.Binding; using AgentCore.Application.Transcript; using AgentCore.TestSupport; using Microsoft.Extensions.AI; @@ -157,9 +157,9 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnThatDrew_LeavesTheRenderCon /// /// Drives a real turn end to end through , with a screen bound and a /// real tool that draws through it, and reads what store 1 actually kept. Every other render - /// test in this suite hand-rolls the ambient with TurnAmbients.Amend, so none of them - /// would notice a broken wire between and - /// — this is the one test that goes through that wire itself. + /// test in this suite hand-rolls collectors, so none of them would notice a broken wire between + /// and the turn's renders — this is the one test that + /// goes through that wire itself. /// [Fact] public async Task ATurnThatDrawsWithAScreenBound_StoresTheRenderContentOnTheToolResultRow() @@ -179,16 +179,20 @@ public async Task ATurnThatDrawsWithAScreenBound_StoresTheRenderContentOnTheTool Assert.Contains(rows.SelectMany(row => row.Content.Contents), content => content is RenderContent); } - /// Builds a real tool that draws through the ambient screen, for . + /// Builds a real tool that draws through the turn's screen, for . private static AITool? DrawingTool(ToolConfiguration tool) => AIFunctionFactory.Create( - () => + (TurnInvocation? turn) => { - CallRenderScope.Current!.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); + turn!.Screen!.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); return "drew it."; }, - tool.Id, - tool.Description ?? tool.Id); + new AIFunctionFactoryOptions + { + Name = tool.Id, + Description = tool.Description ?? tool.Id, + ConfigureParameterBinding = ToolParameterBindings.For, + }); /// /// Step 1's second failure mode: a cut that reached back a turn would replace a sentence the diff --git a/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs index 03f9ffc2..66f7ec59 100644 --- a/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/InnerAgentTranscriptTests.cs @@ -53,7 +53,11 @@ public async Task ADelegatingTurn_WritesTheOuterRoundsOnly() await session.FlushTranscriptAsync(); - Assert.Equal(2, model.Calls); + // Outer tool call, inner answer, outer reply. The old count was two: the inner run + // never reached its own model, so a kind: agent tool never heard its agent. Three is + // the delegation actually working — and the rows below still hold, so its working-out + // stays off store 1 all the same. + Assert.Equal(3, model.Calls); Assert.Equal( ["user", "assistant", "tool", "assistant"], store.Rows.Select(row => row.Content.Role.Value)); diff --git a/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs b/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs index 56ba0935..6dff2b74 100644 --- a/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Call/CallTurnArbiterTests.cs @@ -4,6 +4,7 @@ using AgentCore.AspNetCore.Call; using AgentCore.AspNetCore.Tests.Fakes; using AgentCore.Domain; +using AgentCore.Domain.Knowledge; using Microsoft.Extensions.AI; using Xunit; @@ -204,6 +205,9 @@ internal sealed class ScriptedConversationPort : IConversationPort /// public TurnResult? LastTurn { get; set; } + /// + public KnowledgeScope? Scope { get; set; } + /// Gets what the caller was told it heard, or null before a barge-in. public string? LastHeardText { get; private set; } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index 5ab15794..4eca6775 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -1385,7 +1385,7 @@ public ValueTask CreateSearchAsync( private sealed class FacetCapablePort : IKnowledgeRetrievalPort, IKnowledgeFacetReadPort { public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => ValueTask.FromResult>([]); public ValueTask> ReadByFacetAsync( @@ -1399,7 +1399,7 @@ private sealed class DisposeTrackingKnowledgePort : IKnowledgeRetrievalPort, IDi public bool Closed { get; private set; } public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => ValueTask.FromResult>([]); public void Dispose() => Closed = true; diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs index 06699e51..5d4bdb4a 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs @@ -1,7 +1,6 @@ using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; -using AgentCore.Application.Secrets; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.Tests.Fakes; using AgentCore.Domain.Knowledge; @@ -118,7 +117,7 @@ public ValueTask CreateSearchAsync( private sealed class EmptyPort : IKnowledgeRetrievalPort { public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => ValueTask.FromResult>([]); } } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeLoggingThroughBootTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeLoggingThroughBootTests.cs index 462aa1f8..29658ad4 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeLoggingThroughBootTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeLoggingThroughBootTests.cs @@ -1,4 +1,5 @@ using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.Tests.Fakes; @@ -41,7 +42,7 @@ public async Task BootAsync_TheStoreIsDown_TheCompiledProviderWritesThroughTheHo await boot.BootAsync(TestContext.Current.CancellationToken); // Run the retrieval the way the framework runs it, on the agent the boot actually compiled. - var provider = Assert.Single(Providers(boot.Compiled.Agents["resolver"]).OfType()); + var provider = Assert.Single(Providers(boot.Compiled.Agents["resolver"]).OfType()); #pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. AIContextProvider.InvokingContext context = new( @@ -109,7 +110,7 @@ private static IEnumerable Providers(AIAgent agent) private sealed class ThrowingPort(Exception failure) : IKnowledgeRetrievalPort { public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => throw failure; } } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs index d857b956..eee71888 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeScopeArgumentOrderTests.cs @@ -2,7 +2,6 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using Microsoft.Extensions.AI; -using AgentCore.Application.Secrets; using AgentCore.AspNetCore.DependencyInjection; using AgentCore.AspNetCore.Tests.Fakes; using AgentCore.Domain.Knowledge; @@ -167,7 +166,7 @@ public ValueTask CreateSearchAsync( private sealed class SilentPort : IKnowledgeRetrievalPort { public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => ValueTask.FromResult>([]); } } diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeStartupTests.cs index c619e57a..d882001c 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeStartupTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/KnowledgeStartupTests.cs @@ -3,7 +3,6 @@ using AgentCore.Application.Ports; using Microsoft.Extensions.AI; using AgentCore.AspNetCore.DependencyInjection; -using AgentCore.AspNetCore.DependencyInjection.Startup; using AgentCore.Application.Secrets; using AgentCore.Domain.Knowledge; using Xunit; @@ -181,7 +180,7 @@ public ValueTask CreateSearchAsync( private sealed class FakePort : IKnowledgeRetrievalPort { public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) => ValueTask.FromResult>([]); } } diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/DrawingWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/DrawingWireTests.cs index f1764b88..523130e3 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/DrawingWireTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/DrawingWireTests.cs @@ -3,7 +3,6 @@ using AgentCore.Application.Runtime; using Microsoft.Extensions.AI; using AgentCore.AspNetCore.Tests.Fakes; -using AgentCore.TestSupport; using Xunit; namespace AgentCore.AspNetCore.Tests.Endpoints; @@ -33,9 +32,6 @@ public sealed class DrawingWireTests kind: binding binds: DrawIt description: Draw something for the caller. - parameters: - type: object - properties: { what: { type: string } } agents: defaults: model: { ref: reply } @@ -62,10 +58,10 @@ public async Task AToolThatDraws_ReachesTheBrowserOnItsOwnFieldAndNotInTheReply( await using var host = await ChatCompletionsHost.StartAsync( DrawingYaml, new DrawingChatClient(), - configure: options => options.Bind("DrawIt", (_, _) => + configure: options => options.Bind("DrawIt", (TurnInvocation? turn) => { - // Exactly what PresentTool does: find the call's screen and push to it. - CallRenderScope.Current?.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); + // Exactly what PresentTool does: find the call's screen and push to it. The loop files the turn in the call's arguments, and the binder hands it to this parameter. + turn?.Screen?.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); return ValueTask.FromResult("drew a Card; buttons: none"); })); @@ -104,9 +100,9 @@ public async Task AnAnswerThatIsNotAStream_DropsTheDrawingRatherThanKeepingItFor await using var host = await ChatCompletionsHost.StartAsync( DrawingYaml, new DrawingChatClient(), - configure: options => options.Bind("DrawIt", (_, _) => + configure: options => options.Bind("DrawIt", (TurnInvocation? turn) => { - CallRenderScope.Current?.Publish("generative-ui", "chart-1", new { title = "dropped" }); + turn?.Screen?.Publish("generative-ui", "chart-1", new { title = "dropped" }); return ValueTask.FromResult("drew a Card; buttons: none"); })); @@ -129,9 +125,9 @@ public async Task AnAnswerThatIsNotAStream_ShowsTheToolNoScreenRatherThanTakingW await using var host = await ChatCompletionsHost.StartAsync( DrawingYaml, new DrawingChatClient(), - configure: options => options.Bind("DrawIt", (_, _) => + configure: options => options.Bind("DrawIt", (TurnInvocation? turn) => { - hadScreen = CallRenderScope.Current is not null; + hadScreen = turn?.Screen is not null; return ValueTask.FromResult("drew a Card; buttons: none"); })); diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs index 75f8caf0..2546d610 100644 --- a/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/SourceWireTests.cs @@ -1,6 +1,5 @@ using System.Runtime.CompilerServices; using System.Text.Json; -using System.Text.Json.Nodes; using AgentCore.Application.Runtime; using AgentCore.Domain.Sources; using AgentCore.AspNetCore.Tests.Fakes; @@ -28,9 +27,6 @@ public sealed class SourceWireTests kind: binding binds: LookItUp description: Look something up for the caller. - parameters: - type: object - properties: { what: { type: string } } agents: defaults: model: { ref: reply } @@ -57,9 +53,9 @@ public async Task AToolThatCites_ReachesTheBrowserOnItsOwnFieldAndNotInTheReply( await using var host = await ChatCompletionsHost.StartAsync( SourceYaml, new SourceCitingChatClient(), - configure: options => options.Bind("LookItUp", (_, _) => + configure: options => options.Bind("LookItUp", (TurnInvocation? turn) => { - CallSourceScope.Current?.Publish(new SourceReference + turn?.Sources?.Publish(new SourceReference { SourceId = "card-42", Kind = SourceKind.Document, @@ -127,10 +123,9 @@ public async Task AToolThatCitesUnderTwoParallelCalls_StampsEachSourceWithItsOwn await using var host = await ChatCompletionsHost.StartAsync( SourceYaml, new TwoParallelCallsChatClient(), - configure: options => options.Bind("LookItUp", (arguments, _) => + configure: options => options.Bind("LookItUp", (string? what, TurnInvocation? turn) => { - var what = arguments["what"]?.GetValue(); - CallSourceScope.Current?.Publish(new SourceReference + turn?.Sources?.Publish(new SourceReference { SourceId = what == "left" ? "card-left" : "card-right", Kind = SourceKind.Document, diff --git a/tests/AgentCore.Evals/GoldenSetEvalTests.cs b/tests/AgentCore.Evals/GoldenSetEvalTests.cs index a4da8441..69b2b268 100644 --- a/tests/AgentCore.Evals/GoldenSetEvalTests.cs +++ b/tests/AgentCore.Evals/GoldenSetEvalTests.cs @@ -40,7 +40,7 @@ public async Task Retrieval_DatasetRow_ReturnsEveryExpectedDocument(GoldenRow ro // Arrange, Act // Ruling 14: this harness opens no KnowledgeScope. See DatasetHarness for why requireScope is // false and no per-row scope is meaningful here. - var hits = await harness.Search.SearchAsync(row.Query, TestContext.Current.CancellationToken); + var hits = await harness.Search.SearchAsync(row.Query, null, TestContext.Current.CancellationToken); var ids = hits.Select(card => card.CardId).Distinct(StringComparer.Ordinal).ToArray(); await using ScenarioRun run = await harness.Reporting.CreateScenarioRunAsync( diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs index a533ed37..fc58639f 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs @@ -1,6 +1,4 @@ -using System.Reflection; using System.Runtime.CompilerServices; -using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Compilation; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Validation; @@ -10,7 +8,6 @@ using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; using AgentCore.TestSupport; -using Grpc.Core; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; using Qdrant.Client; @@ -22,21 +19,16 @@ namespace AgentCore.Infrastructure.Tests.Knowledge.VectorData.Qdrant; /// /// Section 12's "probe -- against real Qdrant" list. /// -/// -/// /// , and /// 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 -/// turn's own "reply" model is a fake that, instead of letting the framework's tool-calling loop run, -/// reaches directly into the compiled agent's own TextSearchProvider and calls its private search -/// delegate itself -- the same delegate KnowledgeProviderFactory.Create built from the real store, -/// reached by reflection into a third-party field exactly as -/// AgentCore.Application.Tests.Knowledge.KnowledgeProbeTests already does, which needs no grant -/// because reflection does not go through the C# compiler's accessibility check. Calling it from inside -/// the fake model, rather than after the turn, is what keeps TurnAmbients.Current populated: that -/// ambient is only entered around CallSession's own call into the reply model. +/// 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. /// /// /// The store fuses a plain dense leg with a required-term leg by RRF (K49's amendment): a card the @@ -506,8 +498,6 @@ private async Task RunAsync( Loggers = loggers, }); - capture.Bind(SearchProviderOf(compiled.Agents["only"])); - var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); var session = new CallSessionFactory( compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor) @@ -581,15 +571,6 @@ await _corpus.Client.CreatePayloadIndexAsync( return BuildStoreOver(collection, limit: 10, scoped); } - private static TextSearchProvider SearchProviderOf(AIAgent agent) - { - var inner = agent.GetService() - ?? throw new InvalidOperationException("the compiled agent carries no ChatClientAgent."); - - return inner.AIContextProviders?.OfType().SingleOrDefault() - ?? throw new InvalidOperationException("the compiled agent carries no TextSearchProvider."); - } - /// /// A knowledge store that answers the full-scope (main) search from a real backing store and /// throws for any narrowed one -- the shape §8 step 4's own probe search takes once a facet is @@ -607,11 +588,11 @@ internal ThrowingOnNarrowedScopePort(IKnowledgeRetrievalPort inner, int fullFace } public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) { - if (KnowledgeScopeScope.Current?.Facets.Count == _fullFacetCount) + if (scope?.Facets.Count == _fullFacetCount) { - return _inner.SearchAsync(query, cancellationToken); + return _inner.SearchAsync(query, scope, cancellationToken); } throw new InvalidOperationException("the probe's own second search is down (synthetic, for this row only)."); @@ -619,40 +600,54 @@ public ValueTask> SearchAsync( } /// - /// Stands in for the turn's reply model. Rather than let the framework's own tool-calling loop - /// run, it reaches directly into the compiled agent's TextSearchProvider and calls its - /// private search delegate itself, from inside the same ambient scope - /// already opened around this call -- so TurnAmbients.Current is exactly what a real tool - /// invocation would see. + /// 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 + /// keeps it, so every row asserts on what the production search actually returned. /// private sealed class SearchCapturingChatClient : IChatClient { private readonly string _query; - private Func>>? _search; - internal SearchCapturingChatClient(string query) => _query = query; internal IReadOnlyList Results { get; private set; } = []; - internal void Bind(TextSearchProvider provider) - => _search = TextSearchProviderInternals.SearchDelegate(provider); - public async IAsyncEnumerable GetStreamingResponseAsync( IEnumerable messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(messages); + await Task.Yield(); - if (_search is { } search) + var responseId = Guid.NewGuid().ToString("N"); + + var toolAnswer = messages + .SelectMany(message => message.Contents.OfType()) + .Select(content => content.Result) + .OfType>() + .FirstOrDefault(); + + if (toolAnswer is null) { - Results = [.. await search(_query, cancellationToken).ConfigureAwait(false)]; + yield return new ChatResponseUpdate( + ChatRole.Assistant, + [new FunctionCallContent( + $"search-{responseId}", + "Search", + new Dictionary(StringComparer.Ordinal) { ["userQuestion"] = _query })]) + { + ResponseId = responseId, + MessageId = responseId, + }; + yield break; } - await Task.Yield(); + Results = [.. toolAnswer]; - var responseId = Guid.NewGuid().ToString("N"); yield return new ChatResponseUpdate(ChatRole.Assistant, "noted.") { ResponseId = responseId, @@ -660,6 +655,7 @@ public async IAsyncEnumerable GetStreamingResponseAsync( }; } + public async Task GetResponseAsync( IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) { @@ -736,4 +732,5 @@ public void Dispose() // Nothing to release. } } + } diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/DirectLinkLookupTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/DirectLinkLookupTests.cs index c507123f..bd107431 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/DirectLinkLookupTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/DirectLinkLookupTests.cs @@ -26,7 +26,7 @@ public async Task SearchAsync_DirectLookupWithNonGuidCardId_ThrowsNamingTheId() var store = Store(channel); var thrown = await Assert.ThrowsAsync( - async () => await store.SearchAsync("anything", TestContext.Current.CancellationToken)); + async () => await store.SearchAsync("anything", null, TestContext.Current.CancellationToken)); Assert.Contains(linkedId, thrown.Message, StringComparison.Ordinal); } @@ -38,7 +38,7 @@ public async Task SearchAsync_DirectLookupWithGuidShapedCardId_ResolvesToThatGui var channel = new RecordingSearchChannel([Point("card-1", linkedId.ToString())]); var store = Store(channel); - await store.SearchAsync("anything", TestContext.Current.CancellationToken); + await store.SearchAsync("anything", null, TestContext.Current.CancellationToken); var retrieved = Assert.Single(channel.RetrievedIds); Assert.Equal(linkedId, Assert.Single(retrieved)); diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ForeignSchemaTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ForeignSchemaTests.cs index c1aee6de..1bb39616 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ForeignSchemaTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ForeignSchemaTests.cs @@ -1,6 +1,5 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; -using AgentCore.Application.Runtime; using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; @@ -69,7 +68,7 @@ public async Task Adapter_StartsAgainstAForeignCollection() public async Task Search_MapsEveryRenamedField() { var card = (await Store().SearchAsync( - "warranty returns", TestContext.Current.CancellationToken))[0]; + "warranty returns", null, TestContext.Current.CancellationToken))[0]; Assert.StartsWith("DOC-", card.CardId, StringComparison.Ordinal); Assert.Contains("warranty", card.Text, StringComparison.Ordinal); @@ -82,7 +81,7 @@ public async Task Search_MapsEveryRenamedField() public async Task Search_FollowsLinksByFilterAcrossRandomPointKeys() { var cards = await Store().SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", null, TestContext.Current.CancellationToken); var linked = Assert.Single(cards, card => card.ViaLink); Assert.Equal(ForeignCorpus.Id(ForeignCorpus.Count - 1), linked.CardId); @@ -93,13 +92,13 @@ public async Task Search_TopLevelFacetScopeFiltersAndReChecksLinks() { // Document 0 is emea and links to the last document, which is amer. The scope must keep the // ranked emea documents and drop the linked amer one. - using var _ = KnowledgeScopeScope.Open(new KnowledgeScope + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["region"] = "emea" }, - }); + }; var cards = await Store(scoped: true).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", scope, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); Assert.All(cards, card => Assert.False(card.ViaLink)); @@ -112,7 +111,7 @@ public async Task Search_Limit_IsHonouredOnAForeignCollection() // claim about the store, and the store reads its keys off this document. Proving them only // against the kb-shaped corpus leaves the naming and the ranking entangled. var cards = await Store(limit: 2).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", null, TestContext.Current.CancellationToken); Assert.Equal(2, cards.Count(card => !card.ViaLink)); } @@ -121,9 +120,9 @@ public async Task Search_Limit_IsHonouredOnAForeignCollection() public async Task Search_ScoreFloor_DropsEverythingBelowIt() { var all = await Store(limit: 10, floor: 0.0).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", null, TestContext.Current.CancellationToken); var floored = await Store(limit: 10, floor: 0.25).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", null, TestContext.Current.CancellationToken); Assert.All(floored.Where(card => card.Score is not null), card => Assert.True(card.Score >= 0.25)); Assert.True(floored.Count <= all.Count); @@ -133,7 +132,7 @@ public async Task Search_ScoreFloor_DropsEverythingBelowIt() public async Task Search_NoLinksBlock_NeverExpands() { var cards = await Store(links: false).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", null, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); Assert.All(cards, card => Assert.False(card.ViaLink)); @@ -150,7 +149,7 @@ public async Task Search_TheIdRoleUnmapped_UsesThePointKey() var entry = Entry() with { Fields = BaseEntry().Fields! with { Id = null }, Links = null }; var card = (await StoreFrom(entry).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken))[0]; + "warranty returns", null, TestContext.Current.CancellationToken))[0]; Assert.True(Guid.TryParse(card.CardId, out _)); } @@ -161,7 +160,7 @@ public async Task Search_TheLexicalRoleUnmapped_StillRanksByVector() var entry = Entry() with { Fields = BaseEntry().Fields! with { Lexical = null } }; var cards = await StoreFrom(entry).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken); + "warranty returns", null, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); } @@ -175,7 +174,7 @@ public async Task Search_TheCitationRolesUnmapped_LeaveThemEmpty() }; var card = (await StoreFrom(entry).SearchAsync( - "warranty returns", TestContext.Current.CancellationToken))[0]; + "warranty returns", null, TestContext.Current.CancellationToken))[0]; Assert.Equal(string.Empty, card.SourceRef); Assert.Equal(string.Empty, card.SourceLocator); @@ -198,7 +197,7 @@ public async Task Search_ScopedWithNoAmbient_Throws() var store = Store(scoped: true); await Assert.ThrowsAsync( - async () => await store.SearchAsync("warranty returns", TestContext.Current.CancellationToken)); + async () => await store.SearchAsync("warranty returns", null, TestContext.Current.CancellationToken)); } private static KnowledgeProviderConfiguration BaseEntry() => new() diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs index 3380580d..9cf812ab 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs @@ -3,7 +3,6 @@ using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; -using AgentCore.Application.Ports; using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; @@ -782,7 +781,7 @@ public async Task CreateSearchAsync_CustomMapper_OpensAndMapsEverySearchThroughI entry, secrets: null, Embedder(), requireScope: false, TestContext.Current.CancellationToken); - var cards = await port.SearchAsync("deck", TestContext.Current.CancellationToken); + var cards = await port.SearchAsync("deck", null, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); Assert.All(cards, card => Assert.Equal(card.Text.ToUpperInvariant(), card.Text)); diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs index ea7d5216..9ad75fb1 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs @@ -1,6 +1,5 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; -using AgentCore.Application.Runtime; using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; @@ -68,9 +67,9 @@ public async Task SearchAsync_ScopedSearch_ReturnsOnlyThatProduct() { // Card 0 is in scope and links to card 29, which is not. So this also holds up the scope // re-check on see_also expansion: a key lookup carries no filter of its own. - using var _ = Ct900(); + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["model"] = "ct900" } }; - var cards = await LinkedStore().SearchAsync(KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + var cards = await LinkedStore().SearchAsync(KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); var models = await ModelsOf(cards); @@ -84,7 +83,7 @@ public async Task SearchAsync_Unscoped_WouldMixProducts() // `scoped: false` is the design's own switch for a whole-corpus read. An empty facet map is // not that switch, and now fails closed like an absent ambient. var cards = await Store(scoped: false).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); Assert.True((await ModelsOf(cards)).Distinct(StringComparer.Ordinal).Count() > 1); } @@ -94,9 +93,12 @@ public async Task SearchAsync_ScopedStoreWithNoAmbient_Throws() { // A21, first door. An absent scope fails closed. It never searches every customer's cards. var thrown = await Assert.ThrowsAsync( - async () => await Store().SearchAsync(KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken)); + async () => await Store().SearchAsync(KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken)); - Assert.Contains("no KnowledgeScope is open", thrown.Message, StringComparison.Ordinal); + Assert.Contains( + "This deployment declares scoped: true and the search arrived without a KnowledgeScope", + thrown.Message, + StringComparison.Ordinal); } [QdrantFact] @@ -105,11 +107,10 @@ public async Task SearchAsync_ScopedStoreWithEmptyFacets_Throws() // A21, second door. A host that reads a customer record with no product on it builds this // scope without noticing, and an empty facet map filters nothing. Same leak as no ambient // at all, so the same refusal -- but a different message, because it is a different bug. - using var _ = KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) }); + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) }; var thrown = await Assert.ThrowsAsync( - async () => await Store().SearchAsync(KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken)); + async () => await Store().SearchAsync(KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken)); Assert.Contains("names no facets", thrown.Message, StringComparison.Ordinal); } @@ -138,8 +139,7 @@ public async Task SearchAsync_LookalikeIdentifier_RanksTheIdentifierCardFirst() // A22. Card 7 holds e33 and sits one dense rank BELOW card 6. Only the required // prefetch lifts it. var cards = await Store(scoped: false).SearchAsync( - KbShapedCorpus.LookalikeQuery, TestContext.Current.CancellationToken); - + KbShapedCorpus.LookalikeQuery, null, TestContext.Current.CancellationToken); Assert.Equal(KbShapedCorpus.Id(7), cards[0].CardId); } @@ -150,7 +150,7 @@ public async Task SearchAsync_TwoIdentifiersThatCoOccurNowhere_LeavesTheDenseAns // Under `should` it would match both cards and reorder. `must` and `should` are the // SAME filter for one token, so no single-identifier test can tell them apart. var cards = await Store(scoped: false).SearchAsync( - KbShapedCorpus.TwoIdentifierQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.TwoIdentifierQuery, null, TestContext.Current.CancellationToken); Assert.Equal(KbShapedCorpus.Id(0), cards[0].CardId); } @@ -162,7 +162,7 @@ public async Task SearchAsync_LimitAboveTheDefaultPrefetchDepth_ReturnsThatMany( // depth (10) and the depth a hardcoded constant would use (20), so either one caps the // result below what the caller asked for. var cards = await Store(limit: 25, scoped: false).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); Assert.True( cards.Count(card => !card.ViaLink) >= 25, @@ -176,12 +176,12 @@ public async Task SearchAsync_ScoreFloor_KeepsExactlyTheCardsAtOrAboveIt() // from what the corpus scores: halfway between the second and third card, which leaves two // cards above it and the rest below, with no card sitting on the boundary itself. var all = await Store(floor: 0.0, limit: 20, scoped: false).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); Assert.True(all.Count >= 3); var floor = (all[1].Score!.Value + all[2].Score!.Value) / 2; var floored = await Store(floor: floor, limit: 20, scoped: false).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); Assert.Equal(2, floored.Count(card => !card.ViaLink)); Assert.All(floored.Where(card => !card.ViaLink), card => Assert.True(card.Score > floor)); @@ -194,7 +194,7 @@ public async Task SearchAsync_TopHitHasSeeAlso_PullsTheLinkedCardIn() // on the page already. Nothing is scoped here, so `InScope` is vacuously true and the link // mechanism itself is what the assertion sees. var cards = await LinkedStore(limit: 3, scoped: false).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); var linked = Assert.Single(cards, card => card.ViaLink); Assert.Equal(KbShapedCorpus.Id(KbShapedCorpus.Count - 1), linked.CardId); @@ -208,16 +208,16 @@ public async Task SearchAsync_ScopedOnAListFacetThatHolds_KeepsTheLinkedCard() // and applies_to is a real array facet in the sibling knowledge-bank design, so a deployment // scoped on it would have dropped every linked card with no error. Every card carries // SharedAudience, so this scope holds for card 29 too and the link survives the re-check. - using var _ = KnowledgeScopeScope.Open(new KnowledgeScope + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["applies_to"] = KbShapedCorpus.SharedAudience, }, - }); + }; var cards = await LinkedStore(limit: 3, floor: 0.0).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken); var linked = Assert.Single(cards, card => card.ViaLink); Assert.Equal(KbShapedCorpus.Id(KbShapedCorpus.Count - 1), linked.CardId); @@ -229,13 +229,13 @@ public async Task SearchAsync_ScopedOnAListFacetThatDoesNot_DropsTheLinkedCard() // The other half of the same branch. Card 0 is ct900 and links to card 29, which is ct900ent, // so card 29's applies_to list does NOT hold this scope. Without this fact a list branch that // simply answered true would pass the test above. - using var _ = KnowledgeScopeScope.Open(new KnowledgeScope + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["applies_to"] = "ct900" }, - }); + }; var cards = await LinkedStore(limit: 3, floor: 0.0).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); Assert.DoesNotContain(cards, card => card.ViaLink); @@ -244,9 +244,9 @@ public async Task SearchAsync_ScopedOnAListFacetThatDoesNot_DropsTheLinkedCard() [QdrantFact] public async Task SearchAsync_MapsTheNestedPayload() { - using var _ = Ct900(); + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["model"] = "ct900" } }; - var card = (await Store().SearchAsync(KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken))[0]; + var card = (await Store().SearchAsync(KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken))[0]; Assert.StartsWith("manifest-", card.SourceRef, StringComparison.Ordinal); Assert.Equal("p.1", card.SourceLocator); @@ -273,7 +273,7 @@ public async Task SearchAsync_ChannelHangsPastTheDeadline_Cancels() }); await Assert.ThrowsAnyAsync( - async () => await store.SearchAsync("anything", TestContext.Current.CancellationToken)); + async () => await store.SearchAsync("anything", null, TestContext.Current.CancellationToken)); } [Fact] @@ -299,12 +299,9 @@ public async Task SearchAsync_CallerCancels_Cancels() using var caller = new CancellationTokenSource(TimeSpan.FromMilliseconds(20)); await Assert.ThrowsAnyAsync( - async () => await store.SearchAsync("anything", caller.Token)); + async () => await store.SearchAsync("anything", null, caller.Token)); } - private static IDisposable Ct900() => KnowledgeScopeScope.Open( - new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["model"] = "ct900" } }); - private QdrantKnowledgeStore Store(int limit = 10, double floor = 0.0, bool scoped = true) => new( new QdrantSearchChannel(_corpus.Client), @@ -358,7 +355,7 @@ public async Task SearchAsync_RenamedFields_ReadsThemAndIgnoresTheDefaults() // body field at `text` proves the option is read without needing a second corpus. A store // that ignored Fields.Body would still return non-empty text and pass by accident, so the // assertion below is on a field the corpus gives a DIFFERENT value: the citation. - using var _ = Ct900(); + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["model"] = "ct900" } }; var store = new QdrantKnowledgeStore( new QdrantSearchChannel(_corpus.Client), @@ -375,7 +372,7 @@ public async Task SearchAsync_RenamedFields_ReadsThemAndIgnoresTheDefaults() }); var card = (await store.SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken))[0]; + KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken))[0]; Assert.Equal(card.CardId, card.SourceRef); Assert.NotEmpty(card.SourceLocator); @@ -402,7 +399,7 @@ public async Task SearchAsync_IdRoleDisabled_UsesThePointKeyAsTheCardId() }); var card = (await store.SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken))[0]; + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken))[0]; Assert.True(Guid.TryParse(card.CardId, out _), $"'{card.CardId}' is not a point key"); Assert.NotEmpty(card.Text); @@ -428,7 +425,7 @@ public async Task SearchAsync_LexicalRoleDisabled_StillAnswersAnIdentifierQuery( }); var cards = await store.SearchAsync( - KbShapedCorpus.TwoIdentifierQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.TwoIdentifierQuery, null, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); } @@ -438,7 +435,7 @@ public async Task SearchAsync_NoQueryAnalyzer_StillAnswersTheLookalikeQuery() { // With no required-term leg the identifier card is no longer lifted, so this asserts only // that the single-leg path works at all -- not that ranking is unchanged. - using var _ = Ct900(); + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["model"] = "ct900" } }; var store = new QdrantKnowledgeStore( new QdrantSearchChannel(_corpus.Client), @@ -456,7 +453,7 @@ public async Task SearchAsync_NoQueryAnalyzer_StillAnswersTheLookalikeQuery() }); var cards = await store.SearchAsync( - KbShapedCorpus.LookalikeQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.LookalikeQuery, scope, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); } @@ -484,7 +481,7 @@ public async Task SearchAsync_EveryLookupMode_FollowsTheSameLink(KnowledgeLinkLo }); var cards = await store.SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); var linked = Assert.Single(cards, card => card.ViaLink); Assert.Equal(KbShapedCorpus.Id(KbShapedCorpus.Count - 1), linked.CardId); @@ -496,7 +493,7 @@ public async Task SearchAsync_FilterLookupWithScopeOpen_StillDropsOutOfScopeLink { // The scope re-check must run on the scroll path too. Card 0 is ct900 and links to card 29, // which the interleaved corpus makes ct900ent -- so the link must NOT come back. - using var _ = Ct900(); + var scope = new KnowledgeScope { Facets = new Dictionary(StringComparer.Ordinal) { ["model"] = "ct900" } }; var store = new QdrantKnowledgeStore( new QdrantSearchChannel(_corpus.Client), @@ -514,7 +511,7 @@ public async Task SearchAsync_FilterLookupWithScopeOpen_StillDropsOutOfScopeLink }); var cards = await store.SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, scope, TestContext.Current.CancellationToken); Assert.All(cards, card => Assert.False(card.ViaLink)); } @@ -524,7 +521,7 @@ public async Task SearchAsync_NoLinksBlock_NeverExpands() { // Card 0's payload still says see_also: [syn-29]; with no links: block that is data, not behaviour. var cards = await Store(limit: 3, scoped: false).SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); Assert.All(cards, card => Assert.False(card.ViaLink)); @@ -549,7 +546,7 @@ public async Task SearchAsync_NoLinksFieldInPayload_ReturnsRankedCardsOnly() }); var cards = await store.SearchAsync( - KbShapedCorpus.PlainQuery, TestContext.Current.CancellationToken); + KbShapedCorpus.PlainQuery, null, TestContext.Current.CancellationToken); Assert.NotEmpty(cards); Assert.All(cards, card => Assert.False(card.ViaLink)); @@ -591,7 +588,7 @@ await client.CreateCollectionAsync( }); using var _ = (IDisposable)store; - var card = Assert.Single(await store.SearchAsync("anonymous", TestContext.Current.CancellationToken)); + var card = Assert.Single(await store.SearchAsync("anonymous", null, TestContext.Current.CancellationToken)); Assert.Equal("anonymous vector card", card.Text); } finally diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantWildcardScopeTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantWildcardScopeTests.cs index 0349d3f1..c609f32f 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantWildcardScopeTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantWildcardScopeTests.cs @@ -1,6 +1,4 @@ using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime; -using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; using AgentCore.Infrastructure.Tests.Knowledge.VectorData.Qdrant.Fakes; @@ -28,10 +26,7 @@ public async Task Search_NoWildcardConfigured_EmitsTheKeywordCase() var channel = new CapturingSearchChannel([]); var store = StoreOver(channel, wildcard: null, wildcardFacets: []); - using (KnowledgeScopeScope.Open(Scope(("brand", "sole")))) - { - await store.SearchAsync("belt", TestContext.Current.CancellationToken); - } + await store.SearchAsync("belt", Scope(("brand", "sole")), TestContext.Current.CancellationToken); var condition = channel.Query!.Prefetch[0].Filter.Must[0].Field; Assert.Equal(Match.MatchValueOneofCase.Keyword, condition.Match.MatchValueCase); @@ -43,11 +38,7 @@ public async Task Search_NamedFacet_EmitsBothTheValueAndTheWildcard() { var channel = new CapturingSearchChannel([]); var store = StoreOver(channel, wildcard: "*", wildcardFacets: ["brand"]); - - using (KnowledgeScopeScope.Open(Scope(("brand", "sole")))) - { - await store.SearchAsync("belt", TestContext.Current.CancellationToken); - } + await store.SearchAsync("belt", Scope(("brand", "sole")), TestContext.Current.CancellationToken); var match = channel.Query!.Prefetch[0].Filter.Must[0].Field.Match; Assert.Equal(Match.MatchValueOneofCase.Keywords, match.MatchValueCase); @@ -59,11 +50,8 @@ public async Task Search_FacetNotNamed_StaysExactEvenBesideANamedOne() { var channel = new CapturingSearchChannel([]); var store = StoreOver(channel, wildcard: "*", wildcardFacets: ["brand"]); - - using (KnowledgeScopeScope.Open(Scope(("brand", "sole"), ("customer_id", "c-91")))) - { - await store.SearchAsync("belt", TestContext.Current.CancellationToken); - } + await store.SearchAsync( + "belt", Scope(("brand", "sole"), ("customer_id", "c-91")), TestContext.Current.CancellationToken); var conditions = channel.Query!.Prefetch[0].Filter.Must; var tenant = conditions.Single(c => c.Field.Key.EndsWith("customer_id", StringComparison.Ordinal)); @@ -76,10 +64,7 @@ public async Task Search_ValueEqualsTheWildcard_EmitsOneKeyword() var channel = new CapturingSearchChannel([]); var store = StoreOver(channel, wildcard: "*", wildcardFacets: ["brand"]); - using (KnowledgeScopeScope.Open(Scope(("brand", "*")))) - { - await store.SearchAsync("belt", TestContext.Current.CancellationToken); - } + await store.SearchAsync("belt", Scope(("brand", "*")), TestContext.Current.CancellationToken); var match = channel.Query!.Prefetch[0].Filter.Must[0].Field.Match; Assert.Equal(Match.MatchValueOneofCase.Keyword, match.MatchValueCase); @@ -93,12 +78,9 @@ public async Task Search_LinkedCardTaggedWildcard_IsKept() // gate on them. It has to accept the same set the query did. var store = StoreOver( ChannelWithLink(linkedFacet: "*"), wildcard: "*", wildcardFacets: ["brand"], withLinks: true); - - using (KnowledgeScopeScope.Open(Scope(("brand", "sole")))) - { - var cards = await store.SearchAsync("belt", TestContext.Current.CancellationToken); - Assert.Contains(cards, card => card.ViaLink); - } + var cards = await store.SearchAsync( + "belt", Scope(("brand", "sole")), TestContext.Current.CancellationToken); + Assert.Contains(cards, card => card.ViaLink); } [Fact] @@ -107,11 +89,9 @@ public async Task Search_LinkedCardOutsideTheScope_IsDropped() var store = StoreOver( ChannelWithLink(linkedFacet: "spirit"), wildcard: "*", wildcardFacets: ["brand"], withLinks: true); - using (KnowledgeScopeScope.Open(Scope(("brand", "sole")))) - { - var cards = await store.SearchAsync("belt", TestContext.Current.CancellationToken); - Assert.DoesNotContain(cards, card => card.ViaLink); - } + var cards = await store.SearchAsync( + "belt", Scope(("brand", "sole")), TestContext.Current.CancellationToken); + Assert.DoesNotContain(cards, card => card.ViaLink); } /// A ranked point linking to one fetched point tagged on brand. diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ScoreFloorOnPrefetchTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ScoreFloorOnPrefetchTests.cs index d9d783fc..be2db66d 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ScoreFloorOnPrefetchTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/ScoreFloorOnPrefetchTests.cs @@ -23,7 +23,7 @@ public async Task SearchAsync_PutsTheFloorOnEveryDensePrefetch() { var channel = new CapturingSearchChannel(Points(RankScores)); - await Store(channel, floor: 0.35).SearchAsync("belt", TestContext.Current.CancellationToken); + await Store(channel, floor: 0.35).SearchAsync("belt", null, TestContext.Current.CancellationToken); var leg = Assert.Single(channel.Query!.Prefetch); Assert.True(leg.HasScoreThreshold, "the dense prefetch carries no score_threshold"); @@ -35,7 +35,7 @@ public async Task SearchAsync_WithZeroFloor_EmitsNoScoreThreshold() { var channel = new CapturingSearchChannel(Points(RankScores)); - await Store(channel, floor: 0.0).SearchAsync("belt", TestContext.Current.CancellationToken); + await Store(channel, floor: 0.0).SearchAsync("belt", null, TestContext.Current.CancellationToken); var leg = Assert.Single(channel.Query!.Prefetch); Assert.False(leg.HasScoreThreshold, "a floor of 0 means no floor, so no score_threshold should ride the prefetch"); @@ -46,7 +46,7 @@ public async Task SearchAsync_DoesNotCutTheReturnedPointsByScore() { var channel = new CapturingSearchChannel(Points(RankScores)); - var cards = await Store(channel, floor: 0.35).SearchAsync("belt", TestContext.Current.CancellationToken); + var cards = await Store(channel, floor: 0.35).SearchAsync("belt", null, TestContext.Current.CancellationToken); // Qdrant already applied the floor before these came back. Cutting again by a fused score // would keep one of five here, and three of five at 0.25. @@ -58,7 +58,7 @@ public async Task SearchAsync_WithOneLeg_AsksForTheNearestVectorRatherThanAFusio { var channel = new CapturingSearchChannel(Points(RankScores)); - await Store(channel, floor: 0.35).SearchAsync("belt", TestContext.Current.CancellationToken); + await Store(channel, floor: 0.35).SearchAsync("belt", null, TestContext.Current.CancellationToken); // One leg has nothing to fuse. A nearest query over the prefetch re-scores the same vector, // so a card's score is its cosine similarity and the floor and the score share a scale. @@ -70,7 +70,7 @@ public async Task SearchAsync_WithOneLegOverAnAnonymousVector_NamesNoVectorAnywh { var channel = new CapturingSearchChannel(Points(RankScores)); - await Store(channel, floor: 0.35).SearchAsync("belt", TestContext.Current.CancellationToken); + await Store(channel, floor: 0.35).SearchAsync("belt", null, TestContext.Current.CancellationToken); Assert.Null(channel.Query!.Using); Assert.Equal(string.Empty, Assert.Single(channel.Query.Prefetch).Using); @@ -81,7 +81,7 @@ public async Task SearchAsync_WithOneLegOverANamedVector_NamesItOnBothTheLegAndT { var channel = new CapturingSearchChannel(Points(RankScores)); - await Store(channel, floor: 0.35, vector: "dense").SearchAsync("belt", TestContext.Current.CancellationToken); + await Store(channel, floor: 0.35, vector: "dense").SearchAsync("belt", null, TestContext.Current.CancellationToken); Assert.Equal("dense", channel.Query!.Using); Assert.Equal("dense", Assert.Single(channel.Query.Prefetch).Using); @@ -94,7 +94,7 @@ public async Task SearchAsync_WithABlankVectorName_ReadsItAsTheAnonymousVector() // and a blank name is the same shape as no name at all. var channel = new CapturingSearchChannel(Points(RankScores)); - await Store(channel, floor: 0.35, vector: string.Empty).SearchAsync("belt", TestContext.Current.CancellationToken); + await Store(channel, floor: 0.35, vector: string.Empty).SearchAsync("belt", null, TestContext.Current.CancellationToken); Assert.Null(channel.Query!.Using); Assert.Equal(string.Empty, Assert.Single(channel.Query.Prefetch).Using); diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/StoreNamingNeutralityTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/StoreNamingNeutralityTests.cs index 1aa59703..a695c063 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/StoreNamingNeutralityTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/StoreNamingNeutralityTests.cs @@ -1,6 +1,5 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; -using AgentCore.Application.Runtime; using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; @@ -43,7 +42,7 @@ public async Task Search_ReadsEveryRoleFromThePathTheDocumentNamed() { var channel = new CapturingSearchChannel([Point()]); - var card = Assert.Single(await Store(channel).SearchAsync("anything", TestContext.Current.CancellationToken)); + var card = Assert.Single(await Store(channel).SearchAsync("anything", null, TestContext.Current.CancellationToken)); Assert.Equal("DOC-01", card.CardId); Assert.Equal("the body text", card.Text); @@ -59,11 +58,8 @@ public async Task Search_AScopeFacet_BecomesThePathTheTemplateNames() // and a store that picked one would silently match nothing against the other. var channel = new CapturingSearchChannel([Point()]); - using (KnowledgeScopeScope.Open(Scope("region", "emea"))) - { - await Store(channel, template: "{key}", scoped: true) - .SearchAsync("anything", TestContext.Current.CancellationToken); - } + await Store(channel, template: "{key}", scoped: true) + .SearchAsync("anything", Scope("region", "emea"), TestContext.Current.CancellationToken); Assert.Equal("emea", channel.DenseFilterKeywords["region"]); } @@ -72,12 +68,8 @@ await Store(channel, template: "{key}", scoped: true) public async Task Search_ANestedTemplate_BecomesADottedPath() { var channel = new CapturingSearchChannel([Point()]); - - using (KnowledgeScopeScope.Open(Scope("region", "emea"))) - { - await Store(channel, template: "attributes.{key}", scoped: true) - .SearchAsync("anything", TestContext.Current.CancellationToken); - } + await Store(channel, template: "attributes.{key}", scoped: true) + .SearchAsync("anything", Scope("region", "emea"), TestContext.Current.CancellationToken); Assert.Equal("emea", channel.DenseFilterKeywords["attributes.region"]); Assert.False(channel.DenseFilterKeywords.ContainsKey("facets.region")); @@ -89,7 +81,7 @@ public async Task Search_TheRequiredTermLeg_MatchesOnTheMappedLexicalField() var channel = new CapturingSearchChannel([Point()]); await Store(channel, analyzer: new FixedTermAnalyzer()) - .SearchAsync("the screen says e33", TestContext.Current.CancellationToken); + .SearchAsync("the screen says e33", null, TestContext.Current.CancellationToken); Assert.Equal("content", Assert.Single(channel.LexicalKeys)); } @@ -100,9 +92,8 @@ public async Task Search_NoLexicalRoleMapped_SendsOneLegAndNoTextCondition() // Unmapped means absent, not "fall back to a field called text". A store that guessed would // filter on a key this collection has no index for and drop every row. var channel = new CapturingSearchChannel([Point()]); - await Store(channel, fields: Foreign with { Lexical = null }, analyzer: new FixedTermAnalyzer()) - .SearchAsync("the screen says e33", TestContext.Current.CancellationToken); + .SearchAsync("the screen says e33", null, TestContext.Current.CancellationToken); Assert.Empty(channel.LexicalKeys); Assert.Single(channel.Query!.Prefetch); @@ -115,7 +106,7 @@ public async Task Search_NoIdRoleMapped_FallsBackToThePointKey() var channel = new CapturingSearchChannel([Point(key)]); var card = Assert.Single(await Store(channel, fields: Foreign with { Id = null }) - .SearchAsync("anything", TestContext.Current.CancellationToken)); + .SearchAsync("anything", null, TestContext.Current.CancellationToken)); Assert.Equal(key.ToString(), card.CardId); } @@ -126,7 +117,7 @@ public async Task Search_NoSourceOrLocatorMapped_LeavesBothEmptyRatherThanGuessi var channel = new CapturingSearchChannel([Point()]); var card = Assert.Single(await Store(channel, fields: Foreign with { Source = null, Locator = null }) - .SearchAsync("anything", TestContext.Current.CancellationToken)); + .SearchAsync("anything", null, TestContext.Current.CancellationToken)); Assert.Equal(string.Empty, card.SourceRef); Assert.Equal(string.Empty, card.SourceLocator); @@ -141,7 +132,7 @@ public async Task Search_ALinkFilter_ReadsTheLinkFieldAndMatchesOnTheMappedId() { Field = "related", Lookup = KnowledgeLinkLookup.Filter, - }).SearchAsync("anything", TestContext.Current.CancellationToken); + }).SearchAsync("anything", null, TestContext.Current.CancellationToken); var condition = Assert.Single(channel.ScrollFilter!.Must); Assert.Equal("doc_id", condition.Field.Key); @@ -167,7 +158,7 @@ await Store( Prefix = "doc:", }, linkNamespace: Uuid5PointId.Namespace("dns")) - .SearchAsync("anything", TestContext.Current.CancellationToken); + .SearchAsync("anything", null, TestContext.Current.CancellationToken); Assert.Equal( [Uuid5PointId.For("DOC-99", Uuid5PointId.Namespace("dns"), "doc:")], diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/WildcardScopeIntegrationTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/WildcardScopeIntegrationTests.cs index cea8c70b..5ef4dfda 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/WildcardScopeIntegrationTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/WildcardScopeIntegrationTests.cs @@ -1,6 +1,4 @@ using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime; -using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; using Qdrant.Client; @@ -136,39 +134,33 @@ public sealed class WildcardScopeIntegrationTests : IClassFixture c.CardId).Order(StringComparer.Ordinal)); - } + var cards = await Store.SearchAsync( + "belt", Scope(("brand", "*"), ("applies_to", "*")), TestContext.Current.CancellationToken); + Assert.Equal(["policy"], cards.Select(c => c.CardId).Order(StringComparer.Ordinal)); } [QdrantFact] public async Task Search_BrandOnly_AdmitsBrandWideAndRefusesTheMachineCard() { - using (KnowledgeScopeScope.Open(Scope(("brand", "sole"), ("applies_to", "*")))) - { - var cards = await Store.SearchAsync("belt", TestContext.Current.CancellationToken); - var ids = cards.Select(c => c.CardId).ToList(); + var cards = await Store.SearchAsync( + "belt", Scope(("brand", "sole"), ("applies_to", "*")), TestContext.Current.CancellationToken); + var ids = cards.Select(c => c.CardId).ToList(); - Assert.Contains("sole-care", ids); - Assert.Contains("policy", ids); - Assert.DoesNotContain("f63-belt", ids); - } + Assert.Contains("sole-care", ids); + Assert.Contains("policy", ids); + Assert.DoesNotContain("f63-belt", ids); } [QdrantFact] public async Task Search_BrandAndMachine_AdmitsAllThree() { - using (KnowledgeScopeScope.Open(Scope(("brand", "sole"), ("applies_to", "f63")))) - { - var cards = await Store.SearchAsync("belt", TestContext.Current.CancellationToken); - var ids = cards.Select(c => c.CardId).ToList(); + var cards = await Store.SearchAsync( + "belt", Scope(("brand", "sole"), ("applies_to", "f63")), TestContext.Current.CancellationToken); + var ids = cards.Select(c => c.CardId).ToList(); - Assert.Contains("f63-belt", ids); - Assert.Contains("sole-care", ids); - Assert.Contains("policy", ids); - } + Assert.Contains("f63-belt", ids); + Assert.Contains("sole-care", ids); + Assert.Contains("policy", ids); } private QdrantKnowledgeStore Store => new( diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs b/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs index 6c03298c..7dab24a0 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/ControllableMcpServer.cs @@ -1,3 +1,5 @@ +using System.Text.Json; +using System.Text.Json.Nodes; using System.IO.Pipelines; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol; @@ -34,12 +36,20 @@ private sealed record Connection(McpServer Server, Pipe ClientToServer, Pipe Ser /// Gets or sets how long a tool call takes before it answers. public TimeSpan CallDelay { get; set; } - /// /// Gets or sets whether tools/list fails, so a connection opens and then goes no further. /// public bool RefuseToList { get; set; } + /// Gets the argument names the newest call carried, in order. + public IReadOnlyList LastArgumentNames { get; private set; } = []; + + /// + /// Gets or sets the one string property every offered tool declares, or + /// for tools with no schema at all. + /// + public string? SchemaProperty { get; set; } + /// Gets the description this server gives a tool of one name. /// The tool name. /// The description. @@ -57,10 +67,15 @@ public IClientTransport NewTransport() ? throw new InvalidOperationException("this server will not say what it offers") : ValueTask.FromResult(new ListToolsResult { - Tools = [.. Offered().Select(name => new Tool + Tools = [.. Offered().Select(name => { - Name = name, - Description = DescriptionOf(name), + var tool = new Tool { Name = name, Description = DescriptionOf(name) }; + if (SchemaProperty is not null) + { + tool.InputSchema = SchemaOf(); + } + + return tool; })], }); @@ -71,6 +86,13 @@ public IClientTransport NewTransport() await Task.Delay(CallDelay, ct); } + lock (_sync) + { + LastArgumentNames = request.Params?.Arguments is { } supplied + ? [.. supplied.Keys] + : []; + } + return new CallToolResult { Content = [new TextContentBlock { Text = $"ran {request.Params?.Name}" }] }; }; @@ -89,6 +111,25 @@ public IClientTransport NewTransport() return new StreamClientTransport(clientToServer.Writer.AsStream(), serverToClient.Reader.AsStream()); } + /// Builds the schema every offered tool lists, when one was asked for. + private JsonElement SchemaOf() + { + if (SchemaProperty is null) + { + return default; + } + + JsonObject schema = new() + { + ["type"] = "object", + ["properties"] = new JsonObject + { + [SchemaProperty] = new JsonObject { ["type"] = "string" }, + }, + }; + + return JsonSerializer.SerializeToElement(schema); + } /// Stops offering one tool, without telling anybody. /// The tool to withdraw. public void Withdraw(string toolName) diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs b/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs index ae990f5e..affd0cb3 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs @@ -297,6 +297,32 @@ public async Task AToolThatHangs_IsGivenUpOn_AtTheServersOwnCallTimeout() Assert.True(watch.Elapsed < TimeSpan.FromSeconds(20), $"it waited {watch.Elapsed}."); } + // --------------------------------------------------------------------------------------------- + // Only what the server declared crosses the wire: the filed turn carries delegates. + // --------------------------------------------------------------------------------------------- + [Fact] + public async Task AnEntryTheServerNeverDeclared_NeverCrossesTheWire() + { + const string Declared = "message"; + const string Residue = "urn:agentcore:residue"; + + // Arrange + await using ControllableMcpServer fake = new("echo") { SchemaProperty = Declared }; + await using McpToolSource source = new(_ => fake.NewTransport(), null); + + var registrations = await source.ProvideAsync(ContextFor(Jira()), Token); + var tool = (AIFunction)registrations.Single(r => r.Id == "jira.echo").Materialise(); + + // Act + var result = await tool.InvokeAsync( + new AIFunctionArguments { [Declared] = "hello", [Residue] = new Action(() => { }) }, + Token); + + // Assert + Assert.False(IsError(result), "the call failed instead of reaching the server."); + Assert.Equal([Declared], fake.LastArgumentNames); + } + // --------------------------------------------------------------------------------------------- // Closing a session closes the connection under it, whatever the tools are still holding. // --------------------------------------------------------------------------------------------- diff --git a/tests/AgentCore.TestSupport/TextSearchProviderInternals.cs b/tests/AgentCore.TestSupport/TextSearchProviderInternals.cs deleted file mode 100644 index 3e483b5b..00000000 --- a/tests/AgentCore.TestSupport/TextSearchProviderInternals.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Reflection; -using Microsoft.Agents.AI; - -namespace AgentCore.TestSupport; - -/// -/// Reaches the search delegate a was built around. -/// -/// -/// The delegate is the only way to drive a bound provider uniformly across both -/// SearchTime modes: under OnDemandFunctionCalling the framework never calls it before -/// the model does, and the provider's own SearchAsync wraps the answer into a formatted -/// string rather than the raw result list a test needs to inspect. It lives behind a private field, -/// so this is reflection — verified against Microsoft.Agents.AI 1.17.0. -/// -public static class TextSearchProviderInternals -{ - /// Reads the provider's own search delegate. - /// A provider built by the knowledge factory. - /// The delegate, ready to call. - /// is . - /// is not a . - /// - /// no longer declares the private field this depends on — a newer - /// Microsoft.Agents.AI changed its internals, and this helper needs updating for the new - /// shape rather than every caller seeing a bare . - /// - public static Func>> SearchDelegate( - AIContextProvider provider) - { - ArgumentNullException.ThrowIfNull(provider); - - if (provider is not TextSearchProvider search) - { - throw new ArgumentException( - $"expected a {nameof(TextSearchProvider)}, not a {provider.GetType().Name}.", nameof(provider)); - } - - var field = typeof(TextSearchProvider).GetField("_searchAsync", BindingFlags.NonPublic | BindingFlags.Instance) - ?? throw new InvalidOperationException( - "TextSearchProvider no longer has a private field named '_searchAsync'. " - + "Microsoft.Agents.AI changed its internals; update TextSearchProviderInternals for the new shape."); - - return (Func>>) - field.GetValue(search)!; - } - - /// Runs the provider's own search delegate and collects what it returned. - /// A provider built by the knowledge factory. - /// The search text. - /// The token the delegate receives, as a caller's own would be. - /// What the delegate returned. - public static async Task> SearchAsync( - AIContextProvider provider, - string query, - CancellationToken cancellationToken = default) - => [.. await SearchDelegate(provider)(query, cancellationToken).ConfigureAwait(false)]; -} From 561618eab2de0bb77a0b6cc4fe9e33719be770bf Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 19:55:17 -0600 Subject: [PATCH 18/32] Implement graph state management and routing for guarded edges - Introduced `GraphGuardGate` to handle message routing through guarded edges, ensuring state is available before processing. - Added `GraphStateCarrier` to encapsulate state snapshots for graph runs, facilitating message construction and extraction. - Created `GraphStateEntry` to manage the lifecycle of graph state within workflows, ensuring proper state updates during execution. - Removed `CallStateScope` as it was replaced by the new graph state management approach. - Updated tests to reflect changes in state handling and ensure proper error reporting when state is missing. - Refactored `CallTurnRunner` and `CallTurnStream` to eliminate unnecessary ambient state management, simplifying the execution flow. - Enhanced `GraphStateAgent` to file state snapshots correctly at the start of graph runs, ensuring guards have access to the necessary context. --- .../Compilation/AgentCompilationContext.cs | 6 - .../Compilation/ExplicitGraphRow.cs | 58 +++---- .../Compilation/GraphGuardGate.cs | 52 ++++++ .../Compilation/GraphStateCarrier.cs | 44 +++++ .../Compilation/GraphStateEntry.cs | 39 +++++ .../PublicAPI.Unshipped.txt | 5 - .../Runtime/CallSession/CallTurnRunner.cs | 20 +-- .../Runtime/CallSession/CallTurnStream.cs | 21 +-- .../Runtime/CallStateScope.cs | 67 -------- .../Runtime/Clarifications.cs | 3 +- .../Runtime/GraphStateAgent.cs | 68 ++++++++ .../Runtime/RequireStateAgent.cs | 43 ----- .../Runtime/ScopedEnumerator.cs | 47 ------ .../Runtime/TurnInvocation.cs | 9 + .../Startup/CompilationStartup.cs | 2 - .../Compilation/GraphNoMatchTests.cs | 40 ++++- .../Compilation/GuardedGraphEdgeTests.cs | 46 ++--- .../Runtime/CallStateScopeTests.cs | 157 ------------------ .../KnowledgeScopeThroughCallSessionTests.cs | 3 +- .../Transcript/CallSessionTranscriptTests.cs | 4 +- .../DependencyInjection/AddAgentCoreTests.cs | 2 +- 21 files changed, 305 insertions(+), 431 deletions(-) create mode 100644 src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs create mode 100644 src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs delete mode 100644 src/AgentCore.Application/Runtime/CallStateScope.cs create mode 100644 src/AgentCore.Application/Runtime/GraphStateAgent.cs delete mode 100644 src/AgentCore.Application/Runtime/RequireStateAgent.cs delete mode 100644 src/AgentCore.Application/Runtime/ScopedEnumerator.cs delete mode 100644 tests/AgentCore.Application.Tests/Runtime/CallStateScopeTests.cs diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs index d22225a8..ac91f2f5 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs @@ -1,4 +1,3 @@ -using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Evaluation; using AgentCore.Application.Knowledge; @@ -49,11 +48,6 @@ public AgentCompilationContext(IChatClientFactory chatClients) /// public ICallStore? CallStore { get; init; } - /// - /// Gets or sets the source of the state a guarded graph edge reads. - /// - public Func>? StateSnapshot { get; init; } - /// /// Gets or sets the store every agent's knowledge: block reads through. /// diff --git a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs index 6c9ddd69..90beaccf 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs @@ -1,4 +1,3 @@ -using System.Text.Json.Nodes; using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Runtime; @@ -70,8 +69,12 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( $"the graph declares {starts.Count} start nodes. Check 7 of section 8.5 needs exactly one."); } - WorkflowBuilder builder = new(nodes[starts[0].Id]); - Func>? guardedState = null; + var entry = ExecutorBindingExtensions.BindExecutor(new GraphStateEntry()); + + WorkflowBuilder builder = new(entry); + builder = builder.AddEdge(entry, nodes[starts[0].Id]); + + var guarded = false; for (var index = 0; index < graph.Edges.Count; index++) { @@ -98,24 +101,32 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( continue; } - if (context.Guards is not { } evaluator || context.StateSnapshot is not { } snapshot) + if (context.Guards is not { } evaluator) { throw ConfigurationCompiler.Fail( ConfigurationError.AppendPointer(pointer, "when"), - $"the edge carries a guard, and the compilation context binds {Missing(context)}. Bind " - + "both: AgentCompilationContext.Guards runs the rule, and " - + "AgentCompilationContext.StateSnapshot reads the state of the call that runs now. " - + "AddAgentCore binds them to GuardEvaluator and to CallStateScope.Snapshot. A guarded " - + "edge that silently became unconditional is exactly the silent graph failure " - + "section 8.2 refuses to ship."); + "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."); } - - // The predicate captures no state of its own. The compiled graph is a process singleton - // under T44, so it asks the context for the state of the call that runs now. 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. - builder = builder.AddEdge(from, to, _ => evaluator.Evaluate(guard, snapshot())); - guardedState = snapshot; + // 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); + + builder = builder.AddEdge(from, gate); + builder = builder.AddEdge(gate, to); + guarded = true; } if (outputs.Count > 0) @@ -128,8 +139,9 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( .AsAIAgent(name: configuration.Name); AIAgent withOutputCheck = new RequireOutputAgent(compiled, configuration.Name); + return ( - guardedState is null ? withOutputCheck : new RequireStateAgent(withOutputCheck, guardedState), + guarded ? new GraphStateAgent(withOutputCheck, configuration.Name) : withOutputCheck, NoStages()); } @@ -147,14 +159,4 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry( return outputs.Count == 0 ? null : outputs; } - - /// Names the seams a guarded edge needs and the context left unbound. - /// The seams the document names. - /// The phrase the failure message carries. - private static string Missing(AgentCompilationContext context) => (context.Guards, context.StateSnapshot) switch - { - (null, null) => "no guard evaluator and no state source", - (null, _) => "no guard evaluator", - _ => "no state source", - }; } diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs b/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs new file mode 100644 index 00000000..f3b60a04 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs @@ -0,0 +1,52 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Configuration.Validation; +using Microsoft.Agents.AI.Workflows; + +namespace AgentCore.Application.Configuration.Compilation; + +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, " + + "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."; + + /// Forwards one edge message past a guarded edge, or holds it when the guard is false. + /// The message that reached the edge, forwarded unchanged. + /// The run the edge belongs to, carrying the filed snapshot. + /// The edge's when: guard. + /// The shared evaluator that runs the rule. + /// Cancels the read. + /// The run carries no state. + internal static async ValueTask RouteAsync( + object? message, + IWorkflowContext context, + GuardReference guard, + IGuardEvaluator evaluator, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(guard); + ArgumentNullException.ThrowIfNull(evaluator); + + var snapshot = await context + .ReadStateAsync>( + GraphStateEntry.SlotsKey, GraphStateEntry.StateScope, cancellationToken) + .ConfigureAwait(false); + + if (snapshot is null) + { + throw new InvalidOperationException(NoStateMessage); + } + + if (evaluator.Evaluate(guard, snapshot)) + { + await context.SendMessageAsync(message!, cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs b/src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs new file mode 100644 index 00000000..72dc7fd8 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs @@ -0,0 +1,44 @@ +using System.Text.Json.Nodes; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +internal static class GraphStateCarrier +{ + /// The message key the snapshot rides under. + internal const string ArgumentsKey = "urn:agentcore:graph-state"; + + /// Builds the carrier heading one run's request messages. + /// Every declared slot and the three reserved slots, read at run start. + /// A content-free message only the graph-state entry reads. + internal static ChatMessage Build(IReadOnlyDictionary snapshot) + { + ArgumentNullException.ThrowIfNull(snapshot); + + return new ChatMessage(ChatRole.System, string.Empty) + { + AdditionalProperties = new AdditionalPropertiesDictionary { [ArgumentsKey] = snapshot }, + }; + } + + /// Takes the snapshot off the head of one run's request, when it carries one. + /// The run's accumulated messages, oldest first. + /// The snapshot, without the carrier around it. + /// Whether a carrier headed the messages. The carrier is removed either way it answers. + internal static bool TryTake(List messages, out IReadOnlyDictionary? snapshot) + { + ArgumentNullException.ThrowIfNull(messages); + + snapshot = null; + if (messages.Count == 0 + || messages[0].AdditionalProperties?.TryGetValue(ArgumentsKey, out var filed) != true + || filed is not IReadOnlyDictionary carried) + { + return false; + } + + messages.RemoveAt(0); + snapshot = carried; + return true; + } +} diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs b/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs new file mode 100644 index 00000000..4dc1e0fd --- /dev/null +++ b/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs @@ -0,0 +1,39 @@ +using Microsoft.Agents.AI.Workflows; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Configuration.Compilation; + +internal sealed class GraphStateEntry : ChatProtocolExecutor +{ + /// The workflow scope the snapshot is filed under. Named, because the default + /// scope belongs to each executor alone and a gate would read its own empty one. + internal const string StateScope = "graph-state"; + + /// The workflow state key the snapshot is filed under. + internal const string SlotsKey = "slots"; + + /// Creates the entry of one compiled graph. + internal GraphStateEntry() + : base("agentcore-graph-entry", new ChatProtocolExecutorOptions { AutoSendTurnToken = true }, true) + { + } + + /// + protected override async ValueTask TakeTurnAsync( + List messages, + IWorkflowContext context, + bool? emitEvents, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(messages); + ArgumentNullException.ThrowIfNull(context); + + if (GraphStateCarrier.TryTake(messages, out var snapshot) && snapshot is not null) + { + await context.QueueStateUpdateAsync(SlotsKey, snapshot, StateScope, cancellationToken) + .ConfigureAwait(false); + } + + await context.SendMessageAsync(messages, cancellationToken: cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 6fdff2d0..bfdb6202 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -163,8 +163,6 @@ AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Moderati AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Moderation.init -> void AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Skills.get -> AgentCore.Application.Skills.SkillCatalog? AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Skills.init -> void -AgentCore.Application.Configuration.Compilation.AgentCompilationContext.StateSnapshot.get -> System.Func!>? -AgentCore.Application.Configuration.Compilation.AgentCompilationContext.StateSnapshot.init -> void AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Tools.get -> AgentCore.Application.Tools.Registry.ToolRegistry? AgentCore.Application.Configuration.Compilation.AgentCompilationContext.Tools.init -> void AgentCore.Application.Configuration.Compilation.AgentCompilationContext.WorkspaceRoot.get -> string? @@ -1243,7 +1241,6 @@ 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.CallStateScope AgentCore.Application.Runtime.CallTurnOrigin AgentCore.Application.Runtime.CallTurnOrigin.$() -> AgentCore.Application.Runtime.CallTurnOrigin! AgentCore.Application.Runtime.CallTurnOrigin.CallTurnOrigin(string? MessageId, string? ParentMessageId) -> void @@ -1985,8 +1982,6 @@ static AgentCore.Application.Runtime.CallEvent.operator !=(AgentCore.Application 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.CallStateScope.Enter(AgentCore.Application.State.StateDocument! state) -> System.IDisposable! -static AgentCore.Application.Runtime.CallStateScope.Snapshot() -> System.Collections.Generic.IReadOnlyDictionary! 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.Secrets.ResolvedSecrets.Create(System.Collections.Generic.IEnumerable>! secrets) -> AgentCore.Application.Secrets.ResolvedSecrets! diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs index 0d9fb78d..598f2f6e 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs @@ -63,12 +63,10 @@ internal async Task RunTurnCoreAsync( try { - using var ambients = EnterAmbients(turn); - // The turn travels on the run's own options from here to the invoking client, one - // value per turn, and in the session-keyed registry from here to the providers — - // keyed by the session the run actually gets, which a graph row re-creates per turn. var invocation = TurnInvocationOf(turn); + var runSession = await RunSessionAsync(turn, cancellation.Token).ConfigureAwait(false); + TurnRegistry.Set(runSession, invocation); AgentResponse response; @@ -137,9 +135,9 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur try { // After both guards: a turn refused as terminal or already-running must not drop the - // probe latch out from under the turn actually in flight. Runs exactly once here, and - // never in EnterAmbients, which reopens per streaming step and would drop the latch - // several times inside one streaming turn. + // probe latch out from under the turn actually in flight. Runs exactly once here, in + // BeginTurn, and never per streaming step, which would drop the latch several times + // inside one streaming turn. _session.Clarifications.BeginTurn(); // Behind both guards, because the withdrawal deletes: a turn refused for a terminal call or @@ -280,13 +278,6 @@ internal async ValueTask RunSessionAsync(CallTurn turn, Cancellati return await turn.Agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); } - /// - /// Opens the state scope this turn runs under, so guarded graph edges read this call. - /// - /// The turn about to run. - /// The scope. Disposing it closes the state scope. - internal IDisposable EnterAmbients(CallTurn turn) => CallStateScope.Enter(_session.State); - /// 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. @@ -309,5 +300,6 @@ internal TurnInvocation TurnInvocationOf(CallTurn turn) OnToolFailure = failure => _session.Events.RaiseToolFailure(turn.Index, failure), Tools = _delegatedTools?.Tools, ToolsFor = _delegatedTools?.ToolId, + State = _session.State, }; } diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs index 42f53653..87f815e9 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs @@ -39,23 +39,18 @@ internal async IAsyncEnumerable RunTurnStreamingCoreAsync( List updates = []; string? toolFault = null; - // This scope covers opening the run's session and building the stream, and reaches no - // round: an async iterator restores its caller's execution context at every yield. - using var opening = _session.Runner.EnterAmbients(turn); - var invocation = _session.Runner.TurnInvocationOf(turn); var runSession = await _session.Runner.RunSessionAsync(turn, cancellation.Token).ConfigureAwait(false); + TurnRegistry.Set(runSession, invocation); - var stream = ScopedEnumerator.Over( - turn.Agent - .RunStreamingAsync( - turn.Request, - runSession, - invocation.RunOptions(), - cancellationToken: cancellation.Token) - .GetAsyncEnumerator(cancellation.Token), - () => _session.Runner.EnterAmbients(turn)); + var stream = turn.Agent + .RunStreamingAsync( + turn.Request, + runSession, + invocation.RunOptions(), + cancellationToken: cancellation.Token) + .GetAsyncEnumerator(cancellation.Token); try { diff --git a/src/AgentCore.Application/Runtime/CallStateScope.cs b/src/AgentCore.Application/Runtime/CallStateScope.cs deleted file mode 100644 index 0f5c5d17..00000000 --- a/src/AgentCore.Application/Runtime/CallStateScope.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Text.Json.Nodes; -using AgentCore.Application.State; - -namespace AgentCore.Application.Runtime; - -/// -/// The state of the call that runs on this flow of execution. An explicit open/close seam with -/// its own carrier: the loop opens the turn's document around every run, and a sessionless -/// graph opens its own around the run instead. Nothing reads the turn through this except the -/// guarded edges it was made for. -/// -public static class CallStateScope -{ - private static readonly AsyncLocal Flow = new(); - - /// The message throws with when no scope is open. - internal const string NoScopeMessage = - "A guarded graph edge asked for the state of the running call, and no call scope is open on " - + "this flow of execution. Row 4 of the section 8.2 compile table reads the state of one call, " - + "and CallSession opens that scope for the turn. Run the graph through a CallSession, or open " - + "the scope with CallStateScope.Enter around the run. 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."; - - /// Opens the scope of one call over this flow of execution. - /// The state of the call that runs now. - /// The scope. Disposing it puts back the state that was open before. - /// is . - public static IDisposable Enter(StateDocument state) - { - ArgumentNullException.ThrowIfNull(state); - - var previous = Flow.Value; - Flow.Value = state; - return new Scope(previous); - } - - /// Takes the snapshot a guarded graph edge reads. - /// Every declared slot and the three reserved slots, for the call that runs now. - /// - /// No scope is open on this flow of execution. The message names the fault and says what opens a - /// scope. - /// - public static IReadOnlyDictionary Snapshot() - => (Flow.Value ?? throw new InvalidOperationException(NoScopeMessage)).Snapshot(); - - /// One open scope. Disposing it puts back what was open before. - private sealed class Scope : IDisposable - { - private readonly StateDocument? _previous; - - private bool _closed; - - public Scope(StateDocument? previous) => _previous = previous; - - public void Dispose() - { - if (_closed) - { - return; - } - - _closed = true; - Flow.Value = _previous; - } - } -} diff --git a/src/AgentCore.Application/Runtime/Clarifications.cs b/src/AgentCore.Application/Runtime/Clarifications.cs index 16c4bac3..a5ef1e06 100644 --- a/src/AgentCore.Application/Runtime/Clarifications.cs +++ b/src/AgentCore.Application/Runtime/Clarifications.cs @@ -91,8 +91,7 @@ internal Probe ClaimProbe() /// probe rather than the turn before it. /// /// - /// Must run exactly once per turn, from CallSession.BeginTurn and nowhere else. - /// CallSession.EnterAmbients reopens its state scope once per streaming step. + /// Must run exactly once per turn, from CallTurnRunner.BeginTurn and nowhere else. /// internal void BeginTurn() { diff --git a/src/AgentCore.Application/Runtime/GraphStateAgent.cs b/src/AgentCore.Application/Runtime/GraphStateAgent.cs new file mode 100644 index 00000000..5ede5e22 --- /dev/null +++ b/src/AgentCore.Application/Runtime/GraphStateAgent.cs @@ -0,0 +1,68 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Runtime.Turn; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Runtime; + +/// +/// Files the turn's state snapshot at the head of a guarded row 4 graph run, where the +/// graph-state entry strips it into workflow-scoped state for the guard gates. +/// +internal sealed class GraphStateAgent : DelegatingAIAgent +{ + private readonly string _name; + + /// Puts the state filing in front of one guarded graph. + /// The workflow of row 4, already wrapped by AsAIAgent(). + /// The name of the document, which the failure reports. + public GraphStateAgent(AIAgent inner, string name) + : base(inner) + { + ArgumentNullException.ThrowIfNull(name); + _name = name; + } + + /// + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + { + return base.RunCoreAsync(Filed(messages, session, options), session, options, cancellationToken); + } + + /// + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + { + return base.RunCoreStreamingAsync(Filed(messages, session, options), session, options, cancellationToken); + } + + private List Filed(IEnumerable messages, AgentSession? session, AgentRunOptions? options) + { + ArgumentNullException.ThrowIfNull(messages); + + var invocation = TurnRegistry.For(session) ?? FromOptions(options); + var snapshot = invocation?.State?.Snapshot(); + + if (snapshot is null) + { + throw new InvalidOperationException( + $"The graph '{_name}' runs a guarded edge with no state filed on the run. " + + GraphGuardGate.NoStateMessage); + } + + 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/RequireStateAgent.cs b/src/AgentCore.Application/Runtime/RequireStateAgent.cs deleted file mode 100644 index 02870a75..00000000 --- a/src/AgentCore.Application/Runtime/RequireStateAgent.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Text.Json.Nodes; -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Runtime; - -/// -/// Fails a guarded row 4 graph before it starts when the state its edges read is not there. -/// -internal sealed class RequireStateAgent : DelegatingAIAgent -{ - private readonly Func> _state; - - /// Puts the state pre-check in front of one guarded graph. - public RequireStateAgent(AIAgent inner, Func> state) - : base(inner) - { - ArgumentNullException.ThrowIfNull(state); - _state = state; - } - - /// - protected override Task RunCoreAsync( - IEnumerable messages, - AgentSession? session, - AgentRunOptions? options = null, - CancellationToken cancellationToken = default) - { - _ = _state(); - return base.RunCoreAsync(messages, session, options, cancellationToken); - } - - /// - protected override IAsyncEnumerable RunCoreStreamingAsync( - IEnumerable messages, - AgentSession? session, - AgentRunOptions? options = null, - CancellationToken cancellationToken = default) - { - _ = _state(); - return base.RunCoreStreamingAsync(messages, session, options, cancellationToken); - } -} diff --git a/src/AgentCore.Application/Runtime/ScopedEnumerator.cs b/src/AgentCore.Application/Runtime/ScopedEnumerator.cs deleted file mode 100644 index 2006da02..00000000 --- a/src/AgentCore.Application/Runtime/ScopedEnumerator.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace AgentCore.Application.Runtime; - -/// -/// An enumerator that opens a scope again for every step it takes. -/// -internal static class ScopedEnumerator -{ - /// Wraps one enumerator so each step runs under a freshly opened scope. - /// What the enumerator yields. - /// The enumerator to step. - /// - /// Opens the scope. It is called once per step, and the scope is closed when that step ends. - /// - /// The wrapped enumerator. Disposing it disposes . - /// An argument is . - internal static IAsyncEnumerator Over(IAsyncEnumerator inner, Func enter) - { - ArgumentNullException.ThrowIfNull(inner); - ArgumentNullException.ThrowIfNull(enter); - - return new Stepwise(inner, enter); - } - - private sealed class Stepwise : IAsyncEnumerator - { - private readonly IAsyncEnumerator _inner; - - private readonly Func _enter; - - public Stepwise(IAsyncEnumerator inner, Func enter) - { - _inner = inner; - _enter = enter; - } - - public T Current => _inner.Current; - - public async ValueTask MoveNextAsync() - { - using var scope = _enter(); - - return await _inner.MoveNextAsync().ConfigureAwait(false); - } - - public ValueTask DisposeAsync() => _inner.DisposeAsync(); - } -} diff --git a/src/AgentCore.Application/Runtime/TurnInvocation.cs b/src/AgentCore.Application/Runtime/TurnInvocation.cs index 3431cd8a..c77d2752 100644 --- a/src/AgentCore.Application/Runtime/TurnInvocation.cs +++ b/src/AgentCore.Application/Runtime/TurnInvocation.cs @@ -1,6 +1,7 @@ using AgentCore.Application.Ports; using AgentCore.Application.Runtime.Harness; using AgentCore.Application.Runtime.Turn; +using AgentCore.Application.State; using AgentCore.Domain.Knowledge; using Microsoft.Extensions.AI; using Microsoft.Agents.AI; @@ -72,6 +73,14 @@ internal sealed record TurnInvocation /// Gets whether this turn runs nested inside another tool call. A nested turn neither latches the holder nor records. public bool Nested { get; init; } + /// + /// Gets the live state document of the call 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. + /// + public StateDocument? State { get; init; } + /// Builds the per-run options carrying this turn to the invoking client. internal ChatClientAgentRunOptions RunOptions() { diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs index 95515094..bec59c12 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CompilationStartup.cs @@ -5,7 +5,6 @@ using AgentCore.Application.Evaluation; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; -using AgentCore.Application.Runtime; using AgentCore.Application.Skills; using AgentCore.Application.Tools.Registry; using Microsoft.Extensions.Logging; @@ -65,7 +64,6 @@ internal static ValueTask CompileAsync( Guards = guards, Moderation = PromptModerator.FromRegistry(evaluators), CallStore = calls, - StateSnapshot = CallStateScope.Snapshot, Knowledge = knowledge, Skills = skills, Citations = citations, diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs index ce35c3a1..dc68b28f 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/GraphNoMatchTests.cs @@ -6,6 +6,7 @@ using AgentCore.Application.Runtime; using AgentCore.Application.State; using AgentCore.Application.Tests.Fakes; +using Microsoft.Agents.AI; using Microsoft.Extensions.AI; using Xunit; @@ -67,10 +68,10 @@ public sealed class GraphNoMatchTests public async Task Row4_AGraphWhereNoEdgeGuardIsTrue_ThrowsInsteadOfAnsweringNothing() { using Harness harness = new(); - using var scope = CallStateScope.Enter(harness.NewState(escalate: false)); var failure = await Record.ExceptionAsync(() => harness.Compiled.Agent.RunAsync( - "hello", cancellationToken: TestContext.Current.CancellationToken)); + "hello", null, harness.StateOptions(escalate: false), + cancellationToken: TestContext.Current.CancellationToken)); Assert.IsType(failure); Assert.Contains("no-match-graph", failure.Message, StringComparison.Ordinal); @@ -81,14 +82,14 @@ public async Task Row4_AGraphWhereNoEdgeGuardIsTrue_ThrowsInsteadOfAnsweringNoth public async Task Row4_AGraphWhereNoEdgeGuardIsTrue_ThrowsWhileStreamingToo() { using Harness harness = new(); - using var scope = CallStateScope.Enter(harness.NewState(escalate: false)); // The streaming path hands the updates over one at a time, so the check reads them as they // pass and throws after the last one. A caller that enumerates to the end sees the fault. var failure = await Record.ExceptionAsync(async () => { await foreach (var update in harness.Compiled.Agent.RunStreamingAsync( - "hello", cancellationToken: TestContext.Current.CancellationToken)) + "hello", null, harness.StateOptions(escalate: false), + cancellationToken: TestContext.Current.CancellationToken)) { _ = update; } @@ -102,10 +103,10 @@ public async Task Row4_AGraphWhereNoEdgeGuardIsTrue_ThrowsWhileStreamingToo() public async Task Row4_AGraphWhereAnEdgeGuardIsTrue_StillAnswers() { using Harness harness = new(); - using var scope = CallStateScope.Enter(harness.NewState(escalate: true)); var reply = await harness.Compiled.Agent.RunAsync( - "hello", cancellationToken: TestContext.Current.CancellationToken); + "hello", null, harness.StateOptions(escalate: true), + cancellationToken: TestContext.Current.CancellationToken); // The check sits in front of nothing. A run that produced text is the run it always was. Assert.Contains(EscalatedReply, reply.Text, StringComparison.Ordinal); @@ -115,11 +116,11 @@ public async Task Row4_AGraphWhereAnEdgeGuardIsTrue_StillAnswers() public async Task Row4_AGraphWhereAnEdgeGuardIsTrue_StillStreams() { using Harness harness = new(); - using var scope = CallStateScope.Enter(harness.NewState(escalate: true)); List text = []; await foreach (var update in harness.Compiled.Agent.RunStreamingAsync( - "hello", cancellationToken: TestContext.Current.CancellationToken)) + "hello", null, harness.StateOptions(escalate: true), + cancellationToken: TestContext.Current.CancellationToken)) { text.Add(update.Text); } @@ -191,7 +192,6 @@ public Harness() new AgentCompilationContext(models) { Guards = guards, - StateSnapshot = CallStateScope.Snapshot, }); _sessions = new CallSessionFactory(Compiled, guards); @@ -210,6 +210,28 @@ 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. + /// 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", + TurnIndex = 0, + Stage = string.Empty, + State = NewState(escalate), + }; + + return new ChatClientAgentRunOptions(new ChatOptions + { + AdditionalProperties = new AdditionalPropertiesDictionary + { + [TurnInvocation.ArgumentsKey] = invocation, + }, + }); + } + /// Builds the session of one more call. /// The session. public CallSession NewSession() => _sessions.Create(); diff --git a/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs b/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs index a5149080..4574490e 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Compilation/GuardedGraphEdgeTests.cs @@ -17,8 +17,9 @@ 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. is the seam that -/// holds both: the predicate captures nothing and asks the flow of execution instead. +/// call, and each call 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. /// /// /// Every test here runs offline. There is no network call and no API key in this file. @@ -123,8 +124,8 @@ public async Task AGuardedEdge_TakesTheEdgeTheStateNamesWhileStreaming() text.Add(update.Text); } - // An async iterator restores the execution context of its caller at every yield. The turn - // loop therefore opens the scope once for each round, and this asserts that it does. + // The turn's snapshot rides the run's own messages, so the streaming path needs no + // per-step scope to route: the gate reads what the entry filed before the first model call. Assert.Contains(EscalatedReply, string.Concat(text), StringComparison.Ordinal); Assert.DoesNotContain(HandledReply, string.Concat(text), StringComparison.Ordinal); } @@ -165,18 +166,18 @@ public async Task Rule16_TwentySixSimultaneousCalls_EachTakeTheirOwnEdgeThroughO } [Fact] - public async Task AGuardedEdgeWithNoAmbientState_FailsLoudlyAndNeverAnswersFalse() + public async Task AGuardedEdgeWithNoFiledState_FailsLoudlyAndNeverAnswersFalse() { using Harness harness = new(); - // The run goes straight at the shared graph, with no call scope anywhere. A guarded edge that - // quietly became unconditional is the silent graph failure section 8.2 refuses to ship, so - // the predicate throws instead. + // The run goes straight at the shared graph, with no turn filed on it anywhere. A guarded + // edge that quietly became unconditional is the silent graph failure section 8.2 refuses + // to ship, so the wrapper throws instead. var failure = await Record.ExceptionAsync(() => harness.Compiled.Agent.RunAsync( "hello", cancellationToken: TestContext.Current.CancellationToken)); Assert.NotNull(failure); - Assert.Contains(CallStateScope.NoScopeMessage, Flatten(failure), StringComparison.Ordinal); + Assert.Contains(GraphGuardGate.NoStateMessage, Flatten(failure), StringComparison.Ordinal); } [Fact] @@ -225,32 +226,12 @@ public async Task Rule13_AGuardedGraph_YieldsItsFirstDeltaBeforeTheModelFinishes Assert.Equal("ESCALATED", first); } - [Fact] - public void AGuardedEdgeWithNoStateSource_IsALoadTimeErrorThatNamesTheMissingSeam() - { - var document = ConfigurationLoader.LoadYaml(GuardedGraphYaml); - using ScriptedChatClient client = new("ok"); - AgentCompilationContext context = new(new FakeChatClientFactory(client)) - { - Guards = new GuardEvaluator(document.Guards), - }; - - var failure = Assert.Throws( - () => ConfigurationCompiler.Compile(document, context)); - - Assert.Equal("/graph/edges/0/when", failure.Pointer); - Assert.Contains("binds no state source", failure.Message, StringComparison.Ordinal); - } - [Fact] public void AGuardedEdgeWithNoEvaluator_IsALoadTimeErrorThatNamesTheMissingSeam() { var document = ConfigurationLoader.LoadYaml(GuardedGraphYaml); using ScriptedChatClient client = new("ok"); - AgentCompilationContext context = new(new FakeChatClientFactory(client)) - { - StateSnapshot = CallStateScope.Snapshot, - }; + AgentCompilationContext context = new(new FakeChatClientFactory(client)); var failure = Assert.Throws( () => ConfigurationCompiler.Compile(document, context)); @@ -281,8 +262,8 @@ private static string Flatten(Exception exception) /// One compiled graph, wired the way the composition root wires it. /// /// - /// The seams are the two AddAgentCore binds: the shared guard evaluator, and - /// as the state source. Nothing per call is captured. + /// The seam is the one AddAgentCore bind: the shared guard evaluator. Nothing per call + /// is captured: the turn's snapshot rides each run. /// private sealed class Harness : IDisposable { @@ -317,7 +298,6 @@ public Harness(bool holdEscalatedReply = false) new AgentCompilationContext(models) { Guards = guards, - StateSnapshot = CallStateScope.Snapshot, }); _sessions = new CallSessionFactory(Compiled, guards); diff --git a/tests/AgentCore.Application.Tests/Runtime/CallStateScopeTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallStateScopeTests.cs deleted file mode 100644 index 9e555694..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/CallStateScopeTests.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System.Text.Json.Nodes; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime; -using AgentCore.Application.State; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -/// -/// The seam that carries the state of one call into the graph every call shares. -/// -/// -/// T44 makes the compiled agent a process singleton, so row 4 of the section 8.2 compile table cannot -/// capture the state of one call. It finds the state on the flow of execution instead, and these tests -/// fix what that means: one flow reads one call, a flow that carries none fails loudly, and the scope -/// closes on every exit. -/// -public sealed class CallStateScopeTests -{ - private const string Yaml = - """ - apiVersion: agentcore/v1 - name: scoped - state: - escalate: { type: boolean, writer: extractor, default: false } - agents: - items: - - { id: only } - """; - - [Fact] - public void AnOpenScope_AnswersTheStateOfTheCall() - { - var state = NewState(escalate: true); - - using (CallStateScope.Enter(state)) - { - var snapshot = CallStateScope.Snapshot(); - - Assert.True(snapshot["escalate"]!.GetValue()); - Assert.Equal(0, snapshot[ReservedStateSlots.TurnIndex]!.GetValue()); - } - } - - [Fact] - public void NoScopeAtAll_ThrowsAndDoesNotAnswerFalse() - { - // Section 8.2 refuses the silent graph failure. A guarded edge that quietly became - // unconditional is that failure, so the source throws rather than answering an empty state. - var failure = Assert.Throws(CallStateScope.Snapshot); - - Assert.Equal(CallStateScope.NoScopeMessage, failure.Message); - } - - [Fact] - public void AClosedScope_LeavesNothingBehind() - { - using (CallStateScope.Enter(NewState(escalate: true))) - { - _ = CallStateScope.Snapshot(); - } - - Assert.Throws(CallStateScope.Snapshot); - } - - [Fact] - public void AScopeThatThrows_StillCloses() - { - Action turnThatThrows = () => - { - using (CallStateScope.Enter(NewState(escalate: true))) - { - throw new OperationCanceledException(); - } - }; - - Assert.Throws(turnThatThrows); - - Assert.Throws(CallStateScope.Snapshot); - } - - [Fact] - public void AnInnerScope_PutsTheOuterOneBack() - { - using (CallStateScope.Enter(NewState(escalate: false))) - { - using (CallStateScope.Enter(NewState(escalate: true))) - { - Assert.True(CallStateScope.Snapshot()["escalate"]!.GetValue()); - } - - Assert.False(CallStateScope.Snapshot()["escalate"]!.GetValue()); - } - } - - [Fact] - public void ASecondDispose_ChangesNothing() - { - var outer = CallStateScope.Enter(NewState(escalate: false)); - var inner = CallStateScope.Enter(NewState(escalate: true)); - - inner.Dispose(); - inner.Dispose(); - - // The second dispose must not put the older state back over the scope that now holds. - Assert.False(CallStateScope.Snapshot()["escalate"]!.GetValue()); - outer.Dispose(); - } - - [Fact] - public async Task TheScopeFollowsTheFlowOfExecutionAndNotTheThread() - { - using (CallStateScope.Enter(NewState(escalate: true))) - { - // The continuation lands on a thread pool thread, and it still reads this call. - await Task.Yield(); - - Assert.True(CallStateScope.Snapshot()["escalate"]!.GetValue()); - } - } - - [Fact] - public async Task TwentySixFlowsAtOnce_EachReadTheirOwnCall() - { - const int FanOut = 26; - var token = TestContext.Current.CancellationToken; - using Barrier gate = new(FanOut); - - var flows = Enumerable.Range(0, FanOut).Select(index => Task.Run( - async () => - { - var escalate = index % 2 == 0; - using (CallStateScope.Enter(NewState(escalate))) - { - gate.SignalAndWait(token); - await Task.Yield(); - return (Expected: escalate, Read: CallStateScope.Snapshot()["escalate"]!.GetValue()); - } - }, - token)); - - var results = await Task.WhenAll(flows); - - Assert.All(results, result => Assert.Equal(result.Expected, result.Read)); - } - - /// Builds the state of one call, with the one declared slot already filled. - /// The value the slot holds. - /// The state. - private static StateDocument NewState(bool escalate) - { - StateDocument state = new(ConfigurationLoader.LoadYaml(Yaml)); - state.TryWrite("escalate", JsonValue.Create(escalate)); - return state; - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs index e91b862a..bec0d8a1 100644 --- a/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/KnowledgeScopeThroughCallSessionTests.cs @@ -108,8 +108,7 @@ public async Task RunTurnAsync_UnderAHostScope_TheStoreStillSeesThatScope() [Fact] public async Task RunTurnStreamingAsync_UnderAHostScope_TheStoreStillSeesThatScope() { - // The streaming path enters the ambients a second time, once per step, through - // ScopedEnumerator. That re-entry drops whatever the first entry dropped, so it needs its own + // The streaming path runs the same turn through a second enumeration, so it needs its own // fact rather than an argument from the non-streaming one. using SequencedChatClient reply = new("hello there."); var port = new StubKnowledgePort([Card("a")]); diff --git a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs index ce58a2b0..42b4cdc0 100644 --- a/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs +++ b/tests/AgentCore.Application.Tests/Transcript/CallSessionTranscriptTests.cs @@ -158,8 +158,8 @@ public async Task InterruptAfterTheTurnEnded_ToolTurnThatDrew_LeavesTheRenderCon /// Drives a real turn end to end through , with a screen bound and a /// real tool that draws 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 - /// and the turn's renders — this is the one test that - /// goes through that wire itself. + /// the turn's invocation and its renders — this is the one test that goes through that wire + /// itself. /// [Fact] public async Task ATurnThatDrawsWithAScreenBound_StoresTheRenderContentOnTheToolResultRow() diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index 4eca6775..c8917e7e 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -775,7 +775,7 @@ public async Task AGuardedGraph_Starts() var compiled = provider.GetRequiredService(); // The document passes all eight checks and now compiles too. AddAgentCore binds the guard - // evaluator and CallStateScope, so a guarded edge is reachable from here. + // evaluator, so a guarded edge is reachable from here. Assert.Equal(CompiledAgentShape.ExplicitGraph, compiled.Shape); Assert.Equal("guarded-composed", compiled.Name); } From b4d0a1603a0f473458c5c51b0b0691366be6a93f Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 20:14:07 -0600 Subject: [PATCH 19/32] chore: Update .gitignore to include .sonarqube and remove sonar-project.properties --- .gitignore | 1 + sonar-project.properties | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 sonar-project.properties diff --git a/.gitignore b/.gitignore index 081de50f..0306a2f8 100644 --- a/.gitignore +++ b/.gitignore @@ -512,3 +512,4 @@ docs/ demo/AgentCore.Demo/config/local.yaml .serena +.sonarqube \ No newline at end of file diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index 1d3a723d..00000000 --- a/sonar-project.properties +++ /dev/null @@ -1 +0,0 @@ -sonar.projectKey=agentcore From 8878f72e381d0ace2c24ac629f7b56c67aa4ab93 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 21:48:44 -0600 Subject: [PATCH 20/32] fix: Update regex instantiation to include timeout and suppress security warnings for validation and identifier generation --- demo/chat-ui/src/Widget.tsx | 13 ++++++++++--- demo/chat-ui/src/components/ui/sidebar.tsx | 4 ++-- .../Compilation/AgentHarnessProviders.cs | 2 +- .../Configuration/Validation/StateDomain.cs | 4 ++++ .../Knowledge/VectorData/Qdrant/Uuid5PointId.cs | 4 ++++ 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/demo/chat-ui/src/Widget.tsx b/demo/chat-ui/src/Widget.tsx index 36844e66..3cf8bec9 100644 --- a/demo/chat-ui/src/Widget.tsx +++ b/demo/chat-ui/src/Widget.tsx @@ -44,15 +44,22 @@ type Phase = "closed" | "teaser" | "open"; * posts what it needs and `embed.js` applies it. Without this the frame would be stuck at whatever * size it was created with, and either clip the open panel or leave a 400px invisible rectangle * over the host page swallowing clicks while the bubble is closed. + * + * The message goes to the embedding page named by document.referrer. Hosts that suppress + * referrers get "*" instead; the payload is two numbers, and embed.js checks origin and shape. */ function useFrameSize(phase: Phase) { useEffect(() => { const size = SIZE[phase]; - // "*" rather than a fixed origin: the widget is embedded on sites it cannot know the names of, - // and the message carries no secret — only two numbers. + let target = "*"; + try { + if (document.referrer) target = new URL(document.referrer).origin; + } catch { + target = "*"; + } window.parent?.postMessage( { source: "agentcore-widget", type: "resize", ...size }, - "*", + target, ); }, [phase]); } diff --git a/demo/chat-ui/src/components/ui/sidebar.tsx b/demo/chat-ui/src/components/ui/sidebar.tsx index 35ec0ca6..d1a09569 100644 --- a/demo/chat-ui/src/components/ui/sidebar.tsx +++ b/demo/chat-ui/src/components/ui/sidebar.tsx @@ -604,9 +604,9 @@ function SidebarMenuSkeleton({ }: React.ComponentProps<"div"> & { showIcon?: boolean }) { - // Random width between 50 to 90%. + // Skeleton shimmer width, cosmetic only: feeds no decision, so S2245 does not apply. const width = React.useMemo(() => { - return `${Math.floor(Math.random() * 40) + 50}%` + return `${Math.floor(Math.random() * 40) + 50}%`; // NOSONAR }, []) return ( diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs index c1c3649e..a7563f25 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs @@ -384,7 +384,7 @@ private static bool IsValidRegex(string pattern) { try { - _ = new Regex(pattern); + _ = new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); return true; } catch (ArgumentException) diff --git a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs index f7f879c3..016ef27b 100644 --- a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs +++ b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs @@ -121,6 +121,10 @@ public static long CountPoints(IReadOnlyList domains) /// The slot domains. /// How many points to take. /// The sampled points. The seed is fixed, so a build repeats. + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "Security", + "S2245", + Justification = "Fixed-seed sampling of validation points. Repeatability is required; not a security use.")] public static IEnumerable> Sample(IReadOnlyList domains, int count) { ArgumentNullException.ThrowIfNull(domains); diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/Uuid5PointId.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/Uuid5PointId.cs index 981ed3bd..c9d2355c 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/Uuid5PointId.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/Uuid5PointId.cs @@ -43,6 +43,10 @@ public static Guid Namespace(string name) "Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "RFC 4122 version 5 specifies SHA-1. This is an identifier, not a security boundary.")] + [SuppressMessage( + "Security", + "S4790", + Justification = "RFC 4122 version 5 specifies SHA-1, pinned by Uuid5PointIdTests. Identifier, not a security boundary.")] public static Guid For(string cardId, Guid @namespace, string prefix) { ArgumentNullException.ThrowIfNull(cardId); From b8964e90d82a5bab58370a730ab1918161adfa7f Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 21:55:07 -0600 Subject: [PATCH 21/32] fix: Add CancellationToken to async operations and improve property retrieval logic --- demo/chat-ui/src/components/assistant-ui/image.tsx | 4 ---- src/AgentCore.Application/Audit/QueuedAuditSink.cs | 6 +++--- .../Configuration/Compilation/AgentDelegationTool.cs | 7 +------ .../Configuration/Validation/ReasoningTemperatureCheck.cs | 5 ++++- src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs | 7 +------ src/AgentCore.Application/Policy/StagePolicy.cs | 2 +- .../Call/CallEndpointRouteBuilderExtensions.cs | 2 +- .../Diagnostics/LoggingCallObserverTests.cs | 7 ++++--- .../Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs | 1 + .../Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs | 1 + 10 files changed, 17 insertions(+), 25 deletions(-) diff --git a/demo/chat-ui/src/components/assistant-ui/image.tsx b/demo/chat-ui/src/components/assistant-ui/image.tsx index 30ce6b28..c5da1012 100644 --- a/demo/chat-ui/src/components/assistant-ui/image.tsx +++ b/demo/chat-ui/src/components/assistant-ui/image.tsx @@ -302,10 +302,6 @@ function ImageZoom({ src, alt = "Image preview", children }: ImageZoomProps) { src={src} alt={alt} className="aui-image-zoom-content fade-in zoom-in-95 animate-in max-h-[90vh] max-w-[90vw] cursor-zoom-out object-contain duration-200" - onClick={(e) => { - e.stopPropagation(); - handleClose(); - }} /> , document.body, diff --git a/src/AgentCore.Application/Audit/QueuedAuditSink.cs b/src/AgentCore.Application/Audit/QueuedAuditSink.cs index eae033de..ad2d0738 100644 --- a/src/AgentCore.Application/Audit/QueuedAuditSink.cs +++ b/src/AgentCore.Application/Audit/QueuedAuditSink.cs @@ -80,7 +80,7 @@ public QueuedAuditSink( SingleWriter = false, }); - _writer = Task.Run(WriteAsync); + _writer = Task.Run(WriteAsync, CancellationToken.None); } /// @@ -153,7 +153,7 @@ private async Task DrainedAsync() { try { - await _writer.WaitAsync(DisposeTimeout).ConfigureAwait(false); + await _writer.WaitAsync(DisposeTimeout, CancellationToken.None).ConfigureAwait(false); return true; } #pragma warning disable CA1031 // A drain that failed has already reported itself, and disposal never throws. @@ -171,7 +171,7 @@ private async Task WriteAsync() { List batch = new(_batchSize); - while (await _queue.Reader.WaitToReadAsync().ConfigureAwait(false)) + while (await _queue.Reader.WaitToReadAsync(CancellationToken.None).ConfigureAwait(false)) { // Everything waiting goes in one batch, so the store pays one round trip for a burst // rather than one for each event of it. diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs index 7cff6a59..5912c115 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs @@ -126,12 +126,7 @@ public override JsonElement JsonSchema return null; } - foreach (var property in properties.EnumerateObject()) - { - return property.Name; - } - - return null; + return properties.EnumerateObject().Select(property => property.Name).FirstOrDefault(); } } diff --git a/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs b/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs index 326c5f5f..e451a226 100644 --- a/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs +++ b/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs @@ -24,6 +24,9 @@ internal static class ReasoningTemperatureCheck { /// The one temperature a reasoning entry accepts. private const double ReasoningTemperature = 1; + + /// The tolerance around that still counts as equal. + private const double TemperatureTolerance = 1e-9; /// The one reasoningEffort value that leaves temperature free. private const string NoReasoning = "none"; @@ -86,7 +89,7 @@ private static void Check( List errors) { if (model?.Temperature is not { } temperature - || temperature == ReasoningTemperature + || Math.Abs(temperature - ReasoningTemperature) < TemperatureTolerance || !reasoning.TryGetValue(model.Ref, out var effort)) { return; diff --git a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs index 73cbbafd..70917f98 100644 --- a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs +++ b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs @@ -85,12 +85,7 @@ internal FacetFilteredSearch( return null; } - foreach (var property in properties.EnumerateObject()) - { - return property.Name; - } - - return null; + return properties.EnumerateObject().Select(property => property.Name).FirstOrDefault(); } private static string? QueryText(object? value) diff --git a/src/AgentCore.Application/Policy/StagePolicy.cs b/src/AgentCore.Application/Policy/StagePolicy.cs index 80239024..cc00a4a1 100644 --- a/src/AgentCore.Application/Policy/StagePolicy.cs +++ b/src/AgentCore.Application/Policy/StagePolicy.cs @@ -73,7 +73,7 @@ public StagePolicy(PolicyConfiguration policy, IGuardEvaluator guards) public PolicyConfiguration Configuration => _policy; /// Gets the id of the stage the machine holds. - public string Stage => _machine.State; + public string Stage => _stage; /// Gets the stage the machine holds. public StageConfiguration CurrentStage => _stages[_machine.State]; diff --git a/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs b/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs index 5927b3ba..87ee377a 100644 --- a/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs +++ b/src/AgentCore.AspNetCore/Call/CallEndpointRouteBuilderExtensions.cs @@ -67,6 +67,6 @@ await http.Response.WriteAsJsonAsync(new ProblemDetails Title = "This host routes no inbound call.", Detail = reason, Instance = pattern, - }).ConfigureAwait(false); + }, http.RequestAborted).ConfigureAwait(false); } } diff --git a/tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs b/tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs index 1005ff55..23928eda 100644 --- a/tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs +++ b/tests/AgentCore.Application.Tests/Diagnostics/LoggingCallObserverTests.cs @@ -174,11 +174,12 @@ public async Task AKindTheChainRecords_WritesNoLine(CallEventKind kind) public async Task NoLogger_IsStillAnObserver() { // The library never throws for want of one. - LoggingCallObserver observer = new(); - - await observer.OnCallEventAsync( + var pending = new LoggingCallObserver().OnCallEventAsync( Event(CallEventKind.EmptyReply, turnIndex: 0), TestContext.Current.CancellationToken); + + await pending; + Assert.True(pending.IsCompletedSuccessfully); } [Fact] diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs index 62243f21..a1b7dbaf 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayEndpointTests.cs @@ -131,6 +131,7 @@ public async Task AClientThatVanishesWithNoCloseFrame_ReleasesTheSession() relay.Abort(); await host.WaitForCallEndAsync("call-dropped"); + Assert.Null(await host.FindSessionAsync("call-dropped")); } [Fact(Timeout = 30_000)] diff --git a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs index ab86b2ee..4b855662 100644 --- a/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/Vendors/TelnyxRelay/TelnyxRelayTurnTests.cs @@ -378,6 +378,7 @@ public async Task ARelayThatVanishesWithNoCloseFrame_ReleasesTheSession() relay.Abort(); await host.WaitForCallEndAsync("call-dropped"); + Assert.Null(await host.FindSessionAsync("call-dropped")); } } From 8f5b32e506af93f52109d8b501c884b7483ad6d2 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 22:21:56 -0600 Subject: [PATCH 22/32] refactor: enhance code quality across multiple files --- .../components/GenerativeUiDataUI.test.tsx | 2 +- .../components/assistant-ui/attachment.tsx | 31 ++--- .../assistant-ui/elements/sources.tsx | 8 +- .../src/components/assistant-ui/image.tsx | 22 ++-- .../components/assistant-ui/markdown-text.tsx | 12 +- .../components/assistant-ui/thread-list.tsx | 7 +- .../src/components/assistant-ui/thread.tsx | 44 +++---- .../components/assistant-ui/tool-fallback.tsx | 9 +- .../src/components/elements/error-state.tsx | 15 ++- .../src/components/elements/surfaces.tsx | 8 +- .../components/elements/typing-indicator.tsx | 2 +- demo/chat-ui/src/components/icons/github.tsx | 2 +- demo/chat-ui/src/components/ui/dialog.tsx | 10 +- demo/chat-ui/src/components/ui/sheet.tsx | 10 +- demo/chat-ui/src/components/ui/tooltip.tsx | 4 +- demo/chat-ui/src/index.css | 17 +-- .../Calls/ChatCallTitler.cs | 24 +++- .../Parsing/ConfigurationSchemaValidator.cs | 23 ++-- .../Validation/ConfigurationValidator.cs | 54 ++++----- .../Configuration/Validation/StateDomain.cs | 19 ++- .../Evaluation/RetrievedDocumentsContext.cs | 13 ++- .../Knowledge/FacetFilterProvider.cs | 4 +- .../Knowledge/KnowledgeAuditRecord.cs | 4 +- .../Knowledge/KnowledgePrefetchProvider.cs | 4 +- .../Knowledge/KnowledgeProbe.cs | 13 +-- .../Runtime/AgentCoreAgent.cs | 13 ++- .../Runtime/CallSession.cs | 68 ++++------- .../Runtime/CallSession/CallTurnCompletion.cs | 18 ++- .../Runtime/CallSession/CallTurnRunner.cs | 16 ++- .../Runtime/CallSession/CallTurnStream.cs | 13 ++- .../Compaction/CompactionStrategyFactory.cs | 4 +- .../Runtime/DelegatedAgentRun.cs | 2 +- .../Runtime/FallbackAgent.cs | 4 +- .../Runtime/GraphStateAgent.cs | 4 +- .../Runtime/Harness/CallFilesProvider.cs | 4 +- .../Runtime/Harness/HarnessSessionState.cs | 7 +- .../Runtime/ModelFacingChatClient.cs | 8 +- .../Runtime/ModerationAgent.cs | 18 ++- .../Runtime/RequireOutputAgent.cs | 4 +- .../Runtime/Turn/TurnRegistry.cs | 6 +- .../State/StateDocument.cs | 10 +- .../Tools/Builtin/BuiltinToolSource.cs | 9 +- .../Tools/Drawing/DrawingData.cs | 18 +-- .../Tools/Drawing/DrawingReceipt.cs | 7 +- .../Tools/Registry/ToolRegistryBuilder.cs | 5 +- .../Call/JsonWebSocketPump.cs | 4 +- .../Endpoints/ChatCompletionsEndpoints.cs | 25 ++-- .../TelnyxRelay/TelnyxRelayConnection.cs | 20 ++-- .../Audit/AuditEventVocabulary.cs | 109 ++++++++++-------- .../Audit/Postgres/PostgresAuditSink.cs | 5 + .../Calls/Postgres/PostgresCallStore.cs | 5 + .../Qdrant/QdrantKnowledgeAdapter.cs | 23 ++-- .../VectorData/Qdrant/QdrantKnowledgeStore.cs | 54 +++++---- .../Secrets/ChainedSecretResolver.cs | 5 + .../Tools/Mcp/McpServerSession.cs | 1 - .../Tools/Mcp/McpTool.cs | 9 +- .../Tools/McpToolSource.cs | 1 + .../Knowledge/FacetFilterTests.cs | 2 +- .../Knowledge/KnowledgeAuditRecordTests.cs | 2 +- .../KnowledgeProviderFactoryTests.cs | 2 +- ...ctionInvokingChatClientErrorPolicyTests.cs | 2 +- .../Runtime/CallSessionTests.cs | 2 +- .../Runtime/CappedToolCallFormatterTests.cs | 2 +- .../Runtime/ModelFacingChatClientTests.cs | 10 +- .../Runtime/Turn/TurnResultsTests.cs | 6 +- .../Tools/BindingToolTests.cs | 4 +- .../Tools/DeclaredToolTests.cs | 8 +- .../Tools/DrawingAgentTests.cs | 14 +-- .../Tools/TimeLimitedToolTests.cs | 8 +- .../Tools/TypedBindingToolTests.cs | 4 +- .../Qdrant/QdrantKnowledgeAdapterTests.cs | 6 +- .../Qdrant/QdrantPointConverterTests.cs | 6 +- .../ToolSeamTests.cs | 2 +- .../Tools/Fakes/InProcessMcpServer.cs | 2 +- .../Tools/HttpToolSourceTests.cs | 8 +- .../Tools/McpServerSessionTests.cs | 14 +-- .../RecordingChatClientFactory.cs | 22 ++-- 77 files changed, 528 insertions(+), 458 deletions(-) diff --git a/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx b/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx index 8f7fd130..f01bf1b4 100644 --- a/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx +++ b/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx @@ -155,7 +155,7 @@ describe("the vocabulary the drawing model is taught", () => { const taught = [...vocabulary.matchAll(/^- `([A-Z][A-Za-z]*)`/gm)].map((match) => match[1]); const renderable = new Set(Object.keys(defaultGenerativeUILibrary)); - expect(taught.length).toBe(27); + expect(taught).toHaveLength(27); expect(taught.filter((name) => !renderable.has(name))).toEqual([]); expect([...renderable].filter((name) => !taught.includes(name))).toEqual([]); }); diff --git a/demo/chat-ui/src/components/assistant-ui/attachment.tsx b/demo/chat-ui/src/components/assistant-ui/attachment.tsx index f5682a8d..e1f60be6 100644 --- a/demo/chat-ui/src/components/assistant-ui/attachment.tsx +++ b/demo/chat-ui/src/components/assistant-ui/attachment.tsx @@ -61,8 +61,7 @@ const useAttachmentSrc = () => { useShallow((s): { file?: File; src?: string } => { if (s.attachment.type !== "image") return {}; if (s.attachment.file) return { file: s.attachment.file }; - const src = s.attachment.content?.filter((c) => c.type === "image")[0] - ?.image; + const src = s.attachment.content?.find((c) => c.type === "image")?.image; if (!src) return {}; return { src }; }), @@ -153,17 +152,25 @@ const AttachmentUI: FC = () => { } }); - const uploadState = useAuiState((s) => - s.attachment.status.type === "running" - ? "uploading" - : s.attachment.status.type === "incomplete" && - s.attachment.status.reason === "error" - ? "error" - : undefined, - ); + const uploadState = useAuiState((s) => { + if (s.attachment.status.type === "running") return "uploading"; + if ( + s.attachment.status.type === "incomplete" && + s.attachment.status.reason === "error" + ) { + return "error"; + } + return undefined; + }); const isUploading = uploadState === "uploading"; const isError = uploadState === "error"; + let stateLabel = ""; + if (isError) { + stateLabel = ", upload failed"; + } else if (isUploading) { + stateLabel = ", uploading"; + } const errorMessage = useAuiState((s) => s.attachment.status.type === "incomplete" && s.attachment.status.reason === "error" @@ -205,9 +212,7 @@ const AttachmentUI: FC = () => { onKeyUp={(e) => { if (e.key === " ") e.currentTarget.click(); }} - aria-label={`${typeLabel} attachment${ - isError ? ", upload failed" : isUploading ? ", uploading" : "" - }`} + aria-label={`${typeLabel} attachment${stateLabel}`} > {isUploading && ( diff --git a/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx b/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx index c9d87a39..b6606e11 100644 --- a/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx +++ b/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx @@ -19,10 +19,10 @@ export interface Source { } export interface SourcesProps { - sources: readonly Source[]; - open: boolean; - onOpenChange: (open: boolean) => void; - className?: string; + readonly sources: readonly Source[]; + readonly open: boolean; + readonly onOpenChange: (open: boolean) => void; + readonly className?: string; } export function Sources({ diff --git a/demo/chat-ui/src/components/assistant-ui/image.tsx b/demo/chat-ui/src/components/assistant-ui/image.tsx index c5da1012..ba2f85b3 100644 --- a/demo/chat-ui/src/components/assistant-ui/image.tsx +++ b/demo/chat-ui/src/components/assistant-ui/image.tsx @@ -45,19 +45,19 @@ const extensionForMimeType = (mimeType?: string): string => { const dataUriToBlob = (dataUri: string): Blob => { const [meta, data] = dataUri.split(","); const mime = - meta?.match(/data:([^;]+)/i)?.[1]?.toLowerCase() ?? + /data:([^;]+)/i.exec(meta ?? "")?.[1]?.toLowerCase() ?? "application/octet-stream"; if (!/;base64/i.test(meta ?? "")) { return new Blob([decodeURIComponent(data ?? "")], { type: mime }); } const bytes = atob(data ?? ""); const arr = new Uint8Array(bytes.length); - for (let i = 0; i < bytes.length; i++) arr[i] = bytes.charCodeAt(i); + for (let i = 0; i < bytes.length; i++) arr[i] = bytes.codePointAt(i) ?? 0; return new Blob([arr], { type: mime }); }; const mimeFromImage = (image: string): string | undefined => - image.match(/^data:([^;,]+)/i)?.[1]?.toLowerCase(); + /^data:([^;,]+)/i.exec(image)?.[1]?.toLowerCase(); const downloadImagePart = ( part: Pick, @@ -76,7 +76,7 @@ const downloadImagePart = ( a.rel = "noopener"; document.body.appendChild(a); a.click(); - document.body.removeChild(a); + a.remove(); if (objectUrl) setTimeout(() => URL.revokeObjectURL(objectUrl), 40_000); }; @@ -310,7 +310,7 @@ function ImageZoom({ src, alt = "Image preview", children }: ImageZoomProps) { ); } -function ImageGenerating({ className }: { className?: string }) { +function ImageGenerating({ className }: { readonly className?: string }) { return (
void | Promise; - className?: string; + readonly onRegenerate?: () => void | Promise; + readonly className?: string; }; function RegenerateButton({ onRegenerate, }: { - onRegenerate: () => void | Promise; + readonly onRegenerate: () => void | Promise; }) { const [isRegenerating, setIsRegenerating] = useState(false); return ( diff --git a/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx b/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx index 9c30989d..5d90c910 100644 --- a/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx +++ b/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx @@ -78,7 +78,7 @@ const useCopyToClipboard = ({ const defaultComponents = memoizeMarkdownComponents({ h1: ({ className, ...props }) => ( -

), h2: ({ className, ...props }) => ( -

), h3: ({ className, ...props }) => ( -

), h4: ({ className, ...props }) => ( -

), h5: ({ className, ...props }) => ( -

), h6: ({ className, ...props }) => ( -
= ({ const result: ThreadListGroup[] = []; for (const index of sorted) { const label = dateGroupLabel(dates[index], startOfToday); - const lastGroup = result[result.length - 1]; + const lastGroup = result.at(-1); if (lastGroup?.label === label) { lastGroup.indices.push(index); } else { @@ -249,9 +249,8 @@ const ThreadListSkeleton: FC = () => { return (
{Array.from({ length: 5 }, (_, i) => ( -
{ data-slot="aui_thread-list-skeleton" className="h-3.5 w-full" /> -
+ ))}
); diff --git a/demo/chat-ui/src/components/assistant-ui/thread.tsx b/demo/chat-ui/src/components/assistant-ui/thread.tsx index 7fa7b7e5..e19671f8 100644 --- a/demo/chat-ui/src/components/assistant-ui/thread.tsx +++ b/demo/chat-ui/src/components/assistant-ui/thread.tsx @@ -93,19 +93,15 @@ export type ThreadGroupPart = MessagePrimitive.GroupedParts.GroupPart; * `ToolFallback`. */ export type ThreadComponents = { - AssistantMessage?: ComponentType | undefined; - Welcome?: ComponentType | undefined; - ToolFallback?: ToolCallMessagePartComponent | undefined; - ToolGroup?: - | ComponentType> - | undefined; - ReasoningGroup?: - | ComponentType> - | undefined; + AssistantMessage?: ComponentType; + Welcome?: ComponentType; + ToolFallback?: ToolCallMessagePartComponent; + ToolGroup?: ComponentType>; + ReasoningGroup?: ComponentType>; }; export type ThreadProps = { - components?: ThreadComponents | undefined; + components?: ThreadComponents; }; const EMPTY_COMPONENTS: ThreadComponents = {}; @@ -127,9 +123,8 @@ const isHistoryLoadingView = (s: AssistantState) => !s.threads.isLoading; const ThreadHistorySkeleton: FC = () => ( -
Loading conversation @@ -144,7 +139,7 @@ const ThreadHistorySkeleton: FC = () => (
-
+ ); export const Thread: FC = ({ components = EMPTY_COMPONENTS }) => { @@ -268,13 +263,12 @@ const ThreadMessage: FC = () => { const isEditing = useAuiState((s) => s.message.composer.isEditing); const dayBreak = useDayBreak(); - const message = isEditing ? ( - - ) : role === "user" ? ( - - ) : ( - - ); + let message = ; + if (isEditing) { + message = ; + } else if (role === "user") { + message = ; + } if (!dayBreak) return message; @@ -445,7 +439,15 @@ function errorDetail(error: unknown): string { try { return JSON.stringify(error); } catch { - return String(error); + if ( + typeof error === "object" && + error !== null && + "message" in error && + typeof error.message === "string" + ) { + return error.message; + } + return "The run did not finish."; } } diff --git a/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx b/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx index fa82f7bc..bdb31258 100644 --- a/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx +++ b/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx @@ -291,11 +291,10 @@ function ToolFallbackError({ if (status?.type !== "incomplete") return null; const error = status.error; - const errorText = error - ? typeof error === "string" - ? error - : JSON.stringify(error) - : null; + let errorText: string | null = null; + if (error) { + errorText = typeof error === "string" ? error : JSON.stringify(error); + } if (!errorText) return null; diff --git a/demo/chat-ui/src/components/elements/error-state.tsx b/demo/chat-ui/src/components/elements/error-state.tsx index d7249fd6..33c64471 100644 --- a/demo/chat-ui/src/components/elements/error-state.tsx +++ b/demo/chat-ui/src/components/elements/error-state.tsx @@ -5,14 +5,13 @@ import { CircleAlertIcon, RefreshCwIcon } from "lucide-react"; import { cn } from "@/lib/utils"; import { ShimmerLabel } from "./surfaces"; -export interface ErrorStateProps extends Omit< - ComponentProps<"div">, - "children" | "role" +export interface ErrorStateProps extends Readonly< + Omit, "children" | "role"> > { - title: string; - detail: string; - retrying: boolean; - onRetry: () => void; + readonly title: string; + readonly detail: string; + readonly retrying: boolean; + readonly onRetry: () => void; } export function ErrorState({ @@ -26,9 +25,9 @@ export function ErrorState({ if (retrying) { return (
(null), useRef(null)]; const [width, setWidth] = useState(null); @@ -104,7 +104,7 @@ export function SwapLabel({ > {children.map((layer, index) => ( ) { +}: Readonly>) { return } function DialogTrigger({ ...props -}: React.ComponentProps) { +}: Readonly>) { return } function DialogPortal({ ...props -}: React.ComponentProps) { +}: Readonly>) { return } function DialogClose({ ...props -}: React.ComponentProps) { +}: Readonly>) { return } function DialogOverlay({ className, ...props -}: React.ComponentProps) { +}: Readonly>) { return ( ) { +function Sheet({ ...props }: Readonly>) { return } function SheetTrigger({ ...props -}: React.ComponentProps) { +}: Readonly>) { return } function SheetClose({ ...props -}: React.ComponentProps) { +}: Readonly>) { return } function SheetPortal({ ...props -}: React.ComponentProps) { +}: Readonly>) { return } function SheetOverlay({ className, ...props -}: React.ComponentProps) { +}: Readonly>) { return ( ) { +}: Readonly>) { return ( ) { +}: Readonly>) { return } diff --git a/demo/chat-ui/src/index.css b/demo/chat-ui/src/index.css index 085a3331..30a910e5 100644 --- a/demo/chat-ui/src/index.css +++ b/demo/chat-ui/src/index.css @@ -52,23 +52,10 @@ /* ---break--- */ -.dark { - --sidebar: hsl(240 5.9% 10%); - --sidebar-foreground: hsl(240 4.8% 95.9%); - --sidebar-primary: hsl(224.3 76.3% 48%); - --sidebar-primary-foreground: hsl(0 0% 100%); - --sidebar-accent: hsl(240 3.7% 15.9%); - --sidebar-accent-foreground: hsl(240 4.8% 95.9%); - --sidebar-border: hsl(240 3.7% 15.9%); - --sidebar-ring: hsl(217.2 91.2% 59.8%); - --aui-success: oklch(0.72 0.17 149); - --aui-warning: oklch(0.8 0.17 75); -} /* * The shadcn colour palette, "neutral", exactly as https://ui.shadcn.com/r/colors/neutral.json - * publishes it for Tailwind v4. Generated rather than typed, and placed after the blocks the - * shadcn CLI wrote above so that these oklch values win over the hsl sidebar defaults it emitted. + * publishes it for Tailwind v4. Generated rather than typed. * * It is here rather than produced by `shadcn init` because init cannot run non-interactively * against a components.json that already exists, and this project's components.json was written @@ -185,6 +172,8 @@ --sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-border: oklch(1 0 0 / 10%); --sidebar-ring: oklch(0.556 0 0); + --aui-success: oklch(0.72 0.17 149); + --aui-warning: oklch(0.8 0.17 75); } @theme inline { diff --git a/src/AgentCore.Application/Calls/ChatCallTitler.cs b/src/AgentCore.Application/Calls/ChatCallTitler.cs index 5078d367..4d7e21df 100644 --- a/src/AgentCore.Application/Calls/ChatCallTitler.cs +++ b/src/AgentCore.Application/Calls/ChatCallTitler.cs @@ -20,11 +20,18 @@ public sealed class ChatCallTitler(ICallStore calls, IChatClient client) : ICall + "Reply with the title alone."; /// - public async IAsyncEnumerable GenerateAsync( - string callId, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public IAsyncEnumerable GenerateAsync( + string callId, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(callId); + return GenerateCoreAsync(callId, cancellationToken); + } + + /// Reads the call's messages and streams the title writes. + private async IAsyncEnumerable GenerateCoreAsync( + string callId, [EnumeratorCancellation] CancellationToken cancellationToken) + { var rows = await calls.ReadAsync(callId, cancellationToken).ConfigureAwait(false); if (rows.Count == 0) @@ -40,14 +47,23 @@ public async IAsyncEnumerable GenerateAsync( } /// - public async IAsyncEnumerable GenerateFromAsync( + public IAsyncEnumerable GenerateFromAsync( string callId, IReadOnlyList messages, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(callId); ArgumentNullException.ThrowIfNull(messages); + return GenerateFromCoreAsync(callId, messages, cancellationToken); + } + + /// Streams the title of caller-supplied messages once the call proves to exist. + private async IAsyncEnumerable GenerateFromCoreAsync( + string callId, + IReadOnlyList messages, + [EnumeratorCancellation] CancellationToken cancellationToken) + { if (messages.Count == 0) { yield break; diff --git a/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs b/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs index a5c2f8d7..bd134d32 100644 --- a/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs +++ b/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs @@ -193,11 +193,12 @@ private static bool Speculative(EvaluationResults node) ? $"this key is written exactly '{only[0]}', and nothing else" : "the value is not the one this key holds", - "pattern" => Keyword(node, "pattern")?.GetValue() is not { } pattern - ? "the value is not written in the form this key requires" - : pattern == @"\S" - ? "the text holds no words, and this key needs some" - : $"the text is not written in the form this key requires: {pattern}", + "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}" @@ -342,9 +343,15 @@ private static List Alternatives(EvaluationResults node) /// 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) - => BoundPattern().Match(message) is { Success: true } bound - ? (bound.Groups[1].Value == "least" ? "few" : "many", $"{bound.Groups[1].Value} {bound.Groups[2].Value}") - : null; + { + 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() { diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index ceff6c2e..1bacf9c0 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -19,6 +19,9 @@ public static class ConfigurationValidator /// 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"; + /// Runs checks 2 to 8 and returns everything they find. /// The bound document. /// Every error and every partial-coverage warning. @@ -559,27 +562,21 @@ private static void CheckKnowledgeScopeSlots( } else { - foreach (var facet in widened.Facets) + foreach (var facet in widened.Facets.Where(facet => !scope.FromState.Contains(facet, StringComparer.Ordinal))) { - if (!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.")); - } + 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) + foreach (var name in scope.FromState.Where(name => !widened.Facets.Contains(name, StringComparer.Ordinal))) { - if (!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.")); - } + 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.")); } } @@ -749,7 +746,7 @@ private static void CheckSlotWriters(AgentCoreConfiguration configuration, List< $"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", "increment", "value" }) + foreach (var field in new[] { "from", IncrementField, "value" }) { if (string.Equals(field, owner, StringComparison.Ordinal) || FieldValue(slot, field) is null) { @@ -767,7 +764,7 @@ private static void CheckSlotWriters(AgentCoreConfiguration configuration, List< => writer switch { StateWriter.Tool => "from", - StateWriter.Counter => "increment", + StateWriter.Counter => IncrementField, StateWriter.Const => "value", _ => null, }; @@ -785,7 +782,7 @@ private static string WriterName(StateWriter writer) => field switch { "from" => slot.From, - "increment" => slot.Increment, + IncrementField => slot.Increment, _ => slot.Value, }; @@ -803,7 +800,7 @@ private static void CheckGuardRules(AgentCoreConfiguration configuration, List !GuardOperators.IsAllowed(name))) { - if (!GuardOperators.IsAllowed(name)) - { - errors.Add(Operators(pointer, GuardOperators.DescribeRejection(name))); - } + errors.Add(Operators(pointer, GuardOperators.DescribeRejection(name))); } if (facts.HasDoubleNegationSugar) @@ -854,12 +848,10 @@ private static void CheckOneRule(AgentCoreConfiguration configuration, JsonNode errors.Add(Operators(pointer, GuardOperators.DoubleNegationSugarRejection)); } - foreach (var slot in facts.Variables) + foreach (var slot in facts.Variables.Where(slot => + !configuration.State.ContainsKey(slot) && !ReservedStateSlots.Contains(slot))) { - if (!configuration.State.ContainsKey(slot) && !ReservedStateSlots.Contains(slot)) - { - errors.Add(Operators(pointer, $"the rule reads the slot '{slot}', and state: does not declare it")); - } + errors.Add(Operators(pointer, $"the rule reads the slot '{slot}', and state: does not declare it")); } foreach (var comparison in facts.NumericComparisons) diff --git a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs index 016ef27b..71636fea 100644 --- a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs +++ b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs @@ -86,6 +86,12 @@ public static long CountPoints(IReadOnlyList domains) { ArgumentNullException.ThrowIfNull(domains); + return EnumerateCore(domains); + } + + /// Walks every point of the product. The caller checks the arguments. + private static IEnumerable> EnumerateCore(IReadOnlyList domains) + { if (domains.Count == 0) { yield return new Dictionary(StringComparer.Ordinal); @@ -121,16 +127,23 @@ public static long CountPoints(IReadOnlyList domains) /// The slot domains. /// How many points to take. /// The sampled points. The seed is fixed, so a build repeats. + public static IEnumerable> Sample(IReadOnlyList domains, int count) + { + ArgumentNullException.ThrowIfNull(domains); + + return SampleCore(domains, count); + } + + /// Samples the product with the fixed seed. The caller checks the arguments. [System.Diagnostics.CodeAnalysis.SuppressMessage( "Security", "S2245", Justification = "Fixed-seed sampling of validation points. Repeatability is required; not a security use.")] - public static IEnumerable> Sample(IReadOnlyList domains, int count) + private static IEnumerable> SampleCore(IReadOnlyList domains, int count) { - ArgumentNullException.ThrowIfNull(domains); - // The seed is fixed so that a failing build fails the same way twice. var random = new Random(SampleSeed); + var cursor = new int[domains.Count]; for (var taken = 0; taken < count; taken++) diff --git a/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs b/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs index ec7d850d..f510758c 100644 --- a/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs +++ b/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.AI.Evaluation; +using System.Runtime.CompilerServices; namespace AgentCore.Application.Evaluation; @@ -15,7 +16,7 @@ public sealed class RetrievedDocumentsContext : EvaluationContext /// The document ids the search returned, best first. /// Either list is . public RetrievedDocumentsContext(IEnumerable expected, IEnumerable retrieved) - : this(Materialize(expected, nameof(expected)), Materialize(retrieved, nameof(retrieved))) + : this(Materialize(expected), Materialize(retrieved)) { } @@ -37,9 +38,15 @@ private static string Describe(string[] expected, string[] retrieved) private static string Join(string[] ids) => ids.Length == 0 ? "none" : string.Join(", ", ids); - private static string[] Materialize(IEnumerable ids, string parameterName) + private static string[] Materialize( + IEnumerable ids, + [CallerArgumentExpression(nameof(ids))] string parameterName = "") { - ArgumentNullException.ThrowIfNull(ids, parameterName); + if (ids is null) + { + throw new ArgumentNullException(parameterName); + } + return [.. ids]; } } diff --git a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs index 0e40630a..124e54b8 100644 --- a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs +++ b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs @@ -37,7 +37,7 @@ internal sealed class FacetFilterProvider( /// protected override async ValueTask InvokingCoreAsync( - InvokingContext context, CancellationToken cancellationToken) + InvokingContext context, CancellationToken cancellationToken = default) { var provided = await _inner.InvokingAsync(context, cancellationToken).ConfigureAwait(false); @@ -62,6 +62,6 @@ protected override async ValueTask InvokingCoreAsync( /// protected override ValueTask InvokedCoreAsync( - InvokedContext context, CancellationToken cancellationToken) + InvokedContext context, CancellationToken cancellationToken = default) => _inner.InvokedAsync(context, cancellationToken); } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs index c8cbc965..cb51e1aa 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs @@ -65,7 +65,7 @@ public static KnowledgeAuditRecord For( Scope = scope?.Facets ?? EmptyScope, ScopeOrigins = scope?.Origins ?? EmptyOrigins, LatencyMs = latencyMs, - Cards = [.. cards.Select(CardEntry.For)], + Cards = [.. cards.Select(CardEntry.From)], Failure = failure?.ToString(), }; } @@ -149,7 +149,7 @@ internal sealed record CardEntry /// Reads one card into its audit entry. /// The card to record. /// The entry. - internal static CardEntry For(KnowledgeCard card) => new() + internal static CardEntry From(KnowledgeCard card) => new() { CardId = card.CardId, Score = card.Score, diff --git a/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs index 2f7d6542..072af390 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs @@ -43,7 +43,7 @@ internal sealed class KnowledgePrefetchProvider( /// protected override async ValueTask InvokingCoreAsync( - InvokingContext context, CancellationToken cancellationToken) + InvokingContext context, CancellationToken cancellationToken = default) { var turn = TurnRegistry.For(context.Session); @@ -58,6 +58,6 @@ protected override async ValueTask InvokingCoreAsync( /// protected override ValueTask InvokedCoreAsync( - InvokedContext context, CancellationToken cancellationToken) + InvokedContext context, CancellationToken cancellationToken = default) => _template.InvokedAsync(context, cancellationToken); } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs index 41619bee..6a791d2f 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs @@ -183,16 +183,9 @@ internal static class KnowledgeProbe var path = template.Resolve(facet); SortedSet union = new(StringComparer.Ordinal); - foreach (var card in probeCards) - { - foreach (var value in FacetValues(card, path)) - { - if (!string.Equals(value, wildcardValue, StringComparison.Ordinal)) - { - union.Add(value); - } - } - } + union.UnionWith(probeCards + .SelectMany(card => FacetValues(card, path)) + .Where(value => !string.Equals(value, wildcardValue, StringComparison.Ordinal))); Log.KnowledgeProbeRan(logger, agent, facet, union.Count); diff --git a/src/AgentCore.Application/Runtime/AgentCoreAgent.cs b/src/AgentCore.Application/Runtime/AgentCoreAgent.cs index 766307fd..1a462dfe 100644 --- a/src/AgentCore.Application/Runtime/AgentCoreAgent.cs +++ b/src/AgentCore.Application/Runtime/AgentCoreAgent.cs @@ -213,14 +213,23 @@ protected override async Task RunCoreAsync( } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentSession? session = null, AgentRunOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(messages); + return RunCoreStreamingCoreAsync(messages, session, cancellationToken); + } + + /// Streams one turn of the resolved call, wrapping each update with this agent's id. + private async IAsyncEnumerable RunCoreStreamingCoreAsync( + IEnumerable messages, + AgentSession? session, + [EnumeratorCancellation] CancellationToken cancellationToken) + { var call = Resolve(session); // The stream is already filtered: CallSession drops the lifecycle updates, so every update diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index ae395d04..61a40239 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -1,4 +1,3 @@ -using System.Runtime.CompilerServices; using System.Text.Json; using AgentCore.Application.Calls; using AgentCore.Application.Configuration.Compilation; @@ -81,29 +80,6 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable private readonly Lock _interruptLock = new(); - private AgentSession? _agentSession; - - /// - /// The call'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 . - /// - private AgentSession? _graphSession; - - /// - /// The last serialization of , read back at resume. Refreshed - /// at every turn end; a host snapshotting mid-turn gets the last turn boundary. - /// - private JsonElement? _graphBlob; - - private CancellationTokenSource? _runCancellation; - - private CallInterruptionTracker.Interruption? _interruption; - - private Guid? _amendableEventId; - - private CallSessionState? _checkpoint; - private readonly Clarifications _clarifications = new(); private readonly CallWorkspace? _workspace; @@ -137,20 +113,28 @@ public sealed class CallSession : IConversationPort, IAsyncDisposable internal CallWorkspace? WorkspaceRoot => _workspace; - internal AgentSession? AgentSession { get => _agentSession; set => _agentSession = value; } + internal AgentSession? AgentSession { get; set; } - internal AgentSession? GraphSession { get => _graphSession; set => _graphSession = value; } - - internal JsonElement? GraphBlob { get => _graphBlob; set => _graphBlob = value; } + /// + /// The call'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 . + /// + internal AgentSession? GraphSession { get; set; } - internal CancellationTokenSource? RunCancellation { get => _runCancellation; set => _runCancellation = value; } + /// + /// The last serialization of , read back at resume. Refreshed + /// at every turn end; a host snapshotting mid-turn gets the last turn boundary. + /// + internal JsonElement? GraphBlob { get; set; } - internal CallInterruptionTracker.Interruption? Interruption { get => _interruption; set => _interruption = value; } + internal CancellationTokenSource? RunCancellation { get; set; } - internal Guid? AmendableEventId { get => _amendableEventId; set => _amendableEventId = value; } + internal CallInterruptionTracker.Interruption? Interruption { get; set; } - internal CallSessionState? Checkpoint { get => _checkpoint; set => _checkpoint = value; } + internal Guid? AmendableEventId { get; set; } + internal CallSessionState? Checkpoint { get; set; } internal Clarifications Clarifications => _clarifications; internal CallTurnRunner Runner { get; } @@ -379,35 +363,29 @@ public IAsyncEnumerable RunTurnMessageStreamingAsync( /// /// Runs one streaming turn that knows where it sits in the conversation the caller can see. /// - public async IAsyncEnumerable RunTurnStreamingAtOriginAsync( + public IAsyncEnumerable RunTurnStreamingAtOriginAsync( string userInput, CallTurnOrigin? origin, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(userInput); - await foreach (var update in Stream.RunTurnStreamingCoreAsync( - new ChatMessage(ChatRole.User, userInput), origin, cancellationToken).ConfigureAwait(false)) - { - yield return update; - } + return Stream.RunTurnStreamingCoreAsync( + new ChatMessage(ChatRole.User, userInput), origin, cancellationToken); } /// /// Runs one streaming turn from a message the caller built, that knows where it sits in the /// conversation the caller can see. /// - public async IAsyncEnumerable RunTurnMessageStreamingAtOriginAsync( + public IAsyncEnumerable RunTurnMessageStreamingAtOriginAsync( ChatMessage userInput, CallTurnOrigin? origin, - [EnumeratorCancellation] CancellationToken cancellationToken) + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userInput); - await foreach (var update in Stream.RunTurnStreamingCoreAsync(userInput, origin, cancellationToken).ConfigureAwait(false)) - { - yield return update; - } + return Stream.RunTurnStreamingCoreAsync(userInput, origin, cancellationToken); } /// diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs index db4a1fd0..bca71783 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnCompletion.cs @@ -377,18 +377,16 @@ private void ReportUndeclaredToolCalls(CallTurn turn, AgentResponse response) foreach (var call in response.Messages .SelectMany(message => message.Contents) - .OfType()) + .OfType() + .Where(call => !invoked.Contains(call.CallId))) { - if (!invoked.Contains(call.CallId)) + _session.Events.RaiseToolFailure(turn.Index, new ToolFailure { - _session.Events.RaiseToolFailure(turn.Index, new ToolFailure - { - ToolName = call.Name, - ToolCallId = call.CallId, - Kind = ToolFailureKind.Undeclared, - Message = $"the model called '{call.Name}', and no such tool is declared.", - }); - } + ToolName = call.Name, + ToolCallId = call.CallId, + Kind = ToolFailureKind.Undeclared, + Message = $"the model called '{call.Name}', and no such tool is declared.", + }); } } } diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs index 598f2f6e..9878c509 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnRunner.cs @@ -164,9 +164,19 @@ internal CallTurn BeginTurn(ChatMessage userInput, AgentSession session, CallTur // still recognises. Neither shape puts the caller's message in store 1 yet: the turn // writes what it said and what it heard together, when it commits, so the run that is // about to read the history does not find its own prompt already in it. - List request = _session.SessionCarriesHistory || _session.ReusesGraphSession - ? [spoken] - : TurnMessages.GraphHistory(_session.History.Read(session)) is { } rendered ? [rendered, spoken] : [spoken]; + List request; + if (_session.SessionCarriesHistory || _session.ReusesGraphSession) + { + request = [spoken]; + } + else if (TurnMessages.GraphHistory(_session.History.Read(session)) is { } rendered) + { + request = [rendered, spoken]; + } + else + { + request = [spoken]; + } // One turn is one span. The call 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. diff --git a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs b/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs index 87f815e9..5e798600 100644 --- a/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs +++ b/src/AgentCore.Application/Runtime/CallSession/CallTurnStream.cs @@ -20,13 +20,22 @@ internal CallTurnStream(CallSession session) /// 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 async IAsyncEnumerable RunTurnStreamingCoreAsync( + internal IAsyncEnumerable RunTurnStreamingCoreAsync( ChatMessage userInput, CallTurnOrigin? origin, - [EnumeratorCancellation] CancellationToken cancellationToken) + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userInput); + return RunTurnStreamingIteratorAsync(userInput, origin, cancellationToken); + } + + /// Streams one turn. The caller checks the arguments. + private async IAsyncEnumerable RunTurnStreamingIteratorAsync( + ChatMessage userInput, + CallTurnOrigin? origin, + [EnumeratorCancellation] CancellationToken cancellationToken) + { var session = await _session.Ledger.OpenSessionAsync(cancellationToken).ConfigureAwait(false); var turn = _session.Runner.BeginTurn(userInput, session, origin); diff --git a/src/AgentCore.Application/Runtime/Compaction/CompactionStrategyFactory.cs b/src/AgentCore.Application/Runtime/Compaction/CompactionStrategyFactory.cs index afde5f06..b391ed16 100644 --- a/src/AgentCore.Application/Runtime/Compaction/CompactionStrategyFactory.cs +++ b/src/AgentCore.Application/Runtime/Compaction/CompactionStrategyFactory.cs @@ -36,10 +36,8 @@ private static ToolResultCompactionStrategy ToolResult(ResolvedCompaction settin private static PipelineCompactionStrategy ContextWindow(ResolvedCompaction settings) => new PipelineCompactionStrategy( - [ ToolResult(settings, Trigger(settings.Trigger)), - new TruncationCompactionStrategy(Trigger(settings.Trigger), settings.Keep), - ]); + new TruncationCompactionStrategy(Trigger(settings.Trigger), settings.Keep)); private static CompactionTrigger Trigger(CompactionTriggerConfiguration trigger) => trigger switch { diff --git a/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs b/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs index 13f47a40..7f7e7636 100644 --- a/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs +++ b/src/AgentCore.Application/Runtime/DelegatedAgentRun.cs @@ -33,7 +33,7 @@ internal static class DelegatedAgentRun ChatOptions chat = new() { - AdditionalProperties = new AdditionalPropertiesDictionary(), + AdditionalProperties = [], }; if (nested is not null) diff --git a/src/AgentCore.Application/Runtime/FallbackAgent.cs b/src/AgentCore.Application/Runtime/FallbackAgent.cs index 464e9748..163dc187 100644 --- a/src/AgentCore.Application/Runtime/FallbackAgent.cs +++ b/src/AgentCore.Application/Runtime/FallbackAgent.cs @@ -65,7 +65,7 @@ public FallbackAgent(AIAgent inner, string fallbackReply, IReadOnlySet? /// protected override async Task RunCoreAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { @@ -103,7 +103,7 @@ protected override async Task RunCoreAsync( /// protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { diff --git a/src/AgentCore.Application/Runtime/GraphStateAgent.cs b/src/AgentCore.Application/Runtime/GraphStateAgent.cs index 5ede5e22..4020b9db 100644 --- a/src/AgentCore.Application/Runtime/GraphStateAgent.cs +++ b/src/AgentCore.Application/Runtime/GraphStateAgent.cs @@ -26,7 +26,7 @@ public GraphStateAgent(AIAgent inner, string name) /// protected override Task RunCoreAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { @@ -36,7 +36,7 @@ protected override Task RunCoreAsync( /// protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { diff --git a/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs b/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs index 24913c29..0cc99fcd 100644 --- a/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs +++ b/src/AgentCore.Application/Runtime/Harness/CallFilesProvider.cs @@ -45,7 +45,7 @@ public CallFilesProvider(string root, FileAccessProviderOptions options) /// protected override async ValueTask InvokingCoreAsync( - InvokingContext context, CancellationToken cancellationToken) + InvokingContext context, CancellationToken cancellationToken = default) { var workspace = TurnRegistry.For(context.Session)?.Workspace ?? throw new InvalidOperationException(NoTurnMessage); @@ -60,7 +60,7 @@ protected override async ValueTask InvokingCoreAsync( /// protected override ValueTask InvokedCoreAsync( - InvokedContext context, CancellationToken cancellationToken) + InvokedContext context, CancellationToken cancellationToken = default) => _template.InvokedAsync(context, cancellationToken); /// diff --git a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs index 49c77935..60fa5ae6 100644 --- a/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs +++ b/src/AgentCore.Application/Runtime/Harness/HarnessSessionState.cs @@ -37,12 +37,9 @@ public static IReadOnlyDictionary Capture(AgentSession? ses var serialized = session.StateBag.Serialize(); Dictionary providers = new(StringComparer.Ordinal); - foreach (var property in serialized.EnumerateObject()) + foreach (var property in serialized.EnumerateObject().Where(property => keys.Contains(property.Name))) { - if (keys.Contains(property.Name)) - { - providers[property.Name] = property.Value.Clone(); - } + providers[property.Name] = property.Value.Clone(); } return providers.Count == 0 ? Empty : providers; diff --git a/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs b/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs index 6d7e08f0..d3721a1e 100644 --- a/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs +++ b/src/AgentCore.Application/Runtime/ModelFacingChatClient.cs @@ -8,19 +8,19 @@ namespace AgentCore.Application.Runtime; internal sealed class ModelFacingChatClient(IChatClient inner) : DelegatingChatClient(inner) { public override async Task GetResponseAsync( - IEnumerable messages, ChatOptions? options = null, CancellationToken ct = default) + IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) { using var _ = KeyHider.Hide(options); - return await base.GetResponseAsync(Strip(messages), options, ct).ConfigureAwait(false); + return await base.GetResponseAsync(Strip(messages), options, cancellationToken).ConfigureAwait(false); } public override async IAsyncEnumerable GetStreamingResponseAsync( IEnumerable messages, ChatOptions? options = null, - [EnumeratorCancellation] CancellationToken ct = default) + [EnumeratorCancellation] CancellationToken cancellationToken = default) { using var _ = KeyHider.Hide(options); - await foreach (var update in base.GetStreamingResponseAsync(Strip(messages), options, ct).ConfigureAwait(false)) + await foreach (var update in base.GetStreamingResponseAsync(Strip(messages), options, cancellationToken).ConfigureAwait(false)) { yield return update; } diff --git a/src/AgentCore.Application/Runtime/ModerationAgent.cs b/src/AgentCore.Application/Runtime/ModerationAgent.cs index 0e588466..6484465a 100644 --- a/src/AgentCore.Application/Runtime/ModerationAgent.cs +++ b/src/AgentCore.Application/Runtime/ModerationAgent.cs @@ -36,7 +36,7 @@ public ModerationAgent(AIAgent inner, PromptModerator moderator, string refusalR /// protected override async Task RunCoreAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { @@ -58,14 +58,24 @@ protected override async Task RunCoreAsync( } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(messages); + return RunCoreStreamingCoreAsync(messages, session, options, cancellationToken); + } + + /// Streams the verdict marker and the run, or the refusal when the caller is flagged. + private async IAsyncEnumerable RunCoreStreamingCoreAsync( + IEnumerable messages, + AgentSession? session, + AgentRunOptions? options, + [EnumeratorCancellation] CancellationToken cancellationToken) + { var verdict = await JudgeAsync(messages, cancellationToken).ConfigureAwait(false); if (verdict.Moderation is ModerationOutcome.Flagged) { diff --git a/src/AgentCore.Application/Runtime/RequireOutputAgent.cs b/src/AgentCore.Application/Runtime/RequireOutputAgent.cs index d0e5cd3d..5d936bf1 100644 --- a/src/AgentCore.Application/Runtime/RequireOutputAgent.cs +++ b/src/AgentCore.Application/Runtime/RequireOutputAgent.cs @@ -34,7 +34,7 @@ public RequireOutputAgent(AIAgent inner, string name) /// protected override async Task RunCoreAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { @@ -47,7 +47,7 @@ protected override async Task RunCoreAsync( /// protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, - AgentSession? session, + AgentSession? session = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { diff --git a/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs b/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs index 5685d9ec..038760a8 100644 --- a/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs +++ b/src/AgentCore.Application/Runtime/Turn/TurnRegistry.cs @@ -6,13 +6,13 @@ namespace AgentCore.Application.Runtime.Turn; // The turn running on one session, keyed by the session the framework hands providers — // the MAF AgentSession.StateBag shape, but live: the bag serializes and a turn holds // sessions and tools, so the table carries what the bag cannot. The loop files the turn -// under the session the run actually gets (a graph row re-creates its own per turn); -// providers read it back off the session their InvokingContext carries. Weak keys: an +// under the session the run actually gets, since a graph row re-creates its own per turn. +// Providers read it back off the session their InvokingContext carries. Weak keys: an // entry dies with its session, and each turn overwrites the last, so nothing here leaks // or crosses turns. internal static class TurnRegistry { - private static readonly ConditionalWeakTable Turns = new(); + private static readonly ConditionalWeakTable Turns = []; /// Files the turn running on one session. /// The session the run actually gets. diff --git a/src/AgentCore.Application/State/StateDocument.cs b/src/AgentCore.Application/State/StateDocument.cs index 424c8eed..29d2a71f 100644 --- a/src/AgentCore.Application/State/StateDocument.cs +++ b/src/AgentCore.Application/State/StateDocument.cs @@ -135,15 +135,7 @@ private static bool IsMember(IReadOnlyList members, JsonNode? value) { var written = value?.ToJsonString(); - foreach (var member in members) - { - if (string.Equals(member.ToJsonString(), written, StringComparison.Ordinal)) - { - return true; - } - } - - return false; + return members.Any(member => string.Equals(member.ToJsonString(), written, StringComparison.Ordinal)); } /// Takes a snapshot the guards read. It holds every declared slot and the three reserved slots. diff --git a/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs b/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs index 31ef9c0c..211e634d 100644 --- a/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs +++ b/src/AgentCore.Application/Tools/Builtin/BuiltinToolSource.cs @@ -98,7 +98,14 @@ internal static ConfigurationLoadException Unbound(ToolConfiguration tool, strin /// The declaration the document holds. /// The key, or when the declaration sets neither. private static string? UnreadDial(ToolConfiguration tool) - => tool.Model is not null ? "model:" : tool.MaxRounds is not null ? "maxRounds:" : null; + { + if (tool.Model is not null) + { + return "model:"; + } + + return tool.MaxRounds is not null ? "maxRounds:" : null; + } private static ConfigurationLoadException UnknownName(ToolConfiguration tool) => ToolSourceError.Fail( diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingData.cs b/src/AgentCore.Application/Tools/Drawing/DrawingData.cs index ca669ac2..a6fb3a0c 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingData.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingData.cs @@ -80,21 +80,9 @@ JsonArray list when list.All(item => item is JsonObject) }; private static string Fields(IEnumerable items) - { - List names = []; - foreach (var item in items) - { - foreach (var pair in item) - { - if (!names.Contains(pair.Key, StringComparer.Ordinal)) - { - names.Add(pair.Key); - } - } - } - - return string.Join(", ", names); - } + => string.Join(", ", items + .SelectMany(static item => item.Select(static pair => pair.Key)) + .Distinct(StringComparer.Ordinal)); private static string Sample(JsonNode? node, int depth) { diff --git a/src/AgentCore.Application/Tools/Drawing/DrawingReceipt.cs b/src/AgentCore.Application/Tools/Drawing/DrawingReceipt.cs index 97e9faaf..d7b5dbec 100644 --- a/src/AgentCore.Application/Tools/Drawing/DrawingReceipt.cs +++ b/src/AgentCore.Application/Tools/Drawing/DrawingReceipt.cs @@ -54,12 +54,9 @@ private static void Collect(JsonNode? node, List actions) actions.Add(payload.Length == 0 ? type : $"{type} {payload}"); } - foreach (var pair in item) + foreach (var pair in item.Where(pair => !string.Equals(pair.Key, "$action", StringComparison.Ordinal))) { - if (!string.Equals(pair.Key, "$action", StringComparison.Ordinal)) - { - Collect(pair.Value, actions); - } + Collect(pair.Value, actions); } return; diff --git a/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs b/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs index 7ce8a209..b758e47b 100644 --- a/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs +++ b/src/AgentCore.Application/Tools/Registry/ToolRegistryBuilder.cs @@ -32,7 +32,10 @@ public static async ValueTask BuildAsync( foreach (var source in sources) { - ArgumentNullException.ThrowIfNull(source, nameof(sources)); + if (source is null) + { + throw new ArgumentNullException(nameof(sources)); + } var registrations = await source.ProvideAsync(context, cancellationToken).ConfigureAwait(false); foreach (var registration in registrations) diff --git a/src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs b/src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs index 0dbd89e8..f2c5b6e1 100644 --- a/src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs +++ b/src/AgentCore.AspNetCore/Call/JsonWebSocketPump.cs @@ -168,7 +168,7 @@ public async Task ReadLoopAsync(FrameParser parse, Func dispatch) // now instead of leaving one pending per message for as long as a busy call keeps // sending faster than IdleTimeout — CancelAfter is never involved, so this touches // nothing outside this one local source. - idleCancel.Cancel(); + await idleCancel.CancelAsync().ConfigureAwait(false); result = await receiving.ConfigureAwait(false); // The rest of one message, however many more fragments the vendor chose. A loop @@ -305,7 +305,7 @@ public async Task WriteLoopAsync(ChannelReader reader, FuncThe error type every failure of this endpoint reports. + private const string InvalidRequestError = "invalid_request_error"; + /// Maps the endpoint on . /// The route builder of the host. /// The mapped endpoint, so a host adds its own conventions. @@ -74,7 +77,7 @@ await WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the request body is not well-formed JSON: " + exception.Message, - "invalid_request_error", + InvalidRequestError, "malformed_body", cancellationToken).ConfigureAwait(false); return; @@ -96,7 +99,7 @@ await 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; @@ -108,7 +111,7 @@ await WriteErrorAsync( http, StatusCodes.Status400BadRequest, "the approval answer names no request.", - "invalid_request_error", + InvalidRequestError, "missing_request_id", cancellationToken).ConfigureAwait(false); return; @@ -121,7 +124,7 @@ await WriteErrorAsync( StatusCodes.Status400BadRequest, "an approval answer names the call it resumes. Send it with the " + SessionHeaderName + " header the request arrived with.", - "invalid_request_error", + InvalidRequestError, "missing_session", cancellationToken).ConfigureAwait(false); return; @@ -134,7 +137,7 @@ await WriteErrorAsync( StatusCodes.Status404NotFound, $"no call named '{named}' is open on this host. Send the request with no " + SessionHeaderName + " header to start one.", - "invalid_request_error", + InvalidRequestError, "session_not_found", cancellationToken).ConfigureAwait(false); return; @@ -148,7 +151,7 @@ await WriteErrorAsync( StatusCodes.Status409Conflict, $"the call '{named}' 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; @@ -164,7 +167,7 @@ await 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; @@ -179,7 +182,7 @@ await WriteErrorAsync( StatusCodes.Status404NotFound, $"no call named '{named}' is open on this host. Send the request with no " + SessionHeaderName + " header to start one.", - "invalid_request_error", + InvalidRequestError, "session_not_found", cancellationToken).ConfigureAwait(false); return; @@ -198,8 +201,8 @@ await WriteErrorAsync( var streaming = request?.Stream == true; // Only the stream has a chunk 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; - // with none bound it answers that it cannot draw. Set per request, not once: the session + // one on the whole-reply branch would let the tool report a picture the caller never sees. + // With none bound it answers that it cannot draw. Set per request, not once: the session // outlives a request and the branch can differ per turn. session.SetHasScreen(streaming); @@ -231,7 +234,7 @@ await WriteErrorAsync( http, StatusCodes.Status409Conflict, exception.Message, - "invalid_request_error", + InvalidRequestError, "turn_refused", cancellationToken).ConfigureAwait(false); } diff --git a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs index 46f4bda0..9722c23a 100644 --- a/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs +++ b/src/AgentCore.AspNetCore/Vendors/TelnyxRelay/TelnyxRelayConnection.cs @@ -86,6 +86,8 @@ internal sealed class TelnyxRelayConnection : ICallInputPort, ICallOutputPort private volatile CallSession? _session; + private const string BeforeSetupCallId = "(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; @@ -128,7 +130,7 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt // 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 ?? "(before setup)", + () => _session?.CallId ?? BeforeSetupCallId, (callId, taskName) => TelnyxRelayLog.TeardownTimedOut(_logger, callId, taskName), (kind, callId, fault) => LogFault(kind, callId, fault), ClassifyTelnyxFault); @@ -147,9 +149,9 @@ private TelnyxRelayConnection(HttpContext http, WebSocket socket, TelnyxRelayOpt _options.IdleTimeout, _options.CloseTimeout, (status, message) => new RelayProtocolException(status, message), - frameType => TelnyxRelayLog.UnknownFrameType(_logger, frameType, _session?.CallId ?? "(before setup)"), - frameType => TelnyxRelayLog.FrameBodyRefused(_logger, frameType, _session?.CallId ?? "(before setup)"), - () => TelnyxRelayLog.IdleTimeoutReached(_logger, _session?.CallId ?? "(before setup)")), + frameType => TelnyxRelayLog.UnknownFrameType(_logger, frameType, _session?.CallId ?? BeforeSetupCallId), + frameType => TelnyxRelayLog.FrameBodyRefused(_logger, frameType, _session?.CallId ?? BeforeSetupCallId), + () => TelnyxRelayLog.IdleTimeoutReached(_logger, _session?.CallId ?? BeforeSetupCallId)), timeProvider, _connectionToken); } @@ -197,13 +199,13 @@ private async Task RunAsync() // otherwise strand this call in the store for the life of the process. try { - _cancellation.Cancel(); + await _cancellation.CancelAsync().ConfigureAwait(false); } catch (Exception fault) { ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.CancellationFaulted( _logger, - _session?.CallId ?? "(before setup)", + _session?.CallId ?? BeforeSetupCallId, fault)); } @@ -260,7 +262,7 @@ private async Task RunAsync() { ConnectionTaskObserver.SafeLog(() => TelnyxRelayLog.CloseFaulted( _logger, - _session?.CallId ?? "(before setup)", + _session?.CallId ?? BeforeSetupCallId, fault)); } @@ -531,7 +533,6 @@ private void LogFault(ConnectionTaskKind kind, string callId, Exception fault) TelnyxRelayLog.CallCloseFaulted(_logger, callId, fault); break; - case ConnectionTaskKind.ReadLoop: default: TelnyxRelayLog.ReadLoopFaulted(_logger, callId, fault); break; @@ -633,7 +634,7 @@ 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 ?? "(before setup)", error.Description); + TelnyxRelayLog.FrameRefused(_logger, _session?.CallId ?? BeforeSetupCallId, error.Description); break; } } @@ -826,6 +827,7 @@ public ValueTask StopAsync(CancellationToken cancellationToken = default) while (_outbound.Reader.TryRead(out _)) { + // Drained, never sent: the barge-in above already cut off everything still queued. } return ValueTask.CompletedTask; diff --git a/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs b/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs index bb7ed519..0d974701 100644 --- a/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs +++ b/src/AgentCore.Domain/Audit/AuditEventVocabulary.cs @@ -32,6 +32,40 @@ public static void Validate(AuditEvent auditEvent) nameof(auditEvent)); } + RequireReplyInterrupted(auditEvent); + + if (auditEvent.Payload.TryGetValue(AuditPayloadKeys.ReplyTextSha256, out string? replyText)) + { + // 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); + } + + RequirePromptFlagged(auditEvent); + + RequireCallEnded(auditEvent); + + foreach (KeyValuePair entry in auditEvent.Payload) + { + if (string.IsNullOrEmpty(entry.Key)) + { + throw new ArgumentException("An audit payload key is not empty.", nameof(auditEvent)); + } + + if (entry.Value is null) + { + throw new ArgumentException( + $"The audit payload value of '{entry.Key}' is null. A missing fact is an absent key.", + nameof(auditEvent)); + } + } + } + + + /// Refuses a barge-in that names no turn, or proves no heard text. + private static void RequireReplyInterrupted(AuditEvent auditEvent) + { if (auditEvent.Kind == AuditEventKind.ReplyInterrupted) { // T23: the chain is append-only, so a barge-in is a second event that references the @@ -54,59 +88,42 @@ public static void Validate(AuditEvent auditEvent) RequireHash(auditEvent, AuditPayloadKeys.UtteranceUntilInterruptSha256, utterance); } + } - if (auditEvent.Payload.TryGetValue(AuditPayloadKeys.ReplyTextSha256, out string? replyText)) - { - // 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); - } - if (auditEvent.Kind == AuditEventKind.PromptFlagged) + /// Refuses a flag verdict that carries no categories. + private static void RequirePromptFlagged(AuditEvent auditEvent) + { + // §9 makes this chain the only long-term record. The kind alone says something flagged + // the caller, and the categories are the only other fact the event carries, so the fact + // goes in with the event or it is lost. This is the argument the chain already makes for + // utteranceUntilInterrupt above. No AmendsEventId rule stands here: the verdict is known + // BEFORE the model runs, so the event is written before the turn.completed event of the + // same turn and amends nothing. TurnIndex names the turn. + if (auditEvent.Kind == AuditEventKind.PromptFlagged + && (!auditEvent.Payload.TryGetValue(AuditPayloadKeys.ModerationCategories, out string? categories) + || !IsCommaSeparatedListWithNoEmptyMember(categories))) { - // §9 makes this chain the only long-term record. The kind alone says something flagged - // the caller, and the categories are the only other fact the event carries, so the fact - // goes in with the event or it is lost. This is the argument the chain already makes for - // utteranceUntilInterrupt above. No AmendsEventId rule stands here: the verdict is known - // BEFORE the model runs, so the event is written before the turn.completed event of the - // same turn and amends nothing. TurnIndex names the turn. - if (!auditEvent.Payload.TryGetValue(AuditPayloadKeys.ModerationCategories, out string? categories) - || !IsCommaSeparatedListWithNoEmptyMember(categories)) - { - throw new ArgumentException( - $"A prompt.flagged event carries '{AuditPayloadKeys.ModerationCategories}', a comma-separated list with no empty member. See section 11, item 11.", - nameof(auditEvent)); - } + throw new ArgumentException( + $"A prompt.flagged event carries '{AuditPayloadKeys.ModerationCategories}', a comma-separated list with no empty member. See section 11, item 11.", + nameof(auditEvent)); } + } - if (auditEvent.Kind == AuditEventKind.CallEnded) - { - // 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.Payload.TryGetValue(AuditPayloadKeys.EndReason, out string? endReason) - || !CallEndReasons.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.", - nameof(auditEvent)); - } - } - foreach (KeyValuePair entry in auditEvent.Payload) + /// Refuses a call end that carries no reason from the closed set. + private static void RequireCallEnded(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 + && (!auditEvent.Payload.TryGetValue(AuditPayloadKeys.EndReason, out string? endReason) + || !CallEndReasons.TryParse(endReason, out _))) { - if (string.IsNullOrEmpty(entry.Key)) - { - throw new ArgumentException("An audit payload key is not empty.", nameof(auditEvent)); - } - - if (entry.Value is null) - { - throw new ArgumentException( - $"The audit payload value of '{entry.Key}' is null. A missing fact is an absent key.", - nameof(auditEvent)); - } + throw new ArgumentException( + $"A call.ended event carries '{AuditPayloadKeys.EndReason}', and the value is one token of the closed set. See CallEndReason.", + nameof(auditEvent)); } } diff --git a/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs b/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs index 20c8bd2a..d49e0e0d 100644 --- a/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs +++ b/src/AgentCore.Infrastructure/Audit/Postgres/PostgresAuditSink.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.Json; using AgentCore.Application.Ports; @@ -106,6 +107,10 @@ public async ValueTask AppendManyAsync( /// A task that completes when the pool is closed. public ValueTask DisposeAsync() => _dataSource.DisposeAsync(); + [SuppressMessage( + "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) { NpgsqlBatchCommand command = new(AppendSql); diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs index c37d34a7..af6ab72f 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Text.Json; using AgentCore.Application.Calls; using AgentCore.Application.Ports; @@ -227,6 +228,10 @@ private async ValueTask AmendAsync( } /// + [SuppressMessage( + "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, diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs index 39d70446..43797ef3 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapter.cs @@ -465,15 +465,20 @@ private IKnowledgeQueryAnalyzer ResolveAnalyzer(string name) /// Picks the mapper the document named, or for the built-in fields: mapping. /// No registered mapper answers to that name. private IKnowledgePointMapper? ResolveMapper(string? name) - => name is not { Length: > 0 } - ? null - : _mappers.FirstOrDefault(mapper => string.Equals(mapper.Name, name, StringComparison.Ordinal)) - ?? throw Fail( - "/providers/knowledge/mapper", - $"providers.knowledge.mapper is '{name}', and no registered IKnowledgePointMapper " - + $"answers to it. This host registers " - + $"{(_mappers.Length == 0 ? "none" : string.Join(", ", _mappers.Select(m => $"'{m.Name}'")))}. " - + "Register one with QdrantKnowledgeAdapter.UseMappers, or drop the setting."); + { + if (name is not { Length: > 0 }) + { + return null; + } + + return _mappers.FirstOrDefault(mapper => string.Equals(mapper.Name, name, StringComparison.Ordinal)) + ?? throw Fail( + "/providers/knowledge/mapper", + $"providers.knowledge.mapper is '{name}', and no registered IKnowledgePointMapper " + + $"answers to it. This host registers " + + $"{(_mappers.Length == 0 ? "none" : string.Join(", ", _mappers.Select(m => $"'{m.Name}'")))}. " + + "Register one with QdrantKnowledgeAdapter.UseMappers, or drop the setting."); + } /// Parses the endpoint and resolves the API key, then builds the production client. private static async ValueTask BuildClientAsync( diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs index 22bf82aa..dffd31cb 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs @@ -74,33 +74,43 @@ public QdrantKnowledgeStore( /// public void Dispose() => (_channel as IDisposable)?.Dispose(); - public async ValueTask> SearchAsync( - string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) + /// Refuses an unscoped search when this deployment scopes every query. + /// The scope the search arrived with, or for none. + /// The search is unscoped, or its scope names no facets. + private void RequireScope(KnowledgeScope? scope) { - ArgumentNullException.ThrowIfNull(query); + if (!_options.Scoped) + { + return; + } - if (_options.Scoped) + // Two different host bugs, so two different messages. An empty facet map filters + // nothing, which is the same leak as no scope at all: a host that reads a customer + // record with no product on it builds one without noticing. + if (scope is null) { - // Two different host bugs, so two different messages. An empty facet map filters - // nothing, which is the same leak as no scope at all: a host that reads a customer - // record with no product on it builds one without noticing. - if (scope is null) - { - throw new InvalidOperationException( - "This deployment declares scoped: true and the search arrived without a KnowledgeScope. " - + "An unscoped search serves every customer every card, so it fails instead. Pass the " - + "scope to SearchAsync, or set scoped: false on the agent."); - } + throw new InvalidOperationException( + "This deployment declares scoped: true and the search arrived without a KnowledgeScope. " + + "An unscoped search serves every customer every card, so it fails instead. Pass the " + + "scope to SearchAsync, or set scoped: false on the agent."); + } - if (scope.Facets.Count == 0) - { - throw new InvalidOperationException( - "This deployment declares scoped: true and the open KnowledgeScope names no facets. " - + "An empty facet map filters nothing, so the search would serve every customer every " - + "card, and it fails instead. Give the scope the facets the customer record names, " - + "or set scoped: false on the agent."); - } + if (scope.Facets.Count == 0) + { + throw new InvalidOperationException( + "This deployment declares scoped: true and the open KnowledgeScope names no facets. " + + "An empty facet map filters nothing, so the search would serve every customer every " + + "card, and it fails instead. Give the scope the facets the customer record names, " + + "or set scoped: false on the agent."); } + } + + public async ValueTask> SearchAsync( + string query, KnowledgeScope? scope = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + + RequireScope(scope); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(_options.Deadline); diff --git a/src/AgentCore.Infrastructure/Secrets/ChainedSecretResolver.cs b/src/AgentCore.Infrastructure/Secrets/ChainedSecretResolver.cs index aa94fc3a..cf5dcc79 100644 --- a/src/AgentCore.Infrastructure/Secrets/ChainedSecretResolver.cs +++ b/src/AgentCore.Infrastructure/Secrets/ChainedSecretResolver.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using AgentCore.Application.Ports; using AgentCore.Application.Secrets; @@ -29,6 +30,10 @@ public sealed class ChainedSecretResolver : ISecretResolverPort /// Creates the chain. /// The resolvers, in the order the chain asks them. + [SuppressMessage( + "csharpsquid", + "S3236", + Justification = "The name identifies the validated constructor parameter, not the loop variable; it carries no caller information.")] public ChainedSecretResolver(IEnumerable links) { ArgumentNullException.ThrowIfNull(links); diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs index b8c7a84f..98cc8cb4 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpServerSession.cs @@ -273,7 +273,6 @@ private async ValueTask> ConnectAndListAsync(Ca { client = opened = await _connect(timeout, deadline.Token).ConfigureAwait(false); offered = await client.ListToolsAsync(cancellationToken: deadline.Token).ConfigureAwait(false); - opened = null; } catch (OperationCanceledException) when (deadline.IsCancellationRequested && !cancellationToken.IsCancellationRequested) { diff --git a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs index 595a0974..3c3bb28f 100644 --- a/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs +++ b/src/AgentCore.Infrastructure/Tools/Mcp/McpTool.cs @@ -82,15 +82,12 @@ public McpTool(McpServerSession session, McpToolDescriptor descriptor, string id // residue rather than model intent: the filed turn carries delegates no JSON // writer can hold. A schema that names no properties keeps the old passthrough. var outgoing = arguments; - if (_declared is not null) + if (_declared is { } declared) { outgoing = new AIFunctionArguments(); - foreach (var entry in arguments) + foreach (var entry in arguments.Where(candidate => declared.Contains(candidate.Key))) { - if (_declared.Contains(entry.Key)) - { - outgoing[entry.Key] = entry.Value; - } + outgoing[entry.Key] = entry.Value; } } diff --git a/src/AgentCore.Infrastructure/Tools/McpToolSource.cs b/src/AgentCore.Infrastructure/Tools/McpToolSource.cs index 2b5ac84c..5e693e85 100644 --- a/src/AgentCore.Infrastructure/Tools/McpToolSource.cs +++ b/src/AgentCore.Infrastructure/Tools/McpToolSource.cs @@ -134,6 +134,7 @@ public async ValueTask DisposeAsync() } catch { + // One server's failure to close must not abandon the rest. } } diff --git a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs index 30956825..0832ecfd 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs @@ -227,7 +227,7 @@ private static async Task SearchToolAsync( TestContext.Current.CancellationToken); #pragma warning restore MAAI001 - return Assert.IsAssignableFrom(Assert.Single(context.Tools!)); + return Assert.IsType(Assert.Single(context.Tools!), exactMatch: false); } private static async Task CallAsync( diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs index ef54db04..b296b765 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs @@ -95,7 +95,7 @@ public void CardEntry_CardWithNoAuthorityOrSource_RecordsNulls() { var card = new KnowledgeCard { CardId = "plain-01", Text = "a card", ViaLink = false }; - var entry = KnowledgeAuditRecord.CardEntry.For(card); + var entry = KnowledgeAuditRecord.CardEntry.From(card); Assert.Equal("plain-01", entry.CardId); Assert.Null(entry.Authority); diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs index 04b6ab21..5d12b530 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProviderFactoryTests.cs @@ -100,7 +100,7 @@ public async Task Create_TheStoresOwnDeadlineFires_InjectsTheNoticeAndWritesTheC var line = Assert.Single(loggers.Of(12)); Assert.Equal(LogLevel.Error, line.Level); Assert.Equal("resolver", line.Field("Agent")); - Assert.IsAssignableFrom(line.Exception); + Assert.IsType(line.Exception, exactMatch: false); } [Fact] diff --git a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs index 55dd3110..38e1f0ff 100644 --- a/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/AuditingFunctionInvokingChatClientErrorPolicyTests.cs @@ -190,7 +190,7 @@ public async Task ARealBindingTool_GetsTheSameErrorResultThroughTheRealMiddlewar var registrations = await source.ProvideAsync( new ToolSourceContext(new AgentCoreConfiguration { ApiVersion = "agentcore/v1", Name = "test", Tools = [createCase] }), TestContext.Current.CancellationToken); - var tool = Assert.IsAssignableFrom(Assert.Single(registrations).Materialise()); + var tool = Assert.IsType(Assert.Single(registrations).Materialise(), exactMatch: false); var result = await RunSingleRoundAsync(tool, TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs index 5245ffe4..4b6f29b5 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionTests.cs @@ -987,7 +987,7 @@ public async Task TheSession_SatisfiesTheInboundPort() { using SequencedChatClient reply = new("hello there.", "still here."); using SequencedChatClient fill = new(StayingNull); - var port = Assert.IsAssignableFrom(Build(PolicyYaml, reply, fill).Create("call-9")); + var port = Assert.IsType(Build(PolicyYaml, reply, fill).Create("call-9"), exactMatch: false); var turn = await port.RunTurnAsync("hi", TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs b/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs index 7ab05318..84b93379 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CappedToolCallFormatterTests.cs @@ -69,7 +69,7 @@ public void Create_TwoResultsShareOneCallId_RendersTheLastOneWithoutThrowing() // through. Passing a null tokenizer is fine — AddGroup falls back to an estimate, and this // formatter never reads TokenCount. private static CompactionMessageGroup Group(CompactionGroupKind kind, IReadOnlyList messages) => - new CompactionMessageIndex(new List(), null!).AddGroup(kind, messages, turnIndex: null); + new CompactionMessageIndex([], null!).AddGroup(kind, messages, turnIndex: null); private static CompactionMessageGroup Group(string tool, string result) => Group( CompactionGroupKind.ToolCall, diff --git a/tests/AgentCore.Application.Tests/Runtime/ModelFacingChatClientTests.cs b/tests/AgentCore.Application.Tests/Runtime/ModelFacingChatClientTests.cs index 506e0142..a853971e 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ModelFacingChatClientTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ModelFacingChatClientTests.cs @@ -27,7 +27,7 @@ public async Task GetResponseAsync_StripsRenderContentBeforeTheInnerClientSeesIt new RenderContent { Name = "order-card", RenderId = "order-41", Data = Payload }, ]); - await client.GetResponseAsync([drew], ct: TestContext.Current.CancellationToken); + await client.GetResponseAsync([drew], cancellationToken: TestContext.Current.CancellationToken); var forwarded = Assert.Single(inner.Requests); var message = Assert.Single(forwarded); @@ -47,7 +47,7 @@ public async Task GetStreamingResponseAsync_StripsRenderContentBeforeTheInnerCli ]); await foreach (var _ in client.GetStreamingResponseAsync( - [drew], ct: TestContext.Current.CancellationToken)) + [drew], cancellationToken: TestContext.Current.CancellationToken)) { } @@ -63,7 +63,7 @@ public async Task GetResponseAsync_PassesAMessageWithNoRenderContentThroughByRef var client = new ModelFacingChatClient(inner); var plain = new ChatMessage(ChatRole.User, "hello"); - await client.GetResponseAsync([plain], ct: TestContext.Current.CancellationToken); + await client.GetResponseAsync([plain], cancellationToken: TestContext.Current.CancellationToken); var forwarded = Assert.Single(inner.Requests); Assert.Same(plain, Assert.Single(forwarded)); @@ -77,7 +77,7 @@ public async Task GetStreamingResponseAsync_PassesAMessageWithNoRenderContentThr var plain = new ChatMessage(ChatRole.User, "hello"); await foreach (var _ in client.GetStreamingResponseAsync( - [plain], ct: TestContext.Current.CancellationToken)) + [plain], cancellationToken: TestContext.Current.CancellationToken)) { } @@ -101,7 +101,7 @@ public async Task GetResponseAsync_RebuiltMessageCarriesAdditionalPropertiesAndI AdditionalProperties = new AdditionalPropertiesDictionary { ["k"] = "v" }, }; - await client.GetResponseAsync([drew], ct: TestContext.Current.CancellationToken); + await client.GetResponseAsync([drew], cancellationToken: TestContext.Current.CancellationToken); var forwarded = Assert.Single(Assert.Single(inner.Requests)); Assert.Equal("msg-1", forwarded.MessageId); diff --git a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs index ddebd420..fe27687a 100644 --- a/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/Turn/TurnResultsTests.cs @@ -86,13 +86,13 @@ public void AnUnstructuredResult_IsNotRecorded(object? result) Assert.Null(results.Data()["tool"]); } - public static TheoryData UnstructuredResults => new() - { + public static TheoryData UnstructuredResults => + [ (object?)null, "Order SO-1 shipped on Tuesday.", 42, ToolErrorResult.Create("tool", "it failed."), - }; + ]; [Fact] public async Task AnOutermostToolCall_IsRecordedUnderTheToolsName() diff --git a/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs index 9df35164..e64a6b4b 100644 --- a/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/BindingToolTests.cs @@ -143,7 +143,7 @@ public async Task TheDeclaredSchema_ReachesTheModelUnchanged() ToolBindingRegistry registry = new(); registry.Register("CreateCase", (arguments, cancellationToken) => ValueTask.FromResult(null)); - var function = Assert.IsAssignableFrom(await CreateAsync(registry, CreateCase)); + var function = Assert.IsType(await CreateAsync(registry, CreateCase), exactMatch: false); Assert.Equal("create_case", function.Name); Assert.Equal("Open a service case for a human agent.", function.Description); @@ -205,7 +205,7 @@ public async Task TheBindingSource_ServesNoOtherKind() private static async Task CallAsync(AITool? tool, params (string Name, object? Value)[] arguments) { - var function = Assert.IsAssignableFrom(tool); + var function = Assert.IsType(tool, exactMatch: false); Dictionary values = new(StringComparer.Ordinal); foreach (var argument in arguments) diff --git a/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs b/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs index 978ca588..08b3d18e 100644 --- a/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DeclaredToolTests.cs @@ -61,7 +61,7 @@ public async Task AnyFaultTheBodyThrows_PropagatesUnfiltered(Exception failure) { var thrown = await Assert.ThrowsAnyAsync( async () => await new ThrowingTool(failure).InvokeAsync( - new AIFunctionArguments(), + [], TestContext.Current.CancellationToken)); // The very exception, and not a copy: InvokeCoreAsync no longer catches, so this is a plain @@ -79,7 +79,7 @@ public async Task ACallerThatHungUp_StillPassesTheCancellationThrough() // Nobody reads this result, and swallowing it would keep a dead call running. await Assert.ThrowsAnyAsync( async () => await new ThrowingTool(new OperationCanceledException()).InvokeAsync( - new AIFunctionArguments(), + [], source.Token)); } @@ -94,7 +94,7 @@ public async Task ATimeoutThatIsNotTheCallersCancellation_IsRethrownAndNotSwallo var thrown = await Assert.ThrowsAnyAsync( async () => await new ThrowingTool(timeout).InvokeAsync( - new AIFunctionArguments(), + [], TestContext.Current.CancellationToken)); Assert.Same(timeout, thrown); @@ -106,7 +106,7 @@ public async Task ABodyThatAnswersItself_StillReturnsTheErrorResultDirectly() // The one half of the old rule that still lives here: a tool body may choose to answer a // fault itself, without throwing at all, exactly as a builtin tool definition does today. var result = await new SelfAnsweringTool().InvokeAsync( - new AIFunctionArguments(), + [], TestContext.Current.CancellationToken); Assert.True(ToolErrorResult.IsError(result as System.Text.Json.Nodes.JsonNode)); diff --git a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs index ed91e526..50355b82 100644 --- a/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/DrawingAgentTests.cs @@ -89,7 +89,7 @@ public async Task ADrawingAgent_ThatCallsPresentWithAValidTree_PublishesToTheScr var function = Build(new RecordingChatClientFactory(new PresentCallingChatClient(Card))); - var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }); + var arguments = new AIFunctionArguments { ["query"] = "draw a card" }; arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, }; var result = await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); @@ -158,7 +158,7 @@ public async Task TheSource_BuildsDraw_OnTheModelTheDocumentNames() var registration = await Provide(Declaration with { Model = new ModelReference { Ref = "cheap" } }, factory); - Assert.IsAssignableFrom(registration.Materialise()); + Assert.IsType(registration.Materialise(), exactMatch: false); Assert.Equal("cheap", factory.Asked!.Ref); } @@ -166,7 +166,7 @@ public async Task TheSource_BuildsDraw_OnTheModelTheDocumentNames() public async Task TheSource_WithNoDeclaredDescription_TakesTheShippedDefaultOnBothSides() { var registration = await Provide(Declaration with { Description = null }, new RecordingChatClientFactory()); - var function = Assert.IsAssignableFrom(registration.Materialise()); + var function = Assert.IsType(registration.Materialise(), exactMatch: false); // One string, resolved once: what the boot validates and what the model reads cannot differ. Assert.Equal(new DrawingAgentDefinition().DefaultDescription, registration.Description); @@ -205,7 +205,7 @@ public async Task TheDrawingModel_IsToldWhatThisTurnsToolsAnswered_AfterTheReque var function = Build(new RecordingChatClientFactory(model)); - var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "a table of the lookup_orders result" }); + var arguments = new AIFunctionArguments { ["query"] = "a table of the lookup_orders result" }; arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, Results = results, }; await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); @@ -224,7 +224,7 @@ public async Task WithNothingAnswered_TheRequestGoesThroughUntouched() var function = Build(new RecordingChatClientFactory(model)); - var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }); + var arguments = new AIFunctionArguments { ["query"] = "draw a card" }; arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, Results = new TurnResults(), }; await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); @@ -289,9 +289,9 @@ public void TheVocabulary_TeachesEveryComponentTheValidatorAllows() var registration = await Provide( Declaration, new RecordingChatClientFactory(new PresentCallingChatClient(trees))); - var function = Assert.IsAssignableFrom(registration.Materialise()); + var function = Assert.IsType(registration.Materialise(), exactMatch: false); - var arguments = new AIFunctionArguments(new Dictionary { ["query"] = "draw a card" }); + var arguments = new AIFunctionArguments { ["query"] = "draw a card" }; arguments[TurnInvocation.ArgumentsKey] = new TurnInvocation { CallId = "call", TurnIndex = 0, Stage = "", Screen = screen, }; return await function.InvokeAsync(arguments, TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs index d14e96ba..d169138e 100644 --- a/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TimeLimitedToolTests.cs @@ -24,7 +24,7 @@ public async Task AToolThatAnswersInTime_IsUntouched() { TimeLimitedTool tool = new(Answering("done"), TimeSpan.FromSeconds(30)); - var result = await tool.InvokeAsync(new AIFunctionArguments(), Token); + var result = await tool.InvokeAsync([], Token); Assert.Equal("done", Assert.IsType(result).GetString()); } @@ -34,7 +34,7 @@ public async Task AToolThatRunsLong_ReturnsAnErrorResult_AndDoesNotThrow() { TimeLimitedTool tool = new(Hanging(), TimeSpan.FromMilliseconds(50)); - var result = await tool.InvokeAsync(new AIFunctionArguments(), Token); + var result = await tool.InvokeAsync([], Token); // Section 8.7: the model reads the result and decides what to say next. An exception would // end the turn while a caller is on the line. @@ -56,7 +56,7 @@ public async Task TheTurnBeingCancelled_StillThrows_AndIsNotReportedAsATimeout() await turn.CancelAsync(); await Assert.ThrowsAnyAsync( - async () => await tool.InvokeAsync(new AIFunctionArguments(), turn.Token)); + async () => await tool.InvokeAsync([], turn.Token)); } [Fact] @@ -86,7 +86,7 @@ [new StubSource(new ToolRegistration("slow", "d", Hanging, TimeSpan.FromMillisec new ToolSourceContext(Documents.Empty), Token); - var result = await ((AIFunction)registry.Resolve("slow")).InvokeAsync(new AIFunctionArguments(), Token); + var result = await ((AIFunction)registry.Resolve("slow")).InvokeAsync([], Token); Assert.True(ToolErrorResult.IsError(Assert.IsType(result))); } diff --git a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs index a9373450..d1232256 100644 --- a/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs +++ b/tests/AgentCore.Application.Tests/Tools/TypedBindingToolTests.cs @@ -244,7 +244,7 @@ public async Task ATypedBinding_IsStillADeclaredTool() { var tool = await CreateAsync((string summary) => summary); - Assert.IsAssignableFrom(tool); + Assert.IsType(tool, exactMatch: false); } // --------------------------------------------------------------------------------------------- @@ -293,6 +293,6 @@ private static async Task CreateAsync(Delegate method) var registrations = await new BindingToolSource(bindings).ProvideAsync( ContextFor(OpenCase), TestContext.Current.CancellationToken); - return Assert.IsAssignableFrom(Assert.Single(registrations).Materialise()); + return Assert.IsType(Assert.Single(registrations).Materialise(), exactMatch: false); } } diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs index 9cf812ab..e4946c4e 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeAdapterTests.cs @@ -69,7 +69,7 @@ await Assert.ThrowsAsync( var isDisposed = typeof(QdrantClient) .GetField("_isDisposed", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(captured); - Assert.Equal(true, isDisposed); + Assert.True((bool)isDisposed!); } [QdrantFact] @@ -109,14 +109,14 @@ public async Task CreateSearchAsync_DisposingTheReturnedPort_DisposesTheClient() var isDisposedBeforeCall = typeof(QdrantClient) .GetField("_isDisposed", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(captured); - Assert.Equal(false, isDisposedBeforeCall); + Assert.False((bool)isDisposedBeforeCall!); ((IDisposable)port).Dispose(); var isDisposedAfterCall = typeof(QdrantClient) .GetField("_isDisposed", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(captured); - Assert.Equal(true, isDisposedAfterCall); + Assert.True((bool)isDisposedAfterCall!); } finally { diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantPointConverterTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantPointConverterTests.cs index 479b8a2a..b895d630 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantPointConverterTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantPointConverterTests.cs @@ -34,10 +34,10 @@ public void ToPoint_ConvertsEveryValueKindWithoutALeakedProtobufType() Assert.Equal("text", point.Payload["s"]); Assert.Equal(3L, point.Payload["i"]); Assert.Equal(0.5, point.Payload["d"]); - Assert.Equal(true, point.Payload["b"]); - var nested = Assert.IsAssignableFrom>(point.Payload["nested"]); + Assert.True((bool)point.Payload["b"]!); + var nested = Assert.IsType>(point.Payload["nested"], exactMatch: false); Assert.Equal("deep", nested["inner"]); - var list = Assert.IsAssignableFrom>(point.Payload["list"]); + var list = Assert.IsType>(point.Payload["list"], exactMatch: false); Assert.Equal(["a", 2L], list); } diff --git a/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs b/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs index be703fac..1e31c6c9 100644 --- a/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/ToolSeamTests.cs @@ -106,7 +106,7 @@ public async Task TheWorkedExample_CompilesWithEveryToolBound() Assert.Equal(3, compiled.Agents.Count); // The HTTP tool now makes its call. Before this seam existed it could not. - var lookup = Assert.IsAssignableFrom(registry.Resolve("lookup_order")); + var lookup = Assert.IsType(registry.Resolve("lookup_order"), exactMatch: false); var result = await lookup.InvokeAsync( new AIFunctionArguments(new Dictionary(StringComparer.Ordinal) { ["orderId"] = "A-42" }), diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/InProcessMcpServer.cs b/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/InProcessMcpServer.cs index 6f5c957f..698e1045 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/InProcessMcpServer.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/Fakes/InProcessMcpServer.cs @@ -46,7 +46,7 @@ private InProcessMcpServer(IReadOnlyList<(string Name, string? Description)> too var serverTransport = new StreamServerTransport( clientToServer.Reader.AsStream(), serverToClient.Writer.AsStream()); - var options = new McpServerOptions { ToolCollection = new McpServerPrimitiveCollection() }; + var options = new McpServerOptions { ToolCollection = [] }; foreach (var (name, description) in tools) { options.ToolCollection.Add(McpServerTool.Create( diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs b/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs index 90450f17..8e2d0c1b 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/HttpToolSourceTests.cs @@ -52,7 +52,7 @@ public async Task TheDeclaredSchema_ReachesTheModelUnchanged() using var handler = StubHttpMessageHandler.Answering(HttpStatusCode.OK, "{}"); using HttpClient client = new(handler); - var function = Assert.IsAssignableFrom(await CreateAsync(client, LookupOrder)); + var function = Assert.IsType(await CreateAsync(client, LookupOrder), exactMatch: false); Assert.Equal("lookup_order", function.Name); Assert.Equal("Read one order by its identifier.", function.Description); @@ -113,7 +113,7 @@ public async Task ABodyThatIsNotJson_ComesBackAsText() // The framework carries every tool result as a JSON node, so a text body arrives as a string // value rather than as an object the model would have to unwrap. - Assert.Equal("shipped", Assert.IsAssignableFrom(result).GetValue()); + Assert.Equal("shipped", Assert.IsType(result, exactMatch: false).GetValue()); } // --------------------------------------------------------------------------------------------- @@ -205,7 +205,7 @@ public async Task ACallerThatHangsUp_CancelsAndDoesNotBecomeAnErrorResult() { using var handler = StubHttpMessageHandler.Answering(HttpStatusCode.OK, "{}"); using HttpClient client = new(handler); - var function = Assert.IsAssignableFrom(await CreateAsync(client, LookupOrder)); + var function = Assert.IsType(await CreateAsync(client, LookupOrder), exactMatch: false); using CancellationTokenSource source = new(); await source.CancelAsync(); @@ -290,7 +290,7 @@ private static AIFunctionArguments Arguments(params (string Name, object? Value) private static async Task CallAsync(AITool? tool, params (string Name, object? Value)[] arguments) { - var function = Assert.IsAssignableFrom(tool); + var function = Assert.IsType(tool, exactMatch: false); return await function.InvokeAsync(Arguments(arguments), Token); } diff --git a/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs b/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs index affd0cb3..76d78354 100644 --- a/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Tools/McpServerSessionTests.cs @@ -147,7 +147,7 @@ public async Task AToolStillWorks_AfterTheServerItWasDiscoveredOnHasDied() // The tool object was built while the first connection was alive, and is never rebuilt. await fake.KillNewestConnectionAsync(); - var result = await tool.InvokeAsync(new AIFunctionArguments(), Token); + var result = await tool.InvokeAsync([], Token); Assert.Equal(2, fake.ConnectionsOpened); Assert.False(IsError(result), $"the call returned an error result: {result}"); @@ -170,11 +170,11 @@ public async Task AToolTheServerHasWithdrawn_ReturnsAnErrorResult_AndDoesNotThro await fake.AnnounceToolChangeAsync(Token); await WaitForAsync(async () => { - var probe = await tool.InvokeAsync(new AIFunctionArguments(), Token); + var probe = await tool.InvokeAsync([], Token); return IsError(probe); }); - var result = await tool.InvokeAsync(new AIFunctionArguments(), Token); + var result = await tool.InvokeAsync([], Token); var error = Assert.IsType(result); Assert.True(ToolErrorResult.IsError(error)); @@ -256,7 +256,7 @@ public async Task AToolWithdrawnWhileTheServerWasDown_ReturnsAnErrorResult() object? result = null; await WaitForAsync(async () => { - result = await tool.InvokeAsync(new AIFunctionArguments(), Token); + result = await tool.InvokeAsync([], Token); return IsError(result); }); @@ -268,7 +268,7 @@ await WaitForAsync(async () => StringComparison.Ordinal); // It stays gone: the guard is on the call, not on one unlucky moment. - Assert.True(IsError(await tool.InvokeAsync(new AIFunctionArguments(), Token))); + Assert.True(IsError(await tool.InvokeAsync([], Token))); } // --------------------------------------------------------------------------------------------- @@ -290,7 +290,7 @@ public async Task AToolThatHangs_IsGivenUpOn_AtTheServersOwnCallTimeout() var watch = Stopwatch.StartNew(); var result = await ((AIFunction)registry.Resolve("jira.create_issue")) - .InvokeAsync(new AIFunctionArguments(), Token); + .InvokeAsync([], Token); watch.Stop(); Assert.True(ToolErrorResult.IsError(Assert.IsType(result))); @@ -337,7 +337,7 @@ public async Task DisposingTheSource_LeavesTheToolReturningAnErrorResult_RatherT await source.DisposeAsync(); - var result = await tool.InvokeAsync(new AIFunctionArguments(), Token); + var result = await tool.InvokeAsync([], Token); Assert.True(ToolErrorResult.IsError(Assert.IsType(result))); } diff --git a/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs b/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs index c56ae3ce..eb4e63bb 100644 --- a/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs +++ b/tests/AgentCore.TestSupport/RecordingChatClientFactory.cs @@ -1,4 +1,3 @@ -using System.Runtime.CompilerServices; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using Microsoft.Extensions.AI; @@ -30,20 +29,25 @@ public IChatClient GetChatClient(ModelReference? model) private sealed class StubChatClient : IChatClient { - public async IAsyncEnumerable GetStreamingResponseAsync( + public IAsyncEnumerable GetStreamingResponseAsync( IEnumerable messages, ChatOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(messages); - await Task.Yield(); + return StreamAsync(); - var responseId = Guid.NewGuid().ToString("N"); - yield return new ChatResponseUpdate(ChatRole.Assistant, "ok") + async IAsyncEnumerable StreamAsync() { - ResponseId = responseId, - MessageId = responseId, - }; + await Task.Yield(); + + var responseId = Guid.NewGuid().ToString("N"); + yield return new ChatResponseUpdate(ChatRole.Assistant, "ok") + { + ResponseId = responseId, + MessageId = responseId, + }; + } } public async Task GetResponseAsync( From 15387f813e2834a1e277c2a2b8b7c307f6ee45fb Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Sun, 13 Sep 2026 22:32:56 -0600 Subject: [PATCH 23/32] refactor: consolidate collapsible state management into a reusable hook --- .../components/assistant-ui/tool-fallback.tsx | 27 ++++-------- .../components/assistant-ui/tool-group.tsx | 34 ++++----------- .../assistant-ui/use-collapsible-open.ts | 41 +++++++++++++++++++ 3 files changed, 57 insertions(+), 45 deletions(-) create mode 100644 demo/chat-ui/src/components/assistant-ui/use-collapsible-open.ts diff --git a/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx b/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx index bdb31258..f62b4d98 100644 --- a/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx +++ b/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx @@ -1,6 +1,6 @@ "use client"; -import { memo, useCallback, useRef, useState } from "react"; +import { memo, useState } from "react"; import { AlertCircleIcon, CheckIcon, @@ -9,7 +9,6 @@ import { XCircleIcon, } from "lucide-react"; import { - useScrollLock, useToolCallElapsed, type ToolApprovalOption, type ToolCallMessagePart, @@ -26,6 +25,7 @@ import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { ToolError } from "@/components/elements/tool-error"; import { useActionBarReload } from "@assistant-ui/core/react"; +import { useControlledOpen } from "./use-collapsible-open"; const ANIMATION_DURATION = 200; @@ -48,23 +48,12 @@ function ToolFallbackRoot({ children, ...props }: ToolFallbackRootProps) { - const collapsibleRef = useRef(null); - const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen); - const lockScroll = useScrollLock(collapsibleRef, ANIMATION_DURATION); - - const isControlled = controlledOpen !== undefined; - const isOpen = isControlled ? controlledOpen : uncontrolledOpen; - - const handleOpenChange = useCallback( - (open: boolean) => { - lockScroll(); - if (!isControlled) { - setUncontrolledOpen(open); - } - controlledOnOpenChange?.(open); - }, - [lockScroll, isControlled, controlledOnOpenChange], - ); + const { ref: collapsibleRef, isOpen, handleOpenChange } = useControlledOpen({ + open: controlledOpen, + onOpenChange: controlledOnOpenChange, + defaultOpen, + lockDurationMs: ANIMATION_DURATION, + }); return ( (null); - const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen); - const lockScroll = useScrollLock(collapsibleRef, ANIMATION_DURATION); - - const isControlled = controlledOpen !== undefined; - const isOpen = isControlled ? controlledOpen : uncontrolledOpen; - - const handleOpenChange = useCallback( - (open: boolean) => { - lockScroll(); - if (!isControlled) { - setUncontrolledOpen(open); - } - controlledOnOpenChange?.(open); - }, - [lockScroll, isControlled, controlledOnOpenChange], - ); + const { ref: collapsibleRef, isOpen, handleOpenChange } = useControlledOpen({ + open: controlledOpen, + onOpenChange: controlledOnOpenChange, + defaultOpen, + lockDurationMs: ANIMATION_DURATION, + }); return ( void; + defaultOpen?: boolean; + lockDurationMs: number; +}; + +/** + * One Collapsible's open state, shared by ToolGroupRoot and ToolFallbackRoot. + * A single hook keeps the controlled/uncontrolled split and the scroll lock in + * lockstep; two copies already drifted once. + */ +export function useControlledOpen({ + open: controlledOpen, + onOpenChange, + defaultOpen = false, + lockDurationMs, +}: ControlledOpen) { + const ref = useRef(null); + const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen); + const lockScroll = useScrollLock(ref, lockDurationMs); + + const isControlled = controlledOpen !== undefined; + const isOpen = isControlled ? controlledOpen : uncontrolledOpen; + + const handleOpenChange = useCallback( + (open: boolean) => { + lockScroll(); + if (!isControlled) { + setUncontrolledOpen(open); + } + onOpenChange?.(open); + }, + [lockScroll, isControlled, onOpenChange], + ); + + return { ref, isOpen, handleOpenChange }; +} From c35a6e3d3b91412a90c9aae1815efad63ba4f397 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Mon, 14 Sep 2026 01:56:35 -0600 Subject: [PATCH 24/32] feat: add responses api end point --- Directory.Packages.props | 2 + .../Calls/Memory/InMemoryCallStore.cs | 41 ++ src/AgentCore.Application/Ports/ICallStore.cs | 57 +- .../PublicAPI.Unshipped.txt | 7 + .../Runtime/CallSession.cs | 12 + .../AgentCore.AspNetCore.csproj | 3 + .../AgentCoreServiceCollectionExtensions.cs | 13 +- .../Endpoints/ChatCompletionsEndpoints.cs | 160 ++--- .../Endpoints/ResponsesContracts.cs | 127 ++++ .../Endpoints/ResponsesEndpoints.cs | 531 ++++++++++++++++ .../Endpoints/TurnStreamParts.cs | 138 +++++ .../PublicAPI.Unshipped.txt | 11 + .../Sessions/AgentCoreAgentSessionStore.cs | 76 +++ .../AgentCoreHostEndpointExtensions.cs | 11 +- src/AgentCore.Hosting/PublicAPI.Unshipped.txt | 2 +- .../Calls/Postgres/PostgresCallStore.cs | 45 +- .../Calls/Postgres/PostgresCallStoreSql.cs | 17 +- .../Postgres/Migrations/001_agentcore.sql | 30 +- .../Endpoints/ResponsesTests.cs | 579 ++++++++++++++++++ .../Fakes/ResponsesHost.cs | 105 ++++ .../Calls/Postgres/ContinuationStoreTests.cs | 69 +++ .../DelegatingCallStore.cs | 15 + 22 files changed, 1908 insertions(+), 143 deletions(-) create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs create mode 100644 src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs create mode 100644 src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs create mode 100644 tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs create mode 100644 tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 3fe3173d..8cc5cc51 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -21,6 +21,8 @@ + + diff --git a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs index 3aefe81b..62b677d5 100644 --- a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs +++ b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs @@ -22,6 +22,9 @@ public sealed class InMemoryCallStore : ICallStore 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. @@ -347,6 +350,44 @@ public ValueTask EraseAsync(string callId, CancellationToken cancellationTo } } + /// + 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) diff --git a/src/AgentCore.Application/Ports/ICallStore.cs b/src/AgentCore.Application/Ports/ICallStore.cs index f9c63100..f384ccdc 100644 --- a/src/AgentCore.Application/Ports/ICallStore.cs +++ b/src/AgentCore.Application/Ports/ICallStore.cs @@ -101,7 +101,9 @@ ValueTask> AppendAsync( /// Cancels the write. /// The row as written: its ordinal, its turn index, and its id. async ValueTask AppendMessageAsync( - string callId, ChatMessage message, CancellationToken cancellationToken = default) + string callId, + ChatMessage message, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(message); @@ -121,14 +123,18 @@ async ValueTask AppendMessageAsync( /// What the caller actually heard. /// Cancels the write. ValueTask RewriteAsync( - string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default); + string callId, + string messageId, + ChatMessage content, + CancellationToken cancellationToken = default); /// Reads one whole call's words, oldest message first. /// The call to read. /// Cancels the read. /// Every message of the call, or an empty list when it holds none. ValueTask> ReadAsync( - string callId, CancellationToken cancellationToken = default); + string callId, + CancellationToken cancellationToken = default); /// Withdraws the tail of a call's words, from one ordinal onward. /// The call to cut. @@ -136,7 +142,9 @@ ValueTask> ReadAsync( /// Cancels the delete. /// How many messages went. ValueTask TruncateAsync( - string callId, int fromOrdinal, CancellationToken cancellationToken = default); + string callId, + int fromOrdinal, + CancellationToken cancellationToken = default); /// Erases one call's words, and leaves its row in the listing. /// The call to quieten. @@ -157,7 +165,9 @@ ValueTask TruncateAsync( /// Cancels the sweep between batches, and inside one. /// How many calls went, over every batch. ValueTask SweepAsync( - TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default); + TimeSpan retention, + int batchSize = 500, + CancellationToken cancellationToken = default); /// Gives a principal a claim on a call. /// The call to claim. @@ -165,12 +175,45 @@ ValueTask SweepAsync( /// What the key is to this call. AgentCore assigns its values no meaning. /// Cancels the write. ValueTask AttachPrincipalAsync( - string callId, string principalKey, string role, CancellationToken cancellationToken = default); + string callId, + string principalKey, + string role, + CancellationToken cancellationToken = default); /// Takes a principal's claim off a call. /// The call to unclaim. /// The key to remove. /// Cancels the delete. ValueTask DetachPrincipalAsync( - string callId, string principalKey, CancellationToken cancellationToken = default); + string callId, + string principalKey, + CancellationToken cancellationToken = default); + + /// Files one session envelope under one continuation id, replacing any envelope already there. + /// The continuation id: a conversation id or a response id. + /// 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: + /// a resume must never find the key without the words. + /// + ValueTask SaveContinuationAsync( + string continuationId, + JsonElement envelope, + CancellationToken cancellationToken = default); + + /// Reads the envelope one continuation id names. + /// The continuation id to look up. + /// Cancels the read. + /// The envelope, or when nothing is filed under that id. + ValueTask GetContinuationAsync( + string continuationId, + CancellationToken cancellationToken = default); + + /// Withdraws whatever one continuation id names, if anything. + /// The continuation id to forget. + /// Cancels the delete. + ValueTask DeleteContinuationAsync( + string continuationId, + CancellationToken cancellationToken = default); } diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index bfdb6202..aff92912 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -131,14 +131,17 @@ AgentCore.Application.Calls.Memory.InMemoryCallStore.AppendAsync(string! callId, 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 @@ -1093,13 +1096,16 @@ AgentCore.Application.Ports.ICallStore.AppendAsync(string! callId, System.Collec 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 @@ -1237,6 +1243,7 @@ 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 diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 61a40239..64967944 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -360,6 +360,18 @@ public IAsyncEnumerable RunTurnMessageStreamingAsync( public ChatMessage? TryCreateApprovalAnswer(string requestId, bool approved) => Ledger.TryCreateApprovalAnswer(requestId, approved); + /// Builds the answer message for one queued approval request of a resumed call. + /// The id of the pending request this answers. + /// Whether the tool may run. + /// Cancels the resume. + /// The user message carrying the approval response, or when no queued request carries that id. + public async ValueTask TryCreateApprovalAnswerAsync( + string requestId, bool approved, CancellationToken cancellationToken = default) + { + await Ledger.OpenSessionAsync(cancellationToken).ConfigureAwait(false); + return Ledger.TryCreateApprovalAnswer(requestId, approved); + } + /// /// Runs one streaming turn that knows where it sits in the conversation the caller can see. /// diff --git a/src/AgentCore.AspNetCore/AgentCore.AspNetCore.csproj b/src/AgentCore.AspNetCore/AgentCore.AspNetCore.csproj index 70010bed..74e5c1dc 100644 --- a/src/AgentCore.AspNetCore/AgentCore.AspNetCore.csproj +++ b/src/AgentCore.AspNetCore/AgentCore.AspNetCore.csproj @@ -15,6 +15,9 @@ + + + diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs index c7dc1a48..32f0c642 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs @@ -5,6 +5,7 @@ using AgentCore.Application.Ports; using AgentCore.Application.Sessions.Memory; using AgentCore.AspNetCore.Sessions; +using Microsoft.Agents.AI.Hosting; using Microsoft.AspNetCore.WebSockets; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -50,13 +51,15 @@ public static IServiceCollection AddAgentCore( services.AddSingleton(Boot(boot => boot.Agent)); services.AddSingleton(Boot(boot => boot.AuditQueue)); - // Through the concrete registration, so one factory builds the queue and both service types - // answer with the same instance. + services.TryAddSingleton(provider => + new AgentCoreAgentSessionStore(provider.GetRequiredService())); + + services.TryAddSingleton(provider => + provider.GetRequiredService()); + services.AddSingleton(provider => provider.GetRequiredService()); - // Each of these is null when the host registered no vendor for it, and a factory that - // returns null makes GetService answer null — which is what a caller of an optional seam - // reads them with. + services.AddSingleton(Boot(boot => boot.Telemetry!)); services.AddSingleton(Boot(boot => boot.Knowledge!)); services.AddSingleton(Boot(boot => boot.CallAdapters!)); diff --git a/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs index 3b8a7e03..5605bd1e 100644 --- a/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs +++ b/src/AgentCore.AspNetCore/Endpoints/ChatCompletionsEndpoints.cs @@ -4,9 +4,7 @@ using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.Application.Tools; -using AgentCore.Application.Transcript; using AgentCore.Domain; -using AgentCore.Domain.Sources; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; @@ -321,58 +319,46 @@ await WriteEventAsync( await foreach (var update in session.RunTurnMessageStreamingAtOriginAsync(input, origin, cancellationToken).ConfigureAwait(false)) { - foreach (var drawn in update.Contents.OfType()) + foreach (var part in TurnStreamParts.From(update, toolNames)) { - await WriteEventAsync( - http, - Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) - with - { AgentCoreData = new RenderedPayload { Name = drawn.Name, Data = drawn.Data } }, - cancellationToken).ConfigureAwait(false); - } - - foreach (var cited in update.Contents.OfType()) - { - await WriteEventAsync( - http, - Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) - with - { AgentCoreSource = SourcePayloadOf(cited) }, - cancellationToken).ConfigureAwait(false); - } - - foreach (var tool in ToolPayloadsOf(update, toolNames)) - { - await WriteEventAsync( - http, - Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) - with - { AgentCoreTool = tool }, - cancellationToken).ConfigureAwait(false); - } - - foreach (var asked in update.Contents.OfType()) - { - // A request arrives with no text, so without this the update falls into the - // empty-text skip below and the caller never learns a tool waits on them. - if (asked.ToolCall is not FunctionCallContent call) + switch (part) { - continue; + case TurnStreamRender render: + await WriteEventAsync( + http, + Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) + with + { AgentCoreData = render.Payload }, + cancellationToken).ConfigureAwait(false); + break; + + case TurnStreamSource source: + await WriteEventAsync( + http, + Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) + with + { AgentCoreSource = source.Payload }, + cancellationToken).ConfigureAwait(false); + break; + + case TurnStreamTool tool: + await WriteEventAsync( + http, + Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) + with + { AgentCoreTool = tool.Payload }, + cancellationToken).ConfigureAwait(false); + break; + + case TurnStreamApproval approval: + await WriteEventAsync( + http, + Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) + with + { AgentCoreApproval = approval.Payload }, + cancellationToken).ConfigureAwait(false); + break; } - - await WriteEventAsync( - http, - Chunk(id, created, model, new ChatCompletionMessage(), finishReason: null, turn: null) - with - { - AgentCoreApproval = new ApprovalPayload - { - RequestId = asked.RequestId, - Tool = call.Name, - Arguments = ArgumentsOf(call), - }, - }, - cancellationToken).ConfigureAwait(false); } if (update.Text is not { Length: > 0 } text) @@ -398,78 +384,6 @@ await WriteEventAsync( await http.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false); } - /// Reads the tool facts one update carries, in the order they appear on it. - /// One update of the stream. - /// The pairing of call id to tool name for this turn, written and read here. - /// One payload for each half of a tool call the update carries, possibly none. - private static IEnumerable ToolPayloadsOf( - ChatResponseUpdate update, - ToolCallNames toolNames) - { - foreach (var content in update.Contents) - { - switch (content) - { - case FunctionCallContent call: - toolNames.Called(call); - yield return new ToolPayload - { - CallId = call.CallId, - Name = call.Name, - Phase = "call", - Arguments = ArgumentsOf(call), - }; - break; - - case FunctionResultContent result: - // The answer has no declared shape, so it goes through the one reader that knows - // every shape it arrives in. Reading it twice would let the two disagree. - var answer = ToolResultJson.ToNode(result.Result); - yield return new ToolPayload - { - CallId = result.CallId, - // A result that arrives with no call before it should not be possible, and - // naming it after its id beats naming it nothing if it ever is. - Name = toolNames.Of(result) ?? result.CallId, - Phase = "result", - Result = ResultOf(result, answer), - Failed = result.Exception is not null || ToolErrorResult.IsError(answer), - }; - break; - - default: - break; - } - } - } - - /// Reads one cited source into what the browser receives. - /// The source the message carried. - /// The payload. - private static SourcePayload SourcePayloadOf(SourceContent cited) - => new() - { - CallId = cited.CallId, - Id = cited.Source.SourceId, - SourceType = cited.Source.Kind == SourceKind.Url ? "url" : "document", - Title = cited.Source.Title, - Locator = cited.Source.Locator, - Url = cited.Source.Url, - MediaType = cited.Source.MediaType, - Origin = cited.Source.Origin, - }; - - /// Reads what the model passed to one tool, or when it passed nothing. - private static JsonObject? ArgumentsOf(FunctionCallContent call) - => call.Arguments is { Count: > 0 } arguments ? ToolArgumentJson.ToJsonObject(arguments) : null; - - /// Reads what one tool answered, as the browser receives it. - /// The result half of the call. - /// The same result read as JSON, or when it answered nothing. - private static JsonNode? ResultOf(FunctionResultContent result, JsonNode? answer) - => result.Exception is { } failure - ? JsonValue.Create(failure.GetType().Name + ": " + failure.Message) - : answer; /// Builds one chunk of a stream. /// The id every chunk of one reply shares. diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs new file mode 100644 index 00000000..b83dddae --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesContracts.cs @@ -0,0 +1,127 @@ +using System.Text.Json; +using AgentCore.Application.Runtime; +using AgentCore.Domain; + +namespace AgentCore.AspNetCore.Endpoints; + +/// +/// The wire shapes of POST /v1/responses that are ours, beside the OpenAI shape. +/// +internal static class ResponsesAgentCore +{ + /// Reads the agentcore member of one request body, if it names one. + /// The request body. + /// What the client said about this turn, or for a plain turn. + internal static ResponsesRequestInfo? ReadRequest(JsonElement body) + { + if (!body.TryGetProperty("agentcore", out var agentcore) + || agentcore.ValueKind != JsonValueKind.Object) + { + return null; + } + + string? messageId = null; + if (agentcore.TryGetProperty("message_id", out var message) + && message.ValueKind == JsonValueKind.String) + { + messageId = message.GetString(); + } + + string? parentId = null; + var namesParent = agentcore.TryGetProperty("parent_id", out var parent); + if (namesParent && parent.ValueKind == JsonValueKind.String) + { + parentId = parent.GetString(); + } + + ResponsesApprovalAnswer? approval = null; + if (agentcore.TryGetProperty("approval", out var answer) + && answer.ValueKind == JsonValueKind.Object + && answer.TryGetProperty("request_id", out var requestId) + && requestId.ValueKind == JsonValueKind.String + && requestId.GetString() is { Length: > 0 } id + && answer.TryGetProperty("approved", out var approved) + && (approved.ValueKind == JsonValueKind.True || approved.ValueKind == JsonValueKind.False)) + { + approval = new ResponsesApprovalAnswer(id, approved.ValueKind == JsonValueKind.True); + } + + if (messageId is null && !namesParent && approval is null) + { + return null; + } + + return new ResponsesRequestInfo(messageId, parentId, namesParent, approval); + } + + /// Builds the metadata one finished turn files onto its answer. + /// The call 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) + { + Dictionary metadata = new(StringComparer.Ordinal) + { + ["call_id"] = call.CallId, + ["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) + { + metadata["message_id"] = messageId; + } + + if (turn.ExtractionFailure is { } failure) + { + metadata["extraction_failure"] = failure; + } + + if (turn.Approvals.Count > 0) + { + metadata["approvals"] = ApprovalsJson(turn); + } + + return metadata; + } + + /// 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 }; + + private static string ApprovalsJson(TurnResult turn) + { + System.Text.Json.Nodes.JsonArray approvals = []; + foreach (var approval in turn.Approvals) + { + approvals.Add(new System.Text.Json.Nodes.JsonObject + { + ["request_id"] = approval.RequestId, + ["tool"] = approval.ToolName, + ["arguments"] = System.Text.Json.Nodes.JsonNode.Parse(approval.Arguments.GetRawText()), + }); + } + + return approvals.ToJsonString(); + } +} + +/// 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. +/// Whether the body carried parent_id at all. +/// The approval answer this turn carries, or when it holds words. +internal sealed record ResponsesRequestInfo( + string? MessageId, + string? ParentId, + bool NamesParent, + ResponsesApprovalAnswer? Approval); + +/// One approval answer: which request the caller answers, and whether the tool may run. +/// The id of the pending request this answers. +/// Whether the tool may run. +internal sealed record ResponsesApprovalAnswer(string RequestId, bool Approved); diff --git a/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs new file mode 100644 index 00000000..087711a4 --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/ResponsesEndpoints.cs @@ -0,0 +1,531 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +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.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; + +namespace AgentCore.AspNetCore.Endpoints; + +/// +/// The Responses path: an OpenAI-compatible POST /v1/responses over the turn loop, +/// with the call continuing across requests through the session store. +/// +/// +/// +/// This is the app-owned counterpart to the framework's MapOpenAIResponses, +/// which owns conversation-items storage and runs every turn sessionless. Here the +/// protocol conversion alone comes from the framework +/// (OpenAIResponses.ToAgentRunRequest, GetSessionStoreId, +/// WriteResponse, WriteResponseStreamAsync); the route, the session +/// save and load, and the storage stay here, so a second turn resumes the same +/// call — its stage, its slots, and its words — rather than starting a new one. +/// +/// +/// The turn itself runs on the directly rather than through +/// the AIAgent seam, for the two things that seam cannot carry: where the turn +/// hangs () and an approval answer. The session save and +/// load stay on the agent seam, and the reply is rendered through it, so the stored +/// envelope keeps the one shape the agent reads back. +/// +/// +/// Turn facts travel in the response metadata, the spec's own extension point: +/// call_id, turn_index, stage_before, stage_after, +/// is_terminal, and, when set, message_id, extraction_failure, +/// and approvals (a JSON array of the pending requests). A typed OpenAI client +/// reads these; no bespoke top-level member is added. The stream carries text only — +/// its frames are the framework's fixed shapes — with the stage on a header; renders, +/// sources, and tool-call halves stay a chat-completions-stream capability, and the +/// words stay in store 1 either way. +/// +/// +public static class ResponsesEndpointRouteBuilderExtensions +{ + /// The route this endpoint answers on when the host names none. + public const string DefaultPattern = "/v1/responses"; + + /// The answer header that reports the stage the machine holds. + public const string StageHeaderName = "X-AgentCore-Stage"; + + /// Maps the endpoint on . + /// The route builder of the host. + /// The mapped endpoint, so a host adds its own conventions. + public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder endpoints) + => endpoints.MapResponses(DefaultPattern); + + /// Maps the endpoint on one route. + /// The route builder of the host. + /// The route to answer on. + /// The mapped endpoint, so a host adds its own conventions. + public static IEndpointConventionBuilder MapResponses(this IEndpointRouteBuilder endpoints, string pattern) + { + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentException.ThrowIfNullOrEmpty(pattern); + + return endpoints.MapPost(pattern, HandleAsync); + } + + /// Runs one turn of one call, and files the session under the ids the answer carries. + /// The request. + /// A task that completes when the answer is written. + private static async Task HandleAsync(HttpContext http) + { + var cancellationToken = http.RequestAborted; + + JsonElement body; + try + { + body = 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, + "invalid_request_error", + "malformed_body", + cancellationToken).ConfigureAwait(false); + return; + } + + var agentcore = ResponsesAgentCore.ReadRequest(body); + + OpenAIResponsesRunRequest? runRequest; + string? conversationId; + IReadOnlyList messages; + try + { + 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 + // call, so read it off the body and run the answer alone. + if (agentcore?.Approval is null) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the request is not a Responses request: " + exception.Message, + "invalid_request_error", + "invalid_body", + cancellationToken).ConfigureAwait(false); + return; + } + + runRequest = null; + messages = []; + conversationId = ReadConversationId(body); + } + + var agent = http.RequestServices.GetRequiredService(); + var sessions = http.RequestServices.GetRequiredService(); + + // The continuation this turn hangs off, or null for the first turn of a call. + // 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) + : ReadContinuationId(body); + + AgentSession session; + if (key is null) + { + if (agentcore?.Approval is not null) + { + await WriteErrorAsync( + http, + 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", + "missing_session", + cancellationToken).ConfigureAwait(false); + return; + } + + session = await agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + else if (await sessions.ContainsAsync(key, cancellationToken).ConfigureAwait(false)) + { + session = await sessions.GetSessionAsync(agent, key, cancellationToken).ConfigureAwait(false); + } + else + { + await WriteErrorAsync( + http, + 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", + "continuation_not_found", + cancellationToken).ConfigureAwait(false); + return; + } + + if (session.GetService() is not { } call) + { + throw new InvalidOperationException( + "The session is not one this agent created, so it names no call to run."); + } + + ChatMessage input; + if (agentcore?.Approval is { } approval) + { + if (LastUserText(messages) is { Length: > 0 }) + { + await 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.", + "invalid_request_error", + "mixed_turn", + cancellationToken).ConfigureAwait(false); + return; + } + + // Async: a resumed call 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) + { + await 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.", + "invalid_request_error", + "no_pending_approval", + cancellationToken).ConfigureAwait(false); + return; + } + + input = answer; + } + else if (LastUserMessage(messages) is not { } user) + { + await WriteErrorAsync( + http, + StatusCodes.Status400BadRequest, + "the request carries no user message with text, so there is no turn to run.", + "invalid_request_error", + "no_user_message", + cancellationToken).ConfigureAwait(false); + return; + } + else + { + input = user; + } + + var origin = ResponsesAgentCore.OriginOf(agentcore); + + var streaming = body.TryGetProperty("stream", out var streamFlag) + && streamFlag.ValueKind == JsonValueKind.True; + + // A conversation the request named stays the conversation; a first turn mints + // one so the answer carries something a later turn can hang off. A response id + // is minted every turn either way, so a chain can start from any answer. + var responseId = OpenAIResponses.CreateResponseId(); + conversationId = conversationId + ?? (key is null ? NewConversationId() : null); + + // Only the stream has a chunk to carry a drawing, for the same reason the chat + // endpoint binds its screen per branch: the session outlives a request and the + // branch can differ per turn. + call.SetHasScreen(streaming); + + try + { + if (streaming) + { + // 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) + .ConfigureAwait(false); + } + else + { + await WriteTurnAsync(http, agent, sessions, session, call, 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 + // runs. Both are a caller mistake and neither is a defect of this host. + await WriteErrorAsync( + http, + StatusCodes.Status409Conflict, + exception.Message, + "invalid_request_error", + "turn_refused", + 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); + } + /// 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 the same member shapes the chat + /// endpoint writes, 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: the member shapes the chat endpoint writes, 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, ChatCompletionJson.Options) }, + TurnStreamSource source + => new JsonObject { ["agentcore_source"] = JsonSerializer.SerializeToNode(source.Payload, ChatCompletionJson.Options) }, + TurnStreamTool tool + => new JsonObject { ["agentcore_tool"] = JsonSerializer.SerializeToNode(tool.Payload, ChatCompletionJson.Options) }, + TurnStreamApproval approval + => new JsonObject { ["agentcore_approval"] = JsonSerializer.SerializeToNode(approval.Payload, ChatCompletionJson.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, + /// 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. + /// + private 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); + } + + /// 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/TurnStreamParts.cs b/src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs new file mode 100644 index 00000000..b3ee4870 --- /dev/null +++ b/src/AgentCore.AspNetCore/Endpoints/TurnStreamParts.cs @@ -0,0 +1,138 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Tools; +using AgentCore.Application.Transcript; +using AgentCore.Domain.Sources; +using Microsoft.Extensions.AI; + +namespace AgentCore.AspNetCore.Endpoints; + +/// +/// The non-text parts of one streaming update, read once for every text endpoint. +/// +/// +/// A drawing, a citation, a tool half, and an approval ask ride ChatResponseUpdate +/// contents that no OpenAI shape carries. Each endpoint frames them its own way, but what +/// they mean — and what the browser reads — is one mapping, kept here so a new content +/// kind lands in one place. Text stays endpoint-side: completions deltas it, Responses +/// leaves it to the framework converter. +/// +internal static class TurnStreamParts +{ + /// Reads one update's browser parts, in wire order: renders, sources, tools, approvals. + /// One update of the stream. + /// The pairing of call id to tool name for this turn, written and read here. + /// One part for each browser payload the update carries, possibly none. + internal static IEnumerable From(ChatResponseUpdate update, ToolCallNames toolNames) + { + foreach (var drawn in update.Contents.OfType()) + { + yield return new TurnStreamRender(new RenderedPayload { Name = drawn.Name, Data = drawn.Data }); + } + + foreach (var cited in update.Contents.OfType()) + { + yield return new TurnStreamSource(SourcePayloadOf(cited)); + } + + foreach (var tool in ToolPayloadsOf(update, toolNames)) + { + yield return new TurnStreamTool(tool); + } + + foreach (var asked in update.Contents.OfType()) + { + // A request arrives with no text, so without this the update falls into the + // empty-text skip below and the caller never learns a tool waits on them. + if (asked.ToolCall is FunctionCallContent call) + { + yield return new TurnStreamApproval(new ApprovalPayload + { + RequestId = asked.RequestId, + Tool = call.Name, + Arguments = ArgumentsOf(call), + }); + } + } + } + + /// Reads the tool facts one update carries, in the order they appear on it. + private static IEnumerable ToolPayloadsOf( + ChatResponseUpdate update, + ToolCallNames toolNames) + { + foreach (var content in update.Contents) + { + switch (content) + { + case FunctionCallContent call: + toolNames.Called(call); + yield return new ToolPayload + { + CallId = call.CallId, + Name = call.Name, + Phase = "call", + Arguments = ArgumentsOf(call), + }; + break; + + case FunctionResultContent result: + // The answer has no declared shape, so it goes through the one reader that knows + // every shape it arrives in. Reading it twice would let the two disagree. + var answer = ToolResultJson.ToNode(result.Result); + yield return new ToolPayload + { + CallId = result.CallId, + // A result that arrives with no call before it should not be possible, and + // naming it after its id beats naming it nothing if it ever is. + Name = toolNames.Of(result) ?? result.CallId, + Phase = "result", + Result = ResultOf(result, answer), + Failed = result.Exception is not null || ToolErrorResult.IsError(answer), + }; + break; + + default: + break; + } + } + } + + /// Reads one cited source into what the browser receives. + private static SourcePayload SourcePayloadOf(SourceContent cited) + => new() + { + CallId = cited.CallId, + Id = cited.Source.SourceId, + SourceType = cited.Source.Kind == SourceKind.Url ? "url" : "document", + Title = cited.Source.Title, + Locator = cited.Source.Locator, + Url = cited.Source.Url, + MediaType = cited.Source.MediaType, + Origin = cited.Source.Origin, + }; + + /// Reads what the model passed to one tool, or when it passed nothing. + private static JsonObject? ArgumentsOf(FunctionCallContent call) + => call.Arguments is { Count: > 0 } arguments ? ToolArgumentJson.ToJsonObject(arguments) : null; + + /// Reads what one tool answered, as the browser receives it. + private static JsonNode? ResultOf(FunctionResultContent result, JsonNode? answer) + => result.Exception is { } failure + ? JsonValue.Create(failure.GetType().Name + ": " + failure.Message) + : answer; +} + +/// One browser payload of a streaming update. +internal abstract record TurnStreamPart; + +/// One thing a chunk asks the browser to draw. +internal sealed record TurnStreamRender(RenderedPayload Payload) : TurnStreamPart; + +/// Where one answer came from, as the browser reads it. +internal sealed record TurnStreamSource(SourcePayload Payload) : TurnStreamPart; + +/// One half of one tool call, as the browser reads it. +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; diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 969d4bce..a27d4e58 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -47,6 +47,13 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup.Configuration.get -> AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup.Secrets.get -> AgentCore.Application.Secrets.ResolvedSecrets! AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensions +AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions +AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore +AgentCore.AspNetCore.Sessions.AgentCoreAgentSessionStore.AgentCoreAgentSessionStore(AgentCore.Application.Ports.ICallStore! calls) -> 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! @@ -61,6 +68,8 @@ const AgentCore.AspNetCore.DependencyInjection.AgentCoreHttpClients.PipelineName const AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensions.DefaultPattern = "/v1/chat/completions" -> string! const AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensions.SessionHeaderName = "X-AgentCore-Session" -> string! const AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensions.StageHeaderName = "X-AgentCore-Stage" -> string! +const AgentCore.AspNetCore.Endpoints.ResponsesEndpointRouteBuilderExtensions.DefaultPattern = "/v1/responses" -> 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) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! @@ -69,6 +78,8 @@ static AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtens static AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions.AddAgentCoreWebSockets(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensions.MapChatCompletions(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! static AgentCore.AspNetCore.Endpoints.ChatCompletionsEndpointRouteBuilderExtensions.MapChatCompletions(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern) -> 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/Sessions/AgentCoreAgentSessionStore.cs b/src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs new file mode 100644 index 00000000..5b2bea98 --- /dev/null +++ b/src/AgentCore.AspNetCore/Sessions/AgentCoreAgentSessionStore.cs @@ -0,0 +1,76 @@ +using AgentCore.Application.Ports; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.Hosting; + +namespace AgentCore.AspNetCore.Sessions; + +/// +/// The framework's session seam over the continuation map that lives in the call store. +/// +public sealed class AgentCoreAgentSessionStore : AgentSessionStore +{ + private readonly ICallStore _calls; + + /// Creates the seam over one call store. + /// The store the continuation ids open onto. + /// The store is . + public AgentCoreAgentSessionStore(ICallStore calls) + { + ArgumentNullException.ThrowIfNull(calls); + _calls = calls; + } + + /// Reads whether anything is filed under one continuation id. + /// The conversation id or response id to look up. + /// Cancels the read. + /// when a later load would find an envelope. + public async ValueTask ContainsAsync(string sessionStoreId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(sessionStoreId); + + return await _calls.GetContinuationAsync(sessionStoreId, cancellationToken).ConfigureAwait(false) + is not null; + } + + /// + public override async ValueTask SaveSessionAsync( + AIAgent agent, string sessionStoreId, AgentSession session, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(agent); + ArgumentNullException.ThrowIfNull(sessionStoreId); + ArgumentNullException.ThrowIfNull(session); + + var envelope = await agent + .SerializeSessionAsync(session, cancellationToken: cancellationToken) + .ConfigureAwait(false); + await _calls.SaveContinuationAsync(sessionStoreId, envelope, cancellationToken).ConfigureAwait(false); + } + + /// + public override async ValueTask GetSessionAsync( + AIAgent agent, string sessionStoreId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(agent); + ArgumentNullException.ThrowIfNull(sessionStoreId); + + var envelope = await _calls.GetContinuationAsync(sessionStoreId, cancellationToken).ConfigureAwait(false); + if (envelope is null) + { + return await agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false); + } + + return await agent + .DeserializeSessionAsync(envelope.Value, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + /// + public override ValueTask DeleteSessionAsync( + AIAgent agent, string sessionStoreId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(agent); + ArgumentNullException.ThrowIfNull(sessionStoreId); + + return _calls.DeleteContinuationAsync(sessionStoreId, cancellationToken); + } +} diff --git a/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs b/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs index 8c5c1461..05d99608 100644 --- a/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs +++ b/src/AgentCore.Hosting/AgentCoreHostEndpointExtensions.cs @@ -13,16 +13,21 @@ public static class AgentCoreHostEndpointExtensions /// The route the liveness check answers on. public const string HealthPattern = "/health"; - /// Installs the WebSocket middleware and maps health, chat completions, and the call socket. + /// Installs the WebSocket middleware and maps health, both text endpoints, and the call socket. /// The application to map on. /// /// The route the OpenAI-compatible text endpoint answers on, or for /// . A host that mounts /// another OpenAI-compatible surface of its own moves this one out of the way here. /// + /// + /// The route the OpenAI-compatible Responses endpoint answers on, or for + /// . + /// /// The same application, so a host chains its calls. /// is . - public static WebApplication MapAgentCoreHost(this WebApplication app, string? chatCompletionsPattern = null) + public static WebApplication MapAgentCoreHost( + this WebApplication app, string? chatCompletionsPattern = null, string? responsesPattern = null) { ArgumentNullException.ThrowIfNull(app); @@ -32,6 +37,8 @@ public static WebApplication MapAgentCoreHost(this WebApplication app, string? c app.MapChatCompletions(chatCompletionsPattern ?? ChatCompletionsEndpointRouteBuilderExtensions.DefaultPattern); + app.MapResponses(responsesPattern ?? ResponsesEndpointRouteBuilderExtensions.DefaultPattern); + app.MapCall(); return app; diff --git a/src/AgentCore.Hosting/PublicAPI.Unshipped.txt b/src/AgentCore.Hosting/PublicAPI.Unshipped.txt index cae8a139..71606f0c 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? chatCompletionsPattern = null) -> Microsoft.AspNetCore.Builder.WebApplication! +static AgentCore.Hosting.AgentCoreHostEndpointExtensions.MapAgentCoreHost(this Microsoft.AspNetCore.Builder.WebApplication! app, string? chatCompletionsPattern = null, string? responsesPattern = null) -> Microsoft.AspNetCore.Builder.WebApplication! diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs index af6ab72f..be564591 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStore.cs @@ -365,7 +365,7 @@ public async ValueTask TruncateAsync( } /// - /// The call id is . + /// The continuation id is . public async ValueTask EraseAsync(string callId, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(callId); @@ -376,6 +376,49 @@ public async ValueTask EraseAsync(string callId, CancellationToken cancella return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } + /// + public async ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(continuationId); + + await using var command = _dataSource.CreateCommand(SaveContinuationSql); + command.Parameters.Add(new NpgsqlParameter { Value = continuationId }); + command.Parameters.Add(new NpgsqlParameter + { + NpgsqlDbType = NpgsqlDbType.Jsonb, + Value = envelope.GetRawText(), + }); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(continuationId); + + await using var command = _dataSource.CreateCommand(GetContinuationSql); + command.Parameters.Add(new NpgsqlParameter { Value = continuationId }); + + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + return null; + } + + return JsonDocument.Parse(reader.GetString(0)).RootElement.Clone(); + } + + /// + public async ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(continuationId); + + await using var command = _dataSource.CreateCommand(DeleteContinuationSql); + command.Parameters.Add(new NpgsqlParameter { Value = continuationId }); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + + /// Reads one call's spoken turns beside the hashes the audit chain holds for them. /// The call to check. /// Cancels the read. diff --git a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs index 137a4d33..f2eae1c2 100644 --- a/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs +++ b/src/AgentCore.Infrastructure/Calls/Postgres/PostgresCallStoreSql.cs @@ -1,4 +1,3 @@ -using AgentCore.Domain.Audit; using AgentCore.Infrastructure.Database.Postgres; namespace AgentCore.Infrastructure.Calls.Postgres; @@ -9,6 +8,7 @@ internal static class PostgresCallStoreSql private const string Schema = PostgresSchema.SchemaName; internal const string Regular = "regular"; + internal const string Archived = "archived"; /// The value a listing sorts and pages by. @@ -120,6 +120,21 @@ AS d(turn_index, role, content, message_id, position) internal const string EraseSql = $"DELETE FROM {Schema}.call_message WHERE call_id = $1"; + /// Files one session envelope under one continuation id, replacing any envelope already there. + internal const string SaveContinuationSql = + $""" + INSERT INTO {Schema}.response_continuation (store_id, envelope) VALUES ($1, $2) + ON CONFLICT (store_id) DO UPDATE SET envelope = EXCLUDED.envelope + """; + + /// Reads the envelope one continuation id names. + internal const string GetContinuationSql = + $"SELECT envelope FROM {Schema}.response_continuation WHERE store_id = $1"; + + /// Withdraws whatever one continuation id names, if anything. + internal const string DeleteContinuationSql = + $"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. /// diff --git a/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql b/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql index fca2b634..a808386d 100644 --- a/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql +++ b/src/AgentCore.Infrastructure/Database/Postgres/Migrations/001_agentcore.sql @@ -2,7 +2,8 @@ -- -- 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; audit_event last, with the triggers that refuse to +-- words are a child of the call 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. @@ -135,13 +136,36 @@ 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); --- UPDATE amends a reply the caller cut short. DELETE erases one caller, and withdraws the tail of a --- call an edit replaced. Neither is a hole: this table holds words, and words stay erasable. -- Retention deletes the call 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; +-- 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 +-- 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 +-- 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 +-- unknown id already fails closed at lookup, which is the only integrity this +-- table needs. +CREATE TABLE agentcore.response_continuation ( + store_id text PRIMARY KEY, + envelope jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- The writer files, reads, replaces, and forgets. Nothing here is append-only: +-- a response id is filed once and a conversation id is replaced every turn. +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. -- -- Two numbers, two owners, and the split is the point. event_id is IDENTITY and the CALL allocates diff --git a/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs b/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs new file mode 100644 index 00000000..17e856b0 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Endpoints/ResponsesTests.cs @@ -0,0 +1,579 @@ +using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using AgentCore.AspNetCore.Tests.Fakes; +using Microsoft.Extensions.AI; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.Endpoints; + +/// +/// The Responses path: one request runs one turn, and the continuation carries the call. +/// +/// +/// Every test here runs offline against a fake model. The two-stage document names the +/// stage in each reply, so the text proves which stage spoke: there is no subtler +/// assertion about continuity than the second turn answering with the second agent. +/// +public sealed class ResponsesTests +{ + private const string TwoStagesYaml = + """ + apiVersion: agentcore/v1 + name: responses-turn-loop + guards: + second: { ">=": [ { var: turnIndex }, 1 ] } + third: { ">=": [ { var: turnIndex }, 2 ] } + agents: + defaults: + model: { ref: reply } + items: + - { id: solo, instructions: "answer one" } + - { id: duo, instructions: "answer two" } + policy: + initial: talking + stages: + - { id: talking, agent: solo, to: [ { stage: followup, when: second } ] } + - { id: followup, agent: duo, to: [ { stage: talking, when: third } ] } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + [Fact] + public async Task FirstTurn_MintsConversationAndAnswersStageOne() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var response = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = await ResponsesHost.ReadJsonAsync(response); + Assert.Contains("answer one", body.OutputText(), StringComparison.Ordinal); + Assert.StartsWith("conv_", body.ContinuationId(), StringComparison.Ordinal); + Assert.StartsWith("resp_", body["id"]?.GetValue(), StringComparison.Ordinal); + } + + [Fact] + public async Task SecondTurnOnConversation_ContinuesStageAndTranscript() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var first = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + var convId = (await ResponsesHost.ReadJsonAsync(first)).ContinuationId(); + var firstRequest = reply.LastRequest; + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": "second question" }"""); + + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + var body = await ResponsesHost.ReadJsonAsync(second); + Assert.Contains("answer two", body.OutputText(), StringComparison.Ordinal); + + var secondRequest = reply.LastRequest; + Assert.NotNull(secondRequest); + Assert.Contains(secondRequest, m => m.Text.Contains("first question", StringComparison.Ordinal)); + Assert.Contains(secondRequest, m => m.Text.Contains("answer one", StringComparison.Ordinal)); + Assert.NotSame(firstRequest, secondRequest); + } + + [Fact] + public async Task SecondTurnOnResponseChain_ContinuesStage() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var first = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + var respId = (await ResponsesHost.ReadJsonAsync(first))["id"]?.GetValue(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "previous_response_id": "{{respId}}", "input": "chained question" }"""); + + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + var body = await ResponsesHost.ReadJsonAsync(second); + Assert.Contains("answer two", body.OutputText(), StringComparison.Ordinal); + } + + [Fact] + public async Task SecondTurnStreams_StillContinuesStage() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var first = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + var convId = (await ResponsesHost.ReadJsonAsync(first)).ContinuationId(); + + using var second = await host.PostAsync( + $$"""{ "stream": true, "conversation": "{{convId}}", "input": "second question" }"""); + + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + Assert.Equal("text/event-stream", second.Content.Headers.ContentType?.MediaType); + var text = await ResponsesHost.ReadTextAsync(second); + Assert.Contains("answer two", text, StringComparison.Ordinal); + } + + [Fact] + public async Task UnknownContinuation_ReturnsNotFound() + { + using FragmentingChatClient reply = new("answer one"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var response = await host.PostAsync( + """{ "stream": false, "conversation": "conv_doesnotexist", "input": "hello" }"""); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task MalformedBody_ReturnsBadRequest() + { + using FragmentingChatClient reply = new("answer one"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var response = await host.PostAsync("""{ "stream": false, "input": """); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task MissingInput_ReturnsBadRequest() + { + using FragmentingChatClient reply = new("answer one"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var response = await host.PostAsync("""{ "stream": false }"""); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + [Fact] + public async Task FirstTurn_MetadataCarriesTurnFacts() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var response = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = await ResponsesHost.ReadJsonAsync(response); + var metadata = body["metadata"]!.AsObject(); + Assert.Equal("0", metadata["turn_index"]!.GetValue()); + // The commit advances on the post-increment index, so the first turn already leaves talking. + Assert.Equal("talking", metadata["stage_before"]!.GetValue()); + Assert.Equal("followup", metadata["stage_after"]!.GetValue()); + Assert.Equal("false", metadata["is_terminal"]!.GetValue()); + Assert.False(string.IsNullOrEmpty(metadata["call_id"]!.GetValue())); + Assert.False(string.IsNullOrEmpty(metadata["message_id"]!.GetValue())); + Assert.Null(body["metadata"]!["approvals"]); + Assert.Equal("followup", Assert.Single(response.Headers.GetValues("X-AgentCore-Stage"))); + } + + [Fact] + public async Task SecondTurn_MetadataAdvancesWithTheStage() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var first = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + var convId = (await ResponsesHost.ReadJsonAsync(first)).ContinuationId(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": "second question" }"""); + + var metadata = (await ResponsesHost.ReadJsonAsync(second))["metadata"]!.AsObject(); + Assert.Equal("1", metadata["turn_index"]!.GetValue()); + // The second turn speaks in followup and its post-increment index trips the third guard back. + Assert.Equal("followup", metadata["stage_before"]!.GetValue()); + Assert.Equal("talking", metadata["stage_after"]!.GetValue()); + } + + [Fact] + public async Task TerminalTurn_SignalsTerminalAndRefusesTheNext() + { + using FragmentingChatClient reply = new("answer one"); + await using var host = await ResponsesHost.StartAsync(TerminalYaml, reply); + + using var first = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + var body = await ResponsesHost.ReadJsonAsync(first); + Assert.Equal("true", body["metadata"]!["is_terminal"]!.GetValue()); + var convId = body.ContinuationId(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": "second question" }"""); + + Assert.Equal(HttpStatusCode.Conflict, second.StatusCode); + } + + [Fact] + public async Task GatedToolCall_AnswersWholeWithTheRequestInMetadata() + { + int sent = 0; + await using var host = await ResponsesHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => sent++)))); + + using var response = await host.PostAsync("""{ "stream": false, "input": "send it" }"""); + var body = await ResponsesHost.ReadJsonAsync(response); + + Assert.Equal(string.Empty, body.OutputText()); + var approvals = body["metadata"]!["approvals"]!.GetValue(); + Assert.Contains("send_email", approvals, StringComparison.Ordinal); + Assert.Equal(0, sent); + } + + [Fact] + public async Task ApprovalAnswer_RunsTheToolAndReplies() + { + int sent = 0; + await using var host = await ResponsesHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => sent++)))); + + using var first = await host.PostAsync("""{ "stream": false, "input": "send it" }"""); + var asked = await ResponsesHost.ReadJsonAsync(first); + var convId = asked.ContinuationId(); + var requestId = System.Text.Json.JsonDocument.Parse( + asked["metadata"]!["approvals"]!.GetValue()) + .RootElement[0].GetProperty("request_id").GetString(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": [], "agentcore": { "approval": { "request_id": "{{requestId}}", "approved": true } } }"""); + var replied = await ResponsesHost.ReadJsonAsync(second); + + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + Assert.Equal(1, sent); + Assert.Contains("done.", replied.OutputText(), StringComparison.Ordinal); + } + + [Fact] + public async Task ApprovalAnswerForARequestNothingAsked_IsConflict() + { + await using var host = await ResponsesHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => { })))); + + using var first = await host.PostAsync("""{ "stream": false, "input": "send it" }"""); + var convId = (await ResponsesHost.ReadJsonAsync(first)).ContinuationId(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": [], "agentcore": { "approval": { "request_id": "req-nothing-asked", "approved": true } } }"""); + + Assert.Equal(HttpStatusCode.Conflict, second.StatusCode); + } + + [Fact] + public async Task ApprovalAnswerWithWords_IsBadRequest() + { + await using var host = await ResponsesHost.StartAsync( + ApprovalYaml, + new GatedToolCallingChatClient(), + configure: options => options.AddToolSource(_ => new GatedSource(() => GatedSendEmail(() => { })))); + + using var first = await host.PostAsync("""{ "stream": false, "input": "send it" }"""); + var convId = (await ResponsesHost.ReadJsonAsync(first)).ContinuationId(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": "send it", "agentcore": { "approval": { "request_id": "req-1", "approved": true } } }"""); + + Assert.Equal(HttpStatusCode.BadRequest, second.StatusCode); + } + + [Fact] + public async Task EditAtAnEarlierMessage_WithdrawsTheWordsAfterIt() + { + using FragmentingChatClient reply = new("answer one", "answer two"); + await using var host = await ResponsesHost.StartAsync(TwoStagesYaml, reply); + + using var first = await host.PostAsync("""{ "stream": false, "input": "first question" }"""); + var firstBody = await ResponsesHost.ReadJsonAsync(first); + var convId = firstBody.ContinuationId(); + var anchor = firstBody["metadata"]!["message_id"]!.GetValue(); + + using var second = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": "second question" }"""); + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + + // Hanging the third turn off the first reply takes back everything after it: the model + // sees the first exchange and the corrected words, but never the withdrawn question. + using var third = await host.PostAsync( + $$"""{ "stream": false, "conversation": "{{convId}}", "input": "corrected question", "agentcore": { "message_id": "q3", "parent_id": "{{anchor}}" } }"""); + Assert.Equal(HttpStatusCode.OK, third.StatusCode); + var thirdRequest = reply.LastRequest; + Assert.NotNull(thirdRequest); + Assert.Contains(thirdRequest, m => m.Text.Contains("first question", StringComparison.Ordinal)); + Assert.DoesNotContain(thirdRequest, m => m.Text.Contains("second question", StringComparison.Ordinal)); + Assert.Contains(thirdRequest, m => m.Text.Contains("corrected question", StringComparison.Ordinal)); + } + + [Fact] + public async Task DialectStream_WritesDrawingsAsTheirOwnEvents() + { + await using var host = await ResponsesHost.StartAsync( + DrawingYaml, + new DrawingChatClient(), + configure: options => options.Bind("DrawIt", (AgentCore.Application.Runtime.TurnInvocation? turn) => + { + turn?.Screen?.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); + return ValueTask.FromResult("drew a Card; buttons: none"); + })); + + using var response = await host.PostAsync( + """{ "stream": true, "input": "show me revenue", "agentcore": { "message_id": "m1" } }"""); + var events = await AgentCore.AspNetCore.Tests.Fakes.ChatCompletionsHost.ReadEventsAsync(response); + + var chunks = events + .Where(text => text != "[DONE]") + .Select(text => System.Text.Json.JsonDocument.Parse(text).RootElement) + .ToList(); + var drawing = Assert.Single(chunks, static chunk => chunk.TryGetProperty("agentcore_data", out var data) + && data.ValueKind != System.Text.Json.JsonValueKind.Null); + Assert.Equal("generative-ui", drawing.GetProperty("agentcore_data").GetProperty("name").GetString()); + Assert.Equal( + "Q3 revenue", + drawing.GetProperty("agentcore_data").GetProperty("data").GetProperty("title").GetString()); + } + + [Fact] + public async Task PureStream_WritesNoDialectEvents() + { + await using var host = await ResponsesHost.StartAsync( + DrawingYaml, + new DrawingChatClient(), + configure: options => options.Bind("DrawIt", (AgentCore.Application.Runtime.TurnInvocation? turn) => + { + turn?.Screen?.Publish("generative-ui", "chart-1", new { title = "Q3 revenue" }); + return ValueTask.FromResult("drew a Card; buttons: none"); + })); + + using var response = await host.PostAsync("""{ "stream": true, "input": "show me revenue" }"""); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var events = await AgentCore.AspNetCore.Tests.Fakes.ChatCompletionsHost.ReadEventsAsync(response); + + Assert.DoesNotContain(events + .Where(text => text != "[DONE]") + .Select(text => System.Text.Json.JsonDocument.Parse(text).RootElement), + static chunk => chunk.TryGetProperty("agentcore_data", out var data) + && data.ValueKind != System.Text.Json.JsonValueKind.Null); + } + private const string TerminalYaml = + """ + apiVersion: agentcore/v1 + name: responses-terminal + agents: + defaults: + model: { ref: reply } + items: + - { id: solo, instructions: "answer one" } + policy: + initial: done + stages: + - { id: done, agent: solo, terminal: true } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + private const string ApprovalYaml = + """ + apiVersion: agentcore/v1 + name: responses-approval + agents: + defaults: + model: { ref: reply } + items: + - { id: greeter, instructions: "send the mail", tools: [ send_email ] } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + private const string DrawingYaml = + """ + apiVersion: agentcore/v1 + name: responses-drawing + tools: + - id: draw_it + kind: binding + binds: DrawIt + description: Draw something for the caller. + agents: + defaults: + model: { ref: reply } + items: + - { id: greeter, instructions: "greet the caller", tools: [ draw_it ] } + - { id: closer, instructions: "close the call", tools: [ draw_it ] } + policy: + initial: greeting + stages: + - { id: greeting, agent: greeter, to: [ { stage: close } ] } + - { id: close, agent: closer, to: [ { stage: greeting } ] } + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + llm: + - { kind: openai, model: gpt-4.1-mini, as: reply } + """; + + private static Microsoft.Extensions.AI.ApprovalRequiredAIFunction GatedSendEmail(Action onSend) => + new(Microsoft.Extensions.AI.AIFunctionFactory.Create( + (string to) => + { + onSend(); + return "sent"; + }, + "send_email", + "Send an email.")); + + /// A tool source that serves one gated id, standing in for an approval-required host tool. + private sealed class GatedSource(Func build) + : AgentCore.Application.Ports.IToolSource + { + public ValueTask> ProvideAsync( + AgentCore.Application.Tools.Registry.ToolSourceContext context, CancellationToken cancellationToken = default) + => ValueTask.FromResult>( + [new AgentCore.Application.Tools.Registry.ToolRegistration("send_email", "Send an email.", build)]); + } + + /// Calls the first tool it is offered, once, then answers in words. + private sealed class GatedToolCallingChatClient : Microsoft.Extensions.AI.IChatClient + { + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + Microsoft.Extensions.AI.ChatOptions? options = null, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.Yield(); + + var alreadyCalled = messages.Any(message => message.Contents.OfType().Any()); + + if (!alreadyCalled && options?.Tools?.OfType().FirstOrDefault() is { } tool) + { + yield return new Microsoft.Extensions.AI.ChatResponseUpdate( + Microsoft.Extensions.AI.ChatRole.Assistant, + [new Microsoft.Extensions.AI.FunctionCallContent( + "call_1", + tool.Name, + new Dictionary(StringComparer.Ordinal) { ["to"] = "a@b.com" })]); + yield break; + } + + yield return new Microsoft.Extensions.AI.ChatResponseUpdate(Microsoft.Extensions.AI.ChatRole.Assistant, "done."); + } + + public async Task GetResponseAsync( + IEnumerable messages, + Microsoft.Extensions.AI.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() + { + } + } + + /// Calls the first tool it is offered, once, then answers in words. + private sealed class DrawingChatClient : Microsoft.Extensions.AI.IChatClient + { + public async IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, + Microsoft.Extensions.AI.ChatOptions? options = null, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.Yield(); + + var alreadyDrew = messages.Any(message => message.Contents.OfType().Any()); + + if (!alreadyDrew && options?.Tools?.OfType().FirstOrDefault() is { } tool) + { + yield return new Microsoft.Extensions.AI.ChatResponseUpdate( + Microsoft.Extensions.AI.ChatRole.Assistant, + [new Microsoft.Extensions.AI.FunctionCallContent( + "call_1", + tool.Name, + new Dictionary(StringComparer.Ordinal) { ["what"] = "a card" })]); + yield break; + } + + yield return new Microsoft.Extensions.AI.ChatResponseUpdate(Microsoft.Extensions.AI.ChatRole.Assistant, "here it is."); + } + + public async Task GetResponseAsync( + IEnumerable messages, + Microsoft.Extensions.AI.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() + { + } + } +} + +/// Reads what one Responses answer carries. +internal static class ResponsesAnswer +{ + /// Reads the assistant text of one answer. + /// The answer. + /// Every output text, joined. + internal static string OutputText(this JsonNode body) + => string.Join("", body["output"]?.AsArray() + .SelectMany(o => o?["content"]?.AsArray() ?? []) + .Select(c => c?["text"]?.GetValue() ?? "") ?? []); + + /// Reads the id a later turn hangs off: the conversation, or the response. + /// The answer. + /// The continuation id. + internal static string ContinuationId(this JsonNode body) + { + if (body["conversation"] is JsonObject conversation + && conversation["id"]?.GetValue() is { Length: > 0 } conversationId) + { + return conversationId; + } + + return body["id"]?.GetValue() + ?? throw new InvalidOperationException("Answer carries no continuation id."); + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs new file mode 100644 index 00000000..57d10c6f --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/Fakes/ResponsesHost.cs @@ -0,0 +1,105 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.AspNetCore.DependencyInjection; +using AgentCore.AspNetCore.Endpoints; +using AgentCore.TestSupport; +using System.Text; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.Fakes; + +/// +/// One real host, on a real socket, over a fake model, answering the Responses path. +/// +/// +/// Mirrors : Kestrel takes port zero and reports the +/// port it got, so many tests run at once. No test here reaches a network or needs +/// an API key. +/// +internal sealed class ResponsesHost : IAsyncDisposable +{ + private readonly WebApplication _app; + + private ResponsesHost(WebApplication app, HttpClient client) + { + _app = app; + Client = client; + } + + /// Gets the client that speaks to the host. + public HttpClient Client { get; } + + /// Starts one host over one document. + /// The document, as YAML. + /// The model behind every name the routing factory does not hold. + /// Anything else the test binds on the options. + /// The started host. + public static async Task StartAsync( + string yaml, IChatClient reply, Action? configure = null) + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + + builder.Services.AddAgentCore(options => + { + options.Configuration = ConfigurationLoader.LoadYaml(yaml); + options.UseChatClients(_ => new RoutingChatClientFactory(reply)); + configure?.Invoke(options); + }); + + var app = builder.Build(); + app.MapResponses(); + await app.StartAsync(); + + var address = app.Services + .GetRequiredService() + .Features + .Get()! + .Addresses + .First(); + + HttpClient client = new() { BaseAddress = new Uri(address, UriKind.Absolute) }; + return new ResponsesHost(app, client); + } + + /// Sends one Responses request body. + /// The request body. + /// The answer. + public async Task PostAsync(string json) + { + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + return await Client.PostAsync( + ResponsesEndpointRouteBuilderExtensions.DefaultPattern, content, TestContext.Current.CancellationToken); + } + + /// Reads one answer as a node tree. + /// The answer. + /// The body. + public static async Task ReadJsonAsync(HttpResponseMessage response) + { + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + return JsonNode.Parse(text)!; + } + + /// Reads one answer as text. + /// The answer. + /// The body. + public static Task ReadTextAsync(HttpResponseMessage response) + => response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + /// + public async ValueTask DisposeAsync() + { + Client.Dispose(); + await _app.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs new file mode 100644 index 00000000..db63d3e6 --- /dev/null +++ b/tests/AgentCore.Infrastructure.Tests/Calls/Postgres/ContinuationStoreTests.cs @@ -0,0 +1,69 @@ +using System.Text.Json; +using AgentCore.Infrastructure.Calls.Postgres; +using AgentCore.Infrastructure.Tests.Database.Postgres; +using Xunit; + +namespace AgentCore.Infrastructure.Tests.Calls.Postgres; + +/// The continuation map beside the calls: one envelope per opaque id. +public sealed class ContinuationStoreTests : PostgresDatabaseTest +{ + /// + protected override bool Migrated => true; + + [PostgresFact] + public async Task Migration_Applied_MakesTheContinuationTable() + { + // Act + var tables = await ScalarAsync( + """ + SELECT count(*) FROM information_schema.tables + WHERE table_schema = 'agentcore' AND table_name = 'response_continuation' + """); + + // Assert + Assert.Equal(1, tables); + } + + [PostgresFact] + public async Task RoundTrip_SaveGetDelete() + { + // Arrange + PostgresCallStore store = new(DataSource); + using var document = JsonDocument.Parse("""{ "callId": "c1", "state": {} }"""); + + // Act + await store.SaveContinuationAsync("conv_1", document.RootElement, Token); + var found = await store.GetContinuationAsync("conv_1", Token); + + // Assert + Assert.Equal(document.RootElement.GetRawText(), found?.GetRawText()); + + // Act + using var replacement = JsonDocument.Parse("{}"); + await store.SaveContinuationAsync("conv_1", replacement.RootElement, Token); + var replaced = await store.GetContinuationAsync("conv_1", Token); + + // Assert + Assert.Equal("{}", replaced?.GetRawText()); + + // Act + await store.DeleteContinuationAsync("conv_1", Token); + + // Assert + Assert.Null(await store.GetContinuationAsync("conv_1", Token)); + } + + [PostgresFact] + public async Task GetContinuation_UnknownId_AnswersNull() + { + // Arrange + PostgresCallStore store = new(DataSource); + + // Act + var found = await store.GetContinuationAsync("conv_missing", Token); + + // Assert + Assert.Null(found); + } +} diff --git a/tests/AgentCore.TestSupport/DelegatingCallStore.cs b/tests/AgentCore.TestSupport/DelegatingCallStore.cs index 6d98a71f..56e78c36 100644 --- a/tests/AgentCore.TestSupport/DelegatingCallStore.cs +++ b/tests/AgentCore.TestSupport/DelegatingCallStore.cs @@ -100,4 +100,19 @@ public virtual ValueTask AttachPrincipalAsync( 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); } From 391cb25411cb2ef3548f1fd9f5cb0d5e10144fc6 Mon Sep 17 00:00:00 2001 From: MatthewHsu1 Date: Mon, 14 Sep 2026 02:06:23 -0600 Subject: [PATCH 25/32] refactor: remove demo folder --- .github/workflows/ci.yml | 14 - .github/workflows/release.yml | 6 +- .gitignore | 14 +- README.md | 90 +- .../config => config}/example.yaml | 0 demo/AgentCore.Demo/AgentCore.Demo.csproj | 45 - demo/AgentCore.Demo/Program.cs | 41 - .../Properties/launchSettings.json | 32 - demo/AgentCore.Demo/config/.gitkeep | 0 demo/AgentCore.Demo/config/demo.yaml | 82 - demo/chat-ui/components.json | 24 - demo/chat-ui/index.html | 16 - demo/chat-ui/package-lock.json | 7997 ----------------- demo/chat-ui/package.json | 43 - demo/chat-ui/public/embed.js | 74 - demo/chat-ui/src/App.tsx | 54 - demo/chat-ui/src/README.md | 32 - demo/chat-ui/src/Widget.tsx | 122 - .../src/components/AgentCoreSidebar.tsx | 33 - .../components/GenerativeUiDataUI.test.tsx | 162 - .../src/components/GenerativeUiDataUI.tsx | 54 - .../components/assistant-ui/attachment.tsx | 299 - .../src/components/assistant-ui/draft.tsx | 100 - .../assistant-ui/elements/sources.tsx | 82 - .../src/components/assistant-ui/file.tsx | 265 - .../assistant-ui/follow-up-suggestions.tsx | 83 - .../components/assistant-ui/generative-ui.tsx | 24 - .../src/components/assistant-ui/image.tsx | 479 - .../components/assistant-ui/markdown-text.tsx | 259 - .../src/components/assistant-ui/reasoning.tsx | 398 - .../components/assistant-ui/regenerate.tsx | 60 - .../src/components/assistant-ui/search.tsx | 78 - .../src/components/assistant-ui/speaker.tsx | 70 - .../components/assistant-ui/thread-list.tsx | 433 - .../src/components/assistant-ui/thread.tsx | 872 -- .../assistant-ui/threadlist-sidebar.tsx | 74 - .../components/assistant-ui/tool-fallback.tsx | 620 -- .../components/assistant-ui/tool-group.tsx | 221 - .../assistant-ui/tooltip-icon-button.tsx | 48 - .../assistant-ui/use-collapsible-open.ts | 41 - .../src/components/elements/agent-status.tsx | 86 - .../elements/conversation-search.tsx | 116 - .../src/components/elements/day-separator.tsx | 101 - .../src/components/elements/draft-restore.tsx | 59 - .../src/components/elements/error-state.tsx | 75 - .../components/elements/launcher-bubble.tsx | 128 - .../components/elements/message-timing.tsx | 49 - .../components/elements/regenerate-menu.tsx | 79 - .../src/components/elements/stopped-run.tsx | 72 - .../src/components/elements/surfaces.tsx | 120 - .../elements/thinking-indicator.tsx | 43 - .../src/components/elements/tool-error.tsx | 96 - .../components/elements/typing-indicator.tsx | 59 - demo/chat-ui/src/components/icons/github.tsx | 12 - demo/chat-ui/src/components/ui/avatar.tsx | 107 - demo/chat-ui/src/components/ui/button.tsx | 64 - .../chat-ui/src/components/ui/collapsible.tsx | 31 - demo/chat-ui/src/components/ui/dialog.tsx | 156 - demo/chat-ui/src/components/ui/input.tsx | 21 - demo/chat-ui/src/components/ui/separator.tsx | 26 - demo/chat-ui/src/components/ui/sheet.tsx | 143 - demo/chat-ui/src/components/ui/sidebar.tsx | 724 -- demo/chat-ui/src/components/ui/skeleton.tsx | 13 - demo/chat-ui/src/components/ui/tooltip.tsx | 55 - demo/chat-ui/src/hooks/use-mobile.ts | 19 - demo/chat-ui/src/index.css | 1083 --- demo/chat-ui/src/lib/utils.ts | 6 - demo/chat-ui/src/main.tsx | 10 - .../src/runtime/AgentCoreRuntime.test.ts | 55 - demo/chat-ui/src/runtime/AgentCoreRuntime.ts | 253 - .../runtime/LocalThreadListAdapter.test.ts | 58 - .../src/runtime/LocalThreadListAdapter.ts | 63 - demo/chat-ui/src/runtime/transport.test.ts | 548 -- demo/chat-ui/src/runtime/transport.ts | 517 -- demo/chat-ui/src/vite-env.d.ts | 1 - demo/chat-ui/src/widget-main.tsx | 10 - demo/chat-ui/tsconfig.app.json | 40 - demo/chat-ui/tsconfig.json | 17 - demo/chat-ui/tsconfig.node.json | 16 - demo/chat-ui/tsconfig.test.json | 36 - demo/chat-ui/vite.config.ts | 46 - demo/chat-ui/widget.html | 25 - .../Configuration/ConfigurationLoaderTests.cs | 2 +- .../Validation/ConfigurationValidatorTests.cs | 2 +- 84 files changed, 68 insertions(+), 18615 deletions(-) rename {demo/AgentCore.Demo/config => config}/example.yaml (100%) delete mode 100644 demo/AgentCore.Demo/AgentCore.Demo.csproj delete mode 100644 demo/AgentCore.Demo/Program.cs delete mode 100644 demo/AgentCore.Demo/Properties/launchSettings.json delete mode 100644 demo/AgentCore.Demo/config/.gitkeep delete mode 100644 demo/AgentCore.Demo/config/demo.yaml delete mode 100644 demo/chat-ui/components.json delete mode 100644 demo/chat-ui/index.html delete mode 100644 demo/chat-ui/package-lock.json delete mode 100644 demo/chat-ui/package.json delete mode 100644 demo/chat-ui/public/embed.js delete mode 100644 demo/chat-ui/src/App.tsx delete mode 100644 demo/chat-ui/src/README.md delete mode 100644 demo/chat-ui/src/Widget.tsx delete mode 100644 demo/chat-ui/src/components/AgentCoreSidebar.tsx delete mode 100644 demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx delete mode 100644 demo/chat-ui/src/components/GenerativeUiDataUI.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/attachment.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/draft.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/elements/sources.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/file.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/follow-up-suggestions.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/generative-ui.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/image.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/markdown-text.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/reasoning.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/regenerate.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/search.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/speaker.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/thread-list.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/thread.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/threadlist-sidebar.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/tool-group.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/tooltip-icon-button.tsx delete mode 100644 demo/chat-ui/src/components/assistant-ui/use-collapsible-open.ts delete mode 100644 demo/chat-ui/src/components/elements/agent-status.tsx delete mode 100644 demo/chat-ui/src/components/elements/conversation-search.tsx delete mode 100644 demo/chat-ui/src/components/elements/day-separator.tsx delete mode 100644 demo/chat-ui/src/components/elements/draft-restore.tsx delete mode 100644 demo/chat-ui/src/components/elements/error-state.tsx delete mode 100644 demo/chat-ui/src/components/elements/launcher-bubble.tsx delete mode 100644 demo/chat-ui/src/components/elements/message-timing.tsx delete mode 100644 demo/chat-ui/src/components/elements/regenerate-menu.tsx delete mode 100644 demo/chat-ui/src/components/elements/stopped-run.tsx delete mode 100644 demo/chat-ui/src/components/elements/surfaces.tsx delete mode 100644 demo/chat-ui/src/components/elements/thinking-indicator.tsx delete mode 100644 demo/chat-ui/src/components/elements/tool-error.tsx delete mode 100644 demo/chat-ui/src/components/elements/typing-indicator.tsx delete mode 100644 demo/chat-ui/src/components/icons/github.tsx delete mode 100644 demo/chat-ui/src/components/ui/avatar.tsx delete mode 100644 demo/chat-ui/src/components/ui/button.tsx delete mode 100644 demo/chat-ui/src/components/ui/collapsible.tsx delete mode 100644 demo/chat-ui/src/components/ui/dialog.tsx delete mode 100644 demo/chat-ui/src/components/ui/input.tsx delete mode 100644 demo/chat-ui/src/components/ui/separator.tsx delete mode 100644 demo/chat-ui/src/components/ui/sheet.tsx delete mode 100644 demo/chat-ui/src/components/ui/sidebar.tsx delete mode 100644 demo/chat-ui/src/components/ui/skeleton.tsx delete mode 100644 demo/chat-ui/src/components/ui/tooltip.tsx delete mode 100644 demo/chat-ui/src/hooks/use-mobile.ts delete mode 100644 demo/chat-ui/src/index.css delete mode 100644 demo/chat-ui/src/lib/utils.ts delete mode 100644 demo/chat-ui/src/main.tsx delete mode 100644 demo/chat-ui/src/runtime/AgentCoreRuntime.test.ts delete mode 100644 demo/chat-ui/src/runtime/AgentCoreRuntime.ts delete mode 100644 demo/chat-ui/src/runtime/LocalThreadListAdapter.test.ts delete mode 100644 demo/chat-ui/src/runtime/LocalThreadListAdapter.ts delete mode 100644 demo/chat-ui/src/runtime/transport.test.ts delete mode 100644 demo/chat-ui/src/runtime/transport.ts delete mode 100644 demo/chat-ui/src/vite-env.d.ts delete mode 100644 demo/chat-ui/src/widget-main.tsx delete mode 100644 demo/chat-ui/tsconfig.app.json delete mode 100644 demo/chat-ui/tsconfig.json delete mode 100644 demo/chat-ui/tsconfig.node.json delete mode 100644 demo/chat-ui/tsconfig.test.json delete mode 100644 demo/chat-ui/vite.config.ts delete mode 100644 demo/chat-ui/widget.html diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e33a8eb4..dda9691d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,16 +46,6 @@ jobs: with: dotnet-version: '10.0.x' - - uses: actions/setup-node@v4 - with: - node-version: '24' - cache: npm - cache-dependency-path: demo/chat-ui/package-lock.json - - - name: Chat UI dependencies - run: npm ci - working-directory: demo/chat-ui - - name: Restore run: | dotnet restore @@ -64,10 +54,6 @@ jobs: - name: Build run: dotnet build --no-restore -c Release - - name: Chat UI tests - run: npm test - working-directory: demo/chat-ui - - name: Unit tests run: dotnet test --no-build -c Release --filter "FullyQualifiedName!~AgentCore.Evals" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ae4ee0e9..e02d8fe8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,10 +61,8 @@ jobs: - name: Restore run: dotnet restore - # SkipClientAppBuild keeps the demo's npm target from running. It would build a browser - # bundle that no package contains, and it is the only reason this job would need Node. - name: Build - run: dotnet build --no-restore -c Release -p:SkipClientAppBuild=true + run: dotnet build --no-restore -c Release - name: Unit tests run: dotnet test --no-build -c Release @@ -76,7 +74,7 @@ jobs: run: dotnet pack --no-build -c Release -o artifacts # IsPackable decides what becomes a package; this asserts that decision rather than trusting - # it. Five, not six, is what proves nothing under demo/ leaked into a release. + # it. Five packages ship as a set. - name: Exactly five packages run: | count=$(ls artifacts/*.nupkg | wc -l) diff --git a/.gitignore b/.gitignore index 0306a2f8..b113dca4 100644 --- a/.gitignore +++ b/.gitignore @@ -40,9 +40,6 @@ bld/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ -# The demo's UI bundle. Vite writes it from demo/chat-ui on every build. -demo/AgentCore.Demo/wwwroot/ - # Visual Studio 2017 auto generated files Generated\ Files/ @@ -492,10 +489,11 @@ $RECYCLE.BIN/ !.env.example # The real configuration document belongs to the consuming project. -# Only config/example.yaml and config/demo.yaml are committed here. -demo/AgentCore.Demo/config/config.yaml -demo/AgentCore.Demo/config/config.yml -demo/AgentCore.Demo/config/config.json +# Only config/example.yaml is committed here. +config/config.yaml +config/config.yml +config/config.json +config/local.yaml # The evaluation store and the response cache. The store is a build output: it holds one run, and # `dotnet aieval report` reads it. The committed inputs are golden/ inside tests/AgentCore.Evals. @@ -509,7 +507,5 @@ CLAUDE.md docs/ .superpowers/ -demo/AgentCore.Demo/config/local.yaml - .serena .sonarqube \ No newline at end of file diff --git a/README.md b/README.md index 10838805..100ea185 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,51 @@ # AgentCore -A .NET library for building voice and chat agents. You bring the host; AgentCore brings the turn -loop, the vendor seams, and the configuration document that drives them. - -## Install - -``` -dotnet add package AgentCore.Hosting +A .NET library for building voice and chat agents. The agent is a configuration document; the host is two calls. + +## 1. Describe the agent + +`config/helper.yaml`: + +```yaml +apiVersion: agentcore/v1 +name: helper + +agents: + defaults: + model: { ref: reply } + instructions: | + You are a helpful assistant. Answer plainly and briefly. + items: + - id: helper + instructions: | + Answer whatever the person asks. + tools: [] + +policy: + initial: talk + stages: + - id: talk + agent: helper + terminal: true + +providers: + llm: + - { kind: openai, model: gpt-5.6-luna, as: reply } + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } ``` -`AgentCore.Hosting` brings the rest of the set with it. +`agents` holds the instructions, `policy` holds the stages, `providers` binds the vendors. No C# changes to add a stage, a tool, or a model. +[`config/example.yaml`](https://github.com/MatthewHsu1/AgentCore/blob/main/config/example.yaml) +is the annotated tour of every key. -## Use +## 2. Wire up the host ```csharp +using AgentCore.Hosting; + var builder = WebApplication.CreateBuilder(args); builder.AddAgentCoreHost(); @@ -22,11 +54,26 @@ app.MapAgentCoreHost(); app.Run(); ``` -AgentCore reads `config/example.yaml` unless `AgentCore__ConfigurationPath` names another document. +`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 text endpoints, and the call socket. A document it cannot find is a startup failure, never a silent default. -[`demo/AgentCore.Demo/config/example.yaml`](https://github.com/MatthewHsu1/AgentCore/blob/main/demo/AgentCore.Demo/config/example.yaml) -is the annotated tour of every key. +## Install + +``` +dotnet add package AgentCore.Hosting +``` + +`AgentCore.Hosting` brings the rest of the set with it. + +## 3. Talk to it + +Over the OpenAI-compatible endpoint (`/v1/chat/completions`), the document above holds this conversation: + +``` +User: Hello + +Assistant: How can I help you today! +``` ## The packages @@ -40,25 +87,6 @@ is the annotated tour of every key. They share one version and ship as a set. Mixing versions across them is unsupported. -## The demo - -[`demo/`](https://github.com/MatthewHsu1/AgentCore/tree/main/demo) holds a working host and a React -chat UI. Neither is published. It is how you watch the agent work, and the starting point you copy -when writing a UI of your own. - -``` -export OPENAI_API_KEY=sk-... -cd demo/AgentCore.Demo && dotnet run --launch-profile demo -``` - -The `demo` profile runs -[`config/demo.yaml`](https://github.com/MatthewHsu1/AgentCore/blob/main/demo/AgentCore.Demo/config/demo.yaml), -the smallest document that holds a real conversation: it needs only an OpenAI key. The `example` -profile runs the annotated reference instead, which names tools and vendors this repository cannot -give you a key for, and will not start. - -Node is required to build the demo's UI. - ## Licence MIT diff --git a/demo/AgentCore.Demo/config/example.yaml b/config/example.yaml similarity index 100% rename from demo/AgentCore.Demo/config/example.yaml rename to config/example.yaml diff --git a/demo/AgentCore.Demo/AgentCore.Demo.csproj b/demo/AgentCore.Demo/AgentCore.Demo.csproj deleted file mode 100644 index bf0b5b68..00000000 --- a/demo/AgentCore.Demo/AgentCore.Demo.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - - Exe - d7549002-fd56-4ad5-b74d-3360ef14904e - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demo/AgentCore.Demo/Program.cs b/demo/AgentCore.Demo/Program.cs deleted file mode 100644 index d42cae04..00000000 --- a/demo/AgentCore.Demo/Program.cs +++ /dev/null @@ -1,41 +0,0 @@ -using AgentCore.Hosting; - -var builder = WebApplication.CreateBuilder(args); - -builder.AddAgentCoreHost(); - -var app = builder.Build(); - -app.MapAgentCoreHost(); - -// Which sites may frame the widget. -// -// Configure with, e.g.: -// "Widget": { "AllowedOrigins": [ "https://exmaple.com" ] } -var widgetOrigins = builder.Configuration.GetSection("Widget:AllowedOrigins").Get(); -var frameAncestors = widgetOrigins is { Length: > 0 } - ? string.Join(' ', widgetOrigins) - : "'none'"; - -app.Use(async (context, next) => -{ - if (context.Request.Path.StartsWithSegments("/chat")) - { - context.Response.Headers["Content-Security-Policy"] = $"frame-ancestors {frameAncestors}"; - } - - await next(); -}); - -app.UseStaticFiles(); - -// nonfile: without it, routing selects this fallback for /chat/assets/index.js, the static file -// middleware stands down because an endpoint is already selected, and every script and stylesheet -// is answered with the page. The constraint makes the fallback decline anything whose last segment -// looks like a file, so static files sees no endpoint and serves the real bytes. -// -// The /chat scope: an unmatched /v1 route must answer 404, or a mistyped endpoint reaches the -// browser as a confusing HTML parse error instead of an obvious miss. -app.MapFallbackToFile("/chat/{*path:nonfile}", "chat/index.html"); - -app.Run(); diff --git a/demo/AgentCore.Demo/Properties/launchSettings.json b/demo/AgentCore.Demo/Properties/launchSettings.json deleted file mode 100644 index 0875f03e..00000000 --- a/demo/AgentCore.Demo/Properties/launchSettings.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "profiles": { - "local": { - "commandName": "Project", - "applicationUrl": "http://localhost:5199", - "launchBrowser": false, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development", - "AgentCore__ConfigurationPath": "config/local.yaml" - } - }, - "example": { - "commandName": "Project", - "applicationUrl": "http://localhost:5199", - "launchBrowser": false, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development", - "AgentCore__ConfigurationPath": "config/example.yaml" - } - }, - "demo": { - "commandName": "Project", - "applicationUrl": "http://localhost:5199", - "launchBrowser": false, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development", - "AgentCore__ConfigurationPath": "config/demo.yaml" - } - } - } -} diff --git a/demo/AgentCore.Demo/config/.gitkeep b/demo/AgentCore.Demo/config/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/demo/AgentCore.Demo/config/demo.yaml b/demo/AgentCore.Demo/config/demo.yaml deleted file mode 100644 index e4a3ec1f..00000000 --- a/demo/AgentCore.Demo/config/demo.yaml +++ /dev/null @@ -1,82 +0,0 @@ -# The smallest document that gives you a real conversation in the browser. -# -# example.yaml is the annotated reference: it shows every feature, and it needs a knowledge base, -# an orders API, and a case system before it does anything interesting. This one needs an OpenAI -# key and nothing else. Two stages, one tool-free agent, and an extractor that watches for goodbye. -# -# export OPENAI_API_KEY=sk-... -# cd demo/AgentCore.Demo && dotnet run --launch-profile demo -# open http://localhost:5199/chat -# -# No key is written here. ${secret:...} references are never used by this file: OPENAI_API_KEY is -# read straight from the environment at startup, so this file is safe to commit. -apiVersion: agentcore/v1 -name: demo-chat - -fallbackReply: "Sorry, I could not finish that. Please try again." - -# The extractor reads the reply after every turn and writes the state slots below. It is a second, -# cheaper model call per turn, and it is what moves the conversation between stages. -state: - callerSaidGoodbye: { type: boolean, default: false, writer: extractor } - -extractor: - model: { ref: fill } - when: after_reply - -guards: - saidGoodbye: - { var: callerSaidGoodbye } - -# Drawing. The agent asks for a picture in words and gets back one line naming the buttons; a -# second, private model call turns the request into a tree of cards, charts, tables and buttons and -# sends it straight to the browser. The 27-component vocabulary never reaches the agent below, so -# listing this costs it 239 bytes. -# -# The drawing call uses the first model declared in providers.llm, which is 'reply'. -tools: - - { id: draw, kind: builtin, uses: ui.draw } - -agents: - defaults: - model: { ref: reply } - instructions: | - You are a helpful assistant. Answer plainly and briefly. - Do not invent facts. Say when you do not know something. - items: - - id: helper - instructions: | - Answer whatever the person asks. - When the answer is numbers, a comparison, a list of things, or a choice for the person to - make, call draw and describe what you want shown. Put the data in the request: whoever - draws it cannot see this conversation. Then say one short sentence about it. Do not repeat - the numbers you just had drawn. - tools: [ draw ] - - id: closer - instructions: "If the person is leaving. Say goodbye in one short sentence." - tools: [] - -policy: - initial: talk - stages: - - id: talk - agent: helper - to: - - { stage: close, when: saidGoodbye } - - id: close - agent: closer - terminal: true - -providers: - # Two names, two models. reply is what the person reads; fill is the extractor, which only has to - # answer a small structured question and so does not need the larger model. - llm: - - { kind: openai, model: gpt-5.6-luna, as: reply } - - { kind: openai, model: gpt-5.6-luna, as: fill } - - # Required by the schema even for a text-only host, and inert until something opens /v1/call. The - # chat UI never touches either one. - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } diff --git a/demo/chat-ui/components.json b/demo/chat-ui/components.json deleted file mode 100644 index 38499b27..00000000 --- a/demo/chat-ui/components.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "new-york", - "rsc": false, - "tsx": true, - "tailwind": { - "config": "", - "css": "src/index.css", - "baseColor": "neutral", - "cssVariables": true, - "prefix": "" - }, - "aliases": { - "components": "@/components", - "utils": "@/lib/utils", - "ui": "@/components/ui", - "lib": "@/lib", - "hooks": "@/hooks" - }, - "iconLibrary": "lucide", - "registries": { - "@assistant-ui": "https://r.assistant-ui.com/{name}.json" - } -} diff --git a/demo/chat-ui/index.html b/demo/chat-ui/index.html deleted file mode 100644 index 3756f3fa..00000000 --- a/demo/chat-ui/index.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - AgentCore Chat - - -
- - - diff --git a/demo/chat-ui/package-lock.json b/demo/chat-ui/package-lock.json deleted file mode 100644 index 7f4e6f67..00000000 --- a/demo/chat-ui/package-lock.json +++ /dev/null @@ -1,7997 +0,0 @@ -{ - "name": "agentcore-chat", - "version": "0.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "agentcore-chat", - "version": "0.0.0", - "dependencies": { - "@assistant-ui/core": "^0.3.14", - "@assistant-ui/react": "^0.15.15", - "@assistant-ui/react-generative-ui": "0.0.15", - "@assistant-ui/react-markdown": "^0.14.11", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "lucide-react": "^1.32.0", - "radix-ui": "^1.6.7", - "react": "^19.2.0", - "react-dom": "^19.2.0", - "react-markdown": "^10.1.0", - "remark-gfm": "^4.0.1", - "tailwind-merge": "^3.6.0", - "tw-animate-css": "^1.4.0", - "tw-shimmer": "^0.4.12", - "zustand": "^5.0.15" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.3.3", - "@testing-library/react": "^16.3.2", - "@types/node": "^24.13.3", - "@types/react": "^19.2.0", - "@types/react-dom": "^19.2.0", - "@vitejs/plugin-react": "^5.0.0", - "assistant-ui": "^0.0.111", - "happy-dom": "^20.11.6", - "tailwindcss": "^4.3.3", - "typescript": "^5.9.0", - "vite": "^7.0.0", - "vitest": "^4.1.11" - } - }, - "node_modules/@assistant-ui/agent-launcher": { - "version": "0.1.11", - "resolved": "https://registry.npmjs.org/@assistant-ui/agent-launcher/-/agent-launcher-0.1.11.tgz", - "integrity": "sha512-3kRmHRAeYXy+38kw83l203a/hnCyWUnSEdYv1Oe1ZrP6HWOplXKytPsYj43NmeBTURbvC2ecjSLXREdwyi7+yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.6" - } - }, - "node_modules/@assistant-ui/core": { - "version": "0.3.14", - "resolved": "https://registry.npmjs.org/@assistant-ui/core/-/core-0.3.14.tgz", - "integrity": "sha512-UtjUZLUyCjB0ymv4YXtmNtUIyzznUnpNVFntY9wSvvHG7k25HzffCrpi4jiuW0814Zhf/ejouXZja+RuMWLseA==", - "license": "MIT", - "dependencies": { - "assistant-stream": "^0.3.38", - "nanoid": "^6.0.1" - }, - "peerDependencies": { - "@assistant-ui/store": "^0.3.0", - "@assistant-ui/tap": "^0.9.0", - "@types/react": "*", - "assistant-cloud": "^0.1.31", - "react": "^18 || ^19", - "zustand": "^5.0.11" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "assistant-cloud": { - "optional": true - }, - "react": { - "optional": true - }, - "zustand": { - "optional": true - } - } - }, - "node_modules/@assistant-ui/react": { - "version": "0.15.15", - "resolved": "https://registry.npmjs.org/@assistant-ui/react/-/react-0.15.15.tgz", - "integrity": "sha512-gj46xpSW3g0OBzbK6LhIFW3eUzS5IWTECppYTMt4VD2DwoGDZx1C0VFsRNvMLydVdvDzAiyTZPq6AeM+G/+Naw==", - "license": "MIT", - "dependencies": { - "@assistant-ui/core": "^0.3.14", - "@assistant-ui/store": "^0.3.10", - "@assistant-ui/tap": "^0.9.13", - "@radix-ui/primitive": "^1.1.7", - "@radix-ui/react-collection": "^1.1.15", - "@radix-ui/react-compose-refs": "^1.1.5", - "@radix-ui/react-context": "^1.2.2", - "@radix-ui/react-primitive": "^2.1.10", - "@radix-ui/react-use-callback-ref": "^1.1.4", - "@radix-ui/react-use-controllable-state": "^1.2.6", - "@radix-ui/react-use-escape-keydown": "^1.1.5", - "assistant-cloud": "^0.1.41", - "assistant-stream": "^0.3.38", - "radix-ui": "^1.6.7", - "react-textarea-autosize": "^8.5.9", - "safe-content-frame": "^0.0.27", - "zod": "^4.4.3", - "zustand": "^5.0.14" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^18 || ^19", - "react-dom": "^18 || ^19" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@assistant-ui/react-generative-ui": { - "version": "0.0.15", - "resolved": "https://registry.npmjs.org/@assistant-ui/react-generative-ui/-/react-generative-ui-0.0.15.tgz", - "integrity": "sha512-6+oXQ2NJRf2rmNCY7KQSoYddNiNWff1omDrnYsVlahsqOHdJyxNhwcKZarymezAnWEyKf7LJUCal+TSJBnoCBg==", - "license": "MIT", - "dependencies": { - "assistant-stream": "^0.3.38" - }, - "peerDependencies": { - "@assistant-ui/react": "^0.15.0", - "@types/react": "*", - "react": "^18 || ^19", - "zod": "^4.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@assistant-ui/react-markdown": { - "version": "0.14.11", - "resolved": "https://registry.npmjs.org/@assistant-ui/react-markdown/-/react-markdown-0.14.11.tgz", - "integrity": "sha512-0sj0gwNTtLvWS3T6my/dg70QkGHVT9nSr8vjYndPLLni/tas6e1ep9brfg/sLsTMDyN9ZZWMB1KddW5L31WymQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "^2.1.10", - "@radix-ui/react-use-callback-ref": "^1.1.4", - "classnames": "^2.5.1", - "react-markdown": "^10.1.0" - }, - "peerDependencies": { - "@assistant-ui/react": "^0.15.0", - "@types/react": "*", - "react": "^18 || ^19" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@assistant-ui/store": { - "version": "0.3.10", - "resolved": "https://registry.npmjs.org/@assistant-ui/store/-/store-0.3.10.tgz", - "integrity": "sha512-QSFgodFt/daEjyaY09WdahNewsGPtAeY+DkSb2LM2rPN6634h13R1vJQvCtyWK5YsI5WXgzgbsctzgpIQLU0qw==", - "license": "MIT", - "peerDependencies": { - "@assistant-ui/tap": "^0.9.12", - "@types/react": "*", - "react": "^18 || ^19" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "react": { - "optional": true - } - } - }, - "node_modules/@assistant-ui/tap": { - "version": "0.9.13", - "resolved": "https://registry.npmjs.org/@assistant-ui/tap/-/tap-0.9.13.tgz", - "integrity": "sha512-vNB/9ftdwYZi1wIqaEs8A1qDfbt5ZKBk5+de3wZAoXyuGc8ahKwznWhGjx1XsHuXPM+7e/Gi9iG/ezqrz0xiog==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^18 || ^19" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "react": { - "optional": true - } - } - }, - "node_modules/@babel/code-frame": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.29.7", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", - "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", - "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.8", - "@babel/types": "^7.29.8", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-annotate-as-pure": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", - "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.7.tgz", - "integrity": "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-member-expression-to-functions": "^7.29.7", - "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/traverse": "^7.29.7", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-globals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz", - "integrity": "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", - "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-optimise-call-expression": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.7.tgz", - "integrity": "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", - "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-replace-supers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz", - "integrity": "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-member-expression-to-functions": "^7.29.7", - "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz", - "integrity": "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", - "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", - "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", - "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.8" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-syntax-flow": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.29.7.tgz", - "integrity": "sha512-ajMX6QPcyomotqwpzhkYGxcK2i/us0rs1Qo9QvUpa+Fca0FTmqrzKrctoIYLMxcOhGZldGT/BAVkRGTWBiR8gQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", - "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", - "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-class-properties": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.29.7.tgz", - "integrity": "sha512-GtcpjFvanPfzNQi3eTitsCqtRRmmqzpy/A+yhTR1HaZo1Ly3EA8ZXxlPyHdR8/IuRMYc3E4wdGBewB2QKQjAaA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-flow-strip-types": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.29.7.tgz", - "integrity": "sha512-wRHeUjUjCZnMHmiO5bRgjFLcoEh7JyTdByOW11ahhwNa4V0bmeGEaIvt51yq0zQp2yWIpqfxXXPyUP6GFJZHOQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/plugin-syntax-flow": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz", - "integrity": "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.29.7.tgz", - "integrity": "sha512-idmp1dFaekP9GbcMvG24Kvw2BfhFZjHnNJCkV4WuIY4PskJzwI3f1N5OdgYke38T7rftO6ERulFRn2cFeZwRkg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.29.7.tgz", - "integrity": "sha512-6GM1dhvK3gNODkXcEcMCOLEDCLSoZ/sBbro2Ax8HURyasQ4NshagQixkRFdh5niI6E4gmA/jYI/4aT7rRos3ZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-private-methods": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.29.7.tgz", - "integrity": "sha512-/6Rz4DK1ETDEM/bWHsPHcaEe7ZaT1EqSXjtSP/L0DijOYuaUhiRiOKcwpZ8P7zR4xXEHc2ITdiCgBm9Tpyv9ug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-react-jsx-self": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", - "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-react-jsx-source": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", - "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.7.tgz", - "integrity": "sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/plugin-syntax-typescript": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/preset-flow": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/preset-flow/-/preset-flow-7.29.7.tgz", - "integrity": "sha512-KYIRV0BuaN68CDdsqFkAD7MU7yipUqQNuNElwATdxaIdpTjhvtY82QvkBJs7zV3Evxj2jFAAZ1iO8nyy0nhjqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "@babel/plugin-transform-flow-strip-types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/preset-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.29.7.tgz", - "integrity": "sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "@babel/plugin-syntax-jsx": "^7.29.7", - "@babel/plugin-transform-modules-commonjs": "^7.29.7", - "@babel/plugin-transform-typescript": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/register": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/register/-/register-7.29.7.tgz", - "integrity": "sha512-AMGJoWuES861riy6pcB0fphE1YXybtQnBYQMuIyPv6mKLiosfa79BKTnAOyx215c/3RJPJpdQwoHZ3earVH7AA==", - "dev": true, - "license": "MIT", - "dependencies": { - "clone-deep": "^4.0.1", - "find-cache-dir": "^2.0.0", - "make-dir": "^2.1.0", - "pirates": "^4.0.6", - "source-map-support": "^0.5.16" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/runtime": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", - "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/template": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", - "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", - "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.8", - "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.8", - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.8", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", - "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@clack/core": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.4.3.tgz", - "integrity": "sha512-/kr3UWNtdJfxZtPgDqUOmG2pvwlmcLGheex5yiZKdwbzZJxhV+HMNR9QNmyY5cGwTNV6LrR7Jtp+KjhUAP1qBQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-wrap-ansi": "^0.2.0", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 20.12.0" - } - }, - "node_modules/@clack/prompts": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.7.0.tgz", - "integrity": "sha512-y7/yvZ2TPAnR9+jnc00klvNNLkJiXFFrQA/hlLCcxA9a2A4zQIOimyFQ9XfwYKiGD1fb5GY8vbKIIgO8d5Tb2A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@clack/core": "1.4.3", - "fast-string-width": "^3.0.2", - "fast-wrap-ansi": "^0.2.0", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 20.12.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", - "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", - "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", - "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", - "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", - "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", - "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", - "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", - "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", - "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", - "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", - "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", - "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", - "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", - "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", - "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", - "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", - "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", - "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", - "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", - "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", - "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", - "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", - "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", - "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", - "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", - "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@floating-ui/core": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", - "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", - "license": "MIT", - "dependencies": { - "@floating-ui/utils": "^0.2.12" - } - }, - "node_modules/@floating-ui/dom": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", - "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", - "license": "MIT", - "dependencies": { - "@floating-ui/core": "^1.8.0", - "@floating-ui/utils": "^0.2.12" - } - }, - "node_modules/@floating-ui/react-dom": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", - "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", - "license": "MIT", - "dependencies": { - "@floating-ui/dom": "^1.8.0" - }, - "peerDependencies": { - "react": ">=16.8.0", - "react-dom": ">=16.8.0" - } - }, - "node_modules/@floating-ui/utils": { - "version": "0.2.12", - "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", - "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", - "license": "MIT" - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@napi-rs/lzma-linux-x64-gnu": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", - "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^22.20 || ^24.12 || >=25" - } - }, - "node_modules/@radix-ui/number": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", - "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", - "license": "MIT" - }, - "node_modules/@radix-ui/primitive": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.7.tgz", - "integrity": "sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q==", - "license": "MIT" - }, - "node_modules/@radix-ui/react-accessible-icon": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@radix-ui/react-accessible-icon/-/react-accessible-icon-1.1.15.tgz", - "integrity": "sha512-WTQwcAvQf5sOcuUyi90lKPbhwcvQ+j55cjrSmeaN+L2vKU3DooOvlKw2MDeiJ5IkV5N905KW0/fGojKOBhD11A==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-visually-hidden": "1.2.11" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-accordion": { - "version": "1.2.20", - "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.2.20.tgz", - "integrity": "sha512-jDhG9FvAEnlhnjrsINbNXcUa4G+L1KqSkJSunkbKEzFRcAb52jvM0PjPxPRvhe1HNc5F5yc0yzzWeeqlH4yBIg==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collapsible": "1.1.20", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-alert-dialog": { - "version": "1.1.23", - "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.23.tgz", - "integrity": "sha512-VAYOiQRqj3GPpYJE0I9J+X8Ip05cyVlNdKOFeiGS2Ou1HHGfpl0BxOyZm6nmVDyU+W+NF3/XLzmjHmVGydhwgA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-dialog": "1.1.23", - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-arrow": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.15.tgz", - "integrity": "sha512-v4zggRcjadnI+ClKDuijlQEW4tw3NoaeHc/PwpKnLoLLKNUG4InLegkstooLcRIUWCs+8L22dGURCVuFfOKfnA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-aspect-ratio": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.1.15.tgz", - "integrity": "sha512-fy+dyVR+90nelK8rqIznFlxzx7uPcGbhxH8Nfr2bHb4UfSe+e3hklOC0luK0hDwVwnRX7xTRySpsrQVeW+/oNQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-avatar": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.2.6.tgz", - "integrity": "sha512-4ULOTJ/mqy2hT9GlWa/MFHxHSvH3nJzHnZM1waNsc5Bonv7i70aNenghXmD97S6OJ81ekXONGGt4nT1r0PfEdA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-is-hydrated": "0.1.3", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-checkbox": { - "version": "1.3.11", - "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.11.tgz", - "integrity": "sha512-Gnptr9pDDQxD3hgq2dtPbtrp/c2qH1mBwIzw3X/ivrMb2e1t0jMTi606fVEqFPaQR1ggXIVQWKj3P2WW9v7zGQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-size": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-collapsible": { - "version": "1.1.20", - "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.20.tgz", - "integrity": "sha512-mcGesGplBnzN2sbvJETzpCNfSMyPnb29q1GRLU+Ib7bJrpIG2ywmRoh2V5VbA2uNvKikKUlVbAPks7JDjz4A8Q==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-collection": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.15.tgz", - "integrity": "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-slot": "1.3.3" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-compose-refs": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", - "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-context": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.2.2.tgz", - "integrity": "sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-context-menu": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.3.7.tgz", - "integrity": "sha512-CtXP35dxaB5T3zXSd+E3uHe/QpXcpYnZmxp6OaIbfthtfW4wyb77M23BG+bwIJDtsMwEP/YssdsmNyZu7jhWew==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-menu": "2.1.24", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-dialog": { - "version": "1.1.23", - "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.23.tgz", - "integrity": "sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-focus-guards": "1.1.6", - "@radix-ui/react-focus-scope": "1.1.16", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-slot": "1.3.3", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4", - "aria-hidden": "^1.2.4", - "react-remove-scroll": "^2.7.2" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-direction": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.4.tgz", - "integrity": "sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-dismissable-layer": { - "version": "1.1.19", - "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.19.tgz", - "integrity": "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-effect-event": "0.0.5" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-dropdown-menu": { - "version": "2.1.24", - "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.24.tgz", - "integrity": "sha512-geq8l2rJkxvkXsT9RMgtUE3P8pITFpTsvYpbySi1IH4fZEABD/Gp85myayFgxk0ktljGMJnCbeFkyTusvSvv7g==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-menu": "2.1.24", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-focus-guards": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.6.tgz", - "integrity": "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-focus-scope": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.16.tgz", - "integrity": "sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-form": { - "version": "0.1.16", - "resolved": "https://registry.npmjs.org/@radix-ui/react-form/-/react-form-0.1.16.tgz", - "integrity": "sha512-Q4TLEn2A7TAypxwmd6R9EwrlXDvkfYSDMrq9/887AXAGh+G1rH+kYJKSTv+Si9Y0JPKTwKYv6PviAJosysNimA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-label": "2.1.15", - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-hover-card": { - "version": "1.1.23", - "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.23.tgz", - "integrity": "sha512-H8qONfZd3ltrU3+jHCIgITbWo6e1iTKvP9DHdrvYbX48ooRM5FjEDTn16AMwdfuOGkWdZEhpl3PLL/Wk/AnHDQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-popper": "1.3.7", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-id": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", - "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-label": { - "version": "2.1.15", - "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.15.tgz", - "integrity": "sha512-o/rdYEwZTTo5tjknnPeyQFU45kUC4i/XyeDPP+HGyi6XqpOP6Zf5Ya5vh/Yfe9Id5JiuWnnAx2XqIeD3UYZt0g==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-menu": { - "version": "2.1.24", - "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.24.tgz", - "integrity": "sha512-uW7RVuU6Lp/ZtfeY4b3kL32zccgEWvPv1+cf17ubYzHa9cL8AHokmk36cG/XEiH/smbQvumnieXX9j/e9RqJWA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-focus-guards": "1.1.6", - "@radix-ui/react-focus-scope": "1.1.16", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-popper": "1.3.7", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-slot": "1.3.3", - "@radix-ui/react-use-callback-ref": "1.1.4", - "aria-hidden": "^1.2.4", - "react-remove-scroll": "^2.7.2" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-menubar": { - "version": "1.1.24", - "resolved": "https://registry.npmjs.org/@radix-ui/react-menubar/-/react-menubar-1.1.24.tgz", - "integrity": "sha512-eeVs0vf7cuqXaM0qLQCPcufImiJNVBXdJDLu7ZGYl2732UH23Qat/foNGrr6vYV3/DdTsBqASoggUFgH14OcZA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-menu": "2.1.24", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-navigation-menu": { - "version": "1.2.22", - "resolved": "https://registry.npmjs.org/@radix-ui/react-navigation-menu/-/react-navigation-menu-1.2.22.tgz", - "integrity": "sha512-ou7iLEJ+yrhQndkkA4U21XIdS/CS45F4iXIkTZcb6/Ne9EMsOuDudVmCwmDnfFZZ+y1FZqXRNSIgBy+YMvZVZg==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-use-previous": "1.1.4", - "@radix-ui/react-visually-hidden": "1.2.11" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-one-time-password-field": { - "version": "0.1.16", - "resolved": "https://registry.npmjs.org/@radix-ui/react-one-time-password-field/-/react-one-time-password-field-0.1.16.tgz", - "integrity": "sha512-Tj9P6ntAJEw52oq/F0AGknXR4XncxEt7XU47O3xJQOiWfLzEy3d9gtgKfvjSzGxzHkfL+VzvxGu2KTFsloJqXw==", - "license": "MIT", - "dependencies": { - "@radix-ui/number": "1.1.3", - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-effect-event": "0.0.5", - "@radix-ui/react-use-is-hydrated": "0.1.3", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-password-toggle-field": { - "version": "0.1.11", - "resolved": "https://registry.npmjs.org/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.1.11.tgz", - "integrity": "sha512-4gvFnmDXu3dgj21CqsufzIameRvlRd4SBqaWhcrlrNhRo0Y5i/49AmRJYe1fdAM3G2VNBbmin4b0D6cdQocwgw==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-effect-event": "0.0.5", - "@radix-ui/react-use-is-hydrated": "0.1.3" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-popover": { - "version": "1.1.23", - "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.23.tgz", - "integrity": "sha512-mw58MrBlyHWFisTOYignD0vf/3gdcgAR+9of1s9G/38CbFiUwH1nCDkc0AUM9IrXFgN5Ue8n45j9WCgyM1sbiQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-focus-guards": "1.1.6", - "@radix-ui/react-focus-scope": "1.1.16", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-popper": "1.3.7", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-slot": "1.3.3", - "@radix-ui/react-use-controllable-state": "1.2.6", - "aria-hidden": "^1.2.4", - "react-remove-scroll": "^2.7.2" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-popper": { - "version": "1.3.7", - "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.3.7.tgz", - "integrity": "sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg==", - "license": "MIT", - "dependencies": { - "@floating-ui/react-dom": "^2.0.0", - "@radix-ui/react-arrow": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-use-rect": "1.1.4", - "@radix-ui/react-use-size": "1.1.4", - "@radix-ui/rect": "1.1.3" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-portal": { - "version": "1.1.17", - "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.17.tgz", - "integrity": "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-presence": { - "version": "1.1.10", - "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.10.tgz", - "integrity": "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-primitive": { - "version": "2.1.10", - "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.10.tgz", - "integrity": "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-slot": "1.3.3" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-progress": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.1.16.tgz", - "integrity": "sha512-5XnomAsoZZCY+KNTxbIghpGqPruZvKFNlvcAljVAOdDRDsH4/OZQxhtwo5wdtoDM5R6MhJBb2sPnDuRFep3lzg==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-radio-group": { - "version": "1.4.7", - "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.4.7.tgz", - "integrity": "sha512-cgYFEkntCxppHZgtSZ+7vh0wbZQ+IC7PPMw8DSnRG27B6kDd32/Zw0OJt7dGDigCoprMuWHjg2PvUn3PYvPFoQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-size": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-roving-focus": { - "version": "1.1.19", - "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.19.tgz", - "integrity": "sha512-V9jI6hDjT7l3jsCQD9bLNvDLM3tH/gdbOTp7Tefp3hbbgCGQoK7tUvrWiRlcoBHIZ809ElXwNQwVo0B98LuTXQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-is-hydrated": "0.1.3", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-scroll-area": { - "version": "1.2.18", - "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.2.18.tgz", - "integrity": "sha512-Zn5Cd171wxsO3Dfg8HaW6RifTb9CYTKQJHs/G4+LN1GfmJpaQMZQyQxMprVPHpaz7QY4l9BxK2JwQuzHsXC8nA==", - "license": "MIT", - "dependencies": { - "@radix-ui/number": "1.1.3", - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-select": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.3.7.tgz", - "integrity": "sha512-WFGImkmbzcfxeIwq/+4HvRN0pizBwbwQUED4I13ezQsDdfl38ZntN6TmR8XaSzPBqoCToe8rF75j6NPNDSzhbg==", - "license": "MIT", - "dependencies": { - "@radix-ui/number": "1.1.3", - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-focus-guards": "1.1.6", - "@radix-ui/react-focus-scope": "1.1.16", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-popper": "1.3.7", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-slot": "1.3.3", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-use-previous": "1.1.4", - "@radix-ui/react-visually-hidden": "1.2.11", - "aria-hidden": "^1.2.4", - "react-remove-scroll": "^2.7.2" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-separator": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.15.tgz", - "integrity": "sha512-jOLO4lssEzWpoDu7G+Ze4VjwMRUBt291pnZD0gmalREZipnTX3wadQo7Fy48GCTfe14/YRN6rw/rOJqrE85Wxw==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-slider": { - "version": "1.4.7", - "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.4.7.tgz", - "integrity": "sha512-mTSLf1GC/C0moWjTbvCM6Qn/gBjvlFt1azuWF2v7MN5C3Zq2U2J2lN3ZEYkpujuOU5Ro7A28wkviSxaKnG0BYg==", - "license": "MIT", - "dependencies": { - "@radix-ui/number": "1.1.3", - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-use-previous": "1.1.4", - "@radix-ui/react-use-size": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-slot": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.3.3.tgz", - "integrity": "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.5" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-switch": { - "version": "1.3.7", - "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.3.7.tgz", - "integrity": "sha512-48tB/4dn2UVLBCYhTu9AuR63IHl73l/qLbLgxd86noTUor4/K4LFDAcYjK+isP5313qxaFpjPVogE7+Y0/V3Kw==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-size": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-tabs": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.21.tgz", - "integrity": "sha512-UKxJlZid7FVtsk/WTxj4i4uSEgj2Au+KBbS7SQyTlzMhhn+86Cz3tISZdTa87bfEfcuvZezf2ZsxD4xuEKtkog==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-toast": { - "version": "1.2.23", - "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.23.tgz", - "integrity": "sha512-ofhyAsYaocRGOs/n0XWdUOSVzEAG6BfrMVM8z0c0kLEWY38w/0WuMFPTJP/HVaZPYkMvHZoKIIhNcjbTCBILPg==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-visually-hidden": "1.2.11" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-toggle": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.18.tgz", - "integrity": "sha512-7lonPlKfSacd20GlOBx2ltuVKz9oqWYZz+oMQyOltw6t1y2nyftj2ZmwwUHYn49kqfDWcp8dNZm5NgV+5Z+mug==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-toggle-group": { - "version": "1.1.19", - "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.19.tgz", - "integrity": "sha512-OtnwuSVjd1Ofi+AdnvhsjQdyuhCDwYs1w9RyB5BN/OavXOVQo42SYqQjwUnbPnaiPFBpQ9aX70dWeee+v2oBLA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-toggle": "1.1.18", - "@radix-ui/react-use-controllable-state": "1.2.6" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-toolbar": { - "version": "1.1.19", - "resolved": "https://registry.npmjs.org/@radix-ui/react-toolbar/-/react-toolbar-1.1.19.tgz", - "integrity": "sha512-Ph0IvtYw4VB12ZnZg+YtrGs8yJQsnizwo/zu0R4Y/nWugtJzA7Pg1eWeuDR9+LSqn+xjamss+UOSOJJJ4gx8jw==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-separator": "1.1.15", - "@radix-ui/react-toggle-group": "1.1.19" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-tooltip": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.2.16.tgz", - "integrity": "sha512-6EamKFRRnlpdadndbZ6LMwycfwkwPte1B42hs6QA0gYhjaOKqW4PZ4pjaW9UrlDX5eVt/OjncE7BFTPL5nmZhg==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-id": "1.1.4", - "@radix-ui/react-popper": "1.3.7", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-slot": "1.3.3", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-visually-hidden": "1.2.11" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-callback-ref": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.4.tgz", - "integrity": "sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-controllable-state": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.6.tgz", - "integrity": "sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-use-effect-event": "0.0.5", - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-effect-event": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", - "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-escape-keydown": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.5.tgz", - "integrity": "sha512-ge3ipobwSXTj4JyVtswQ7qZj0ZHdtbGuOno/LrgAAeSxtsJ6Vs4Gz5IkPH2bmqpjcLUFoqGhA/mueuIf63UXlA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-callback-ref": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-is-hydrated": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", - "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-layout-effect": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", - "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-previous": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.4.tgz", - "integrity": "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-rect": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", - "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/rect": "1.1.3" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-size": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.4.tgz", - "integrity": "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-layout-effect": "1.1.4" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-visually-hidden": { - "version": "1.2.11", - "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.11.tgz", - "integrity": "sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-primitive": "2.1.10" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/rect": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", - "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", - "license": "MIT" - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.3", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz", - "integrity": "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.4.tgz", - "integrity": "sha512-RrPokAb7dmbxFoeO3TloqHyOjgye8RkBhSqmp4aJMIex4c9r46ZstPnleDQOq1t46VOVjwIuwNogIqbodV1Vvg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.4.tgz", - "integrity": "sha512-JKuJc+pnpks2pjy7L/N3v/cAkZxYlnmuZoD840ldbMI5KDbC4iO9NKwPKYdjYFCMAIIlBzYSFHxIJVYzRo2/8A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.4.tgz", - "integrity": "sha512-krw5uS2STmvJ02x0uTXHbqQNuz+9eZ1iw+qXk9dmW2gvV4jV7O2hEoOnuhFrpOPiel1mBFtqbxYZZtC46hXLOw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.4.tgz", - "integrity": "sha512-wsTxtgApb4PrOsNJIm0FZ1h3WvCC+k9uxLJ4ad75hgoS4NiRes2SoJFlDAyMwiUY8IssDqGcHbXuN0sx1tfF1A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.4.tgz", - "integrity": "sha512-GUOnQlyZe3yAXhWOtOMsn5Qkrv5E5mZXa0thbARWi5Ei2szlVXJFQhddZ4HbAzh8q92w5twp+CQvs/eFanz9YQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.4.tgz", - "integrity": "sha512-/Y7f3QuxjzPKsjA/rfEDa3+0vXqyjmJ50Ln8dPpCmWkKTrUoWHG1cWhTqaAMLob2m2nESWuC7yGrREz019Ztqg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.4.tgz", - "integrity": "sha512-81wiiX3v7aqy+T+bT61TJ78yJjRquqFFTTbAPt08imfQQzkPIW8t6aJbkTagtCCrXMNc9D66+geqlK7ydLPNqA==", - "cpu": [ - "arm" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.4.tgz", - "integrity": "sha512-9kmDIvNZqdoHOBZgNtpTBeLWYO/LVipM3H/j62P8848/l/VPEQL6N3uxU9pvP1oZAsXyC2MEnFP3ovRjo7WYNQ==", - "cpu": [ - "arm" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.4.tgz", - "integrity": "sha512-CcnXHWnXg69g+DX5VWL3FHts3qMRN2uVEHX+BZvGLdd07/gXkn3ePjYtO1LDJvxkGKVHMclKBRa1QUTH+6toYQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.4.tgz", - "integrity": "sha512-iFOibiHnTRuhrWLlRsOQFdZJJIa7S8OwkneJr4ocALP16u5yk6lWLINFwhHaEqBFMsKDUZofLkGos7+CPzGB3g==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.4.tgz", - "integrity": "sha512-XnWYMI7euHlb5a871xPja+Gm7DRCFU+FGRrtS2sMq9N8FvqtpagUy6gD4YOemC5MRk9xbh8+jYMEJbigFQwsgA==", - "cpu": [ - "loong64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.4.tgz", - "integrity": "sha512-qGDAlO0U8xedCcsdRm9oaoQY8DAx/QT7uIxJWhCdx0ceIWX783UC9QSYkdpzAe29wNiVfp24+bZdQmn49o45SQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.4.tgz", - "integrity": "sha512-ru4H6ezD7ysA5EiEK6qkkaEb4modH8CTej6kUy/gQi20u3kB3G7Zn8snXXkeJSCOFKG/rbPPtM/+9Wgas1961w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.4.tgz", - "integrity": "sha512-2W4MO5WQVJnbJaZdvDb9rhBDuFU1nKIepPFpJUBsTh2k1YY2g+ODViaWuyOAjQ5cOP7NvrvLzt3wvHOoiAvc7w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.4.tgz", - "integrity": "sha512-+fxjfuoAmVMCYV5QyjoIpu0cp5DOiOTeqYFk1AVaxGr+/ravWLX89XfQmptsoWcaVy/TGf2hexzbUOrCQIL1CQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.4.tgz", - "integrity": "sha512-jTn8JfHGL4djjFxPuM06LmNUJDsst2jeVlsd9OmIH6zc5sC9K6rIuO4YajXatLUpBmBKl6b35ro1QZocLi+tcA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.4.tgz", - "integrity": "sha512-oCJCJL4pXsoDcP2QZ+JVlPTIRc6266zsIaeJJsWImmF7HO0W8nb6HuSgZlMWxJwaPf8ehbSw8yo0EUw925hKsA==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.4.tgz", - "integrity": "sha512-W69hukhZ3KKNRCaMIEzKvcFye42hh0FE1+YoYaf5+Ikacuftoco6yO/xouz0hc5d5W/s3yBro5jRiuEE/Q5vUw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.4.tgz", - "integrity": "sha512-qiXbGG2jkjXhzXpsFZSR2Xpb8DN/UaxYsbb/STbuR/6fpaDgRmmaq1B/LmtF2wQFOFOSsK2jdE0RZ3a0zHn4QA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.4.tgz", - "integrity": "sha512-nWeM//hxv8mIo6jD7Hu4o48DVmV9pbV6gsKaWU+4NFyqHoPKwrkRiZGLKUhOBk8qNmDmpwFtPKg80Bo/Tn4xiQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ] - }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.4.tgz", - "integrity": "sha512-s62SQ/vgsRSvMwDkOEfTqfgASF0f26ZNaQuTA6Aok5lrikf89yI2W0gFHvZb2Jpgc6N8JnOKZgCK2iciO3CsxQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.4.tgz", - "integrity": "sha512-J6wGf8TVGbXJq+HH+ttTvrcfNKPbuZecV6KT1B8I18BC5IURUh5kl4Yl5OEP5eFIUoI5BWxCsyYMhFsDx8kekw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.4.tgz", - "integrity": "sha512-zmfrQd/0wu6oJs8Vq8KwY/YtsKSsLtKe/HwAP4Wqy8LhWjeT55fHRAkOhYQ12wI3ayS4Tt12d5CDRD7N96SAYQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.4.tgz", - "integrity": "sha512-qPzHqdj9rfUD+w79dtE07zi/kFwKyCJqplp5K5ygeLTp7jLpAoc16OAH39HSmRC9UpozaecsleI8uAdEj6v2yw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.4.tgz", - "integrity": "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "license": "MIT" - }, - "node_modules/@tailwindcss/node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz", - "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/remapping": "^2.3.5", - "enhanced-resolve": "^5.24.1", - "jiti": "^2.7.0", - "lightningcss": "1.32.0", - "magic-string": "^0.30.21", - "source-map-js": "^1.2.1", - "tailwindcss": "4.3.3" - } - }, - "node_modules/@tailwindcss/oxide": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz", - "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 20" - }, - "optionalDependencies": { - "@tailwindcss/oxide-android-arm64": "4.3.3", - "@tailwindcss/oxide-darwin-arm64": "4.3.3", - "@tailwindcss/oxide-darwin-x64": "4.3.3", - "@tailwindcss/oxide-freebsd-x64": "4.3.3", - "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", - "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", - "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", - "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", - "@tailwindcss/oxide-linux-x64-musl": "4.3.3", - "@tailwindcss/oxide-wasm32-wasi": "4.3.3", - "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", - "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" - } - }, - "node_modules/@tailwindcss/oxide-android-arm64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz", - "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-darwin-arm64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz", - "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-darwin-x64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz", - "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-freebsd-x64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz", - "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz", - "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz", - "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-musl": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz", - "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-gnu": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz", - "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-musl": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz", - "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz", - "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==", - "bundleDependencies": [ - "@napi-rs/wasm-runtime", - "@emnapi/core", - "@emnapi/runtime", - "@tybys/wasm-util", - "@emnapi/wasi-threads", - "tslib" - ], - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "^1.11.1", - "@emnapi/runtime": "^1.11.1", - "@emnapi/wasi-threads": "^1.2.2", - "@napi-rs/wasm-runtime": "^1.1.4", - "@tybys/wasm-util": "^0.10.2", - "tslib": "^2.8.1" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", - "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-win32-x64-msvc": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz", - "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/vite": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.3.tgz", - "integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@tailwindcss/node": "4.3.3", - "@tailwindcss/oxide": "4.3.3", - "tailwindcss": "4.3.3" - }, - "peerDependencies": { - "vite": "^5.2.0 || ^6 || ^7 || ^8" - } - }, - "node_modules/@testing-library/dom": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", - "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.10.4", - "@babel/runtime": "^7.12.5", - "@types/aria-query": "^5.0.1", - "aria-query": "5.3.0", - "dom-accessibility-api": "^0.5.9", - "lz-string": "^1.5.0", - "picocolors": "1.1.1", - "pretty-format": "^27.0.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@testing-library/react": { - "version": "16.3.2", - "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz", - "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.12.5" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@testing-library/dom": "^10.0.0", - "@types/react": "^18.0.0 || ^19.0.0", - "@types/react-dom": "^18.0.0 || ^19.0.0", - "react": "^18.0.0 || ^19.0.0", - "react-dom": "^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@types/aria-query": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", - "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", - "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", - "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.28.2" - } - }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" - } - }, - "node_modules/@types/debug": { - "version": "4.1.13", - "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", - "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", - "license": "MIT", - "dependencies": { - "@types/ms": "*" - } - }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "license": "MIT" - }, - "node_modules/@types/estree-jsx": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz", - "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==", - "license": "MIT", - "dependencies": { - "@types/estree": "*" - } - }, - "node_modules/@types/hast": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", - "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/mdast": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", - "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/ms": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", - "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "24.13.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", - "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.18.0" - } - }, - "node_modules/@types/react": { - "version": "19.2.18", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz", - "integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==", - "license": "MIT", - "dependencies": { - "csstype": "^3.2.2" - } - }, - "node_modules/@types/react-dom": { - "version": "19.2.4", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.4.tgz", - "integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==", - "devOptional": true, - "license": "MIT", - "peerDependencies": { - "@types/react": "^19.2.0" - } - }, - "node_modules/@types/unist": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", - "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", - "license": "MIT" - }, - "node_modules/@types/whatwg-mimetype": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", - "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.3.tgz", - "integrity": "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg==", - "license": "ISC" - }, - "node_modules/@vitejs/plugin-react": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz", - "integrity": "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.29.0", - "@babel/plugin-transform-react-jsx-self": "^7.27.1", - "@babel/plugin-transform-react-jsx-source": "^7.27.1", - "@rolldown/pluginutils": "1.0.0-rc.3", - "@types/babel__core": "^7.20.5", - "react-refresh": "^0.18.0" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "peerDependencies": { - "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/@vitest/expect": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", - "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.1.0", - "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", - "chai": "^6.2.2", - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/mocker": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", - "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/spy": "4.1.11", - "estree-walker": "^3.0.3", - "magic-string": "^0.30.21" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "msw": "^2.4.9", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - } - }, - "node_modules/@vitest/pretty-format": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", - "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/runner": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", - "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/utils": "4.1.11", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/snapshot": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", - "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "4.1.11", - "@vitest/utils": "4.1.11", - "magic-string": "^0.30.21", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/spy": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", - "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/utils": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", - "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "4.1.11", - "convert-source-map": "^2.0.0", - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/aria-hidden": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", - "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", - "license": "MIT", - "dependencies": { - "tslib": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/aria-query": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", - "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", - "dev": true, - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "dequal": "^2.0.3" - } - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/assistant-cloud": { - "version": "0.1.41", - "resolved": "https://registry.npmjs.org/assistant-cloud/-/assistant-cloud-0.1.41.tgz", - "integrity": "sha512-lrH9USOoNaAWAAbujeHa/PEiWoqNQHjIPIAeeA3y3GUXOdlmTjIyR/7GbEZBKbHhm1Lyt7aAYKvdxHFkhuEbJw==", - "license": "MIT", - "dependencies": { - "assistant-stream": "^0.3.38" - } - }, - "node_modules/assistant-stream": { - "version": "0.3.38", - "resolved": "https://registry.npmjs.org/assistant-stream/-/assistant-stream-0.3.38.tgz", - "integrity": "sha512-WASh+97pCN1+Q0pRS8m1fZ56eqWYmDucGs5uLTfsb/Iel69K+GAIntVDn2HTaaOBDyAGs2QBizT7d7lcUcllvA==", - "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.1.0", - "nanoid": "^6.0.1", - "secure-json-parse": "^4.1.0" - }, - "peerDependencies": { - "ioredis": "^5.10.1 || ^6.0.0", - "redis": "^5.12.1" - }, - "peerDependenciesMeta": { - "ioredis": { - "optional": true - }, - "redis": { - "optional": true - } - } - }, - "node_modules/assistant-ui": { - "version": "0.0.111", - "resolved": "https://registry.npmjs.org/assistant-ui/-/assistant-ui-0.0.111.tgz", - "integrity": "sha512-J/Z8tG+1ERSkgIPRDjrrWwy1JtLOYKwTZbpm5h1uYJqvZ7AFEo6mDGVq/gIoeGlExxodQB1mqYmggdxxshH74Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@assistant-ui/agent-launcher": "0.1.11", - "@clack/prompts": "^1.7.0", - "chalk": "^6.0.0", - "cli-progress": "^3.12.0", - "commander": "^15.0.0", - "cross-spawn": "^7.0.6", - "debug": "^4.4.3", - "detect-package-manager": "^3.0.2", - "giget": "^3.3.1", - "glob": "^13.0.6", - "jscodeshift": "^17.4.0", - "jsonc-parser": "^3.3.1", - "semver": "^7.8.5" - }, - "bin": { - "assistant-ui": "bin/assistant-ui.js" - } - }, - "node_modules/assistant-ui/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/ast-types": { - "version": "0.16.1", - "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.16.1.tgz", - "integrity": "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==", - "dev": true, - "license": "MIT", - "dependencies": { - "tslib": "^2.0.1" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/bail": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", - "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/baseline-browser-mapping": { - "version": "2.11.15", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.15.tgz", - "integrity": "sha512-FwMjJJ7HnyZpWe+oWxegG0fezZyBZUagI5LZEoO3GCbtbKNwRfMH9Ue5d5v01PNePBy1QSfPSDTTeVL0Hb9EzA==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/browserslist": { - "version": "4.28.8", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz", - "integrity": "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.11.12", - "caniuse-lite": "^1.0.30001809", - "electron-to-chromium": "^1.5.402", - "node-releases": "^2.0.53", - "update-browserslist-db": "^1.3.0" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/buffer-image-size": { - "version": "0.6.4", - "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", - "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001809", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001809.tgz", - "integrity": "sha512-xxWVywk6a6Arlk+hymeycyn/VgqEfLDxupvhH/xiY5SJ/18kmi9o6MiO320DCUzypORHLtvh0I4i04tUhCNHNQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/ccount": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", - "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/chalk": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-6.0.0.tgz", - "integrity": "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=22" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/character-entities": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", - "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/character-entities-html4": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", - "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/character-entities-legacy": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", - "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/character-reference-invalid": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz", - "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/class-variance-authority": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", - "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", - "license": "Apache-2.0", - "dependencies": { - "clsx": "^2.1.1" - }, - "funding": { - "url": "https://polar.sh/cva" - } - }, - "node_modules/classnames": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", - "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==", - "license": "MIT" - }, - "node_modules/cli-progress": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/cli-progress/-/cli-progress-3.12.0.tgz", - "integrity": "sha512-tRkV3HJ1ASwm19THiiLIXLO7Im7wlTuKnvkYaTkyoAPefqjNg7W7DHKUlGRxy9vxDvbyCYQkQozvptuMkGCg8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "string-width": "^4.2.3" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/clone-deep": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", - "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-plain-object": "^2.0.4", - "kind-of": "^6.0.2", - "shallow-clone": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/comma-separated-tokens": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", - "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/commander": { - "version": "15.0.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", - "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=22.12.0" - } - }, - "node_modules/commondir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", - "dev": true, - "license": "MIT" - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "license": "MIT" - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decode-named-character-reference": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", - "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", - "license": "MIT", - "dependencies": { - "character-entities": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/detect-node-es": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", - "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", - "license": "MIT" - }, - "node_modules/detect-package-manager": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/detect-package-manager/-/detect-package-manager-3.0.2.tgz", - "integrity": "sha512-8JFjJHutStYrfWwzfretQoyNGoZVW1Fsrp4JO9spa7h/fBfwgTMEIy4/LBzRDGsxwVPHU0q+T9YvwLDJoOApLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "execa": "^5.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/devlop": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", - "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", - "license": "MIT", - "dependencies": { - "dequal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/dom-accessibility-api": { - "version": "0.5.16", - "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", - "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/electron-to-chromium": { - "version": "1.5.409", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.409.tgz", - "integrity": "sha512-ChI4N44d0B4A6C8prnNjMOaGgE59fUyEVYcRYm2XEXIjMbbvF5i9UL1cblDbpGqiU0uS8FE8UcKxqZqTXdmzbQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/enhanced-resolve": { - "version": "5.24.5", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", - "integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "tapable": "^2.3.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/entities": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", - "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/es-module-lexer": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", - "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", - "dev": true, - "license": "MIT" - }, - "node_modules/esbuild": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", - "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.2", - "@esbuild/android-arm": "0.28.2", - "@esbuild/android-arm64": "0.28.2", - "@esbuild/android-x64": "0.28.2", - "@esbuild/darwin-arm64": "0.28.2", - "@esbuild/darwin-x64": "0.28.2", - "@esbuild/freebsd-arm64": "0.28.2", - "@esbuild/freebsd-x64": "0.28.2", - "@esbuild/linux-arm": "0.28.2", - "@esbuild/linux-arm64": "0.28.2", - "@esbuild/linux-ia32": "0.28.2", - "@esbuild/linux-loong64": "0.28.2", - "@esbuild/linux-mips64el": "0.28.2", - "@esbuild/linux-ppc64": "0.28.2", - "@esbuild/linux-riscv64": "0.28.2", - "@esbuild/linux-s390x": "0.28.2", - "@esbuild/linux-x64": "0.28.2", - "@esbuild/netbsd-arm64": "0.28.2", - "@esbuild/netbsd-x64": "0.28.2", - "@esbuild/openbsd-arm64": "0.28.2", - "@esbuild/openbsd-x64": "0.28.2", - "@esbuild/openharmony-arm64": "0.28.2", - "@esbuild/sunos-x64": "0.28.2", - "@esbuild/win32-arm64": "0.28.2", - "@esbuild/win32-ia32": "0.28.2", - "@esbuild/win32-x64": "0.28.2" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-string-regexp": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", - "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/estree-util-is-identifier-name": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz", - "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==", - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/expect-type": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", - "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/extend": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", - "license": "MIT" - }, - "node_modules/fast-string-truncated-width": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", - "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-string-width": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", - "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-string-truncated-width": "^3.0.2" - } - }, - "node_modules/fast-wrap-ansi": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", - "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-string-width": "^3.0.2" - } - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/find-cache-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", - "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "commondir": "^1.0.1", - "make-dir": "^2.0.0", - "pkg-dir": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/flow-estree": { - "version": "0.328.0", - "resolved": "https://registry.npmjs.org/flow-estree/-/flow-estree-0.328.0.tgz", - "integrity": "sha512-uMB3dC4nfZYn+dd7/PYkyAK1mqBR4TJ4TWRdOjubpb/ObrLvPFdFSmMTq55fqttCCTygQ4NtD1Zdd+wcjC5t0g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/flow-parser": { - "version": "0.328.0", - "resolved": "https://registry.npmjs.org/flow-parser/-/flow-parser-0.328.0.tgz", - "integrity": "sha512-F+Ik2Of7ndl2FyPmZ77NrhbZp9lYjIsreDXeq4fo0sjxa3SIFv48QAszBqvPeMMzmw7JzqySJUxGR8CSD7EdXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flow-estree": "0.328.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-nonce": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", - "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/giget": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", - "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", - "dev": true, - "license": "MIT", - "bin": { - "giget": "dist/cli.mjs" - } - }, - "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/happy-dom": { - "version": "20.11.6", - "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.6.tgz", - "integrity": "sha512-Hldbg8AdAa5a5oDcZpjqnGitp7JB0hqWmfv/8qr+kft4vzSD8BHsbdRfzYvL/0QcbKcURC/yyoygbeDQarPvYg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": ">=20.0.0", - "@types/whatwg-mimetype": "^3.0.2", - "@types/ws": "^8.18.1", - "buffer-image-size": "^0.6.4", - "entities": "^7.0.1", - "whatwg-mimetype": "^3.0.0", - "ws": "^8.21.0" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/hast-util-to-jsx-runtime": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", - "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==", - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0", - "@types/hast": "^3.0.0", - "@types/unist": "^3.0.0", - "comma-separated-tokens": "^2.0.0", - "devlop": "^1.0.0", - "estree-util-is-identifier-name": "^3.0.0", - "hast-util-whitespace": "^3.0.0", - "mdast-util-mdx-expression": "^2.0.0", - "mdast-util-mdx-jsx": "^3.0.0", - "mdast-util-mdxjs-esm": "^2.0.0", - "property-information": "^7.0.0", - "space-separated-tokens": "^2.0.0", - "style-to-js": "^1.0.0", - "unist-util-position": "^5.0.0", - "vfile-message": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-whitespace": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", - "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/html-url-attributes": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", - "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==", - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inline-style-parser": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", - "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", - "license": "MIT" - }, - "node_modules/is-alphabetical": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", - "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/is-alphanumerical": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", - "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", - "license": "MIT", - "dependencies": { - "is-alphabetical": "^2.0.0", - "is-decimal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/is-decimal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", - "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-hexadecimal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz", - "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/is-plain-obj": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", - "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/is-plain-object": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", - "dev": true, - "license": "MIT", - "dependencies": { - "isobject": "^3.0.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/jiti": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", - "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", - "dev": true, - "license": "MIT", - "bin": { - "jiti": "lib/jiti-cli.mjs" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/jscodeshift": { - "version": "17.4.0", - "resolved": "https://registry.npmjs.org/jscodeshift/-/jscodeshift-17.4.0.tgz", - "integrity": "sha512-i3ESKiiTsGynxzTg5BhsZViD0ai72/6SsI1efDZxG6/5KCoElsmquxtyhXK5lpEgoO7MTNpYkjFEdEL97SkBNg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.24.7", - "@babel/parser": "^7.24.7", - "@babel/plugin-transform-class-properties": "^7.24.7", - "@babel/plugin-transform-modules-commonjs": "^7.24.7", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.24.7", - "@babel/plugin-transform-optional-chaining": "^7.24.7", - "@babel/plugin-transform-private-methods": "^7.24.7", - "@babel/preset-flow": "^7.24.7", - "@babel/preset-typescript": "^7.24.7", - "@babel/register": "^7.24.6", - "flow-parser": "0.*", - "graceful-fs": "^4.2.4", - "neo-async": "^2.5.0", - "picocolors": "^1.0.1", - "picomatch": "^4.0.2", - "recast": "^0.23.11", - "tmp": "^0.2.3", - "write-file-atomic": "^5.0.1" - }, - "bin": { - "jscodeshift": "bin/jscodeshift.js" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@babel/preset-env": "^7.1.6" - }, - "peerDependenciesMeta": { - "@babel/preset-env": { - "optional": true - } - } - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/jsonc-parser": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", - "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/kind-of": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", - "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/longest-streak": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", - "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/lucide-react": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.32.0.tgz", - "integrity": "sha512-txX56hMFnRxPi1f9/nH69YN8uvAO6a7Y1KSWKjCDAtdD9+soEgmWuCt6iRm1pkxUZo2+YntSdsE1L6bIuKoY8Q==", - "license": "ISC", - "peerDependencies": { - "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, - "node_modules/lz-string": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", - "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "lz-string": "bin/bin.js" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/make-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", - "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pify": "^4.0.1", - "semver": "^5.6.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/markdown-table": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", - "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/mdast-util-find-and-replace": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz", - "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "escape-string-regexp": "^5.0.0", - "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-from-markdown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz", - "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "@types/unist": "^3.0.0", - "decode-named-character-reference": "^1.0.0", - "devlop": "^1.0.0", - "mdast-util-to-string": "^4.0.0", - "micromark": "^4.0.0", - "micromark-util-decode-numeric-character-reference": "^2.0.0", - "micromark-util-decode-string": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0", - "unist-util-stringify-position": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-gfm": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz", - "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==", - "license": "MIT", - "dependencies": { - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-gfm-autolink-literal": "^2.0.0", - "mdast-util-gfm-footnote": "^2.0.0", - "mdast-util-gfm-strikethrough": "^2.0.0", - "mdast-util-gfm-table": "^2.0.0", - "mdast-util-gfm-task-list-item": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-gfm-autolink-literal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz", - "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "ccount": "^2.0.0", - "devlop": "^1.0.0", - "mdast-util-find-and-replace": "^3.0.0", - "micromark-util-character": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-gfm-footnote": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz", - "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "devlop": "^1.1.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-gfm-strikethrough": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz", - "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-gfm-table": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz", - "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "devlop": "^1.0.0", - "markdown-table": "^3.0.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-gfm-task-list-item": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz", - "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "devlop": "^1.0.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-mdx-expression": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz", - "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==", - "license": "MIT", - "dependencies": { - "@types/estree-jsx": "^1.0.0", - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "devlop": "^1.0.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-mdx-jsx": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz", - "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==", - "license": "MIT", - "dependencies": { - "@types/estree-jsx": "^1.0.0", - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "@types/unist": "^3.0.0", - "ccount": "^2.0.0", - "devlop": "^1.1.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0", - "parse-entities": "^4.0.0", - "stringify-entities": "^4.0.0", - "unist-util-stringify-position": "^4.0.0", - "vfile-message": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-mdxjs-esm": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz", - "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==", - "license": "MIT", - "dependencies": { - "@types/estree-jsx": "^1.0.0", - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "devlop": "^1.0.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-phrasing": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", - "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "unist-util-is": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-to-hast": { - "version": "13.2.1", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", - "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "@ungap/structured-clone": "^1.0.0", - "devlop": "^1.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "trim-lines": "^3.0.0", - "unist-util-position": "^5.0.0", - "unist-util-visit": "^5.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-to-markdown": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz", - "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "@types/unist": "^3.0.0", - "longest-streak": "^3.0.0", - "mdast-util-phrasing": "^4.0.0", - "mdast-util-to-string": "^4.0.0", - "micromark-util-classify-character": "^2.0.0", - "micromark-util-decode-string": "^2.0.0", - "unist-util-visit": "^5.0.0", - "zwitch": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-to-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", - "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true, - "license": "MIT" - }, - "node_modules/micromark": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", - "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "@types/debug": "^4.0.0", - "debug": "^4.0.0", - "decode-named-character-reference": "^1.0.0", - "devlop": "^1.0.0", - "micromark-core-commonmark": "^2.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-combine-extensions": "^2.0.0", - "micromark-util-decode-numeric-character-reference": "^2.0.0", - "micromark-util-encode": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-resolve-all": "^2.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "micromark-util-subtokenize": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-core-commonmark": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", - "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "decode-named-character-reference": "^1.0.0", - "devlop": "^1.0.0", - "micromark-factory-destination": "^2.0.0", - "micromark-factory-label": "^2.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-factory-title": "^2.0.0", - "micromark-factory-whitespace": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-classify-character": "^2.0.0", - "micromark-util-html-tag-name": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-resolve-all": "^2.0.0", - "micromark-util-subtokenize": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-extension-gfm": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz", - "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==", - "license": "MIT", - "dependencies": { - "micromark-extension-gfm-autolink-literal": "^2.0.0", - "micromark-extension-gfm-footnote": "^2.0.0", - "micromark-extension-gfm-strikethrough": "^2.0.0", - "micromark-extension-gfm-table": "^2.0.0", - "micromark-extension-gfm-tagfilter": "^2.0.0", - "micromark-extension-gfm-task-list-item": "^2.0.0", - "micromark-util-combine-extensions": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-extension-gfm-autolink-literal": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz", - "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==", - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-extension-gfm-footnote": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz", - "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==", - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-core-commonmark": "^2.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-extension-gfm-strikethrough": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz", - "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==", - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-classify-character": "^2.0.0", - "micromark-util-resolve-all": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-extension-gfm-table": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz", - "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==", - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-extension-gfm-tagfilter": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz", - "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==", - "license": "MIT", - "dependencies": { - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-extension-gfm-task-list-item": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz", - "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==", - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-factory-destination": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", - "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-label": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", - "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-space": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", - "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-title": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", - "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-whitespace": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", - "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-character": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", - "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-chunked": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", - "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-classify-character": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", - "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-combine-extensions": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", - "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-chunked": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-decode-numeric-character-reference": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", - "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-decode-string": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", - "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "decode-named-character-reference": "^1.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-decode-numeric-character-reference": "^2.0.0", - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-encode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", - "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-html-tag-name": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", - "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-normalize-identifier": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", - "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-resolve-all": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", - "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-sanitize-uri": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", - "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-encode": "^2.0.0", - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-subtokenize": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", - "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-symbol": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", - "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.8" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz", - "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.js" - }, - "engines": { - "node": "^22 || ^24 || >=26" - } - }, - "node_modules/neo-async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", - "dev": true, - "license": "MIT" - }, - "node_modules/node-releases": { - "version": "2.0.53", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.53.tgz", - "integrity": "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/obug": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", - "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", - "dev": true, - "funding": [ - "https://github.com/sponsors/sxzz", - "https://opencollective.com/debug" - ], - "license": "MIT", - "engines": { - "node": ">=12.20.0" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^2.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/parse-entities": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz", - "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==", - "license": "MIT", - "dependencies": { - "@types/unist": "^2.0.0", - "character-entities-legacy": "^3.0.0", - "character-reference-invalid": "^2.0.0", - "decode-named-character-reference": "^1.0.0", - "is-alphanumerical": "^2.0.0", - "is-decimal": "^2.0.0", - "is-hexadecimal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/parse-entities/node_modules/@types/unist": { - "version": "2.0.11", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", - "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", - "license": "MIT" - }, - "node_modules/path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/pathe": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", - "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", - "dev": true, - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", - "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pify": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/pirates": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", - "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "dev": true, - "license": "MIT", - "dependencies": { - "find-up": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/postcss": { - "version": "8.5.26", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", - "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.17", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/postcss/node_modules/nanoid": { - "version": "3.3.18", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", - "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/pretty-format": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", - "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-regex": "^5.0.1", - "ansi-styles": "^5.0.0", - "react-is": "^17.0.1" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/property-information": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", - "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/radix-ui": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.6.7.tgz", - "integrity": "sha512-QBdhh1arIEUvPC0dQ5+nwWAxt7+N+oP/9jPwjJkGFoSk/sqxg32gJtSXGtFh8frAIcS6oC9cx2Q+7KYCQLOAeA==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.7", - "@radix-ui/react-accessible-icon": "1.1.15", - "@radix-ui/react-accordion": "1.2.20", - "@radix-ui/react-alert-dialog": "1.1.23", - "@radix-ui/react-arrow": "1.1.15", - "@radix-ui/react-aspect-ratio": "1.1.15", - "@radix-ui/react-avatar": "1.2.6", - "@radix-ui/react-checkbox": "1.3.11", - "@radix-ui/react-collapsible": "1.1.20", - "@radix-ui/react-collection": "1.1.15", - "@radix-ui/react-compose-refs": "1.1.5", - "@radix-ui/react-context": "1.2.2", - "@radix-ui/react-context-menu": "2.3.7", - "@radix-ui/react-dialog": "1.1.23", - "@radix-ui/react-direction": "1.1.4", - "@radix-ui/react-dismissable-layer": "1.1.19", - "@radix-ui/react-dropdown-menu": "2.1.24", - "@radix-ui/react-focus-guards": "1.1.6", - "@radix-ui/react-focus-scope": "1.1.16", - "@radix-ui/react-form": "0.1.16", - "@radix-ui/react-hover-card": "1.1.23", - "@radix-ui/react-label": "2.1.15", - "@radix-ui/react-menu": "2.1.24", - "@radix-ui/react-menubar": "1.1.24", - "@radix-ui/react-navigation-menu": "1.2.22", - "@radix-ui/react-one-time-password-field": "0.1.16", - "@radix-ui/react-password-toggle-field": "0.1.11", - "@radix-ui/react-popover": "1.1.23", - "@radix-ui/react-popper": "1.3.7", - "@radix-ui/react-portal": "1.1.17", - "@radix-ui/react-presence": "1.1.10", - "@radix-ui/react-primitive": "2.1.10", - "@radix-ui/react-progress": "1.1.16", - "@radix-ui/react-radio-group": "1.4.7", - "@radix-ui/react-roving-focus": "1.1.19", - "@radix-ui/react-scroll-area": "1.2.18", - "@radix-ui/react-select": "2.3.7", - "@radix-ui/react-separator": "1.1.15", - "@radix-ui/react-slider": "1.4.7", - "@radix-ui/react-slot": "1.3.3", - "@radix-ui/react-switch": "1.3.7", - "@radix-ui/react-tabs": "1.1.21", - "@radix-ui/react-toast": "1.2.23", - "@radix-ui/react-toggle": "1.1.18", - "@radix-ui/react-toggle-group": "1.1.19", - "@radix-ui/react-toolbar": "1.1.19", - "@radix-ui/react-tooltip": "1.2.16", - "@radix-ui/react-use-callback-ref": "1.1.4", - "@radix-ui/react-use-controllable-state": "1.2.6", - "@radix-ui/react-use-effect-event": "0.0.5", - "@radix-ui/react-use-escape-keydown": "1.1.5", - "@radix-ui/react-use-is-hydrated": "0.1.3", - "@radix-ui/react-use-layout-effect": "1.1.4", - "@radix-ui/react-use-size": "1.1.4", - "@radix-ui/react-visually-hidden": "1.2.11" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/react": { - "version": "19.2.8", - "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", - "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "19.2.8", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz", - "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==", - "license": "MIT", - "dependencies": { - "scheduler": "^0.27.0" - }, - "peerDependencies": { - "react": "^19.2.8" - } - }, - "node_modules/react-is": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", - "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/react-markdown": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", - "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "devlop": "^1.0.0", - "hast-util-to-jsx-runtime": "^2.0.0", - "html-url-attributes": "^3.0.0", - "mdast-util-to-hast": "^13.0.0", - "remark-parse": "^11.0.0", - "remark-rehype": "^11.0.0", - "unified": "^11.0.0", - "unist-util-visit": "^5.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - }, - "peerDependencies": { - "@types/react": ">=18", - "react": ">=18" - } - }, - "node_modules/react-refresh": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", - "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-remove-scroll": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", - "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==", - "license": "MIT", - "dependencies": { - "react-remove-scroll-bar": "^2.3.7", - "react-style-singleton": "^2.2.3", - "tslib": "^2.1.0", - "use-callback-ref": "^1.3.3", - "use-sidecar": "^1.1.3" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/react-remove-scroll-bar": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", - "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", - "license": "MIT", - "dependencies": { - "react-style-singleton": "^2.2.2", - "tslib": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/react-style-singleton": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", - "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", - "license": "MIT", - "dependencies": { - "get-nonce": "^1.0.0", - "tslib": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/react-textarea-autosize": { - "version": "8.5.9", - "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.5.9.tgz", - "integrity": "sha512-U1DGlIQN5AwgjTyOEnI1oCcMuEr1pv1qOtklB2l4nyMGbHzWrI0eFsYK0zos2YWqAolJyG0IWJaqWmWj5ETh0A==", - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.20.13", - "use-composed-ref": "^1.3.0", - "use-latest": "^1.2.1" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, - "node_modules/recast": { - "version": "0.23.21", - "resolved": "https://registry.npmjs.org/recast/-/recast-0.23.21.tgz", - "integrity": "sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw==", - "dev": true, - "license": "MIT", - "dependencies": { - "ast-types": "^0.16.1", - "esprima": "~4.0.0", - "source-map": "~0.6.1", - "tiny-invariant": "^1.3.3", - "tslib": "^2.0.1" - }, - "engines": { - "node": ">= 4" - } - }, - "node_modules/remark-gfm": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz", - "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "mdast-util-gfm": "^3.0.0", - "micromark-extension-gfm": "^3.0.0", - "remark-parse": "^11.0.0", - "remark-stringify": "^11.0.0", - "unified": "^11.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/remark-parse": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", - "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "mdast-util-from-markdown": "^2.0.0", - "micromark-util-types": "^2.0.0", - "unified": "^11.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/remark-rehype": { - "version": "11.1.2", - "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz", - "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "mdast-util-to-hast": "^13.0.0", - "unified": "^11.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/remark-stringify": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz", - "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "mdast-util-to-markdown": "^2.0.0", - "unified": "^11.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rollup": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.4.tgz", - "integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.9" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@napi-rs/lzma-linux-x64-gnu": "1.5.1", - "@rollup/rollup-android-arm-eabi": "4.62.4", - "@rollup/rollup-android-arm64": "4.62.4", - "@rollup/rollup-darwin-arm64": "4.62.4", - "@rollup/rollup-darwin-x64": "4.62.4", - "@rollup/rollup-freebsd-arm64": "4.62.4", - "@rollup/rollup-freebsd-x64": "4.62.4", - "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", - "@rollup/rollup-linux-arm-musleabihf": "4.62.4", - "@rollup/rollup-linux-arm64-gnu": "4.62.4", - "@rollup/rollup-linux-arm64-musl": "4.62.4", - "@rollup/rollup-linux-loong64-gnu": "4.62.4", - "@rollup/rollup-linux-loong64-musl": "4.62.4", - "@rollup/rollup-linux-ppc64-gnu": "4.62.4", - "@rollup/rollup-linux-ppc64-musl": "4.62.4", - "@rollup/rollup-linux-riscv64-gnu": "4.62.4", - "@rollup/rollup-linux-riscv64-musl": "4.62.4", - "@rollup/rollup-linux-s390x-gnu": "4.62.4", - "@rollup/rollup-linux-x64-gnu": "4.62.4", - "@rollup/rollup-linux-x64-musl": "4.62.4", - "@rollup/rollup-openbsd-x64": "4.62.4", - "@rollup/rollup-openharmony-arm64": "4.62.4", - "@rollup/rollup-win32-arm64-msvc": "4.62.4", - "@rollup/rollup-win32-ia32-msvc": "4.62.4", - "@rollup/rollup-win32-x64-gnu": "4.62.4", - "@rollup/rollup-win32-x64-msvc": "4.62.4", - "fsevents": "~2.3.2" - } - }, - "node_modules/safe-content-frame": { - "version": "0.0.27", - "resolved": "https://registry.npmjs.org/safe-content-frame/-/safe-content-frame-0.0.27.tgz", - "integrity": "sha512-IFUSMjElIp8q46wUU5HViHNEqoDWRlCzqqThQmhOLimuXPe/QC6Jr/AQ+BKxSYziQdNXUpapBq4Ir/t6dS0Ldg==", - "license": "MIT" - }, - "node_modules/scheduler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", - "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "license": "MIT" - }, - "node_modules/secure-json-parse": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", - "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/shallow-clone": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", - "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", - "dev": true, - "license": "MIT", - "dependencies": { - "kind-of": "^6.0.2" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true, - "license": "ISC" - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true, - "license": "MIT" - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/space-separated-tokens": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", - "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true, - "license": "MIT" - }, - "node_modules/std-env": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", - "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", - "dev": true, - "license": "MIT" - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/stringify-entities": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", - "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", - "license": "MIT", - "dependencies": { - "character-entities-html4": "^2.0.0", - "character-entities-legacy": "^3.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/style-to-js": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz", - "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==", - "license": "MIT", - "dependencies": { - "style-to-object": "1.0.14" - } - }, - "node_modules/style-to-object": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", - "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==", - "license": "MIT", - "dependencies": { - "inline-style-parser": "0.2.7" - } - }, - "node_modules/tailwind-merge": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.6.0.tgz", - "integrity": "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/dcastil" - } - }, - "node_modules/tailwindcss": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", - "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", - "license": "MIT" - }, - "node_modules/tapable": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", - "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/tiny-invariant": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", - "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinybench": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", - "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinyexec": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz", - "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.17", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", - "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/tinyrainbow": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", - "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/tmp": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", - "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.14" - } - }, - "node_modules/trim-lines": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", - "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/trough": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", - "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/tw-animate-css": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz", - "integrity": "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/Wombosvideo" - } - }, - "node_modules/tw-shimmer": { - "version": "0.4.12", - "resolved": "https://registry.npmjs.org/tw-shimmer/-/tw-shimmer-0.4.12.tgz", - "integrity": "sha512-kWSpAeUC+MV0UDSf1LmuTDW4EMf9JLNqR9QaBQNN+cknE0NjIewfLFDn8pUXvh1YKXKWyEsE+R86uoSdTxXzyg==", - "license": "MIT", - "peerDependencies": { - "tailwindcss": ">=4.0.0-0" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "7.18.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", - "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/unified": { - "version": "11.0.5", - "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", - "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "bail": "^2.0.0", - "devlop": "^1.0.0", - "extend": "^3.0.0", - "is-plain-obj": "^4.0.0", - "trough": "^2.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-is": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", - "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-position": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", - "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-stringify-position": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", - "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", - "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.1.tgz", - "integrity": "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/use-callback-ref": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", - "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", - "license": "MIT", - "dependencies": { - "tslib": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/use-composed-ref": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/use-composed-ref/-/use-composed-ref-1.4.0.tgz", - "integrity": "sha512-djviaxuOOh7wkj0paeO1Q/4wMZ8Zrnag5H6yBvzN7AKKe8beOaED9SF5/ByLqsku8NP4zQqsvM2u3ew/tJK8/w==", - "license": "MIT", - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/use-isomorphic-layout-effect": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.2.1.tgz", - "integrity": "sha512-tpZZ+EX0gaghDAiFR37hj5MgY6ZN55kLiPkJsKxBMZ6GZdOSPJXiOzPM984oPYZ5AnehYx5WQp1+ME8I/P/pRA==", - "license": "MIT", - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/use-latest": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/use-latest/-/use-latest-1.3.0.tgz", - "integrity": "sha512-mhg3xdm9NaM8q+gLT8KryJPnRFOz1/5XPBhmDEVZK1webPzDjrPk7f/mbpeLqTgB9msytYWANxgALOCJKnLvcQ==", - "license": "MIT", - "dependencies": { - "use-isomorphic-layout-effect": "^1.1.1" - }, - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/use-sidecar": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", - "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", - "license": "MIT", - "dependencies": { - "detect-node-es": "^1.1.0", - "tslib": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/vfile": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", - "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "vfile-message": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-stringify-position": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vite": { - "version": "7.3.6", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", - "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.27.0 || ^0.28.0", - "fdir": "^6.5.0", - "picomatch": "^4.0.3", - "postcss": "^8.5.6", - "rollup": "^4.43.0", - "tinyglobby": "^0.2.15" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "lightningcss": "^1.21.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vitest": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", - "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/expect": "4.1.11", - "@vitest/mocker": "4.1.11", - "@vitest/pretty-format": "4.1.11", - "@vitest/runner": "4.1.11", - "@vitest/snapshot": "4.1.11", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", - "es-module-lexer": "^2.0.0", - "expect-type": "^1.3.0", - "magic-string": "^0.30.21", - "obug": "^2.1.1", - "pathe": "^2.0.3", - "picomatch": "^4.0.3", - "std-env": "^4.0.0-rc.1", - "tinybench": "^2.9.0", - "tinyexec": "^1.0.2", - "tinyglobby": "^0.2.15", - "tinyrainbow": "^3.1.0", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", - "why-is-node-running": "^2.3.0" - }, - "bin": { - "vitest": "vitest.mjs" - }, - "engines": { - "node": "^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@opentelemetry/api": "^1.9.0", - "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.11", - "@vitest/browser-preview": "4.1.11", - "@vitest/browser-webdriverio": "4.1.11", - "@vitest/coverage-istanbul": "4.1.11", - "@vitest/coverage-v8": "4.1.11", - "@vitest/ui": "4.1.11", - "happy-dom": "*", - "jsdom": "*", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@opentelemetry/api": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser-playwright": { - "optional": true - }, - "@vitest/browser-preview": { - "optional": true - }, - "@vitest/browser-webdriverio": { - "optional": true - }, - "@vitest/coverage-istanbul": { - "optional": true - }, - "@vitest/coverage-v8": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - }, - "vite": { - "optional": false - } - } - }, - "node_modules/whatwg-mimetype": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", - "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/why-is-node-running": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", - "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, - "bin": { - "why-is-node-running": "cli.js" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/write-file-atomic": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", - "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/write-file-atomic/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - }, - "node_modules/zod": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", - "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/zustand": { - "version": "5.0.15", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz", - "integrity": "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==", - "license": "MIT", - "engines": { - "node": ">=12.20.0" - }, - "peerDependencies": { - "@types/react": ">=18.0.0", - "immer": ">=9.0.6", - "react": ">=18.0.0", - "use-sync-external-store": ">=1.2.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "immer": { - "optional": true - }, - "react": { - "optional": true - }, - "use-sync-external-store": { - "optional": true - } - } - }, - "node_modules/zwitch": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", - "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - } - } -} diff --git a/demo/chat-ui/package.json b/demo/chat-ui/package.json deleted file mode 100644 index 2bac1204..00000000 --- a/demo/chat-ui/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "agentcore-chat", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc -b && vite build", - "test": "vitest run" - }, - "dependencies": { - "@assistant-ui/core": "^0.3.14", - "@assistant-ui/react": "^0.15.15", - "@assistant-ui/react-generative-ui": "0.0.15", - "@assistant-ui/react-markdown": "^0.14.11", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "lucide-react": "^1.32.0", - "radix-ui": "^1.6.7", - "react": "^19.2.0", - "react-dom": "^19.2.0", - "react-markdown": "^10.1.0", - "remark-gfm": "^4.0.1", - "tailwind-merge": "^3.6.0", - "tw-animate-css": "^1.4.0", - "tw-shimmer": "^0.4.12", - "zustand": "^5.0.15" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.3.3", - "@testing-library/react": "^16.3.2", - "@types/node": "^24.13.3", - "@types/react": "^19.2.0", - "@types/react-dom": "^19.2.0", - "@vitejs/plugin-react": "^5.0.0", - "assistant-ui": "^0.0.111", - "happy-dom": "^20.11.6", - "tailwindcss": "^4.3.3", - "typescript": "^5.9.0", - "vite": "^7.0.0", - "vitest": "^4.1.11" - } -} diff --git a/demo/chat-ui/public/embed.js b/demo/chat-ui/public/embed.js deleted file mode 100644 index 7d271fa0..00000000 --- a/demo/chat-ui/public/embed.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * The one file another site adds to put the chat bubble on their page. - * - * - * - * Everything else is served from this host, so the embedding site takes no dependency beyond the - * one tag and can drop it again by deleting the tag. - * - * The widget runs inside an iframe rather than in the host page's DOM. That is the whole design: - * their CSS cannot reach into it and break the chat, ours cannot leak out and break their page, and - * the turn requests are same-origin with the frame — so the API needs no CORS at all. - * - * An iframe cannot size itself, so the page inside posts what it needs and this applies it. - */ -(function () { - "use strict"; - - // The origin this script was served from is the origin the widget is loaded from, so a host page - // never has to configure a URL and can never point it somewhere unintended. - var self = document.currentScript; - if (!self) return; - - var origin = new URL(self.src, window.location.href).origin; - var src = origin + "/chat/widget.html"; - - if (document.querySelector('iframe[data-agentcore-widget]')) return; - - var frame = document.createElement("iframe"); - frame.src = src; - frame.title = "Chat"; - frame.setAttribute("data-agentcore-widget", ""); - frame.setAttribute("allow", "clipboard-write"); - - frame.style.cssText = [ - "position:fixed", - "bottom:0", - "right:0", - "width:96px", - "height:96px", - "border:0", - "background:transparent", - // Below a modal but above ordinary page content. - "z-index:2147483000", - "color-scheme:normal", - // The frame is only as large as the widget currently needs, but it is still a rectangle over - // the host page. A transition keeps the growth from looking like a glitch. - "transition:width .18s ease,height .18s ease", - ].join(";"); - - window.addEventListener("message", function (event) { - // Two checks, both required. The origin check rejects messages from any other frame on the - // page; the source tag rejects unrelated messages from our own origin. - if (event.origin !== origin) return; - - var data = event.data; - if (!data || data.source !== "agentcore-widget" || data.type !== "resize") return; - - var width = Number(data.width); - var height = Number(data.height); - if (!isFinite(width) || !isFinite(height)) return; - - // Never taller or wider than the window it sits in, or the widget runs off a phone screen with - // no way to scroll it back. - frame.style.width = Math.min(width, window.innerWidth - 8) + "px"; - frame.style.height = Math.min(height, window.innerHeight - 8) + "px"; - }); - - function mount() { - document.body.appendChild(frame); - } - - if (document.body) mount(); - else document.addEventListener("DOMContentLoaded", mount); -})(); diff --git a/demo/chat-ui/src/App.tsx b/demo/chat-ui/src/App.tsx deleted file mode 100644 index a4d99d40..00000000 --- a/demo/chat-ui/src/App.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { Thread } from "@/components/assistant-ui/thread"; -import { SidebarProvider } from "@/components/ui/sidebar"; -import { TooltipProvider } from "@/components/ui/tooltip"; -import { AssistantRuntimeProvider, useRemoteThreadListRuntime } from "@assistant-ui/react"; -import { AgentCoreSidebar } from "@/components/AgentCoreSidebar"; -import { GenerativeUiDataUI } from "@/components/GenerativeUiDataUI"; -import { useAgentCoreRuntime } from "./runtime/AgentCoreRuntime"; -import { localThreadListAdapter } from "./runtime/LocalThreadListAdapter"; - -/** - * The route the text endpoint answers on. - * - * It is read from the page rather than compiled in, because the host can move the endpoint — - * `MapAgentCoreHost` takes a pattern — and a rebuilt bundle should not be the price of that. The - * default is the one `MapChatCompletions` uses when a host names none. - */ -const endpoint = - document.documentElement.dataset.agentcoreEndpoint || "/v1/chat/completions"; - -/** - * The application: assistant-ui's thread and thread list, over AgentCore's endpoint. - * - * This is their `templates/default` composition with the Next.js parts left out — the `"use client"` - * directive, the breadcrumb header that links to their docs, and the AI SDK transport. Our runtime - * hook and our thread list adapter stand where `useChatRuntime` stood. - * - * `TooltipProvider` is not decoration. The vendored action bar renders `Tooltip` for every control - * it shows, and those throw without a provider above them. - */ -export function App() { - // `useRemoteThreadListRuntime` calls `runtimeHook` once per thread, which is what makes the - // session id inside `useAgentCoreRuntime` belong to one conversation rather than to the whole - // tab. The adapter beside it is the stub — see runtime/LocalThreadListAdapter.ts. - const runtime = useRemoteThreadListRuntime({ - runtimeHook: () => useAgentCoreRuntime(endpoint), - adapter: localThreadListAdapter(), - }); - - return ( - - - - -
- -
- -
-
-
-
-
- ); -} diff --git a/demo/chat-ui/src/README.md b/demo/chat-ui/src/README.md deleted file mode 100644 index c8a755a5..00000000 --- a/demo/chat-ui/src/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# What is ours and what is not - -`runtime/` is ours. Everything in it is written and maintained here, and it is the only place a -change to this application's behaviour belongs. - -`components/`, `hooks/`, and `lib/` are assistant-ui's and shadcn's. Those files arrived through -their registries and are byte-identical to what the CLI wrote. **Do not edit them.** They carry no -explanatory comments for the same reason: a diff against upstream is the cheap way to see whether -one has been tampered with, and re-running the commands below has to stay a clean overwrite rather -than a merge. - -To refresh them: - - npx shadcn@latest add https://r.assistant-ui.com/thread.json - npx shadcn@latest add https://r.assistant-ui.com/threadlist-sidebar.json - npx shadcn@latest add https://ui.shadcn.com/r/styles/new-york-v4/utils.json - -The first two pull everything else transitively — the message parts, the thread list, and the -shadcn primitives under `components/ui`. The third is listed separately because the CLI does not -write `lib/utils.ts` when it believes the file already exists, and a fresh checkout that runs only -the first two therefore ends up without it. - -The CLI resolves `@/components` by reading `../tsconfig.json` — the solution file, not -`tsconfig.app.json`. That is why the solution file carries a `compilerOptions.paths` entry it never -compiles with. Remove it and the next `shadcn add` writes its files into a directory literally named -`@`. - -Radix is the primitive library here, not Base UI. assistant-ui publishes both flavours and the -registry's default entries resolved to Radix on their own; nothing was chosen by hand. - -If a vendored file ever needs a change to work here, it is not vendorable. Wrap it from `runtime/` -instead of editing it in place. \ No newline at end of file diff --git a/demo/chat-ui/src/Widget.tsx b/demo/chat-ui/src/Widget.tsx deleted file mode 100644 index 3cf8bec9..00000000 --- a/demo/chat-ui/src/Widget.tsx +++ /dev/null @@ -1,122 +0,0 @@ -import { Thread } from "@/components/assistant-ui/thread"; -import { LauncherBubble } from "@/components/elements/launcher-bubble"; -import { TooltipProvider } from "@/components/ui/tooltip"; -import { GenerativeUiDataUI } from "@/components/GenerativeUiDataUI"; -import { AssistantRuntimeProvider } from "@assistant-ui/react"; -import { XIcon } from "lucide-react"; -import { useEffect, useState } from "react"; -import { useAgentCoreRuntime } from "./runtime/AgentCoreRuntime"; - -/** - * The embeddable form of the chat: a bubble on someone else's page that opens into a panel. - * - * It is a second page rather than a mode of the main one. The full app owns the whole viewport and - * carries a sidebar and a thread list; a widget owns a corner, has no room for either, and has to - * be able to render as *nothing but a bubble* so the host page shows through around it. Those are - * different layouts, not one layout with a flag. - * - * Read {@link ../public/embed.js} next: this half only knows how big it wants to be, and says so. - * The script on the host page is what actually resizes the frame. - */ - -/** The size the frame should be, in CSS pixels, for each state. */ -const SIZE = { - closed: { width: 96, height: 96 }, - teaser: { width: 336, height: 420 }, - open: { width: 400, height: 620 }, -} as const; - -const endpoint = - document.documentElement.dataset.agentcoreEndpoint || "/v1/chat/completions"; - -const PROMPTS = [ - "What treadmill fits a small room?", - "How do I service my elliptical?", - "Where is my order?", -] as const; - -type Phase = "closed" | "teaser" | "open"; - -/** - * Tells the host page how much room to give the frame. - * - * An iframe cannot resize itself — its size belongs to the document that embedded it. So the widget - * posts what it needs and `embed.js` applies it. Without this the frame would be stuck at whatever - * size it was created with, and either clip the open panel or leave a 400px invisible rectangle - * over the host page swallowing clicks while the bubble is closed. - * - * The message goes to the embedding page named by document.referrer. Hosts that suppress - * referrers get "*" instead; the payload is two numbers, and embed.js checks origin and shape. - */ -function useFrameSize(phase: Phase) { - useEffect(() => { - const size = SIZE[phase]; - let target = "*"; - try { - if (document.referrer) target = new URL(document.referrer).origin; - } catch { - target = "*"; - } - window.parent?.postMessage( - { source: "agentcore-widget", type: "resize", ...size }, - target, - ); - }, [phase]); -} - -export function Widget() { - const runtime = useAgentCoreRuntime(endpoint); - const [phase, setPhase] = useState("closed"); - const [pending, setPending] = useState(null); - - useFrameSize(phase); - - // A prompt picked from the teaser has to wait for the thread to exist before it can be sent. - useEffect(() => { - if (phase !== "open" || !pending) return; - - runtime.thread.append({ - role: "user", - content: [{ type: "text", text: pending }], - }); - setPending(null); - }, [phase, pending, runtime]); - - return ( - - - -
- {phase === "open" ? ( -
- - -
- ) : ( - - setPhase(phase === "teaser" ? "closed" : "teaser") - } - onPick={(prompt) => { - setPending(prompt); - setPhase("open"); - }} - onStart={() => setPhase("open")} - /> - )} -
-
-
- ); -} diff --git a/demo/chat-ui/src/components/AgentCoreSidebar.tsx b/demo/chat-ui/src/components/AgentCoreSidebar.tsx deleted file mode 100644 index b5ca1f42..00000000 --- a/demo/chat-ui/src/components/AgentCoreSidebar.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type * as React from "react"; -import { Sidebar, SidebarContent, SidebarRail } from "@/components/ui/sidebar"; -import { ThreadList } from "@/components/assistant-ui/thread-list"; - -/** - * The sidebar, holding the thread list and nothing else. - * - * This stands in for the vendored `components/assistant-ui/threadlist-sidebar.tsx`, which is a - * seventy-line shell whose only substance is the `ThreadList` below. The rest of it is a header - * linking to assistant-ui.com and a footer linking to their repository — right for their template, - * wrong for a UI a consumer of this library serves to their own callers. - * - * Copying the shell rather than editing theirs is what keeps `npx shadcn add` a clean overwrite. - * Their file stays on disk and stays re-pullable; nothing imports it, so it never reaches the - * bundle. - * - * `ThreadList` already carries the new-thread control and the search box, so there is no header to - * replace — dropping theirs leaves nothing missing. - */ -export function AgentCoreSidebar({ - ...props -}: React.ComponentProps) { - return ( - - - - - {/* The drag handle that resizes and collapses the sidebar. Part of the shadcn sidebar - contract rather than decoration: without it the collapse control has nothing to grab. */} - - - ); -} diff --git a/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx b/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx deleted file mode 100644 index f01bf1b4..00000000 --- a/demo/chat-ui/src/components/GenerativeUiDataUI.test.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { Thread } from "@/components/assistant-ui/thread"; -import { - AssistantRuntimeProvider, - useLocalRuntime, - type ChatModelAdapter, -} from "@assistant-ui/react"; -import { defaultGenerativeUILibrary } from "@assistant-ui/react-generative-ui"; -import { act, cleanup, render, screen } from "@testing-library/react"; -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import { afterEach, describe, expect, test } from "vitest"; -import { GENERATIVE_UI_PART, GenerativeUiDataUI } from "./GenerativeUiDataUI"; - -/** - * The renderer for what `ui.draw` sends. - * - * The drawing never travels as a tool call: the server owns the tool loop and the reply carries - * only text, so the tree arrives as a `data` part on its own SSE field. Nothing renders a data part - * until a renderer is registered by name, which is what these tests hold in place. - */ - -// Testing-library only registers its own cleanup when vitest runs with `globals: true`. It does -// not here, so each test would otherwise leave its DOM in the body and the next one would find two -// of everything. -afterEach(cleanup); - -const CARD = { - $type: "Card", - title: "Q3 revenue", - children: [ - { $type: "Fact", label: "Bookings", value: "$1.2M" }, - { $type: "Button", label: "Approve", $action: { type: "approve", id: 42 } }, - ], -}; - -/** Drives a thread that answers with one drawing, and reports what the caller sent back. */ -function mount(options: { hold?: boolean } = {}) { - const sent: string[] = []; - let release: (() => void) | undefined; - const held = new Promise((resolve) => { - release = resolve; - }); - - const adapter: ChatModelAdapter = { - async *run({ messages }) { - sent.push(messages.at(-1)?.content.map((part) => ("text" in part ? part.text : "")).join("") ?? ""); - - yield { - content: [{ type: "data" as const, name: GENERATIVE_UI_PART, data: CARD }], - }; - - if (options.hold) { - await held; - } - }, - }; - - function Harness() { - const runtime = useLocalRuntime(adapter); - return ( - - - - - ); - } - - const view = render(); - return { view, sent, release: () => release?.() }; -} - -async function ask(view: ReturnType) { - const box = view.container.querySelector("textarea") ?? view.container.querySelector("input"); - const { fireEvent } = await import("@testing-library/react"); - - await act(async () => { - fireEvent.change(box!, { target: { value: "show me revenue" } }); - }); - await act(async () => { - fireEvent.keyDown(box!, { key: "Enter", code: "Enter" }); - }); -} - -describe("the drawing renderer", () => { - test("draws a data part that would otherwise render as nothing", async () => { - const { view } = mount(); - await ask(view); - - expect(await screen.findByText("Q3 revenue")).toBeTruthy(); - expect(screen.getByText("Bookings")).toBeTruthy(); - expect(screen.getByText("$1.2M")).toBeTruthy(); - }); - - test("a click on an idle thread sends the payload back as the next user turn", async () => { - const { view, sent } = mount(); - await ask(view); - - const button = await screen.findByRole("button", { name: "Approve" }); - const { fireEvent } = await import("@testing-library/react"); - await act(async () => { - fireEvent.click(button); - }); - - // Wrapped in prose, not bare JSON: the wire layer flattens a user message to its text, and the - // agent would otherwise read raw JSON as something the caller typed. - const clicked = sent.find((text) => text.includes("clicked")); - expect(clicked).toContain("approve"); - expect(clicked).toContain("42"); - }); - - test("the controls are inert while a turn is still running", async () => { - const { view } = mount({ hold: true }); - await ask(view); - - await screen.findByText("Q3 revenue"); - - const drawing = view.container.querySelector("[data-agentcore-drawing]"); - expect(drawing?.hasAttribute("inert")).toBe(true); - }); - - test("an action type nobody registered still reaches the agent", async () => { - // The agent names its own action types and reports them in its receipt. A fixed registry here - // would render buttons that silently do nothing for every name it had not been told about. - const registered = Object.keys(defaultGenerativeUILibrary); - expect(registered).toContain("Button"); - - const { view, sent } = mount(); - await ask(view); - - const button = await screen.findByRole("button", { name: "Approve" }); - const { fireEvent } = await import("@testing-library/react"); - await act(async () => { - fireEvent.click(button); - }); - - expect(sent.some((text) => text.includes("approve"))).toBe(true); - }); -}); - -describe("the vocabulary the drawing model is taught", () => { - test("names only components this app can actually render", () => { - // The drift guard. The C# skill file is the model's whole vocabulary and the library is what - // draws it; an upgrade that renames a component would otherwise show the caller a hole. - // From demo/chat-ui, which is where vitest runs. `import.meta.url` is not a file URL under - // happy-dom. - // - // This reaches outside demo/chat-ui into AgentCore's own source tree, so this test breaks if - // chat-ui is copied into another repo, per the README's suggestion. There is no fix here short - // of publishing the vocabulary as its own artifact both sides read. - const vocabulary = readFileSync( - resolve(process.cwd(), "../../src/AgentCore.Application/Tools/Drawing/vocabulary.md"), - "utf8", - ); - - const taught = [...vocabulary.matchAll(/^- `([A-Z][A-Za-z]*)`/gm)].map((match) => match[1]); - const renderable = new Set(Object.keys(defaultGenerativeUILibrary)); - - expect(taught).toHaveLength(27); - expect(taught.filter((name) => !renderable.has(name))).toEqual([]); - expect([...renderable].filter((name) => !taught.includes(name))).toEqual([]); - }); -}); diff --git a/demo/chat-ui/src/components/GenerativeUiDataUI.tsx b/demo/chat-ui/src/components/GenerativeUiDataUI.tsx deleted file mode 100644 index a2e497ac..00000000 --- a/demo/chat-ui/src/components/GenerativeUiDataUI.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { styledGenerativeUILibrary } from "@/components/assistant-ui/generative-ui"; -import { - useAssistantDataUI, - useAui, - useAuiState, - type DataMessagePartProps, -} from "@assistant-ui/react"; -import { renderGenerativeUI } from "@assistant-ui/react-generative-ui"; -import type { FC } from "react"; - -/** The data-part name the server publishes drawings under. It matches `PresentTool.RendererName`. */ -export const GENERATIVE_UI_PART = "generative-ui"; - -/** - * Draws one `generative-ui` data part, and turns a click on it into the next user turn. - * - * Module scope, not an inline arrow inside the registering component: `useAssistantDataUI` keys the - * renderer by component identity, so a fresh function per render remounts the whole subtree and any - * form state inside it goes with it. - */ -const GenerativeUiPart: FC = ({ data }) => { - const aui = useAui(); - const isRunning = useAuiState((state) => state.thread.isRunning); - - // Every action type the model invents is handled, rather than a fixed registry of names. The - // agent chooses those names itself and reports them in its receipt, so a registry here would have - // to be kept in step with something no code owns. An unhandled type would render a button that - // silently does nothing. - const dispatch = (action: { type: string }) => { - // Appending mid-stream aborts the running turn rather than queueing behind it. - if (aui.thread.getState().isRunning) return; - - // Wrapped in prose. The wire layer flattens a user message to its text, and bare JSON would - // read to the agent as something the caller typed. - aui.thread.append({ - role: "user", - content: [{ type: "text", text: `the caller clicked: ${JSON.stringify(action)}` }], - }); - }; - - return ( - // The guard above stops the click landing; `inert` stops the caller believing it did, and takes - // the controls out of the tab order rather than only ignoring the mouse. -
- {renderGenerativeUI(data, styledGenerativeUILibrary, { status: "done", dispatch })} -
- ); -}; - -/** Registers the renderer for as long as it is mounted. Draws nothing itself. */ -export function GenerativeUiDataUI() { - useAssistantDataUI({ name: GENERATIVE_UI_PART, render: GenerativeUiPart }); - return null; -} diff --git a/demo/chat-ui/src/components/assistant-ui/attachment.tsx b/demo/chat-ui/src/components/assistant-ui/attachment.tsx deleted file mode 100644 index e1f60be6..00000000 --- a/demo/chat-ui/src/components/assistant-ui/attachment.tsx +++ /dev/null @@ -1,299 +0,0 @@ -"use client"; - -import { type PropsWithChildren, useEffect, useState, type FC } from "react"; -import { - XIcon, - PlusIcon, - FileText, - Loader2Icon, - AlertCircleIcon, -} from "lucide-react"; -import { - AttachmentPrimitive, - ComposerPrimitive, - MessagePrimitive, - useAuiState, - useAui, -} from "@assistant-ui/react"; -import { useShallow } from "zustand/shallow"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { - Dialog, - DialogTitle, - DialogContent, - DialogTrigger, -} from "@/components/ui/dialog"; -import { - Avatar, - AvatarImage, - AvatarFallback, -} from "@/components/ui/avatar"; -import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button"; -import { cn } from "@/lib/utils"; - -const useFileSrc = (file: File | undefined) => { - const [src, setSrc] = useState(undefined); - - useEffect(() => { - if (!file) { - setSrc(undefined); - return; - } - - const objectUrl = URL.createObjectURL(file); - setSrc(objectUrl); - - return () => { - URL.revokeObjectURL(objectUrl); - }; - }, [file]); - - return src; -}; - -const useAttachmentSrc = () => { - const { file, src } = useAuiState( - useShallow((s): { file?: File; src?: string } => { - if (s.attachment.type !== "image") return {}; - if (s.attachment.file) return { file: s.attachment.file }; - const src = s.attachment.content?.find((c) => c.type === "image")?.image; - if (!src) return {}; - return { src }; - }), - ); - - return useFileSrc(file) ?? src; -}; - -type AttachmentPreviewProps = { - src: string; -}; - -const AttachmentPreview: FC = ({ src }) => { - const [isLoaded, setIsLoaded] = useState(false); - return ( - Attachment preview setIsLoaded(true)} - /> - ); -}; - -const AttachmentPreviewDialog: FC = ({ children }) => { - const src = useAttachmentSrc(); - - if (!src) return children; - - return ( - - - {children} - - - - Image Attachment Preview - -
- -
-
-
- ); -}; - -const AttachmentThumb: FC = () => { - const src = useAttachmentSrc(); - - return ( - - - - - - - ); -}; - -const AttachmentUI: FC = () => { - const aui = useAui(); - const isComposer = aui.attachment.source !== "message"; - - const isImage = useAuiState((s) => s.attachment.type === "image"); - const typeLabel = useAuiState((s) => { - const type = s.attachment.type; - switch (type) { - case "image": - return "Image"; - case "document": - return "Document"; - case "file": - return "File"; - default: - return type; - } - }); - - const uploadState = useAuiState((s) => { - if (s.attachment.status.type === "running") return "uploading"; - if ( - s.attachment.status.type === "incomplete" && - s.attachment.status.reason === "error" - ) { - return "error"; - } - return undefined; - }); - const isUploading = uploadState === "uploading"; - const isError = uploadState === "error"; - - let stateLabel = ""; - if (isError) { - stateLabel = ", upload failed"; - } else if (isUploading) { - stateLabel = ", uploading"; - } - const errorMessage = useAuiState((s) => - s.attachment.status.type === "incomplete" && - s.attachment.status.reason === "error" - ? (s.attachment.status.message ?? "Upload failed") - : undefined, - ); - - return ( - - - - - -
{ - if (e.key === "Enter") { - e.preventDefault(); - e.currentTarget.click(); - } else if (e.key === " ") { - e.preventDefault(); - } - }} - onKeyUp={(e) => { - if (e.key === " ") e.currentTarget.click(); - }} - aria-label={`${typeLabel} attachment${stateLabel}`} - > - - {isUploading && ( - - )} - {isError && ( - - )} -
-
-
- {isComposer && } -
- - - {errorMessage && ( -

{errorMessage}

- )} -
-
-
- ); -}; - -const AttachmentRemove: FC = () => { - return ( - - - - - - ); -}; - -export const UserMessageAttachments: FC = () => { - return ( -
- - {() => } - -
- ); -}; - -export const ComposerAttachments: FC = () => { - return ( -
- - {() => } - -
- ); -}; - -export const ComposerAddAttachment: FC = () => { - return ( - - - - - - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/draft.tsx b/demo/chat-ui/src/components/assistant-ui/draft.tsx deleted file mode 100644 index 272a3818..00000000 --- a/demo/chat-ui/src/components/assistant-ui/draft.tsx +++ /dev/null @@ -1,100 +0,0 @@ -"use client"; - -import { DraftRestore } from "@/components/elements/draft-restore"; -import { useAui, useAuiState } from "@assistant-ui/react"; -import { useEffect, useState, type FC } from "react"; - -const KEY = "agentcore.composer-draft"; - -/** A draft is only worth keeping if there is enough of it to have been worth typing. */ -const MIN_LENGTH = 8; - -type Draft = { text: string; savedAt: number }; - -function read(): Draft | null { - try { - const raw = localStorage.getItem(KEY); - if (!raw) return null; - - const parsed: unknown = JSON.parse(raw); - if ( - typeof parsed === "object" && - parsed !== null && - typeof (parsed as Draft).text === "string" && - typeof (parsed as Draft).savedAt === "number" - ) { - return parsed as Draft; - } - } catch { - // A private window, cleared site data, or a half-written value. No draft is a fine answer. - } - return null; -} - -function write(draft: Draft | null) { - try { - if (draft) localStorage.setItem(KEY, JSON.stringify(draft)); - else localStorage.removeItem(KEY); - } catch { - // Storage can be full or blocked outright. Losing a draft must never break the composer. - } -} - -/** "3 minutes ago", roughly. Precision here would be false: the draft is not a log entry. */ -function ago(savedAt: number): string { - const seconds = Math.max(0, Math.round((Date.now() - savedAt) / 1000)); - if (seconds < 60) return "just now"; - - const minutes = Math.round(seconds / 60); - if (minutes < 60) return `${minutes} min ago`; - - const hours = Math.round(minutes / 60); - if (hours < 24) return `${hours}h ago`; - - return `${Math.round(hours / 24)}d ago`; -} - -/** - * Keeps what the caller typed but never sent, and offers it back after a reload. - * - * The composer is cleared on send, so this saves only while there is text in it and clears the - * moment there is not — which covers both sending and deleting, without either needing an event. - * - * Only the draft found *at mount* is offered. Re-offering the text as it is being typed would put a - * banner over the composer the whole time the composer is in use. - */ -export const ComposerDraft: FC = () => { - const aui = useAui(); - const text = useAuiState((s) => s.composer.text); - const [found, setFound] = useState(null); - const [dismissed, setDismissed] = useState(false); - - useEffect(() => { - const draft = read(); - if (draft && draft.text.trim().length >= MIN_LENGTH) setFound(draft); - }, []); - - useEffect(() => { - if (text.trim().length >= MIN_LENGTH) write({ text, savedAt: Date.now() }); - else if (text.length === 0) write(null); - }, [text]); - - // Whatever the caller is typing now beats whatever they typed before. - if (dismissed || !found || text.length > 0) return null; - - return ( - { - aui.composer.setText(found.text); - setDismissed(true); - }} - onDiscard={() => { - write(null); - setDismissed(true); - }} - /> - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx b/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx deleted file mode 100644 index b6606e11..00000000 --- a/demo/chat-ui/src/components/assistant-ui/elements/sources.tsx +++ /dev/null @@ -1,82 +0,0 @@ -"use client"; - -import { ChevronDownIcon } from "lucide-react"; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@/components/ui/collapsible"; -import { cn } from "@/lib/utils"; -import { collapsePanel, fieldInteractive, mono, paper } from "@/components/elements/surfaces"; - -export interface Source { - /** - * Distinct per card, and unlike `domain` never blank or shared — used only as the list key. - */ - id: string; - domain: string; - title: string; -} - -export interface SourcesProps { - readonly sources: readonly Source[]; - readonly open: boolean; - readonly onOpenChange: (open: boolean) => void; - readonly className?: string; -} - -export function Sources({ - sources, - open, - onOpenChange, - className, -}: SourcesProps) { - return ( - - - - Sources - - {sources.length} - - - - - -
- {sources.map((source) => ( -
-
- - {source.domain.charAt(0).toUpperCase()} - - - {source.domain} - -
- - {source.title} - -
- ))} -
-
-
- ); -} diff --git a/demo/chat-ui/src/components/assistant-ui/file.tsx b/demo/chat-ui/src/components/assistant-ui/file.tsx deleted file mode 100644 index cdc1180a..00000000 --- a/demo/chat-ui/src/components/assistant-ui/file.tsx +++ /dev/null @@ -1,265 +0,0 @@ -"use client"; - -import { memo, type FC } from "react"; -import { cva, type VariantProps } from "class-variance-authority"; -import { - FileIcon, - FileTextIcon, - ImageIcon, - MusicIcon, - VideoIcon, - BracesIcon, - DownloadIcon, -} from "lucide-react"; -import type { FileMessagePartComponent } from "@assistant-ui/react"; -import { cn } from "@/lib/utils"; - -const fileVariants = cva( - "aui-file-root inline-flex items-center gap-3 rounded-lg transition-colors", - { - variants: { - variant: { - outline: "border-border hover:bg-muted/50 border", - ghost: "hover:bg-muted/50", - muted: "bg-muted/50 hover:bg-muted/70", - }, - size: { - sm: "px-2.5 py-1.5 text-xs", - default: "px-3 py-2 text-sm", - lg: "px-4 py-3 text-base", - }, - }, - defaultVariants: { - variant: "outline", - size: "default", - }, - }, -); - -function getMimeTypeIcon(mimeType: string): FC<{ className?: string }> { - const type = mimeType.toLowerCase(); - if (type.startsWith("image/")) { - return ImageIcon; - } - if (type === "application/pdf") { - return FileTextIcon; - } - if (type === "application/json") { - return BracesIcon; - } - if (type.startsWith("text/")) { - return FileTextIcon; - } - if (type.startsWith("audio/")) { - return MusicIcon; - } - if (type.startsWith("video/")) { - return VideoIcon; - } - return FileIcon; -} - -export type FileDataKind = "data-uri" | "url" | "base64" | "id"; - -function getFileDataKind( - data: string, - sourceType?: "url" | "id", -): FileDataKind { - if (sourceType === "url" && /^data:/i.test(data)) return "data-uri"; - if (sourceType) return sourceType; - if (/^data:/i.test(data)) return "data-uri"; - if (/^https?:\/\//i.test(data)) return "url"; - return "base64"; -} - -function getBase64Size(base64: string): number { - const commaIndex = base64.indexOf(","); - const base64Data = commaIndex >= 0 ? base64.slice(commaIndex + 1) : base64; - const padding = (base64Data.match(/=/g) || []).length; - return Math.floor((base64Data.length * 3) / 4) - padding; -} - -function formatFileSize(bytes: number): string { - if (bytes < 1024) { - return `${bytes} B`; - } - if (bytes < 1024 * 1024) { - return `${(bytes / 1024).toFixed(1)} KB`; - } - return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; -} - -export type FileRootProps = React.ComponentProps<"div"> & - VariantProps; - -function FileRoot({ - className, - variant, - size, - children, - ...props -}: FileRootProps) { - return ( -
- {children} -
- ); -} - -type FileIconDisplayProps = React.ComponentProps<"span"> & { - mimeType?: string; -}; - -function FileIconDisplay({ - mimeType, - className, - children, - ...props -}: FileIconDisplayProps) { - const IconComponent = mimeType ? getMimeTypeIcon(mimeType) : FileIcon; - - return ( - - {children ?? } - - ); -} - -function FileName({ - className, - children, - ...props -}: React.ComponentProps<"span">) { - return ( - - {children || "Unnamed file"} - - ); -} - -type FileSizeProps = React.ComponentProps<"span"> & { - bytes: number; -}; - -function FileSize({ bytes, className, ...props }: FileSizeProps) { - return ( - - {formatFileSize(bytes)} - - ); -} - -type FileDownloadProps = Omit, "href"> & { - data: string; - mimeType: string; - filename?: string; - sourceType?: "url" | "id"; -}; - -function FileDownload({ - data, - mimeType, - filename, - sourceType, - className, - children, - ...props -}: FileDownloadProps) { - if (typeof data !== "string") return null; - const kind = getFileDataKind(data, sourceType); - if (kind === "id") return null; - if (kind === "url" && !/^(https?:\/\/|blob:)/i.test(data)) return null; - const href = kind === "base64" ? `data:${mimeType};base64,${data}` : data; - - return ( - - {children || } - - ); -} - -const FileImpl: FileMessagePartComponent = ({ - filename, - data, - mimeType, - sourceType, -}) => { - const kind = getFileDataKind(data, sourceType); - const showSize = - typeof data === "string" && (kind === "base64" || kind === "data-uri"); - - return ( - - -
- {filename} - {showSize && ( - - )} -
- -
- ); -}; - -const File = memo(FileImpl) as unknown as FileMessagePartComponent & { - Root: typeof FileRoot; - Icon: typeof FileIconDisplay; - Name: typeof FileName; - Size: typeof FileSize; - Download: typeof FileDownload; -}; - -File.displayName = "File"; -File.Root = FileRoot; -File.Icon = FileIconDisplay; -File.Name = FileName; -File.Size = FileSize; -File.Download = FileDownload; - -export { - File, - FileRoot, - FileIconDisplay, - FileName, - FileSize, - FileDownload, - fileVariants, - getMimeTypeIcon, - getFileDataKind, - getBase64Size, - formatFileSize, -}; diff --git a/demo/chat-ui/src/components/assistant-ui/follow-up-suggestions.tsx b/demo/chat-ui/src/components/assistant-ui/follow-up-suggestions.tsx deleted file mode 100644 index 77de2e4c..00000000 --- a/demo/chat-ui/src/components/assistant-ui/follow-up-suggestions.tsx +++ /dev/null @@ -1,83 +0,0 @@ -"use client"; - -import { AuiIf, useAuiState, ThreadPrimitive } from "@assistant-ui/react"; -import { useCallback, useEffect, useRef, useState, type FC } from "react"; - -const FollowupSuggestionsRow: FC = () => { - const suggestions = useAuiState((s) => s.thread.suggestions); - const scrollRef = useRef(null); - const rtlRef = useRef(null); - const [fades, setFades] = useState({ left: false, right: false }); - - const updateFades = useCallback(() => { - const el = scrollRef.current; - if (!el) return; - const maxScroll = el.scrollWidth - el.clientWidth; - // scrollLeft runs 0..-max in RTL; normalize to hidden width per physical edge. - const fromStart = Math.abs(el.scrollLeft); - // getComputedStyle forces a style recalc per scroll event; direction is stable, read it once. - const rtl = (rtlRef.current ??= getComputedStyle(el).direction === "rtl"); - const [left, right] = rtl - ? [maxScroll - fromStart, fromStart] - : [fromStart, maxScroll - fromStart]; - setFades((prev) => { - const next = { left: left > 1, right: right > 1 }; - return prev.left === next.left && prev.right === next.right ? prev : next; - }); - }, []); - - useEffect(() => { - updateFades(); - const el = scrollRef.current; - if (!el?.firstElementChild) return undefined; - const observer = new ResizeObserver(updateFades); - observer.observe(el); - observer.observe(el.firstElementChild); - return () => observer.disconnect(); - }, [updateFades]); - - const maskImage = `linear-gradient(to right, ${ - fades.left ? "transparent, black 2rem" : "black" - }, ${fades.right ? "black calc(100% - 2rem), transparent" : "black"})`; - - return ( -
-
- {suggestions.map((suggestion, idx) => ( - - {suggestion.title ?? suggestion.prompt} - {suggestion.label && ( - - {suggestion.label} - - )} - - ))} -
-
- ); -}; - -export const ThreadFollowupSuggestions: FC = () => ( - - !s.thread.isEmpty && - !s.thread.isRunning && - s.thread.suggestions.length > 0 - } - > - - -); diff --git a/demo/chat-ui/src/components/assistant-ui/generative-ui.tsx b/demo/chat-ui/src/components/assistant-ui/generative-ui.tsx deleted file mode 100644 index fc3ffec0..00000000 --- a/demo/chat-ui/src/components/assistant-ui/generative-ui.tsx +++ /dev/null @@ -1,24 +0,0 @@ -"use client"; - -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { GenerativeUILibrary } from "@assistant-ui/react-generative-ui"; -import { defaultGenerativeUILibrary } from "@assistant-ui/react-generative-ui"; - -const markdownBase = defaultGenerativeUILibrary.Markdown!; - -/** `MarkdownTextPrimitive` cannot be reused here: it reads from message-part context, not a prop string. */ -export const styledGenerativeUILibrary: GenerativeUILibrary = { - ...defaultGenerativeUILibrary, - Markdown: { - properties: markdownBase.properties, - streamProperties: markdownBase.streamProperties, - description: "A markdown string, rendered with GitHub-flavored markdown.", - render: ({ value, children }) => ( -
- {value ?? ""} - {children} -
- ), - }, -}; diff --git a/demo/chat-ui/src/components/assistant-ui/image.tsx b/demo/chat-ui/src/components/assistant-ui/image.tsx deleted file mode 100644 index ba2f85b3..00000000 --- a/demo/chat-ui/src/components/assistant-ui/image.tsx +++ /dev/null @@ -1,479 +0,0 @@ -"use client"; - -import { - memo, - useState, - useEffect, - useRef, - type PropsWithChildren, -} from "react"; -import { createPortal } from "react-dom"; -import { cva, type VariantProps } from "class-variance-authority"; -import { - CopyIcon, - DownloadIcon, - ImageIcon, - ImageOffIcon, - Loader2Icon, - RefreshCwIcon, - ShieldAlertIcon, -} from "lucide-react"; -import type { - ImageMessagePart, - ImageMessagePartComponent, -} from "@assistant-ui/react"; -import { cn } from "@/lib/utils"; - -const extensionForMimeType = (mimeType?: string): string => { - switch (mimeType) { - case "image/png": - return "png"; - case "image/jpeg": - case "image/jpg": - return "jpg"; - case "image/webp": - return "webp"; - case "image/gif": - return "gif"; - case "image/svg+xml": - return "svg"; - default: - return "png"; - } -}; - -const dataUriToBlob = (dataUri: string): Blob => { - const [meta, data] = dataUri.split(","); - const mime = - /data:([^;]+)/i.exec(meta ?? "")?.[1]?.toLowerCase() ?? - "application/octet-stream"; - if (!/;base64/i.test(meta ?? "")) { - return new Blob([decodeURIComponent(data ?? "")], { type: mime }); - } - const bytes = atob(data ?? ""); - const arr = new Uint8Array(bytes.length); - for (let i = 0; i < bytes.length; i++) arr[i] = bytes.codePointAt(i) ?? 0; - return new Blob([arr], { type: mime }); -}; - -const mimeFromImage = (image: string): string | undefined => - /^data:([^;,]+)/i.exec(image)?.[1]?.toLowerCase(); - -const downloadImagePart = ( - part: Pick, -): void => { - if (typeof document === "undefined") return; - const ext = extensionForMimeType(mimeFromImage(part.image)); - const filename = part.filename ?? `image.${ext}`; - const isDataUri = /^data:/i.test(part.image); - const objectUrl = isDataUri - ? URL.createObjectURL(dataUriToBlob(part.image)) - : null; - const href = objectUrl ?? part.image; - const a = document.createElement("a"); - a.href = href; - a.download = filename; - a.rel = "noopener"; - document.body.appendChild(a); - a.click(); - a.remove(); - if (objectUrl) setTimeout(() => URL.revokeObjectURL(objectUrl), 40_000); -}; - -const copyImagePart = async ( - part: Pick, -): Promise => { - if ( - typeof navigator === "undefined" || - !navigator.clipboard || - typeof ClipboardItem === "undefined" - ) { - throw new Error("Clipboard API is not available in this environment."); - } - const blob = /^data:/i.test(part.image) - ? dataUriToBlob(part.image) - : await fetch(part.image).then((r) => r.blob()); - const mime = mimeFromImage(part.image) ?? blob.type ?? "image/png"; - await navigator.clipboard.write([new ClipboardItem({ [mime]: blob })]); -}; - -const imageVariants = cva( - "aui-image-root relative overflow-hidden rounded-lg", - { - variants: { - variant: { - outline: "border-border border", - ghost: "", - muted: "bg-muted/50", - }, - size: { - sm: "max-w-64", - default: "max-w-96", - lg: "max-w-[512px]", - full: "w-full", - }, - }, - defaultVariants: { - variant: "outline", - size: "default", - }, - }, -); - -export type ImageRootProps = React.ComponentProps<"div"> & - VariantProps; - -function ImageRoot({ - className, - variant, - size, - children, - ...props -}: ImageRootProps) { - return ( -
- {children} -
- ); -} - -type ImagePreviewProps = Omit, "children"> & { - containerClassName?: string; -}; - -function ImagePreview({ - className, - containerClassName, - onLoad, - onError, - alt = "Image content", - src, - ...props -}: ImagePreviewProps) { - const imgRef = useRef(null); - const [loadedSrc, setLoadedSrc] = useState(undefined); - const [errorSrc, setErrorSrc] = useState(undefined); - - const loaded = loadedSrc === src; - const error = errorSrc === src; - - useEffect(() => { - if ( - typeof src === "string" && - imgRef.current?.complete && - imgRef.current.naturalWidth > 0 - ) { - setLoadedSrc(src); - } - }, [src]); - - return ( -
- {!loaded && !error && ( -
- -
- )} - {error ? ( -
- -
- ) : ( - {alt} { - if (typeof src === "string") setLoadedSrc(src); - onLoad?.(e); - }} - onError={(e) => { - if (typeof src === "string") setErrorSrc(src); - onError?.(e); - }} - {...props} - /> - )} -
- ); -} - -function ImageFilename({ - className, - children, - ...props -}: React.ComponentProps<"span">) { - if (!children) return null; - - return ( - - {children} - - ); -} - -type ImageZoomProps = PropsWithChildren<{ - src: string; - alt?: string; -}>; - -function ImageZoom({ src, alt = "Image preview", children }: ImageZoomProps) { - const [isMounted, setIsMounted] = useState(false); - const [isOpen, setIsOpen] = useState(false); - - useEffect(() => { - setIsMounted(true); - }, []); - - const handleOpen = () => setIsOpen(true); - const handleClose = () => setIsOpen(false); - - useEffect(() => { - if (!isOpen) return; - const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === "Escape") setIsOpen(false); - }; - document.addEventListener("keydown", handleKeyDown); - return () => document.removeEventListener("keydown", handleKeyDown); - }, [isOpen]); - - useEffect(() => { - if (!isOpen) return; - const originalOverflow = document.body.style.overflow; - document.body.style.overflow = "hidden"; - return () => { - document.body.style.overflow = originalOverflow; - }; - }, [isOpen]); - - return ( - <> -
e.key === "Enter" && handleOpen()} - role="button" - tabIndex={0} - className="aui-image-zoom-trigger cursor-zoom-in" - aria-label="Click to zoom image" - > - {children} -
- {isMounted && - isOpen && - createPortal( -
e.key === "Enter" && handleClose()} - aria-label="Close zoomed image" - > - {alt} -
, - document.body, - )} - - ); -} - -function ImageGenerating({ className }: { readonly className?: string }) { - return ( -
- - Generating image… -
- ); -} - -function ImageContentFilterError({ - className, - reason, -}: { - readonly className?: string; - readonly reason?: string; -}) { - return ( -
- -

Image could not be generated

- {reason &&

{reason}

} -
- ); -} - -export type ImageActionsProps = { - readonly part: ImageMessagePart; - /** - * Wire to your own generation call to show a regenerate button. The button - * renders only when this is set and the part carries a `prompt`. - */ - readonly onRegenerate?: () => void | Promise; - readonly className?: string; -}; - -function RegenerateButton({ - onRegenerate, -}: { - readonly onRegenerate: () => void | Promise; -}) { - const [isRegenerating, setIsRegenerating] = useState(false); - return ( - - ); -} - -function ImageActions({ part, onRegenerate, className }: ImageActionsProps) { - return ( -
- - - {onRegenerate && } -
- ); -} - -const ImageImpl: ImageMessagePartComponent = (props) => { - const { image, filename, status } = props; - - if (status?.type === "running") { - return ( - - - {filename} - - ); - } - - if (status?.type === "incomplete" && status.reason === "content-filter") { - return ( - - - - ); - } - - return ( - - - - - {filename} - - ); -}; - -const Image = memo(ImageImpl) as unknown as ImageMessagePartComponent & { - Root: typeof ImageRoot; - Preview: typeof ImagePreview; - Filename: typeof ImageFilename; - Zoom: typeof ImageZoom; - Actions: typeof ImageActions; - Generating: typeof ImageGenerating; - ContentFilterError: typeof ImageContentFilterError; -}; - -Image.displayName = "Image"; -Image.Root = ImageRoot; -Image.Preview = ImagePreview; -Image.Filename = ImageFilename; -Image.Zoom = ImageZoom; -Image.Actions = ImageActions; -Image.Generating = ImageGenerating; -Image.ContentFilterError = ImageContentFilterError; - -export { - Image, - ImageRoot, - ImagePreview, - ImageFilename, - ImageZoom, - ImageActions, - ImageGenerating, - ImageContentFilterError, - imageVariants, -}; diff --git a/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx b/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx deleted file mode 100644 index 5d90c910..00000000 --- a/demo/chat-ui/src/components/assistant-ui/markdown-text.tsx +++ /dev/null @@ -1,259 +0,0 @@ -"use client"; - -import "@assistant-ui/react-markdown/styles/dot.css"; - -import { - type CodeHeaderProps, - MarkdownTextPrimitive, - unstable_memoizeMarkdownComponents as memoizeMarkdownComponents, - useIsMarkdownCodeBlock, -} from "@assistant-ui/react-markdown"; -import remarkGfm from "remark-gfm"; -import { type FC, memo, useState } from "react"; -import { CheckIcon, CopyIcon } from "lucide-react"; - -import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button"; -import { cn } from "@/lib/utils"; - -const MarkdownTextImpl = () => { - return ( - - ); -}; - -export const MarkdownText = memo(MarkdownTextImpl); - -const CodeHeader: FC = ({ language, code }) => { - const { isCopied, copyToClipboard } = useCopyToClipboard(); - const onCopy = () => { - if (!code || isCopied) return; - copyToClipboard(code); - }; - - return ( -
- - {language} - - - {!isCopied && ( - - )} - {isCopied && ( - - )} - -
- ); -}; - -const useCopyToClipboard = ({ - copiedDuration = 3000, -}: { - copiedDuration?: number; -} = {}) => { - const [isCopied, setIsCopied] = useState(false); - - const copyToClipboard = (value: string) => { - if (!value || typeof navigator === "undefined" || !navigator.clipboard) { - return; - } - - navigator.clipboard.writeText(value).then( - () => { - setIsCopied(true); - setTimeout(() => setIsCopied(false), copiedDuration); - }, - () => {}, - ); - }; - - return { isCopied, copyToClipboard }; -}; - -const defaultComponents = memoizeMarkdownComponents({ - h1: ({ className, ...props }) => ( -

- ), - h2: ({ className, ...props }) => ( -

- ), - h3: ({ className, ...props }) => ( -

- ), - h4: ({ className, ...props }) => ( -

- ), - h5: ({ className, ...props }) => ( -

- ), - h6: ({ className, ...props }) => ( -
- ), - p: ({ className, ...props }) => ( -

- ), - a: ({ className, ...props }) => ( - - ), - blockquote: ({ className, ...props }) => ( -

- ), - ul: ({ className, ...props }) => ( -
    li]:mt-1", - className, - )} - {...props} - /> - ), - ol: ({ className, ...props }) => ( -
      li]:mt-1", - className, - )} - {...props} - /> - ), - hr: ({ className, ...props }) => ( -
      - ), - table: ({ className, ...props }) => ( - - ), - th: ({ className, ...props }) => ( - td:first-child]:rounded-es-lg [&:last-child>td:last-child]:rounded-ee-lg", - className, - )} - {...props} - /> - ), - li: ({ className, ...props }) => ( -
    1. - ), - strong: ({ className, ...props }) => ( - - ), - sup: ({ className, ...props }) => ( - a]:text-xs [&>a]:no-underline", className)} - {...props} - /> - ), - pre: ({ className, ...props }) => ( -
      -  ),
      -  code: function Code({ className, ...props }) {
      -    const isCodeBlock = useIsMarkdownCodeBlock();
      -    return (
      -      
      -    );
      -  },
      -  CodeHeader,
      -});
      diff --git a/demo/chat-ui/src/components/assistant-ui/reasoning.tsx b/demo/chat-ui/src/components/assistant-ui/reasoning.tsx
      deleted file mode 100644
      index 52f0172b..00000000
      --- a/demo/chat-ui/src/components/assistant-ui/reasoning.tsx
      +++ /dev/null
      @@ -1,398 +0,0 @@
      -"use client";
      -
      -import {
      -  createContext,
      -  memo,
      -  useCallback,
      -  useContext,
      -  useEffect,
      -  useLayoutEffect,
      -  useRef,
      -  useState,
      -} from "react";
      -import { cva, type VariantProps } from "class-variance-authority";
      -import { BrainIcon, ChevronDownIcon } from "lucide-react";
      -import {
      -  useScrollLock,
      -  useAuiState,
      -  type ReasoningMessagePartComponent,
      -  type ReasoningGroupComponent,
      -} from "@assistant-ui/react";
      -import { MarkdownText } from "@/components/assistant-ui/markdown-text";
      -import {
      -  Collapsible,
      -  CollapsibleContent,
      -  CollapsibleTrigger,
      -} from "@/components/ui/collapsible";
      -import { cn } from "@/lib/utils";
      -
      -const ANIMATION_DURATION = 200;
      -
      -const ReasoningPreviewContext = createContext(false);
      -
      -const reasoningVariants = cva("aui-reasoning-root mb-4 w-full", {
      -  variants: {
      -    variant: {
      -      outline: "rounded-lg border px-3 py-2",
      -      ghost: "",
      -      muted: "bg-muted/50 rounded-lg px-3 py-2",
      -    },
      -  },
      -  defaultVariants: {
      -    variant: "outline",
      -  },
      -});
      -
      -export type ReasoningRootProps = Omit<
      -  React.ComponentProps,
      -  "open" | "onOpenChange"
      -> &
      -  VariantProps & {
      -    open?: boolean;
      -    onOpenChange?: (open: boolean) => void;
      -    defaultOpen?: boolean;
      -    /**
      -     * Whether the reasoning is currently streaming. While `true` the
      -     * disclosure is held open with a bottom-pinned live preview; when
      -     * streaming ends it returns to `defaultOpen`, and the first manual
      -     * toggle takes over the open/close state permanently. The live preview
      -     * keeps following the newest tokens while the disclosure is open during
      -     * streaming, even after a manual toggle, and pauses while the reader is
      -     * scrolled up.
      -     */
      -    streaming?: boolean;
      -  };
      -
      -function ReasoningRoot({
      -  className,
      -  variant,
      -  open: controlledOpen,
      -  onOpenChange: controlledOnOpenChange,
      -  defaultOpen = false,
      -  streaming,
      -  children,
      -  ...props
      -}: ReasoningRootProps) {
      -  const collapsibleRef = useRef(null);
      -  const initialOpenRef = useRef(defaultOpen);
      -  const [userOpen, setUserOpen] = useState(null);
      -  const lockScroll = useScrollLock(collapsibleRef, ANIMATION_DURATION);
      -
      -  const isControlled = controlledOpen !== undefined;
      -  const isOpen = isControlled
      -    ? controlledOpen
      -    : (userOpen ?? (streaming || initialOpenRef.current));
      -  const isPreview = streaming === true && isOpen;
      -
      -  const prevStreamingRef = useRef(streaming);
      -  useLayoutEffect(() => {
      -    if (prevStreamingRef.current === streaming) return;
      -    prevStreamingRef.current = streaming;
      -    // A streaming transition only animates the panel when the resting state
      -    // is collapsed; with `defaultOpen` the disclosure stays open across it.
      -    if (!isControlled && userOpen === null && !initialOpenRef.current) {
      -      lockScroll();
      -    }
      -  }, [streaming, isControlled, userOpen, lockScroll]);
      -
      -  const handleOpenChange = useCallback(
      -    (open: boolean) => {
      -      lockScroll();
      -      if (!isControlled) {
      -        setUserOpen(open);
      -      }
      -      controlledOnOpenChange?.(open);
      -    },
      -    [lockScroll, isControlled, controlledOnOpenChange],
      -  );
      -
      -  return (
      -    
      -      
      -        {children}
      -      
      -    
      -  );
      -}
      -
      -function ReasoningFade({
      -  side = "bottom",
      -  className,
      -  ...props
      -}: React.ComponentProps<"div"> & { side?: "top" | "bottom" }) {
      -  if (side === "top") {
      -    return (
      -      
      - ); - } - - return ( -
      - ); -} - -function ReasoningTrigger({ - active, - duration, - className, - ...props -}: React.ComponentProps & { - active?: boolean; - duration?: number; -}) { - const durationText = duration ? ` (${duration}s)` : ""; - - return ( - - - - Reasoning{durationText} - {active ? ( - - Reasoning{durationText} - - ) : null} - - - - ); -} - -function ReasoningContent({ - className, - children, - ...props -}: React.ComponentProps) { - const isPreview = useContext(ReasoningPreviewContext); - - return ( - - - {children} - {isPreview ? : null} - - ); -} - -function ReasoningText({ - className, - children, - ...props -}: React.ComponentProps<"div">) { - const isPreview = useContext(ReasoningPreviewContext); - const scrollRef = useRef(null); - const contentRef = useRef(null); - - useEffect(() => { - if (!isPreview) return; - const scrollEl = scrollRef.current; - const contentEl = contentRef.current; - if (!scrollEl || !contentEl) return; - - let pinned = true; - let lastScrollTop = scrollEl.scrollTop; - let lastScrollHeight = scrollEl.scrollHeight; - const isAtBottom = () => - Math.abs( - scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight, - ) <= 1 || scrollEl.scrollHeight <= scrollEl.clientHeight; - - const pin = () => { - if (!pinned) return; - scrollEl.scrollTop = scrollEl.scrollHeight; - }; - // A pin's own scroll event can arrive after new content grew the scroll - // height and read as "not at bottom"; only an upward move at unchanged - // scroll height is user intent. - const onScroll = () => { - if (isAtBottom()) { - pinned = true; - } else if ( - scrollEl.scrollTop < lastScrollTop && - scrollEl.scrollHeight === lastScrollHeight - ) { - pinned = false; - } - lastScrollTop = scrollEl.scrollTop; - lastScrollHeight = scrollEl.scrollHeight; - }; - - pin(); - scrollEl.addEventListener("scroll", onScroll); - const observer = new ResizeObserver(pin); - observer.observe(contentEl); - return () => { - scrollEl.removeEventListener("scroll", onScroll); - observer.disconnect(); - }; - }, [isPreview]); - - return ( -
      -
      - {children} -
      -
      - ); -} - -const ReasoningImpl: ReasoningMessagePartComponent = () => ; - -const ReasoningGroupImpl: ReasoningGroupComponent = ({ - children, - startIndex, - endIndex, -}) => { - const isReasoningStreaming = useAuiState((s) => { - if (s.message.status?.type !== "running") return false; - for (let index = startIndex; index <= endIndex; index++) { - if (s.message.parts[index]?.status.type === "running") return true; - } - return false; - }); - - return ( - - - - {children} - - - ); -}; - -const Reasoning = memo( - ReasoningImpl, -) as unknown as ReasoningMessagePartComponent & { - Root: typeof ReasoningRoot; - Trigger: typeof ReasoningTrigger; - Content: typeof ReasoningContent; - Text: typeof ReasoningText; - Fade: typeof ReasoningFade; -}; - -Reasoning.displayName = "Reasoning"; -Reasoning.Root = ReasoningRoot; -Reasoning.Trigger = ReasoningTrigger; -Reasoning.Content = ReasoningContent; -Reasoning.Text = ReasoningText; -Reasoning.Fade = ReasoningFade; - -/** - * @deprecated This wrapper targets the legacy `components.ReasoningGroup` - * prop on ``. Use `` - * with a `groupBy` returning `"group-reasoning"` and compose `ReasoningRoot` - * / `ReasoningTrigger` / `ReasoningContent` / `ReasoningText` directly. - * See `thread.tsx` for an example. - */ -const ReasoningGroup = memo(ReasoningGroupImpl); -ReasoningGroup.displayName = "ReasoningGroup"; - -export { - Reasoning, - ReasoningGroup, - ReasoningRoot, - ReasoningTrigger, - ReasoningContent, - ReasoningText, - ReasoningFade, - reasoningVariants, -}; diff --git a/demo/chat-ui/src/components/assistant-ui/regenerate.tsx b/demo/chat-ui/src/components/assistant-ui/regenerate.tsx deleted file mode 100644 index 352eac85..00000000 --- a/demo/chat-ui/src/components/assistant-ui/regenerate.tsx +++ /dev/null @@ -1,60 +0,0 @@ -"use client"; - -import { RegenerateMenu } from "@/components/elements/regenerate-menu"; -import { useAui, useAuiState } from "@assistant-ui/react"; -import { useActionBarReload } from "@assistant-ui/core/react"; -import { useState, type FC } from "react"; - -/** - * The ways to ask again. - * - * Only the first is a regenerate in assistant-ui's sense. The other two cannot be: the runtime - * replays the same request, and AgentCore takes no per-turn steering, so "shorter" has nowhere to - * live on a reload. They are sent as a new instruction instead, which is a turn the agent can - * actually act on — and which keeps the answer being complained about in view. - */ -const OPTIONS = [ - { id: "again", label: "Try again", detail: "Same question, fresh answer" }, - { id: "shorter", label: "Shorter", detail: "Ask for the short version" }, - { id: "detail", label: "More detail", detail: "Ask it to go deeper" }, -] as const; - -const FOLLOW_UP: Record = { - shorter: "That was too long. Answer again, much shorter.", - detail: "Go deeper on that answer. Add the detail you left out.", -}; - -export const Regenerate: FC = () => { - const aui = useAui(); - const { disabled, reload } = useActionBarReload(); - const isRunning = useAuiState((s) => s.thread.isRunning); - const [open, setOpen] = useState(false); - - const pick = (id: string) => { - setOpen(false); - - // A turn is already in flight: appending would abort it, and reloading is refused anyway. - if (isRunning) return; - - if (id === "again") { - if (!disabled) reload(); - return; - } - - const text = FOLLOW_UP[id]; - if (text) { - aui.thread.append({ role: "user", content: [{ type: "text", text }] }); - } - }; - - return ( - - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/search.tsx b/demo/chat-ui/src/components/assistant-ui/search.tsx deleted file mode 100644 index ec8353e3..00000000 --- a/demo/chat-ui/src/components/assistant-ui/search.tsx +++ /dev/null @@ -1,78 +0,0 @@ -"use client"; - -import { - ConversationSearch, - type SearchHit, -} from "@/components/elements/conversation-search"; -import { useAuiState } from "@assistant-ui/react"; -import { useMemo, useState, type FC } from "react"; - -/** How much of the line around a match to show on each side. */ -const CONTEXT = 40; - -/** The flattened text of one message, since only text is searchable. */ -function textOf(parts: readonly { type: string }[]): string { - return parts - .filter((p): p is { type: "text"; text: string } => p.type === "text") - .map((p) => p.text) - .join(""); -} - -/** - * Search over the messages of the open thread. - * - * The whole thread is already in memory — assistant-ui holds it to render it — so this is a scan, - * not a query. That also means it finds only what the browser has: a thread whose history has not - * been loaded is not searched, and cannot be. - * - * Matching is first-hit-per-message. A second match inside one long answer is not worth a second - * row that looks almost identical to the first. - */ -export const ThreadMessageSearch: FC = () => { - const messages = useAuiState((s) => s.thread.messages); - const [query, setQuery] = useState(""); - const [activeIndex, setActiveIndex] = useState(0); - - const hits = useMemo(() => { - const needle = query.trim().toLowerCase(); - if (needle.length < 2) return []; - - const found: SearchHit[] = []; - - messages.forEach((message, position) => { - const text = textOf(message.content); - const at = text.toLowerCase().indexOf(needle); - if (at < 0) return; - - found.push({ - id: message.id, - before: text.slice(Math.max(0, at - CONTEXT), at), - match: text.slice(at, at + needle.length), - after: text.slice(at + needle.length, at + needle.length + CONTEXT), - position, - }); - }); - - return found; - }, [messages, query]); - - const step = (direction: number) => { - if (hits.length === 0) return; - // Wrap both ways, so stepping past either end lands on the other rather than sticking. - setActiveIndex((i) => (i + direction + hits.length) % hits.length); - }; - - return ( - { - setQuery(next); - setActiveIndex(0); - }} - onStep={step} - /> - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/speaker.tsx b/demo/chat-ui/src/components/assistant-ui/speaker.tsx deleted file mode 100644 index 708b35e9..00000000 --- a/demo/chat-ui/src/components/assistant-ui/speaker.tsx +++ /dev/null @@ -1,70 +0,0 @@ -"use client"; - -import type { Speaker } from "@/runtime/transport"; -import { useAuiState } from "@assistant-ui/react"; -import { BotIcon, HeadsetIcon, ServerIcon } from "lucide-react"; -import type { FC } from "react"; - -/** - * The name on an answer, when it was not the model that wrote it. - * - * Nothing populates this yet — see `Speaker` in runtime/transport.ts for the contract AgentCore - * would emit. Until it does, `useSpeaker` returns `null` and this renders nothing, which is exactly - * what an app with one speaker should show. - * - * The shipped `elements-speaker-identity` is not used here. It takes an array of turns and renders - * the whole conversation itself, bubbles and all, which suits the gallery demo and cannot be put - * inside a `ThreadPrimitive.Messages` list that already owns its messages. This is the same idea at - * the size the thread can actually use: one line, above one answer. - */ -export function useSpeaker(): Speaker | null { - return useAuiState((s) => { - if (s.message.role !== "assistant") return null; - - const custom = s.message.metadata?.custom as - | { speaker?: unknown } - | undefined; - const speaker = custom?.speaker; - - if ( - typeof speaker === "object" && - speaker !== null && - typeof (speaker as Speaker).name === "string" - ) { - return speaker as Speaker; - } - - // The stored object, not a fresh one: `useAuiState` compares by identity, and a new object per - // call is an infinite render loop rather than a re-render. - return null; - }); -} - -const ICONS = { - agent: BotIcon, - human: HeadsetIcon, - system: ServerIcon, -} as const; - -export const MessageSpeaker: FC = () => { - const speaker = useSpeaker(); - - // The model is the default author. Labelling every answer "Assistant" is noise, so only a speaker - // the caller would not otherwise assume earns a line. - if (!speaker || speaker.kind === "agent") return null; - - const Icon = ICONS[speaker.kind] ?? ICONS.agent; - - return ( -
      - - {speaker.name} - {speaker.detail && ( - · {speaker.detail} - )} -
      - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/thread-list.tsx b/demo/chat-ui/src/components/assistant-ui/thread-list.tsx deleted file mode 100644 index 6415d65c..00000000 --- a/demo/chat-ui/src/components/assistant-ui/thread-list.tsx +++ /dev/null @@ -1,433 +0,0 @@ -"use client"; - -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Skeleton } from "@/components/ui/skeleton"; -import { cn } from "@/lib/utils"; -import { - AuiIf, - ThreadListItemMorePrimitive, - ThreadListItemPrimitive, - ThreadListPrimitive, - useAui, - useAuiState, -} from "@assistant-ui/react"; -import { - ArchiveIcon, - Loader2Icon, - MoreHorizontalIcon, - PencilIcon, - PlusIcon, - SearchIcon, - TrashIcon, -} from "lucide-react"; -import { - forwardRef, - Fragment, - useEffect, - useMemo, - useRef, - useState, - type ComponentPropsWithoutRef, - type FC, -} from "react"; - -export const ThreadList: FC = () => { - const [search, setSearch] = useState(""); - const hasThreads = useAuiState((s) => s.threads.threadIds.length > 0); - - return ( - - - {hasThreads && ( - - )} - - - ); -}; - -export const ThreadListSearch = forwardRef< - HTMLInputElement, - Omit, "value" | "onChange"> & { - value: string; - onValueChange: (value: string) => void; - } ->(({ className, value, onValueChange, ...props }, ref) => { - return ( -
      - - onValueChange(event.target.value)} - aria-label="Search threads" - placeholder="Search threads" - className={cn("h-8 ps-8 text-sm", className)} - {...props} - /> -
      - ); -}); - -ThreadListSearch.displayName = "ThreadListSearch"; - -export const ThreadListRoot: FC< - ComponentPropsWithoutRef -> = ({ className, ...props }) => { - return ( - - ); -}; - -export const ThreadListItems: FC< - ComponentPropsWithoutRef<"div"> & { searchQuery?: string } -> = ({ className, searchQuery = "", ...props }) => { - return ( -
      - s.threads.isLoading}> - - - !s.threads.isLoading}> - - -
      - ); -}; - -const DAY_IN_MS = 86_400_000; - -const dateGroupLabel = ( - date: Date | undefined, - startOfToday: number, -): string => { - if (!date || date.getTime() >= startOfToday) return "Today"; - if (date.getTime() >= startOfToday - DAY_IN_MS) return "Yesterday"; - return "Earlier"; -}; - -type ThreadListGroup = { label: string; indices: number[] }; - -const ThreadListItemGroups: FC<{ searchQuery?: string }> = ({ - searchQuery = "", -}) => { - const threadIds = useAuiState((s) => s.threads.threadIds); - const threadItems = useAuiState((s) => s.threads.threadItems); - - const query = searchQuery.trim().toLowerCase(); - - const { filteredIndices, groups } = useMemo(() => { - const itemsById = new Map(threadItems.map((item) => [item.id, item])); - const dates = threadIds.map((id) => itemsById.get(id)?.lastMessageAt); - const filteredIndices = threadIds - .map((id, index) => ({ id, index })) - .filter( - ({ id }) => - !query || - (itemsById.get(id)?.title || "New Chat") - .toLowerCase() - .includes(query), - ) - .map(({ index }) => index); - if (!filteredIndices.some((index) => dates[index])) { - return { filteredIndices, groups: null }; - } - - const now = new Date(); - const startOfToday = new Date( - now.getFullYear(), - now.getMonth(), - now.getDate(), - ).getTime(); - const time = (index: number) => - dates[index]?.getTime() ?? Number.MAX_SAFE_INTEGER; - const sorted = [...filteredIndices].sort((a, b) => time(b) - time(a)); - - const result: ThreadListGroup[] = []; - for (const index of sorted) { - const label = dateGroupLabel(dates[index], startOfToday); - const lastGroup = result.at(-1); - if (lastGroup?.label === label) { - lastGroup.indices.push(index); - } else { - result.push({ label, indices: [index] }); - } - } - return { filteredIndices, groups: result }; - }, [threadIds, threadItems, query]); - - if (query && filteredIndices.length === 0) { - return ( -
      - No threads found -
      - ); - } - - if (!groups) { - return filteredIndices.map((index) => ( - - )); - } - - return groups.map((group) => ( - -
      - {group.label} -
      - {group.indices.map((index) => ( - - ))} -
      - )); -}; - -export const ThreadListNew = forwardRef< - HTMLButtonElement, - ComponentPropsWithoutRef & { labelClassName?: string } ->(({ className, labelClassName, children, ...props }, ref) => { - return ( - - - - ); -}); - -ThreadListNew.displayName = "ThreadListNew"; - -const ThreadListSkeleton: FC = () => { - return ( -
      - {Array.from({ length: 5 }, (_, i) => ( - - - - ))} -
      - ); -}; - -export const ThreadListItem: FC = () => { - const isRunning = useAuiState((s) => s.threadListItem.isRunning); - const [isRenaming, setIsRenaming] = useState(false); - const triggerRef = useRef(null); - const restoreFocusRef = useRef(false); - - useEffect(() => { - if (isRenaming || !restoreFocusRef.current) return; - restoreFocusRef.current = false; - triggerRef.current?.focus(); - }, [isRenaming]); - - return ( - - {isRenaming ? ( - { - restoreFocusRef.current = restoreFocus; - setIsRenaming(false); - }} - /> - ) : ( - - {isRunning && ( - - )} - - - - {isRunning && Running} - - )} - setIsRenaming(true)} /> - - ); -}; - -const ThreadListItemRename: FC<{ - onDone: (restoreFocus: boolean) => void; -}> = ({ onDone }) => { - const aui = useAui(); - const title = useAuiState((s) => s.threadListItem.title) ?? ""; - const [value, setValue] = useState(title); - const inputRef = useRef(null); - const settledRef = useRef(false); - - useEffect(() => { - inputRef.current?.select(); - }, []); - - const commit = (restoreFocus: boolean) => { - if (settledRef.current) return; - settledRef.current = true; - - const next = value.trim(); - if (!next || next === title) { - onDone(restoreFocus); - return; - } - - // Deferred so a synchronous throw lands on the rejection path too. - Promise.resolve() - .then(() => aui.threadListItem.rename(next)) - .then( - () => onDone(restoreFocus), - () => { - settledRef.current = false; - if (restoreFocus) inputRef.current?.focus(); - }, - ); - }; - - const cancel = () => { - if (settledRef.current) return; - settledRef.current = true; - onDone(true); - }; - - return ( - setValue(event.target.value)} - onBlur={() => commit(false)} - onKeyDown={(event) => { - if (event.key === "Enter") { - event.preventDefault(); - commit(true); - } else if (event.key === "Escape") { - event.preventDefault(); - cancel(); - } - }} - /> - ); -}; - -const ThreadListItemMore: FC<{ onRename: () => void }> = ({ onRename }) => { - return ( - - - - - - - - Rename - - - - - Archive - - - - - - Delete - - - - - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/thread.tsx b/demo/chat-ui/src/components/assistant-ui/thread.tsx deleted file mode 100644 index e19671f8..00000000 --- a/demo/chat-ui/src/components/assistant-ui/thread.tsx +++ /dev/null @@ -1,872 +0,0 @@ -"use client"; - -import { - ComposerAddAttachment, - ComposerAttachments, - UserMessageAttachments, -} from "@/components/assistant-ui/attachment"; -import { - Sources, - type Source, -} from "@/components/assistant-ui/elements/sources"; -import { File } from "@/components/assistant-ui/file"; -import { ThreadFollowupSuggestions } from "@/components/assistant-ui/follow-up-suggestions"; -import { Image } from "@/components/assistant-ui/image"; -import { MarkdownText } from "@/components/assistant-ui/markdown-text"; -import { - Reasoning, - ReasoningContent, - ReasoningRoot, - ReasoningText, - ReasoningTrigger, -} from "@/components/assistant-ui/reasoning"; -import { ToolFallback } from "@/components/assistant-ui/tool-fallback"; -import { - ToolGroupContent, - ToolGroupRoot, - ToolGroupTrigger, -} from "@/components/assistant-ui/tool-group"; -import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button"; -import { Button } from "@/components/ui/button"; -import { Skeleton } from "@/components/ui/skeleton"; -import { cn } from "@/lib/utils"; -import { - ActionBarMorePrimitive, - ActionBarPrimitive, - AuiIf, - BranchPickerPrimitive, - ComposerPrimitive, - groupPartByType, - MessagePrimitive, - SuggestionPrimitive, - ThreadPrimitive, - useAuiState, - useMessageTiming, - type AssistantState, - type FileMessagePartComponent, - type ImageMessagePartComponent, - type PartProviderMetadata, - type PartState, - type ToolCallMessagePartComponent, -} from "@assistant-ui/react"; -// `@assistant-ui/react` re-exports most hooks but not this one, so it comes from the core package -// the app already depends on directly. -import { ComposerDraft } from "@/components/assistant-ui/draft"; -import { Regenerate } from "@/components/assistant-ui/regenerate"; -import { ThreadMessageSearch } from "@/components/assistant-ui/search"; -import { MessageSpeaker } from "@/components/assistant-ui/speaker"; -import { DayDivider } from "@/components/elements/day-separator"; -import { ErrorState } from "@/components/elements/error-state"; -import { MessageTiming as MessageTimingStats } from "@/components/elements/message-timing"; -import { StoppedRun } from "@/components/elements/stopped-run"; -import { TypingIndicator } from "@/components/elements/typing-indicator"; -import { useActionBarReload } from "@assistant-ui/core/react"; -import { - ArrowDownIcon, - ArrowUpIcon, - CheckIcon, - ChevronLeftIcon, - ChevronRightIcon, - CopyIcon, - DownloadIcon, - MicIcon, - MoreHorizontalIcon, - PencilIcon, - SquareIcon, -} from "lucide-react"; -import { - createContext, - useContext, - useState, - type ComponentType, - type FC, - type PropsWithChildren, -} from "react"; - -export type ThreadGroupPart = MessagePrimitive.GroupedParts.GroupPart; - -/** - * Optional component overrides for the thread. `AssistantMessage` and - * `Welcome` replace whole sections; the remaining slots override how the - * assistant message renders tool calls and part groups. Tool UIs registered - * by name (toolkit `render`, `useAssistantDataUI`) take precedence over - * `ToolFallback`. - */ -export type ThreadComponents = { - AssistantMessage?: ComponentType; - Welcome?: ComponentType; - ToolFallback?: ToolCallMessagePartComponent; - ToolGroup?: ComponentType>; - ReasoningGroup?: ComponentType>; -}; - -export type ThreadProps = { - components?: ThreadComponents; -}; - -const EMPTY_COMPONENTS: ThreadComponents = {}; - -const ThreadComponentsContext = - createContext(EMPTY_COMPONENTS); - -// Startup exposes a loading placeholder thread; treat it as a new chat so -// the composer mounts centered. Loads after startup keep the docked layout. -const isNewChatView = (s: AssistantState) => - s.thread.messages.length === 0 && - (!s.thread.isLoading || s.threads.isLoading); - -// A switched thread that is still fetching its history: skeleton, not welcome. -const isHistoryLoadingView = (s: AssistantState) => - s.thread.messages.length === 0 && - s.thread.isLoading && - !s.thread.isDisabled && - !s.threads.isLoading; - -const ThreadHistorySkeleton: FC = () => ( - - Loading conversation - -
      - - - -
      - -
      - - -
      -
      -); - -export const Thread: FC = ({ components = EMPTY_COMPONENTS }) => { - const isEmpty = useAuiState(isNewChatView); - - return ( - - - - ); -}; - -const ThreadRoot: FC<{ isEmpty: boolean }> = ({ isEmpty }) => { - const { Welcome = ThreadWelcome } = useContext(ThreadComponentsContext); - - return ( - - -
      - - - - - - - -
      - - {() => } - -
      - - - - s.thread.messages.length > 0}> - - - - - - isNewChatView(s) && s.composer.isEmpty}> - - - -
      -
      -
      - ); -}; - -/** The local calendar day, as a value two dates on the same day always share. */ -const dayKey = (date: Date) => - `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`; - -/** "Today" and "Yesterday" beat a date nobody has to decode; older days get the date. */ -function dayLabel(date: Date): string { - const today = new Date(); - const yesterday = new Date(today); - yesterday.setDate(today.getDate() - 1); - - if (dayKey(date) === dayKey(today)) return "Today"; - if (dayKey(date) === dayKey(yesterday)) return "Yesterday"; - - return date.toLocaleDateString(undefined, { - month: "short", - day: "numeric", - // A year is noise until the conversation actually spans one. - ...(date.getFullYear() === today.getFullYear() ? {} : { year: "numeric" }), - }); -} - -/** - * The label for a rule above this message, or `null` when it continues the day above it. - * - * The selector returns a string rather than the message it derived it from, so a re-render with an - * unchanged day is not a state change and does not repaint the thread. - */ -const useDayBreak = () => - useAuiState((s) => { - // `s.message.index` rather than a search through `s.thread.messages`: this selector re-runs on - // every store update, and streaming updates the store per chunk, so a scan here would cost the - // whole thread on every frame of every answer. - const previous = s.thread.messages[s.message.index - 1]; - const day = dayKey(s.message.createdAt); - - if (previous && dayKey(previous.createdAt) === day) return null; - - return dayLabel(s.message.createdAt); - }); - -const ThreadMessage: FC = () => { - const { AssistantMessage: AssistantMessageComponent = AssistantMessage } = - useContext(ThreadComponentsContext); - const role = useAuiState((s) => s.message.role); - const isEditing = useAuiState((s) => s.message.composer.isEditing); - const dayBreak = useDayBreak(); - - let message = ; - if (isEditing) { - message = ; - } else if (role === "user") { - message = ; - } - - if (!dayBreak) return message; - - return ( - <> - - {message} - - ); -}; - -const ThreadScrollToBottom: FC = () => { - return ( - - - - - - ); -}; - -const ThreadWelcome: FC = () => { - return ( -
      -

      - How can I help you today? -

      -
      - ); -}; - -const ThreadSuggestions: FC = () => { - return ( -
      - - {() => } - -
      - ); -}; - -const ThreadSuggestionItem: FC = () => { - return ( -
      - - - -
      - ); -}; - -const Composer: FC = () => { - return ( - - -
      - - - -
      -
      -
      - ); -}; - -const ComposerAction: FC = () => { - return ( -
      - -
      - s.thread.capabilities.dictation}> - s.composer.dictation == null}> - - - - - - - s.composer.dictation != null}> - - - - - - - - !s.thread.isRunning}> - - - - - - - s.thread.isRunning}> - - - - -
      -
      - ); -}; - -/** How this message ended, or `undefined` while it is still running or is the caller's own. */ -const useAssistantStatus = () => - useAuiState((s) => - s.message.role === "assistant" ? s.message.status : undefined, - ); - -/** The error a run carries is `unknown`, and only a string of it can go on screen. */ -function errorDetail(error: unknown): string { - if (error === undefined || error === null) return "The run did not finish."; - if (typeof error === "string") return error; - if (error instanceof Error) return error.message; - - try { - return JSON.stringify(error); - } catch { - if ( - typeof error === "object" && - error !== null && - "message" in error && - typeof error.message === "string" - ) { - return error.message; - } - return "The run did not finish."; - } -} - -const MessageError: FC = () => { - const status = useAssistantStatus(); - const { disabled, reload } = useActionBarReload(); - const [retrying, setRetrying] = useState(false); - - if (status?.type !== "incomplete" || status.reason !== "error") return null; - - return ( - { - if (disabled) return; - setRetrying(true); - reload(); - }} - /> - ); -}; - -/** - * The marker under an answer the caller stopped. - * - * Without it a cancelled turn just ends mid-sentence and reads as a crash. `words` is empty on - * purpose — the partial answer is already drawn above by the message parts, and passing it again - * would print it twice. What is left of that paragraph is the caret, which marks the cut. - */ -const StoppedRunNotice: FC = () => { - const status = useAssistantStatus(); - const { disabled, reload } = useActionBarReload(); - const [discarded, setDiscarded] = useState(false); - - if (discarded) return null; - if (status?.type !== "incomplete" || status.reason !== "cancelled") return null; - - return ( - { - if (!disabled) reload(); - }} - onDiscard={() => setDiscarded(true)} - /> - ); -}; - -/** - * How long the turn took, under the answer. - * - * Reads `message.metadata.timing`, which nothing fills in by default — see `newTurnClock` in - * runtime/AgentCoreRuntime.ts, which is what puts it there. - */ -const MessageTimingFooter: FC = () => { - const timing = useMessageTiming(); - if (timing?.totalStreamTime === undefined) return null; - - const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`; - - return ( - - ); -}; - -/** - * One provider-metadata bag, read defensively: the shape is ours by convention, not by type. - */ -function metadataString( - bag: PartProviderMetadata[string] | undefined, - key: string, -): string { - const value = bag?.[key]; - return typeof value === "string" ? value : ""; -} - -/** - * Turns one cited part into the card `Sources` draws. A `url` source gets its hostname, the - * closest thing a card grid built for web citations has to a "domain". A `document` source has no - * URL at all — a knowledge card's locator (`p.27`) says more than its media type ever could, so - * that leads, and the producer name (`knowledge`) is the fallback when a card has no locator. - */ -function sourceCardOf(part: Extract): Source { - if (part.sourceType === "url") { - // `title` is optional on the `url` variant of the wire type even though this app's own - // producer always sets it (see `foldSource`'s `title ?? id` fallback) — fall back the same - // way here so the type matches what is already true at runtime. - return { id: part.id, domain: new URL(part.url).hostname, title: part.title ?? part.id }; - } - - const agentcore = part.providerMetadata?.agentcore; - const locator = metadataString(agentcore, "locator"); - const origin = metadataString(agentcore, "origin"); - - return { id: part.id, domain: locator || origin, title: part.title }; -} - -/** - * `Sources` is a collection component — one "Sources N" toggle over a card grid — not a chip - * meant to repeat per citation. So this reads the whole message's parts once and draws one grid, - * instead of the switch below drawing one grid per part. - * - * Selects the parts array itself, not a filtered copy: `useAuiState` runs the selector inside - * `getSnapshot`, and a selector that allocates a new array every call never sees its result count - * as equal to the last, so it would re-render forever. Filtering happens after the selector - * returns, on a plain array. - */ -const MessageSources: FC = () => { - const parts = useAuiState((s) => s.message.parts); - const [open, setOpen] = useState(false); - - const sources = parts.filter( - (part): part is Extract => part.type === "source", - ); - - if (sources.length === 0) return null; - - return ( - - ); -}; - -const AssistantMessage: FC = () => { - const { - ToolFallback: ToolFallbackComponent = ToolFallback, - ToolGroup, - ReasoningGroup, - } = useContext(ThreadComponentsContext); - - const ACTION_BAR_PT = "pt-1.5"; - // Keep the action bar inside the contained root's paint box, then cancel its reserved space in flow. - const ACTION_BAR_HEIGHT = `min-h-7.5 ${ACTION_BAR_PT}`; - - return ( - -
      - - - {({ part, children }) => { - switch (part.type) { - case "group-chainOfThought": - return
      {children}
      ; - case "group-tool": - if (ToolGroup) { - return {children}; - } - return ( - - - {children} - - ); - case "group-reasoning": { - if (ReasoningGroup) { - return ( - {children} - ); - } - const running = part.status.type === "running"; - return ( - - - - {children} - - - ); - } - case "text": - return ; - case "reasoning": - return ; - case "tool-call": - return part.toolUI ?? ; - case "data": - return part.dataRendererUI; - case "file": - return ( -
      - -
      - ); - case "image": - return ( -
      - -
      - ); - case "source": - // Drawn collectively in `MessageSources`, below — the element is a collection - // (one grid, `sources: {domain,title}[]`). - return null; - case "indicator": - return ( - - ); - default: - return null; - } - }} -
      - - - - -
      - -
      - - -
      -
      - ); -}; - -const AssistantActionBar: FC = () => { - return ( - - - - s.message.isCopied}> - - - !s.message.isCopied}> - - - - - - - - - - - - - - - - Export as Markdown - - - - - - ); -}; - -const UserFilePart: FileMessagePartComponent = (part) => ( -
      - -
      -); - -const UserImagePart: ImageMessagePartComponent = (part) => ( -
      - -
      -); - -const UserMessage: FC = () => { - return ( - - - -
      -
      - -
      -
      - -
      -
      - - -
      - ); -}; - -const UserActionBar: FC = () => { - return ( - - - - - - - - ); -}; - -const EditComposer: FC = () => { - return ( - - - -
      - - - - - - -
      -
      -
      - ); -}; - -const BranchPicker: FC = ({ - className, - ...rest -}) => { - return ( - - - - - - - - / - - - - - - - - ); -}; diff --git a/demo/chat-ui/src/components/assistant-ui/threadlist-sidebar.tsx b/demo/chat-ui/src/components/assistant-ui/threadlist-sidebar.tsx deleted file mode 100644 index 3c431381..00000000 --- a/demo/chat-ui/src/components/assistant-ui/threadlist-sidebar.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import type * as React from "react"; -import { MessagesSquare } from "lucide-react"; -import { GitHubIcon } from "@/components/icons/github"; -import { - Sidebar, - SidebarContent, - SidebarFooter, - SidebarHeader, - SidebarMenu, - SidebarMenuButton, - SidebarMenuItem, - SidebarRail, -} from "@/components/ui/sidebar"; -import { ThreadList } from "@/components/assistant-ui/thread-list"; - -export function ThreadListSidebar({ - ...props -}: React.ComponentProps) { - return ( - - - - - - - - - - - - - -
      - -
      -
      - - GitHub - - View Source -
      -
      -
      -
      -
      -
      -
      - ); -} diff --git a/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx b/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx deleted file mode 100644 index f62b4d98..00000000 --- a/demo/chat-ui/src/components/assistant-ui/tool-fallback.tsx +++ /dev/null @@ -1,620 +0,0 @@ -"use client"; - -import { memo, useState } from "react"; -import { - AlertCircleIcon, - CheckIcon, - ChevronDownIcon, - LoaderIcon, - XCircleIcon, -} from "lucide-react"; -import { - useToolCallElapsed, - type ToolApprovalOption, - type ToolCallMessagePart, - type ToolCallMessagePartProps, - type ToolCallMessagePartStatus, - type ToolCallMessagePartComponent, -} from "@assistant-ui/react"; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@/components/ui/collapsible"; -import { cn } from "@/lib/utils"; -import { Button } from "@/components/ui/button"; -import { ToolError } from "@/components/elements/tool-error"; -import { useActionBarReload } from "@assistant-ui/core/react"; -import { useControlledOpen } from "./use-collapsible-open"; - -const ANIMATION_DURATION = 200; - -const pressable = "active:scale-[0.98]"; - -export type ToolFallbackRootProps = Omit< - React.ComponentProps, - "open" | "onOpenChange" -> & { - open?: boolean; - onOpenChange?: (open: boolean) => void; - defaultOpen?: boolean; -}; - -function ToolFallbackRoot({ - className, - open: controlledOpen, - onOpenChange: controlledOnOpenChange, - defaultOpen = false, - children, - ...props -}: ToolFallbackRootProps) { - const { ref: collapsibleRef, isOpen, handleOpenChange } = useControlledOpen({ - open: controlledOpen, - onOpenChange: controlledOnOpenChange, - defaultOpen, - lockDurationMs: ANIMATION_DURATION, - }); - - return ( - - {children} - - ); -} - -type ToolStatus = ToolCallMessagePartStatus["type"]; - -const statusIconMap: Record = { - running: LoaderIcon, - complete: CheckIcon, - incomplete: XCircleIcon, - "requires-action": AlertCircleIcon, -}; - -const formatToolDuration = (ms: number) => { - if (ms < 1000) return "<1s"; - const seconds = ms / 1000; - if (seconds < 10) return `${(Math.floor(seconds * 10) / 10).toFixed(1)}s`; - if (seconds < 60) return `${Math.floor(seconds)}s`; - return `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`; -}; - -function ToolFallbackDuration({ - className, - ...props -}: React.ComponentProps<"span">) { - const elapsedMs = useToolCallElapsed(); - if (elapsedMs === undefined) return null; - - return ( - - {formatToolDuration(elapsedMs)} - - ); -} - -function ToolFallbackTrigger({ - toolName, - status, - className, - ...props -}: React.ComponentProps & { - toolName: string; - status?: ToolCallMessagePartStatus; -}) { - const statusType = status?.type ?? "complete"; - const isRunning = statusType === "running"; - const isCancelled = - status?.type === "incomplete" && status.reason === "cancelled"; - - const Icon = statusIconMap[statusType]; - const label = isCancelled ? "Cancelled tool" : "Used tool"; - - return ( - - - - - {label}: {toolName} - - {isRunning && ( - - {label}: {toolName} - - )} - - - - - ); -} - -function ToolFallbackContent({ - className, - children, - ...props -}: React.ComponentProps) { - return ( - -
      - {children} -
      -
      - ); -} - -function ToolFallbackArgs({ - argsText, - className, - ...props -}: React.ComponentProps<"div"> & { - argsText?: string; -}) { - if (!argsText) return null; - - return ( -
      -
      -        {argsText}
      -      
      -
      - ); -} - -function ToolFallbackResult({ - result, - className, - ...props -}: React.ComponentProps<"div"> & { - result?: unknown; -}) { - if (result === undefined) return null; - - return ( -
      -

      - Result: -

      -
      -        {typeof result === "string" ? result : JSON.stringify(result, null, 2)}
      -      
      -
      - ); -} - -function ToolFallbackError({ - status, - toolName, - className, - ...props -}: React.ComponentProps<"div"> & { - status?: ToolCallMessagePartStatus; - toolName?: string; -}) { - const { disabled, reload } = useActionBarReload(); - - if (status?.type !== "incomplete") return null; - - const error = status.error; - let errorText: string | null = null; - if (error) { - errorText = typeof error === "string" ? error : JSON.stringify(error); - } - - if (!errorText) return null; - - const isCancelled = status.reason === "cancelled"; - - // A cancelled tool is not a failure, and dressing it as one — red, with a retry — would tell the - // caller something broke when what actually happened is that they stopped it. - if (isCancelled) { - return ( -
      -

      - Cancelled reason: -

      -

      - {errorText} -

      -
      - ); - } - - return ( - - ); -} - -const APPROVED_RESULT = "Approved by user"; -const DENIED_RESULT = "User denied tool execution"; - -const APPROVAL_OPTION_DEFAULT_LABELS: Record = { - "allow-once": "Allow", - "allow-always": "Always allow", - "reject-once": "Deny", - "reject-always": "Always deny", -}; - -const isAllowKind = (kind: string) => - kind === "allow-once" || kind === "allow-always"; - -const approvalOptionLabel = (option: ToolApprovalOption) => - option.label ?? - (Object.hasOwn(APPROVAL_OPTION_DEFAULT_LABELS, option.kind) - ? APPROVAL_OPTION_DEFAULT_LABELS[option.kind] - : undefined) ?? - option.id; - -function ToolFallbackApproval({ - className, - addResult, - resume, - interrupt, - approval, - respondToApproval, - ...props -}: React.ComponentProps<"div"> & - Partial< - Pick - > & { - interrupt?: ToolCallMessagePart["interrupt"]; - approval?: ToolCallMessagePart["approval"]; - }) { - const [submitted, setSubmitted] = useState(false); - const [confirmingId, setConfirmingId] = useState(null); - - if ( - approval != null && - (approval.approved !== undefined || approval.resolution !== undefined) - ) - return null; - - // Custom (`_`-prefixed) kinds cannot be resolved to a boolean by the kit; - // hosts using custom kinds render their own bar. A declared option list is - // a host constraint: the kit never adds an approval path beyond it, but - // always preserves a refusal path. - const declaredOptions = respondToApproval ? approval?.options : undefined; - const options = declaredOptions?.filter((o) => - Object.hasOwn(APPROVAL_OPTION_DEFAULT_LABELS, o.kind), - ); - - const respond = (approved: boolean) => { - if (submitted) return; - if ( - approval != null && - approval.approved === undefined && - respondToApproval - ) { - respondToApproval({ approved }); - } else if (interrupt) { - resume?.({ approved }); - } else { - addResult?.(approved ? APPROVED_RESULT : DENIED_RESULT); - } - setSubmitted(true); - }; - - const respondWithOption = (option: ToolApprovalOption) => { - if (submitted) return; - respondToApproval?.({ optionId: option.id }); - setSubmitted(true); - setConfirmingId(null); - }; - - const handleOption = (option: ToolApprovalOption) => { - if (option.confirm) { - setConfirmingId(option.id); - } else { - respondWithOption(option); - } - }; - - const confirming = - confirmingId != null - ? options?.find((o) => o.id === confirmingId) - : undefined; - - if (confirming) { - const confirmMeta = - typeof confirming.confirm === "object" ? confirming.confirm : undefined; - const confirmDescription = - confirmMeta?.description ?? confirming.description; - return ( -
      -

      - {confirmMeta?.title ?? `${approvalOptionLabel(confirming)}?`} -

      - {confirmDescription && ( -

      - {confirmDescription} -

      - )} - {confirming.grants && confirming.grants.length > 0 && ( -
        - {confirming.grants.map((grant) => ( -
      • - - {grant} - -
      • - ))} -
      - )} -
      - - -
      -
      - ); - } - - if (declaredOptions && declaredOptions.length > 0) { - const allowOptions = options?.filter((o) => isAllowKind(o.kind)) ?? []; - const rejectOptions = options?.filter((o) => !isAllowKind(o.kind)) ?? []; - return ( -
      - {[...allowOptions, ...rejectOptions].map((option) => ( - - ))} - {rejectOptions.length === 0 && ( - - )} -
      - ); - } - - return ( -
      - - -
      - ); -} - -const ToolFallbackImpl: ToolCallMessagePartComponent = ({ - toolName, - argsText, - result, - status, - addResult, - resume, - interrupt, - approval, - respondToApproval, -}) => { - const isCancelled = - status?.type === "incomplete" && status.reason === "cancelled"; - const isRequiresAction = status?.type === "requires-action"; - - const [open, setOpen] = useState(isRequiresAction); - const [prevRequiresAction, setPrevRequiresAction] = - useState(isRequiresAction); - if (isRequiresAction !== prevRequiresAction) { - setPrevRequiresAction(isRequiresAction); - if (isRequiresAction) setOpen(true); - } - - return ( - - - - - - {isRequiresAction && ( - - )} - {!isCancelled && } - - - ); -}; - -const ToolFallback = memo( - ToolFallbackImpl, -) as unknown as ToolCallMessagePartComponent & { - Root: typeof ToolFallbackRoot; - Trigger: typeof ToolFallbackTrigger; - Content: typeof ToolFallbackContent; - Args: typeof ToolFallbackArgs; - Result: typeof ToolFallbackResult; - Error: typeof ToolFallbackError; - Approval: typeof ToolFallbackApproval; -}; - -ToolFallback.displayName = "ToolFallback"; -ToolFallback.Root = ToolFallbackRoot; -ToolFallback.Trigger = ToolFallbackTrigger; -ToolFallback.Content = ToolFallbackContent; -ToolFallback.Args = ToolFallbackArgs; -ToolFallback.Result = ToolFallbackResult; -ToolFallback.Error = ToolFallbackError; -ToolFallback.Approval = ToolFallbackApproval; - -export { - ToolFallback, - ToolFallbackRoot, - ToolFallbackTrigger, - ToolFallbackContent, - ToolFallbackArgs, - ToolFallbackResult, - ToolFallbackError, - ToolFallbackApproval, -}; diff --git a/demo/chat-ui/src/components/assistant-ui/tool-group.tsx b/demo/chat-ui/src/components/assistant-ui/tool-group.tsx deleted file mode 100644 index 5db73166..00000000 --- a/demo/chat-ui/src/components/assistant-ui/tool-group.tsx +++ /dev/null @@ -1,221 +0,0 @@ -"use client"; - -import { memo, type FC, type PropsWithChildren } from "react"; -import { ChevronDownIcon, LoaderIcon } from "lucide-react"; -import { cva, type VariantProps } from "class-variance-authority"; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@/components/ui/collapsible"; -import { cn } from "@/lib/utils"; -import { useControlledOpen } from "./use-collapsible-open"; - -const ANIMATION_DURATION = 200; - -const toolGroupVariants = cva("aui-tool-group-root group/tool-group w-full", { - variants: { - variant: { - outline: "rounded-lg border py-3", - ghost: "", - muted: "border-muted-foreground/30 bg-muted/30 rounded-lg border py-3", - }, - }, - defaultVariants: { variant: "outline" }, -}); - -export type ToolGroupRootProps = Omit< - React.ComponentProps, - "open" | "onOpenChange" -> & - VariantProps & { - open?: boolean; - onOpenChange?: (open: boolean) => void; - defaultOpen?: boolean; - }; - -function ToolGroupRoot({ - className, - variant, - open: controlledOpen, - onOpenChange: controlledOnOpenChange, - defaultOpen = false, - children, - ...props -}: ToolGroupRootProps) { - const { ref: collapsibleRef, isOpen, handleOpenChange } = useControlledOpen({ - open: controlledOpen, - onOpenChange: controlledOnOpenChange, - defaultOpen, - lockDurationMs: ANIMATION_DURATION, - }); - - return ( - - {children} - - ); -} - -function ToolGroupTrigger({ - count, - active = false, - className, - ...props -}: React.ComponentProps & { - count: number; - active?: boolean; -}) { - const label = `${count} tool ${count === 1 ? "call" : "calls"}`; - - return ( - - {active && ( - - )} - - {label} - {active && ( - - {label} - - )} - - - - ); -} - -function ToolGroupContent({ - className, - children, - ...props -}: React.ComponentProps) { - return ( - -
      *]:animate-in [&>*]:fade-in-0 [&>*]:blur-in-[2px] [&>*]:slide-in-from-top-1 [&>*]:duration-(--animation-duration) [&>*]:ease-[cubic-bezier(0.32,0.72,0,1)]", - "[&>*]:motion-reduce:animate-none", - "[&>*:nth-child(2)]:[animation-delay:40ms]", - "[&>*:nth-child(3)]:[animation-delay:80ms]", - "[&>*:nth-child(4)]:[animation-delay:120ms]", - "[&>*:nth-child(n+5)]:[animation-delay:160ms]", - )} - > - {children} -
      -
      - ); -} - -type ToolGroupComponent = FC< - PropsWithChildren<{ startIndex: number; endIndex: number }> -> & { - Root: typeof ToolGroupRoot; - Trigger: typeof ToolGroupTrigger; - Content: typeof ToolGroupContent; -}; - -const ToolGroupImpl: FC< - PropsWithChildren<{ startIndex: number; endIndex: number }> -> = ({ children, startIndex, endIndex }) => { - const toolCount = endIndex - startIndex + 1; - - return ( - - - {children} - - ); -}; - -/** - * @deprecated This wrapper targets the legacy `components.ToolGroup` prop - * on ``. Use `` with - * a `groupBy` returning `"group-tool"` and compose `ToolGroupRoot` / - * `ToolGroupTrigger` / `ToolGroupContent` directly. See `thread.tsx`. - */ -const ToolGroup = memo(ToolGroupImpl) as unknown as ToolGroupComponent; - -ToolGroup.displayName = "ToolGroup"; -ToolGroup.Root = ToolGroupRoot; -ToolGroup.Trigger = ToolGroupTrigger; -ToolGroup.Content = ToolGroupContent; - -export { - ToolGroup, - ToolGroupRoot, - ToolGroupTrigger, - ToolGroupContent, - toolGroupVariants, -}; diff --git a/demo/chat-ui/src/components/assistant-ui/tooltip-icon-button.tsx b/demo/chat-ui/src/components/assistant-ui/tooltip-icon-button.tsx deleted file mode 100644 index 476c5ed1..00000000 --- a/demo/chat-ui/src/components/assistant-ui/tooltip-icon-button.tsx +++ /dev/null @@ -1,48 +0,0 @@ -"use client"; - -import { type ComponentPropsWithRef, forwardRef } from "react"; -import { Slot } from "radix-ui"; - -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { Button } from "@/components/ui/button"; -import { cn } from "@/lib/utils"; - -export type TooltipIconButtonProps = ComponentPropsWithRef & { - tooltip: string; - side?: "top" | "bottom" | "left" | "right"; -}; - -export const TooltipIconButton = forwardRef< - HTMLButtonElement, - TooltipIconButtonProps ->(({ children, tooltip, side = "bottom", className, ...rest }, ref) => { - return ( - - - - - - {tooltip} - - - ); -}); - -TooltipIconButton.displayName = "TooltipIconButton"; diff --git a/demo/chat-ui/src/components/assistant-ui/use-collapsible-open.ts b/demo/chat-ui/src/components/assistant-ui/use-collapsible-open.ts deleted file mode 100644 index 757d8cf2..00000000 --- a/demo/chat-ui/src/components/assistant-ui/use-collapsible-open.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { useCallback, useRef, useState } from "react"; -import { useScrollLock } from "@assistant-ui/react"; - -type ControlledOpen = { - open?: boolean; - onOpenChange?: (open: boolean) => void; - defaultOpen?: boolean; - lockDurationMs: number; -}; - -/** - * One Collapsible's open state, shared by ToolGroupRoot and ToolFallbackRoot. - * A single hook keeps the controlled/uncontrolled split and the scroll lock in - * lockstep; two copies already drifted once. - */ -export function useControlledOpen({ - open: controlledOpen, - onOpenChange, - defaultOpen = false, - lockDurationMs, -}: ControlledOpen) { - const ref = useRef(null); - const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen); - const lockScroll = useScrollLock(ref, lockDurationMs); - - const isControlled = controlledOpen !== undefined; - const isOpen = isControlled ? controlledOpen : uncontrolledOpen; - - const handleOpenChange = useCallback( - (open: boolean) => { - lockScroll(); - if (!isControlled) { - setUncontrolledOpen(open); - } - onOpenChange?.(open); - }, - [lockScroll, isControlled, onOpenChange], - ); - - return { ref, isOpen, handleOpenChange }; -} diff --git a/demo/chat-ui/src/components/elements/agent-status.tsx b/demo/chat-ui/src/components/elements/agent-status.tsx deleted file mode 100644 index 76e892ca..00000000 --- a/demo/chat-ui/src/components/elements/agent-status.tsx +++ /dev/null @@ -1,86 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { CheckIcon, PauseIcon, RotateCcwIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { ghostButton, mono, paper } from "./surfaces"; - -export type AgentState = "working" | "waiting" | "done"; - -export interface StatusStep { - state: AgentState; - label: string; -} - -export function AgentStatus({ - state, - label, - elapsed, - onAct, - className, - ...props -}: Omit< - ComponentProps<"div">, - "children" | "state" | "label" | "elapsed" | "onAct" -> & { - state: AgentState; - label: string; - elapsed?: string; - /** Stops the run while working, and runs it again once done. */ - onAct?: () => void; -}) { - return ( -
      - {state === "done" ? ( - - ) : ( - - )} - - {label} - - {elapsed !== undefined && state !== "done" && ( - - {elapsed} - - )} - {/* The shipped element renders this button with no handler at all — a control labelled - "Pause agent" that cannot pause anything. `onAct` is added here so it does what it says, - and the button is dropped entirely when the caller gives it nothing to do. */} - {onAct && ( - - )} -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/conversation-search.tsx b/demo/chat-ui/src/components/elements/conversation-search.tsx deleted file mode 100644 index 447bc062..00000000 --- a/demo/chat-ui/src/components/elements/conversation-search.tsx +++ /dev/null @@ -1,116 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { ChevronDownIcon, ChevronUpIcon, SearchIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { field, ghostButton, mono, paper } from "./surfaces"; - -export interface SearchHit { - id: string; - before: string; - match: string; - after: string; - position: number; -} - -export function ConversationSearch({ - query, - hits, - activeIndex, - onQueryChange, - onStep, - className, - ...props -}: Omit< - ComponentProps<"div">, - "children" | "query" | "hits" | "activeIndex" | "onQueryChange" | "onStep" -> & { - query: string; - hits: readonly SearchHit[]; - activeIndex: number; - onQueryChange?: (query: string) => void; - onStep?: (delta: number) => void; -}) { - const index = - hits.length === 0 - ? -1 - : Math.min(Math.max(activeIndex, 0), hits.length - 1); - const active = index === -1 ? undefined : hits[index]; - - return ( -
      -
      -
      - - onQueryChange?.(event.target.value)} - placeholder="Find in conversation" - aria-label="Find in conversation" - className="text-foreground/85 placeholder:text-foreground/30 min-w-0 flex-1 bg-transparent text-[13px] outline-none" - /> - - {hits.length === 0 ? "0" : `${index + 1}/${hits.length}`} - - - -
      - - {active && ( -
      - {active.before} - - {active.match} - - {active.after} -
      - )} -
      - -
      - {hits.map((hit, i) => ( - - ))} -
      -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/day-separator.tsx b/demo/chat-ui/src/components/elements/day-separator.tsx deleted file mode 100644 index 094ea593..00000000 --- a/demo/chat-ui/src/components/elements/day-separator.tsx +++ /dev/null @@ -1,101 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { cn } from "@/lib/utils"; -import { mono } from "./surfaces"; - -export interface DatedMessage { - id: string; - day: string; - time: string; - role: "user" | "assistant"; - text: string; -} - -/** - * The dated rule on its own, for a thread that already draws its own messages. - * - * `DaySeparator` below renders a whole conversation — bubbles, text and all — which suits the - * gallery demo but not a `ThreadPrimitive.Messages` list, where assistant-ui owns the messages. - * This is the same rule markup, liftable to sit above one message. - */ -export function DayDivider({ - day, - className, - ...props -}: Omit, "children"> & { day: string }) { - return ( -
      - - {day} - -
      - ); -} - -export function DaySeparator({ - messages, - className, - ...props -}: Omit, "children" | "messages"> & { - messages: readonly DatedMessage[]; -}) { - let lastDay = ""; - - return ( -
      - {messages.map((message) => { - const newDay = message.day !== lastDay; - lastDay = message.day; - - return ( -
      - {newDay && ( -
      - - - {message.day} - - -
      - )} -
      - - {message.text} - - - {message.time} - -
      -
      - ); - })} -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/draft-restore.tsx b/demo/chat-ui/src/components/elements/draft-restore.tsx deleted file mode 100644 index 5f5db3ec..00000000 --- a/demo/chat-ui/src/components/elements/draft-restore.tsx +++ /dev/null @@ -1,59 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { PencilLineIcon, XIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { ghostButton, mono, paper } from "./surfaces"; - -export function DraftRestore({ - draft, - savedAt, - onRestore, - onDiscard, - className, - ...props -}: Omit< - ComponentProps<"div">, - "children" | "draft" | "savedAt" | "onRestore" | "onDiscard" -> & { - draft: string; - savedAt: string; - onRestore?: () => void; - onDiscard?: () => void; -}) { - return ( -
      - -
      - {draft} - - unsent draft · {savedAt} - -
      - - -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/error-state.tsx b/demo/chat-ui/src/components/elements/error-state.tsx deleted file mode 100644 index 33c64471..00000000 --- a/demo/chat-ui/src/components/elements/error-state.tsx +++ /dev/null @@ -1,75 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { CircleAlertIcon, RefreshCwIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { ShimmerLabel } from "./surfaces"; - -export interface ErrorStateProps extends Readonly< - Omit, "children" | "role"> -> { - readonly title: string; - readonly detail: string; - readonly retrying: boolean; - readonly onRetry: () => void; -} - -export function ErrorState({ - title, - detail, - retrying, - onRetry, - className, - ...props -}: ErrorStateProps) { - if (retrying) { - return ( -
      - - - Retrying - -
      - ); - } - - return ( -
      - -
      -

      {title}

      -

      - {detail} -

      -
      - -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/launcher-bubble.tsx b/demo/chat-ui/src/components/elements/launcher-bubble.tsx deleted file mode 100644 index 9c43b868..00000000 --- a/demo/chat-ui/src/components/elements/launcher-bubble.tsx +++ /dev/null @@ -1,128 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { MessageCircleIcon, XIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { field, floating, inkButton, mono } from "./surfaces"; - -export function LauncherBubble({ - open, - unread, - greeting, - prompts, - onToggle, - onPick, - onStart, - className, - ...props -}: Omit< - ComponentProps<"div">, - | "children" - | "open" - | "unread" - | "greeting" - | "prompts" - | "onToggle" - | "onPick" - | "onStart" -> & { - open: boolean; - unread: number; - greeting: string; - prompts: readonly string[]; - onToggle?: () => void; - onPick?: (prompt: string) => void; - onStart?: () => void; -}) { - return ( -
      - {open && ( -
      -
      - {greeting} - - typically replies in a minute - -
      - -
      - {prompts.map((prompt) => ( - - ))} -
      - - -
      - )} - - -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/message-timing.tsx b/demo/chat-ui/src/components/elements/message-timing.tsx deleted file mode 100644 index 1b0b7f17..00000000 --- a/demo/chat-ui/src/components/elements/message-timing.tsx +++ /dev/null @@ -1,49 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { cn } from "@/lib/utils"; -import { mono } from "./surfaces"; - -export interface TimingStat { - label: string; - value: string; -} - -export function MessageTiming({ - stats, - streaming, - className, - ...props -}: Omit, "children" | "stats" | "streaming"> & { - stats: readonly TimingStat[]; - streaming?: boolean; -}) { - return ( -
      - {stats.map((stat) => ( - - {stat.label} - - {stat.value} - - - ))} -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/regenerate-menu.tsx b/demo/chat-ui/src/components/elements/regenerate-menu.tsx deleted file mode 100644 index 4ba84927..00000000 --- a/demo/chat-ui/src/components/elements/regenerate-menu.tsx +++ /dev/null @@ -1,79 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { RefreshCwIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { floating, ghostButton, mono } from "./surfaces"; - -export interface RegenerateOption { - id: string; - label: string; - detail: string; -} - -export function RegenerateMenu({ - options, - open, - currentId, - onOpenChange, - onPick, - className, - ...props -}: Omit< - ComponentProps<"div">, - "children" | "options" | "open" | "currentId" | "onOpenChange" | "onPick" -> & { - options: readonly RegenerateOption[]; - open: boolean; - currentId: string; - onOpenChange?: (open: boolean) => void; - onPick?: (id: string) => void; -}) { - return ( -
      - - - {open && ( -
      - {options.map((option) => ( - - ))} -
      - )} -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/stopped-run.tsx b/demo/chat-ui/src/components/elements/stopped-run.tsx deleted file mode 100644 index 8d9eefc9..00000000 --- a/demo/chat-ui/src/components/elements/stopped-run.tsx +++ /dev/null @@ -1,72 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { ArrowRightIcon, SquareIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { field, mono } from "./surfaces"; - -export function StoppedRun({ - words, - reason, - onContinue, - onDiscard, - className, - ...props -}: Omit< - ComponentProps<"div">, - "children" | "words" | "reason" | "onContinue" | "onDiscard" -> & { - words: readonly string[]; - reason: string; - onContinue?: () => void; - onDiscard?: () => void; -}) { - return ( -
      -

      - {words.join(" ")} - -

      - -
      - - - {reason} - - - - -
      -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/surfaces.tsx b/demo/chat-ui/src/components/elements/surfaces.tsx deleted file mode 100644 index 508b77f4..00000000 --- a/demo/chat-ui/src/components/elements/surfaces.tsx +++ /dev/null @@ -1,120 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { useLayoutEffect, useRef, useState } from "react"; -import { cn } from "@/lib/utils"; - -export const paper = "bg-background border border-border/60 dark:bg-popover"; - -export const floating = "bg-background border border-border/60 dark:bg-popover"; - -export const field = "bg-foreground/[0.04] dark:bg-foreground/[0.06]"; - -export const fieldInteractive = - "bg-foreground/[0.04] transition-colors hover:bg-foreground/[0.07] dark:bg-foreground/[0.06] dark:hover:bg-foreground/[0.09]"; - -export const pressable = - "transition-transform duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] active:scale-[0.96] motion-reduce:transition-none"; - -export const ghostButton = - "flex items-center justify-center rounded-full text-foreground/45 outline-none transition-[background-color,color,scale] duration-150 hover:bg-foreground/[0.06] hover:text-foreground/90 active:scale-[0.96] focus-visible:ring-1 focus-visible:ring-foreground/20 motion-reduce:transition-none dark:hover:bg-foreground/[0.09]"; - -export const inkButton = - "bg-foreground text-background transition-[opacity,scale] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] hover:opacity-90 active:scale-[0.96] motion-reduce:transition-none"; - -export const iconSwap = - "[grid-area:1/1] transition-[opacity,scale,filter] duration-200 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none"; - -export const iconSwapIn = "scale-100 opacity-100 blur-none"; - -export const iconSwapOut = "scale-[0.25] opacity-0 blur-[4px]"; - -export const labelSwap = - "col-start-1 row-start-1 flex w-max items-center gap-1.5 leading-none transition-[opacity,filter] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none"; - -export const labelSwapIn = "opacity-100 blur-none"; - -export const labelSwapOut = - "pointer-events-none select-none opacity-0 blur-[2px]"; - -export const collapsePanel = - "h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] data-[ending-style]:h-0 data-[starting-style]:h-0 motion-reduce:transition-none"; - -export const live = "text-blue-500 dark:text-blue-400"; - -export const mono = "font-mono text-[11px] tracking-tight"; - -export function ShimmerLabel({ - active = true, - className, - ...props -}: ComponentProps<"span"> & { active?: boolean }) { - return ( - - ); -} - -/** - * Scroll region for content that keeps its own whitespace. `whitespace-pre` in - * a bounded box clips a long line with no way to reach it, so the rows scroll - * instead. - * - * `codeSurface` wraps all the rows as one block, and the rows are its children. - * It cannot go on each row: `min-width: 100%` resolves against the scroll - * container's visible width rather than its scroll width, so a per-row width - * leaves every row except the longest ending its background at the fold. - */ -export const codeScroll = "overflow-x-auto"; - -export const codeSurface = "w-max min-w-full"; - -export function SwapLabel({ - active, - children, - className, -}: { - readonly active: 0 | 1; - readonly children: [React.ReactNode, React.ReactNode]; - readonly className?: string; -}) { - const layers = [useRef(null), useRef(null)]; - const [width, setWidth] = useState(null); - - useLayoutEffect(() => { - const target = layers[active]?.current; - if (!target) return undefined; - const measure = () => - setWidth(Math.ceil(target.getBoundingClientRect().width)); - measure(); - const observer = new ResizeObserver(measure); - observer.observe(target); - return () => observer.disconnect(); - }, [active]); - - return ( - - {children.map((layer, index) => ( - - {layer} - - ))} - - ); -} diff --git a/demo/chat-ui/src/components/elements/thinking-indicator.tsx b/demo/chat-ui/src/components/elements/thinking-indicator.tsx deleted file mode 100644 index 29e19ea5..00000000 --- a/demo/chat-ui/src/components/elements/thinking-indicator.tsx +++ /dev/null @@ -1,43 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { cn } from "@/lib/utils"; -import { mono, ShimmerLabel } from "./surfaces"; - -export function ThinkingIndicator({ - label, - elapsed, - className, - ...props -}: Omit, "children" | "label" | "elapsed"> & { - label: string; - elapsed?: string; -}) { - return ( -
      - - - {label} - - {elapsed !== undefined && ( - - {elapsed} - - )} -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/tool-error.tsx b/demo/chat-ui/src/components/elements/tool-error.tsx deleted file mode 100644 index eb926a56..00000000 --- a/demo/chat-ui/src/components/elements/tool-error.tsx +++ /dev/null @@ -1,96 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { AlertCircleIcon, Loader2Icon, RotateCwIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { field, mono, paper } from "./surfaces"; - -export function ToolError({ - name, - target, - message, - attempt, - maxAttempts, - retrying, - onRetry, - onSkip, - className, - ...props -}: Omit< - ComponentProps<"div">, - | "children" - | "name" - | "target" - | "message" - | "attempt" - | "maxAttempts" - | "retrying" - | "onRetry" - | "onSkip" -> & { - name: string; - target: string; - message: string; - attempt: number; - maxAttempts: number; - retrying: boolean; - onRetry?: () => void; - onSkip?: () => void; -}) { - return ( -
      -
      - - {name} - - {target} - - - {attempt}/{maxAttempts} - -
      - -
      - {message} -
      - -
      - - -
      -
      - ); -} diff --git a/demo/chat-ui/src/components/elements/typing-indicator.tsx b/demo/chat-ui/src/components/elements/typing-indicator.tsx deleted file mode 100644 index 38346d3d..00000000 --- a/demo/chat-ui/src/components/elements/typing-indicator.tsx +++ /dev/null @@ -1,59 +0,0 @@ -"use client"; - -import type { ComponentProps } from "react"; -import { cn } from "@/lib/utils"; -import { paper } from "./surfaces"; - -const DOT_DELAYS = ["-0.32s", "-0.16s", "0s"]; - -export function TypingIndicator({ - variant = "bubble", - className, - ...props -}: Omit< - ComponentProps<"div">, - "children" | "variant" | "role" | "aria-label" -> & { - variant?: "bubble" | "bare"; -}) { - const dots = DOT_DELAYS.map((delay) => ( - - )); - - if (variant === "bare") { - return ( -
      - {dots} -
      - ); - } - - return ( -
      -
      - {dots} -
      -
      - ); -} diff --git a/demo/chat-ui/src/components/icons/github.tsx b/demo/chat-ui/src/components/icons/github.tsx deleted file mode 100644 index b82ccd2d..00000000 --- a/demo/chat-ui/src/components/icons/github.tsx +++ /dev/null @@ -1,12 +0,0 @@ -export function GitHubIcon({ className }: { readonly className?: string }) { - return ( - - ); -} diff --git a/demo/chat-ui/src/components/ui/avatar.tsx b/demo/chat-ui/src/components/ui/avatar.tsx deleted file mode 100644 index 52ef0c0f..00000000 --- a/demo/chat-ui/src/components/ui/avatar.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import * as React from "react" -import { Avatar as AvatarPrimitive } from "radix-ui" - -import { cn } from "@/lib/utils" - -function Avatar({ - className, - size = "default", - ...props -}: React.ComponentProps & { - size?: "default" | "sm" | "lg" -}) { - return ( - - ) -} - -function AvatarImage({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function AvatarFallback({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) { - return ( - svg]:hidden", - "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2", - "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2", - className - )} - {...props} - /> - ) -} - -function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) { - return ( -
      - ) -} - -function AvatarGroupCount({ - className, - ...props -}: React.ComponentProps<"div">) { - return ( -
      svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3", - className - )} - {...props} - /> - ) -} - -export { - Avatar, - AvatarImage, - AvatarFallback, - AvatarBadge, - AvatarGroup, - AvatarGroupCount, -} diff --git a/demo/chat-ui/src/components/ui/button.tsx b/demo/chat-ui/src/components/ui/button.tsx deleted file mode 100644 index 4d38506c..00000000 --- a/demo/chat-ui/src/components/ui/button.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { Slot } from "radix-ui" - -import { cn } from "@/lib/utils" - -const buttonVariants = cva( - "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", - { - variants: { - variant: { - default: "bg-primary text-primary-foreground hover:bg-primary/90", - destructive: - "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40", - outline: - "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", - secondary: - "bg-secondary text-secondary-foreground hover:bg-secondary/80", - ghost: - "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", - link: "text-primary underline-offset-4 hover:underline", - }, - size: { - default: "h-9 px-4 py-2 has-[>svg]:px-3", - xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", - sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", - lg: "h-10 rounded-md px-6 has-[>svg]:px-4", - icon: "size-9", - "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", - "icon-sm": "size-8", - "icon-lg": "size-10", - }, - }, - defaultVariants: { - variant: "default", - size: "default", - }, - } -) - -function Button({ - className, - variant = "default", - size = "default", - asChild = false, - ...props -}: React.ComponentProps<"button"> & - VariantProps & { - asChild?: boolean - }) { - const Comp = asChild ? Slot.Root : "button" - - return ( - - ) -} - -export { Button, buttonVariants } diff --git a/demo/chat-ui/src/components/ui/collapsible.tsx b/demo/chat-ui/src/components/ui/collapsible.tsx deleted file mode 100644 index 63fc8eff..00000000 --- a/demo/chat-ui/src/components/ui/collapsible.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Collapsible as CollapsiblePrimitive } from "radix-ui" - -function Collapsible({ - ...props -}: React.ComponentProps) { - return -} - -function CollapsibleTrigger({ - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function CollapsibleContent({ - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { Collapsible, CollapsibleTrigger, CollapsibleContent } diff --git a/demo/chat-ui/src/components/ui/dialog.tsx b/demo/chat-ui/src/components/ui/dialog.tsx deleted file mode 100644 index 6d8b3af0..00000000 --- a/demo/chat-ui/src/components/ui/dialog.tsx +++ /dev/null @@ -1,156 +0,0 @@ -import * as React from "react" -import { XIcon } from "lucide-react" -import { Dialog as DialogPrimitive } from "radix-ui" - -import { cn } from "@/lib/utils" -import { Button } from "@/components/ui/button" - -function Dialog({ - ...props -}: Readonly>) { - return -} - -function DialogTrigger({ - ...props -}: Readonly>) { - return -} - -function DialogPortal({ - ...props -}: Readonly>) { - return -} - -function DialogClose({ - ...props -}: Readonly>) { - return -} - -function DialogOverlay({ - className, - ...props -}: Readonly>) { - return ( - - ) -} - -function DialogContent({ - className, - children, - showCloseButton = true, - ...props -}: React.ComponentProps & { - showCloseButton?: boolean -}) { - return ( - - - - {children} - {showCloseButton && ( - - - Close - - )} - - - ) -} - -function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { - return ( -
      - ) -} - -function DialogFooter({ - className, - showCloseButton = false, - children, - ...props -}: React.ComponentProps<"div"> & { - showCloseButton?: boolean -}) { - return ( -
      - {children} - {showCloseButton && ( - - - - )} -
      - ) -} - -function DialogTitle({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function DialogDescription({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogOverlay, - DialogPortal, - DialogTitle, - DialogTrigger, -} diff --git a/demo/chat-ui/src/components/ui/input.tsx b/demo/chat-ui/src/components/ui/input.tsx deleted file mode 100644 index f1124aea..00000000 --- a/demo/chat-ui/src/components/ui/input.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from "react" - -import { cn } from "@/lib/utils" - -function Input({ className, type, ...props }: React.ComponentProps<"input">) { - return ( - - ) -} - -export { Input } diff --git a/demo/chat-ui/src/components/ui/separator.tsx b/demo/chat-ui/src/components/ui/separator.tsx deleted file mode 100644 index db91e97a..00000000 --- a/demo/chat-ui/src/components/ui/separator.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import * as React from "react" -import { Separator as SeparatorPrimitive } from "radix-ui" - -import { cn } from "@/lib/utils" - -function Separator({ - className, - orientation = "horizontal", - decorative = true, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { Separator } diff --git a/demo/chat-ui/src/components/ui/sheet.tsx b/demo/chat-ui/src/components/ui/sheet.tsx deleted file mode 100644 index 3e679170..00000000 --- a/demo/chat-ui/src/components/ui/sheet.tsx +++ /dev/null @@ -1,143 +0,0 @@ -"use client" - -import * as React from "react" -import { XIcon } from "lucide-react" -import { Dialog as SheetPrimitive } from "radix-ui" - -import { cn } from "@/lib/utils" - -function Sheet({ ...props }: Readonly>) { - return -} - -function SheetTrigger({ - ...props -}: Readonly>) { - return -} - -function SheetClose({ - ...props -}: Readonly>) { - return -} - -function SheetPortal({ - ...props -}: Readonly>) { - return -} - -function SheetOverlay({ - className, - ...props -}: Readonly>) { - return ( - - ) -} - -function SheetContent({ - className, - children, - side = "right", - showCloseButton = true, - ...props -}: React.ComponentProps & { - side?: "top" | "right" | "bottom" | "left" - showCloseButton?: boolean -}) { - return ( - - - - {children} - {showCloseButton && ( - - - Close - - )} - - - ) -} - -function SheetHeader({ className, ...props }: React.ComponentProps<"div">) { - return ( -
      - ) -} - -function SheetFooter({ className, ...props }: React.ComponentProps<"div">) { - return ( -
      - ) -} - -function SheetTitle({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function SheetDescription({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { - Sheet, - SheetTrigger, - SheetClose, - SheetContent, - SheetHeader, - SheetFooter, - SheetTitle, - SheetDescription, -} diff --git a/demo/chat-ui/src/components/ui/sidebar.tsx b/demo/chat-ui/src/components/ui/sidebar.tsx deleted file mode 100644 index d1a09569..00000000 --- a/demo/chat-ui/src/components/ui/sidebar.tsx +++ /dev/null @@ -1,724 +0,0 @@ -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { PanelLeftIcon } from "lucide-react" -import { Slot } from "radix-ui" - -import { useIsMobile } from "@/hooks/use-mobile" -import { cn } from "@/lib/utils" -import { Button } from "@/components/ui/button" -import { Input } from "@/components/ui/input" -import { Separator } from "@/components/ui/separator" -import { - Sheet, - SheetContent, - SheetDescription, - SheetHeader, - SheetTitle, -} from "@/components/ui/sheet" -import { Skeleton } from "@/components/ui/skeleton" -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip" - -const SIDEBAR_COOKIE_NAME = "sidebar_state" -const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7 -const SIDEBAR_WIDTH = "16rem" -const SIDEBAR_WIDTH_MOBILE = "18rem" -const SIDEBAR_WIDTH_ICON = "3rem" -const SIDEBAR_KEYBOARD_SHORTCUT = "b" - -type SidebarContextProps = { - state: "expanded" | "collapsed" - open: boolean - setOpen: (open: boolean) => void - openMobile: boolean - setOpenMobile: (open: boolean) => void - isMobile: boolean - toggleSidebar: () => void -} - -const SidebarContext = React.createContext(null) - -function useSidebar() { - const context = React.useContext(SidebarContext) - if (!context) { - throw new Error("useSidebar must be used within a SidebarProvider.") - } - - return context -} - -function SidebarProvider({ - defaultOpen = true, - open: openProp, - onOpenChange: setOpenProp, - className, - style, - children, - ...props -}: React.ComponentProps<"div"> & { - defaultOpen?: boolean - open?: boolean - onOpenChange?: (open: boolean) => void -}) { - const isMobile = useIsMobile() - const [openMobile, setOpenMobile] = React.useState(false) - - // This is the internal state of the sidebar. - // We use openProp and setOpenProp for control from outside the component. - const [_open, _setOpen] = React.useState(defaultOpen) - const open = openProp ?? _open - const setOpen = React.useCallback( - (value: boolean | ((value: boolean) => boolean)) => { - const openState = typeof value === "function" ? value(open) : value - if (setOpenProp) { - setOpenProp(openState) - } else { - _setOpen(openState) - } - - // This sets the cookie to keep the sidebar state. - document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}` - }, - [setOpenProp, open] - ) - - // Helper to toggle the sidebar. - const toggleSidebar = React.useCallback(() => { - return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open) - }, [isMobile, setOpen, setOpenMobile]) - - // Adds a keyboard shortcut to toggle the sidebar. - React.useEffect(() => { - const handleKeyDown = (event: KeyboardEvent) => { - if ( - event.key === SIDEBAR_KEYBOARD_SHORTCUT && - (event.metaKey || event.ctrlKey) - ) { - event.preventDefault() - toggleSidebar() - } - } - - window.addEventListener("keydown", handleKeyDown) - return () => window.removeEventListener("keydown", handleKeyDown) - }, [toggleSidebar]) - - // We add a state so that we can do data-state="expanded" or "collapsed". - // This makes it easier to style the sidebar with Tailwind classes. - const state = open ? "expanded" : "collapsed" - - const contextValue = React.useMemo( - () => ({ - state, - open, - setOpen, - isMobile, - openMobile, - setOpenMobile, - toggleSidebar, - }), - [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar] - ) - - return ( - - -
      - {children} -
      -
      -
      - ) -} - -function Sidebar({ - side = "left", - variant = "sidebar", - collapsible = "offcanvas", - className, - children, - ...props -}: React.ComponentProps<"div"> & { - side?: "left" | "right" - variant?: "sidebar" | "floating" | "inset" - collapsible?: "offcanvas" | "icon" | "none" -}) { - const { isMobile, state, openMobile, setOpenMobile } = useSidebar() - - if (collapsible === "none") { - return ( -
      - {children} -
      - ) - } - - if (isMobile) { - return ( - - - - Sidebar - Displays the mobile sidebar. - -
      {children}
      -
      -
      - ) - } - - return ( -
      - {/* This is what handles the sidebar gap on desktop */} -
      - -
      - ) -} - -function SidebarTrigger({ - className, - onClick, - ...props -}: React.ComponentProps) { - const { toggleSidebar } = useSidebar() - - return ( - - ) -} - -function SidebarRail({ className, ...props }: React.ComponentProps<"button">) { - const { toggleSidebar } = useSidebar() - - return ( -
    2. - ), - td: ({ className, ...props }) => ( - - ), - tr: ({ className, ...props }) => ( -