using System.Text; namespace AIStudio.Tools.AssistantSessions; /// /// Restores typed assistant session state values from a snapshot. /// /// The captured snapshot fields. /// The user-visible assistant title. public sealed class AssistantSessionStateReader(IReadOnlyDictionary fields, string assistantTitle) { private static readonly ILogger LOG = Program.LOGGER_FACTORY.CreateLogger(); /// /// Restores a typed value when it exists in the snapshot. /// /// The value type. /// The typed state key. /// The action that applies the restored value. public void Restore(AssistantSessionStateKey key, Action apply) { if (this.TryRead(key, out var value)) apply(value!); } /// /// Restores a list into an existing list instance. /// /// The list item type. /// The typed state key. /// The existing list to update. public void RestoreList(AssistantSessionStateKey> key, List target) { this.Restore(key, values => { target.Clear(); target.AddRange(values); }); } /// /// Restores a hash set into an existing hash set instance. /// /// The set item type. /// The typed state key. /// The existing hash set to update. public void RestoreHashSet(AssistantSessionStateKey> key, HashSet target) { this.Restore(key, values => { target.Clear(); target.UnionWith(values); }); } /// /// Restores a dictionary into an existing dictionary instance. /// /// The dictionary key type. /// The dictionary value type. /// The typed state key. /// The existing dictionary to update. public void RestoreDictionary(AssistantSessionStateKey> key, Dictionary target) where TKey : notnull { this.Restore(key, values => { target.Clear(); foreach (var (itemKey, itemValue) in values) target[itemKey] = itemValue; }); } /// /// Restores text into an existing string builder instance. /// /// The typed state key. /// The existing string builder to update. public void RestoreStringBuilder(AssistantSessionStateKey key, StringBuilder target) { this.Restore(key, value => { target.Clear(); target.Append(value); }); } /// /// Tries to read a typed value from the snapshot. /// /// The requested value type. /// The typed state key. /// The restored value when reading succeeds. /// true when a value exists and matches the requested type; otherwise, false. private bool TryRead(AssistantSessionStateKey key, out T? value) { value = default; if (!fields.TryGetValue(key.Name, out var field)) return false; if (field.TryRead(out value)) return true; LOG.LogWarning( "Could not restore assistant session field '{FieldStateKey}' for assistant '{AssistantTitle}'. ExpectedType='{ExpectedType}', CapturedValueType='{CapturedValueType}'. The current value is kept.", key.Name, assistantTitle, typeof(T).FullName, field.ValueType.FullName); return false; } }