// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable using System; using System.Collections.Generic; using System.Management.Automation.Language; using System.Threading; using System.Threading.Tasks; namespace System.Management.Automation.Subsystem.Prediction { /// /// The class represents the prediction result from a predictor. /// public sealed class PredictionResult { /// /// Gets the Id of the predictor. /// public Guid Id { get; } /// /// Gets the name of the predictor. /// public string Name { get; } /// /// Gets the mini-session id that represents a specific invocation to the API of the predictor. /// When it's not specified, it's considered by a client that the predictor doesn't expect feedback. /// public uint? Session { get; } /// /// Gets the suggestions. /// public IReadOnlyList Suggestions { get; } internal PredictionResult(Guid id, string name, uint? session, List suggestions) { Id = id; Name = name; Session = session; Suggestions = suggestions; } } /// /// Provides a set of possible predictions for given input. /// public static class CommandPrediction { /// /// Collect the predictive suggestions from registered predictors using the default timeout. /// /// Represents the client that initiates the call. /// The object from parsing the current command line input. /// The objects from parsing the current command line input. /// A list of objects. public static Task?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens) { return PredictInputAsync(client, ast, astTokens, millisecondsTimeout: 20); } /// /// Collect the predictive suggestions from registered predictors using the specified timeout. /// /// Represents the client that initiates the call. /// The object from parsing the current command line input. /// The objects from parsing the current command line input. /// The milliseconds to timeout. /// A list of objects. public static async Task?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens, int millisecondsTimeout) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(millisecondsTimeout); var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) { return null; } var context = new PredictionContext(ast, astTokens); var tasks = new Task[predictors.Count]; using var cancellationSource = new CancellationTokenSource(); Func callBack = GetCallBack(client, context, cancellationSource); for (int i = 0; i < predictors.Count; i++) { ICommandPredictor predictor = predictors[i]; tasks[i] = Task.Factory.StartNew( callBack, predictor, cancellationSource.Token, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } await Task.WhenAny( Task.WhenAll(tasks), Task.Delay(millisecondsTimeout, cancellationSource.Token)).ConfigureAwait(false); cancellationSource.Cancel(); var resultList = new List(predictors.Count); foreach (Task task in tasks) { if (task.IsCompletedSuccessfully) { PredictionResult? result = task.Result; if (result != null) { resultList.Add(result); } } } return resultList; // A local helper function to avoid creating an instance of the generated delegate helper class // when no predictor is registered. static Func GetCallBack( PredictionClient client, PredictionContext context, CancellationTokenSource cancellationSource) { return state => { var predictor = (ICommandPredictor)state!; SuggestionPackage pkg = predictor.GetSuggestion(client, context, cancellationSource.Token); return pkg.SuggestionEntries?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, pkg.Session, pkg.SuggestionEntries) : null; }; } } /// /// Allow registered predictors to do early processing when a command line is accepted. /// /// Represents the client that initiates the call. /// History command lines provided as references for prediction. public static void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { ArgumentNullException.ThrowIfNull(history); var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) { return; } Action? callBack = null; foreach (ICommandPredictor predictor in predictors) { if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.CommandLineAccepted)) { callBack ??= GetCallBack(client, history); ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); } } // A local helper function to avoid creating an instance of the generated delegate helper class // when no predictor is registered, or no registered predictor accepts this feedback. static Action GetCallBack(PredictionClient client, IReadOnlyList history) { return predictor => predictor.OnCommandLineAccepted(client, history); } } /// /// Allow registered predictors to know the execution result (success/failure) of the last accepted command line. /// /// Represents the client that initiates the call. /// The last accepted command line. /// Whether the execution of the last command line was successful. public static void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) { return; } Action? callBack = null; foreach (ICommandPredictor predictor in predictors) { if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.CommandLineExecuted)) { callBack ??= GetCallBack(client, commandLine, success); ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); } } // A local helper function to avoid creating an instance of the generated delegate helper class // when no predictor is registered, or no registered predictor accepts this feedback. static Action GetCallBack(PredictionClient client, string commandLine, bool success) { return predictor => predictor.OnCommandLineExecuted(client, commandLine, success); } } /// /// Send feedback to a predictor when one or more suggestions from it were displayed to the user. /// /// Represents the client that initiates the call. /// The identifier of the predictor whose prediction result was accepted. /// The mini-session where the displayed suggestions came from. /// /// When the value is greater than 0, it's the number of displayed suggestions from the list returned in , starting from the index 0. /// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value. /// public static void OnSuggestionDisplayed(PredictionClient client, Guid predictorId, uint session, int countOrIndex) { var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) { return; } foreach (ICommandPredictor predictor in predictors) { if (predictor.Id == predictorId) { if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.SuggestionDisplayed)) { Action callBack = GetCallBack(client, session, countOrIndex); ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); } break; } } // A local helper function to avoid creating an instance of the generated delegate helper class // when no predictor is registered, or no registered predictor accepts this feedback. static Action GetCallBack(PredictionClient client, uint session, int countOrIndex) { return predictor => predictor.OnSuggestionDisplayed(client, session, countOrIndex); } } /// /// Send feedback to a predictor when a suggestion from it was accepted. /// /// Represents the client that initiates the call. /// The identifier of the predictor whose prediction result was accepted. /// The mini-session where the accepted suggestion came from. /// The accepted suggestion text. public static void OnSuggestionAccepted(PredictionClient client, Guid predictorId, uint session, string suggestionText) { ArgumentException.ThrowIfNullOrEmpty(suggestionText); var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) { return; } foreach (ICommandPredictor predictor in predictors) { if (predictor.Id == predictorId) { if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.SuggestionAccepted)) { Action callBack = GetCallBack(client, session, suggestionText); ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); } break; } } // A local helper function to avoid creating an instance of the generated delegate helper class // when no predictor is registered, or no registered predictor accepts this feedback. static Action GetCallBack(PredictionClient client, uint session, string suggestionText) { return predictor => predictor.OnSuggestionAccepted(client, session, suggestionText); } } } }