|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using A2A; |
| 9 | +using Microsoft.Agents.AI.Hosting.A2A.Converters; |
| 10 | +using Microsoft.Shared.DiagnosticIds; |
| 11 | + |
| 12 | +namespace Microsoft.Agents.AI.Hosting.A2A; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// Writes a stream of <see cref="AgentResponseUpdate"/> instances to a <see cref="TaskUpdater"/> as A2A artifacts. |
| 16 | +/// </summary> |
| 17 | +/// <remarks> |
| 18 | +/// Each contiguous run of updates sharing a message ID becomes a single artifact streamed through artifact updates. |
| 19 | +/// The latest parts are buffered until another update or message boundary determines whether they are the last |
| 20 | +/// artifact update; earlier updates are appended and the final update closes the artifact. Updates without a message |
| 21 | +/// ID continue the current artifact, or start one with a generated ID. A message ID is used as the artifact ID when |
| 22 | +/// available; if it reappears later, a new artifact ID prevents the earlier artifact from being replaced. |
| 23 | +/// </remarks> |
| 24 | +[Experimental(DiagnosticIds.Experiments.AIResponseContinuations)] |
| 25 | +internal sealed class ArtifactStreamWriter |
| 26 | +{ |
| 27 | + /// <summary> |
| 28 | + /// The updater used to send artifact events. |
| 29 | + /// </summary> |
| 30 | + private readonly TaskUpdater _updater; |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// The artifact IDs already assigned by this writer, used to detect repeated message IDs. |
| 34 | + /// </summary> |
| 35 | + private readonly HashSet<string> _usedArtifactIds = []; |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// The message whose updates belong to the current artifact. |
| 39 | + /// </summary> |
| 40 | + private string? _currentMessageId; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// The unique ID used to write the current artifact. |
| 44 | + /// </summary> |
| 45 | + private string? _currentArtifactId; |
| 46 | + |
| 47 | + /// <summary> |
| 48 | + /// The update awaiting emission, held back until it is known whether it ends the artifact. |
| 49 | + /// </summary> |
| 50 | + private List<Part>? _bufferedParts; |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// Whether the next flushed parts should be appended to the current artifact. |
| 54 | + /// </summary> |
| 55 | + private bool _shouldAppend; |
| 56 | + |
| 57 | + /// <summary> |
| 58 | + /// Whether an artifact write failed. |
| 59 | + /// </summary> |
| 60 | + private bool _writeFailed; |
| 61 | + |
| 62 | + /// <summary> |
| 63 | + /// Initializes a new instance of the <see cref="ArtifactStreamWriter"/> class. |
| 64 | + /// </summary> |
| 65 | + /// <param name="updater">The updater the artifacts are written to.</param> |
| 66 | + public ArtifactStreamWriter(TaskUpdater updater) |
| 67 | + { |
| 68 | + this._updater = updater; |
| 69 | + } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Processes an update, writing the previously buffered parts once their position in the artifact is known. |
| 73 | + /// </summary> |
| 74 | + /// <param name="update">The update to write.</param> |
| 75 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param> |
| 76 | + public async Task WriteAsync(AgentResponseUpdate update, CancellationToken cancellationToken) |
| 77 | + { |
| 78 | + try |
| 79 | + { |
| 80 | + // Start the first artifact, generating an ID when the update does not provide one. |
| 81 | + if (this._currentArtifactId is null) |
| 82 | + { |
| 83 | + this.StartArtifact(update.MessageId); |
| 84 | + } |
| 85 | + // A different message ID ends the current artifact and starts the next one. |
| 86 | + else if (this.IsNewMessage(update.MessageId)) |
| 87 | + { |
| 88 | + await this.FlushBufferedPartsIfAnyAsync(lastChunk: true, cancellationToken).ConfigureAwait(false); |
| 89 | + this.StartArtifact(update.MessageId); |
| 90 | + } |
| 91 | + |
| 92 | + // Flush the previous parts as a non-final artifact update before buffering the next content-bearing update. |
| 93 | + if (update.ToParts() is { Count: > 0 } parts) |
| 94 | + { |
| 95 | + await this.FlushBufferedPartsIfAnyAsync(lastChunk: false, cancellationToken).ConfigureAwait(false); |
| 96 | + this._bufferedParts = parts; |
| 97 | + } |
| 98 | + } |
| 99 | + catch |
| 100 | + { |
| 101 | + this._writeFailed = true; |
| 102 | + throw; |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + /// <summary> |
| 107 | + /// Completes the stream by writing the buffered parts as the final artifact update. |
| 108 | + /// </summary> |
| 109 | + /// <remarks> |
| 110 | + /// Completion is skipped after an artifact write fails to avoid retrying and potentially duplicating that update. |
| 111 | + /// </remarks> |
| 112 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param> |
| 113 | + public async Task CompleteAsync(CancellationToken cancellationToken) |
| 114 | + { |
| 115 | + if (this._writeFailed) |
| 116 | + { |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + try |
| 121 | + { |
| 122 | + await this.FlushBufferedPartsIfAnyAsync(lastChunk: true, cancellationToken).ConfigureAwait(false); |
| 123 | + } |
| 124 | + catch |
| 125 | + { |
| 126 | + this._writeFailed = true; |
| 127 | + throw; |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + /// <summary> |
| 132 | + /// Flushes buffered parts to the current artifact. |
| 133 | + /// </summary> |
| 134 | + /// <param name="lastChunk">Whether the buffered parts form the final artifact update.</param> |
| 135 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param> |
| 136 | + private async Task FlushBufferedPartsIfAnyAsync(bool lastChunk, CancellationToken cancellationToken) |
| 137 | + { |
| 138 | + if (this._bufferedParts is null) |
| 139 | + { |
| 140 | + return; |
| 141 | + } |
| 142 | + |
| 143 | + await this._updater.AddArtifactAsync( |
| 144 | + this._bufferedParts, |
| 145 | + artifactId: this._currentArtifactId, |
| 146 | + lastChunk: lastChunk, |
| 147 | + append: this._shouldAppend, |
| 148 | + cancellationToken: cancellationToken).ConfigureAwait(false); |
| 149 | + |
| 150 | + this._bufferedParts = null; |
| 151 | + this._shouldAppend = true; |
| 152 | + } |
| 153 | + |
| 154 | + /// <summary> |
| 155 | + /// Determines whether the update starts a new message. |
| 156 | + /// </summary> |
| 157 | + /// <param name="messageId">The message ID from the update.</param> |
| 158 | + /// <returns><see langword="true"/> when the non-empty message ID differs from the current message ID.</returns> |
| 159 | + private bool IsNewMessage(string? messageId) |
| 160 | + { |
| 161 | + return messageId is { Length: > 0 } && messageId != this._currentMessageId; |
| 162 | + } |
| 163 | + |
| 164 | + /// <summary> |
| 165 | + /// Starts a new artifact, generating an ID when the message ID is missing or already used. |
| 166 | + /// </summary> |
| 167 | + /// <param name="messageId">The message ID, or <see langword="null"/> when the update does not provide one.</param> |
| 168 | + private void StartArtifact(string? messageId) |
| 169 | + { |
| 170 | + // Use a generated ID to group updates when the message ID is missing. |
| 171 | + this._currentMessageId = messageId is { Length: > 0 } |
| 172 | + ? messageId |
| 173 | + : Guid.NewGuid().ToString("N"); |
| 174 | + |
| 175 | + // Preserve the message ID when possible, but avoid replacing an earlier artifact when it reappears. |
| 176 | + if (this._usedArtifactIds.Add(this._currentMessageId)) |
| 177 | + { |
| 178 | + this._currentArtifactId = this._currentMessageId; |
| 179 | + } |
| 180 | + else |
| 181 | + { |
| 182 | + this._currentArtifactId = Guid.NewGuid().ToString("N"); |
| 183 | + this._usedArtifactIds.Add(this._currentArtifactId); |
| 184 | + } |
| 185 | + |
| 186 | + this._shouldAppend = false; |
| 187 | + } |
| 188 | +} |
0 commit comments