diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index d22c40eee..47f5d54bd 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -225,6 +225,12 @@ public ActionType(string value) public static readonly ActionType ResourceWatchChanged = new ActionType("resourceWatch/changed"); + public static readonly ActionType SearchQueryChanged = new ActionType("search/queryChanged"); + + public static readonly ActionType SearchResultsChanged = new ActionType("search/resultsChanged"); + + public static readonly ActionType SearchLifecycleChanged = new ActionType("search/lifecycleChanged"); + public static readonly ActionType AutomationCreateRequested = new ActionType("automation/createRequested"); public static readonly ActionType AutomationUpdateRequested = new ActionType("automation/updateRequested"); @@ -2548,6 +2554,76 @@ public sealed record ResourceWatchChangedAction public JsonElement Changes { get; init; } } +/// Replaces the search's query and restarts the search. +/// +/// Keeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to +/// {@link SearchLifecycleStatus.Pending | pending}. The old results stay +/// visible until the host replaces them, so the client does not flash an empty +/// list. +/// +/// After the host applies this action, it stops the previous search and drops +/// any of its results that it has not dispatched yet. The host MUST then +/// dispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with +/// `replace: true` before any other search action. The replacement can keep +/// old results that still match the new query, and can be empty. If the new +/// query is not valid, +/// for example because it contains an invalid regular expression, the host +/// replaces the results with an empty list and then changes the lifecycle to +/// {@link SearchLifecycleStatus.Failed | failed}. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchQueryChangedAction +{ + public ActionType Type { get; init; } = ActionType.SearchQueryChanged; + + /// The new query. + public required SearchQuery Query { get; init; } +} + +/// Adds results to {@link SearchState.results}, or replaces them. +/// +/// By default, the reducer appends `results`. Set `replace` to `true` to +/// replace every result instead; if {@link SearchState.lifecycle} is +/// {@link SearchLifecycleStatus.Pending | pending}, a replacement also changes +/// it to {@link SearchLifecycleStatus.Running | running}. +/// +/// The host MUST dispatch a replacement first after a +/// {@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also +/// replace the results at other times, for example to re-rank them, to remove +/// duplicates, or to update a completed search when a watched file changes. +/// The host MUST NOT dispatch an empty `results` list unless `replace` is +/// `true`. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchResultsChangedAction +{ + public ActionType Type { get; init; } = ActionType.SearchResultsChanged; + + /// The results to append, in the order the host found them, or the replacement results. + public required List Results { get; init; } + + /// When `true`, replaces every result instead of appending. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? Replace { get; init; } +} + +/// Replaces {@link SearchState.lifecycle}. +/// +/// The host dispatches this to complete or fail a search, or to move a +/// completed search back to {@link SearchLifecycleStatus.Running | running} when it +/// searches again, for example after a watched file changes. The host MUST NOT +/// change the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only +/// {@link SearchQueryChangedAction | `search/queryChanged`} does that. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchLifecycleChangedAction +{ + public ActionType Type { get; init; } = ActionType.SearchLifecycleChanged; + + /// The new lifecycle. + public required SearchLifecycleState Lifecycle { get; init; } +} + /// Upsert an {@link Annotation} in the annotations channel — adds a new /// annotation, or replaces an existing one identified by /// {@link Annotation.id}. @@ -2996,6 +3072,9 @@ public StateActionConverter() ["terminal/commandExecuted"] = typeof(TerminalCommandExecutedAction), ["terminal/commandFinished"] = typeof(TerminalCommandFinishedAction), ["resourceWatch/changed"] = typeof(ResourceWatchChangedAction), + ["search/queryChanged"] = typeof(SearchQueryChangedAction), + ["search/resultsChanged"] = typeof(SearchResultsChangedAction), + ["search/lifecycleChanged"] = typeof(SearchLifecycleChangedAction), ["annotations/set"] = typeof(AnnotationsSetAction), ["annotations/removed"] = typeof(AnnotationsRemovedAction), ["annotations/entrySet"] = typeof(AnnotationsEntrySetAction), diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 0ff02cab5..4f12cff59 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -530,6 +530,13 @@ public sealed record InitializeResult [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public TcpConnectionsCapability? TcpConnections { get; init; } + /// Present when the host supports `createSearch`, which searches files, + /// sessions, and chats and streams the results on an `ahp-search:` channel. + /// + /// Stability: 1.0 - Early development. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public SearchCapability? Search { get; init; } + /// Present when chats in one session may be backed by different agent /// providers (see {@link CreateChatParams.provider} and /// {@link ChatState.provider}). @@ -1872,6 +1879,42 @@ public sealed record CreateResourceWatchResult public required string Channel { get; init; } } +/// Starts a search on the host. +/// +/// The client chooses the channel URI and then subscribes to it to receive the +/// search's {@link SearchState} and its results. The client replaces the query +/// by dispatching {@link SearchQueryChangedAction | `search/queryChanged`}, +/// and cancels the search by unsubscribing. +/// +/// The client MUST NOT send this command unless `InitializeResult.search` is +/// present, and MUST NOT include a target whose kind is not listed in +/// {@link SearchCapability.targets}. +/// +/// Stability: 1.0 - Early development. +public sealed record CreateSearchParams +{ + /// The client-chosen URI for the new channel, for example `ahp-search:/<uuid>`. + public required string Channel { get; init; } + + /// Optional JSON-serializable metadata associated with this request. + /// Receivers MUST ignore keys they do not understand. + [JsonPropertyName("_meta")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public Dictionary? Meta { get; init; } + + /// What to search for and where. + public required SearchQuery Query { get; init; } +} + +/// Result of the `createSearch` command. +/// +/// An empty object on success. +/// +/// Stability: 1.0 - Early development. +public sealed record CreateSearchResult +{ +} + /// Requests that the host load older historical turns into a chat state. /// /// The command result does not carry turns. Instead, before responding, the host diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 8164a013a..b60d5aa3a 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -164,6 +164,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ChatInteractivity))] [JsonSerializable(typeof(ChatIsArchivedChangedAction))] [JsonSerializable(typeof(ChatIsReadChangedAction))] +[JsonSerializable(typeof(ChatMessageSearchResult))] +[JsonSerializable(typeof(ChatMessagesSearchTarget))] [JsonSerializable(typeof(ChatMovableChangedAction))] [JsonSerializable(typeof(ChatMovedAction))] [JsonSerializable(typeof(ChatMoveDestination))] @@ -220,6 +222,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(CreateChatParams))] [JsonSerializable(typeof(CreateResourceWatchParams))] [JsonSerializable(typeof(CreateResourceWatchResult))] +[JsonSerializable(typeof(CreateSearchParams))] +[JsonSerializable(typeof(CreateSearchResult))] [JsonSerializable(typeof(CreateSessionParams))] [JsonSerializable(typeof(CreateTcpConnectionParams))] [JsonSerializable(typeof(CreateTcpConnectionResult))] @@ -259,6 +263,10 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(FileEditCollection))] [JsonSerializable(typeof(FileEditDiffStats))] [JsonSerializable(typeof(FileEditSide))] +[JsonSerializable(typeof(FileNameSearchResult))] +[JsonSerializable(typeof(FileNamesSearchTarget))] +[JsonSerializable(typeof(FileTextSearchResult))] +[JsonSerializable(typeof(FileTextSearchTarget))] [JsonSerializable(typeof(ForkChatSource))] [JsonSerializable(typeof(HookCustomization))] [JsonSerializable(typeof(HostEnvironment))] @@ -370,6 +378,25 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RuleCustomization))] [JsonSerializable(typeof(RunAutomationParams))] [JsonSerializable(typeof(RunAutomationResult))] +[JsonSerializable(typeof(SearchCapability))] +[JsonSerializable(typeof(SearchCompletedLifecycleState))] +[JsonSerializable(typeof(SearchCompletionReason))] +[JsonSerializable(typeof(SearchFailedLifecycleState))] +[JsonSerializable(typeof(SearchHighlight))] +[JsonSerializable(typeof(SearchLifecycleChangedAction))] +[JsonSerializable(typeof(SearchLifecycleState))] +[JsonSerializable(typeof(SearchLifecycleStatus))] +[JsonSerializable(typeof(SearchMatch))] +[JsonSerializable(typeof(SearchPendingLifecycleState))] +[JsonSerializable(typeof(SearchQuery))] +[JsonSerializable(typeof(SearchQueryChangedAction))] +[JsonSerializable(typeof(SearchResult))] +[JsonSerializable(typeof(SearchResultKind))] +[JsonSerializable(typeof(SearchResultsChangedAction))] +[JsonSerializable(typeof(SearchRunningLifecycleState))] +[JsonSerializable(typeof(SearchState))] +[JsonSerializable(typeof(SearchTarget))] +[JsonSerializable(typeof(SearchTargetKind))] [JsonSerializable(typeof(SessionActiveClient))] [JsonSerializable(typeof(SessionActiveClientRemovedAction))] [JsonSerializable(typeof(SessionActiveClientSetAction))] @@ -419,7 +446,9 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(SessionReasoningAction))] [JsonSerializable(typeof(SessionRemovedParams))] [JsonSerializable(typeof(SessionResponsePartAction))] +[JsonSerializable(typeof(SessionSearchResult))] [JsonSerializable(typeof(SessionServerToolsChangedAction))] +[JsonSerializable(typeof(SessionsSearchTarget))] [JsonSerializable(typeof(SessionState))] [JsonSerializable(typeof(SessionStatus))] [JsonSerializable(typeof(SessionSummary))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 29b4469f4..63a0b163c 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1848,6 +1848,241 @@ public enum AutomationRunOriginKind Trigger, } +/// Discriminant for {@link SearchTarget}. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(SearchTargetKindConverter))] +public readonly struct SearchTargetKind : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public SearchTargetKind(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// File paths. + public static readonly SearchTargetKind FileNames = new SearchTargetKind("fileNames"); + + /// The text content of files. + public static readonly SearchTargetKind FileText = new SearchTargetKind("fileText"); + + /// The host's sessions. + public static readonly SearchTargetKind Sessions = new SearchTargetKind("sessions"); + + /// The text of chat requests and responses. + public static readonly SearchTargetKind ChatMessages = new SearchTargetKind("chatMessages"); + + /// + public bool Equals(SearchTargetKind other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is SearchTargetKind other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(SearchTargetKind left, SearchTargetKind right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(SearchTargetKind left, SearchTargetKind right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class SearchTargetKindConverter : JsonConverter +{ + /// + public override SearchTargetKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new SearchTargetKind(reader.GetString() ?? throw new JsonException("SearchTargetKind expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, SearchTargetKind value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + +/// Discriminant for {@link SearchResult}. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(SearchResultKindConverter))] +public readonly struct SearchResultKind : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public SearchResultKind(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + public static readonly SearchResultKind FileName = new SearchResultKind("fileName"); + + public static readonly SearchResultKind FileText = new SearchResultKind("fileText"); + + public static readonly SearchResultKind Session = new SearchResultKind("session"); + + public static readonly SearchResultKind ChatMessage = new SearchResultKind("chatMessage"); + + /// + public bool Equals(SearchResultKind other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is SearchResultKind other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(SearchResultKind left, SearchResultKind right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(SearchResultKind left, SearchResultKind right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class SearchResultKindConverter : JsonConverter +{ + /// + public override SearchResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new SearchResultKind(reader.GetString() ?? throw new JsonException("SearchResultKind expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, SearchResultKind value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + +/// Lifecycle status of a search. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(SearchLifecycleStatusConverter))] +public readonly struct SearchLifecycleStatus : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public SearchLifecycleStatus(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// The query changed and the host has not replaced the results yet. + /// {@link SearchState.results} belong to the previous query. + public static readonly SearchLifecycleStatus Pending = new SearchLifecycleStatus("pending"); + + /// The host is searching. + public static readonly SearchLifecycleStatus Running = new SearchLifecycleStatus("running"); + + /// The host found every result for the query. + public static readonly SearchLifecycleStatus Completed = new SearchLifecycleStatus("completed"); + + /// The search failed. + public static readonly SearchLifecycleStatus Failed = new SearchLifecycleStatus("failed"); + + /// + public bool Equals(SearchLifecycleStatus other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is SearchLifecycleStatus other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(SearchLifecycleStatus left, SearchLifecycleStatus right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(SearchLifecycleStatus left, SearchLifecycleStatus right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class SearchLifecycleStatusConverter : JsonConverter +{ + /// + public override SearchLifecycleStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new SearchLifecycleStatus(reader.GetString() ?? throw new JsonException("SearchLifecycleStatus expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, SearchLifecycleStatus value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + +/// Why a search completed. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(SearchCompletionReasonConverter))] +public readonly struct SearchCompletionReason : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public SearchCompletionReason(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// The host searched every target. + public static readonly SearchCompletionReason Exhausted = new SearchCompletionReason("exhausted"); + + /// The host stopped at the result limit. More results may exist. + public static readonly SearchCompletionReason LimitReached = new SearchCompletionReason("limitReached"); + + /// + public bool Equals(SearchCompletionReason other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is SearchCompletionReason other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(SearchCompletionReason left, SearchCompletionReason right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(SearchCompletionReason left, SearchCompletionReason right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class SearchCompletionReasonConverter : JsonConverter +{ + /// + public override SearchCompletionReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new SearchCompletionReason(reader.GetString() ?? throw new JsonException("SearchCompletionReason expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, SearchCompletionReason value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + // ─── Classes ────────────────────────────────────────────────────────── /// Present when the host supports `createTcpConnection`. @@ -7653,6 +7888,342 @@ public sealed class AutomationRunState public Dictionary? Meta { get; set; } } +/// Present when the host supports `createSearch`. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchCapability +{ + /// The target kinds the host can search. A client MUST NOT send a + /// {@link SearchTarget} whose kind is not listed here. + public required List Targets { get; init; } +} + +/// What a search looks for and where. +/// +/// The client sends a query in `createSearch` and replaces it with +/// {@link SearchQueryChangedAction | `search/queryChanged`}. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchQuery +{ + /// The text to search for. Its meaning depends on the target: see + /// {@link SearchTarget}. An empty `text` matches nothing; the host completes + /// the search with no results. + public required string Text { get; init; } + + /// Match case. Defaults to `false`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? MatchCase { get; init; } + + /// Match only whole words. Defaults to `false`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? WholeWord { get; init; } + + /// Treat `text` as a regular expression. Defaults to `false`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? IsRegex { get; init; } + + /// A hint that precise matching isn't expected, for example because the + /// search powers a quick-find picker. The host MAY then match loosely, rank + /// results by how well they match, and ignore {@link isRegex} and + /// {@link wholeWord}. Defaults to `false`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? Fuzzy { get; init; } + + /// Where to search. MUST contain at least one target. + public required List Targets { get; init; } + + /// The maximum number of results. The host MAY apply a lower limit, and + /// completes the search with {@link SearchCompletionReason.LimitReached} + /// when it reaches the limit that applies. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? MaxResults { get; init; } + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// Searches file paths under {@link FileSearchTargetBase.roots}. +/// +/// The host decides how to match {@link SearchQuery.text} against file paths, +/// for example with fuzzy matching, and which query options apply. Results +/// are {@link FileNameSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public sealed record FileNamesSearchTarget +{ + /// The folders to search. MUST contain at least one URI. + public required List Roots { get; init; } + + /// Glob patterns relative to a root. When present, only matching files are searched. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Includes { get; init; } + + /// Glob patterns relative to a root. Matching files are not searched. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Excludes { get; init; } + + /// Also search files that the host's ignore rules, such as `.gitignore` + /// files, would otherwise skip. Defaults to `false`. `excludes` still apply. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? IncludeIgnored { get; init; } + + public SearchTargetKind Kind { get; init; } = SearchTargetKind.FileNames; + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// Searches the text content of files under {@link FileSearchTargetBase.roots}. +/// Results are {@link FileTextSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public sealed record FileTextSearchTarget +{ + /// The folders to search. MUST contain at least one URI. + public required List Roots { get; init; } + + /// Glob patterns relative to a root. When present, only matching files are searched. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Includes { get; init; } + + /// Glob patterns relative to a root. Matching files are not searched. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Excludes { get; init; } + + /// Also search files that the host's ignore rules, such as `.gitignore` + /// files, would otherwise skip. Defaults to `false`. `excludes` still apply. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? IncludeIgnored { get; init; } + + public SearchTargetKind Kind { get; init; } = SearchTargetKind.FileText; + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// Searches the host's sessions, the same sessions that `listSessions` +/// returns. The host decides which session content it matches, for example +/// titles or requests. Results are {@link SessionSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public sealed record SessionsSearchTarget +{ + public SearchTargetKind Kind { get; init; } = SearchTargetKind.Sessions; + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// Searches the visible text of chat requests and responses, including the +/// responses of deferred turns. Results are +/// {@link ChatMessageSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public sealed record ChatMessagesSearchTarget +{ + public SearchTargetKind Kind { get; init; } = SearchTargetKind.ChatMessages; + + /// The chats to search. MUST contain at least one chat URI. + public required List Chats { get; init; } + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// A matched span within {@link SearchMatch.text}: the half-open interval +/// `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code +/// units, as in {@link CompletionItem.rangeStart}. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchHighlight +{ + /// The start of the span. + public long RangeStart { get; init; } + + /// The end of the span, exclusive. MUST be greater than {@link rangeStart} + /// and at most the length of {@link SearchMatch.text}. + public long RangeEnd { get; init; } +} + +/// The matched text of a result, with the matched spans highlighted. The host +/// chooses how much text around the match to include. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchMatch +{ + /// The text to display. + public required string Text { get; init; } + + /// The matched spans, in order. Spans MUST NOT overlap. + public required List Highlights { get; init; } +} + +/// A file whose path matches. {@link SearchResultBase.resource} is the file; +/// the match text is its path, usually relative to the root that contains it. +/// +/// Stability: 1.0 - Early development. +public sealed record FileNameSearchResult +{ + /// The resource that contains the match. + public required string Resource { get; init; } + + /// The text to display, with the matched spans highlighted. + public required SearchMatch Match { get; init; } + + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? Score { get; init; } + + public SearchResultKind Kind { get; init; } = SearchResultKind.FileName; +} + +/// A match in the text of a file. {@link SearchResultBase.resource} is the +/// file; the match text is the text around the match, usually its line. +/// +/// Stability: 1.0 - Early development. +public sealed record FileTextSearchResult +{ + /// The resource that contains the match. + public required string Resource { get; init; } + + /// The text to display, with the matched spans highlighted. + public required SearchMatch Match { get; init; } + + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? Score { get; init; } + + public SearchResultKind Kind { get; init; } = SearchResultKind.FileText; + + /// The location of the match in the file. + public required TextRange Range { get; init; } +} + +/// A session whose content matches. {@link SearchResultBase.resource} is the +/// session URI. +/// +/// Stability: 1.0 - Early development. +public sealed record SessionSearchResult +{ + /// The resource that contains the match. + public required string Resource { get; init; } + + /// The text to display, with the matched spans highlighted. + public required SearchMatch Match { get; init; } + + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? Score { get; init; } + + public SearchResultKind Kind { get; init; } = SearchResultKind.Session; + + /// The session's title. + public required string Title { get; init; } +} + +/// A match in a chat request or response. {@link SearchResultBase.resource} +/// is the chat URI. +/// +/// Stability: 1.0 - Early development. +public sealed record ChatMessageSearchResult +{ + /// The resource that contains the match. + public required string Resource { get; init; } + + /// The text to display, with the matched spans highlighted. + public required SearchMatch Match { get; init; } + + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? Score { get; init; } + + public SearchResultKind Kind { get; init; } = SearchResultKind.ChatMessage; + + /// The chat's title. + public required string Title { get; init; } + + /// The ID of the turn that contains the match. + public required string TurnId { get; init; } +} + +/// The query changed and the host has not replaced the results yet. Clients +/// MAY show the previous query's results differently, for example dimmed. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchPendingLifecycleState +{ + public SearchLifecycleStatus Status { get; init; } = SearchLifecycleStatus.Pending; +} + +/// The host is searching and may add more results. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchRunningLifecycleState +{ + public SearchLifecycleStatus Status { get; init; } = SearchLifecycleStatus.Running; +} + +/// The host found every result for the query. A host that watches the +/// searched files, sessions, or chats MAY still change the results later. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchCompletedLifecycleState +{ + public SearchLifecycleStatus Status { get; init; } = SearchLifecycleStatus.Completed; + + /// Why the search completed. + public SearchCompletionReason Reason { get; init; } +} + +/// The search failed. Results found before the failure remain in +/// {@link SearchState.results}. +/// +/// Stability: 1.0 - Early development. +public sealed record SearchFailedLifecycleState +{ + public SearchLifecycleStatus Status { get; init; } = SearchLifecycleStatus.Failed; + + /// Why the search failed, for example an invalid regular expression. + public required ErrorInfo Error { get; init; } +} + +/// Full state for one search, returned when a client subscribes to its +/// `ahp-search:` URI. +/// +/// Stability: 1.0 - Early development. +public sealed class SearchState +{ + /// The current query. + public required SearchQuery Query { get; set; } + + /// Results in the order the host found them. Sort by + /// {@link SearchResultBase.score} to rank them. While {@link lifecycle} is + /// {@link SearchLifecycleStatus.Pending | pending}, these are results for the + /// previous query. + public required List Results { get; set; } + + /// Where the search is in its lifecycle. + public required SearchLifecycleState Lifecycle { get; set; } +} + // ─── Discriminated Unions ───────────────────────────────────────────── /// A single explicit customization enablement decision. @@ -8420,6 +8991,93 @@ public AutomationRunLifecycleConverter() } } +/// SearchTarget is one place to search. +[JsonConverter(typeof(SearchTargetConverter))] +public sealed class SearchTarget : AhpUnion +{ + /// Creates an empty SearchTarget (no active variant). + public SearchTarget() { } + + /// Creates a SearchTarget wrapping the given variant value. + public SearchTarget(object? value) : base(value) { } +} + +/// System.Text.Json converter for the SearchTarget discriminated union. +internal sealed class SearchTargetConverter : UnionConverter +{ + public SearchTargetConverter() + : base( + discriminator: "kind", + variants: new Dictionary + { + ["fileNames"] = typeof(FileNamesSearchTarget), + ["fileText"] = typeof(FileTextSearchTarget), + ["sessions"] = typeof(SessionsSearchTarget), + ["chatMessages"] = typeof(ChatMessagesSearchTarget), + }, + allowUnknown: true) + { + } +} + +/// SearchResult is one search match. +[JsonConverter(typeof(SearchResultConverter))] +public sealed class SearchResult : AhpUnion +{ + /// Creates an empty SearchResult (no active variant). + public SearchResult() { } + + /// Creates a SearchResult wrapping the given variant value. + public SearchResult(object? value) : base(value) { } +} + +/// System.Text.Json converter for the SearchResult discriminated union. +internal sealed class SearchResultConverter : UnionConverter +{ + public SearchResultConverter() + : base( + discriminator: "kind", + variants: new Dictionary + { + ["fileName"] = typeof(FileNameSearchResult), + ["fileText"] = typeof(FileTextSearchResult), + ["session"] = typeof(SessionSearchResult), + ["chatMessage"] = typeof(ChatMessageSearchResult), + }, + allowUnknown: true) + { + } +} + +/// SearchLifecycleState is the lifecycle of a search. +[JsonConverter(typeof(SearchLifecycleStateConverter))] +public sealed class SearchLifecycleState : AhpUnion +{ + /// Creates an empty SearchLifecycleState (no active variant). + public SearchLifecycleState() { } + + /// Creates a SearchLifecycleState wrapping the given variant value. + public SearchLifecycleState(object? value) : base(value) { } +} + +/// System.Text.Json converter for the SearchLifecycleState discriminated union. +internal sealed class SearchLifecycleStateConverter : UnionConverter +{ + public SearchLifecycleStateConverter() + : base( + discriminator: "status", + variants: new Dictionary + { + ["pending"] = typeof(SearchPendingLifecycleState), + ["running"] = typeof(SearchRunningLifecycleState), + ["completed"] = typeof(SearchCompletedLifecycleState), + ["failed"] = typeof(SearchFailedLifecycleState), + }, + allowUnknown: true) + { + } +} + /// /// ChatOrigin describes how a chat came into existence. /// @@ -8600,9 +9258,9 @@ public override void Write(Utf8JsonWriter writer, ToolInput value, JsonSerialize /// /// SnapshotState is the state payload of a snapshot — root, session, /// chat, canvas, terminal, changeset, resource-watch, annotations, automation catalogue, - /// automation-run, or empty state. Read + /// automation-run, search, or empty state. Read /// probes for distinctive fields in an order where no probe shadows another -/// (empty → chat → session → canvas → terminal → changeset → resource-watch → annotations → root). +/// (empty → chat → search → session → canvas → terminal → changeset → resource-watch → annotations → root). /// An object with no members is an empty state, used by channels whose state has no fields. /// [JsonConverter(typeof(SnapshotStateConverter))] @@ -8641,6 +9299,9 @@ public sealed class SnapshotState /// Automation run state variant, when populated. public AutomationRunState? AutomationRun { get; set; } + /// Search state variant, when populated. + public SearchState? Search { get; set; } + /// /// A state that this version does not recognize, such as the state of a channel /// added in a later protocol version. Kept as raw JSON so it re-encodes unchanged. @@ -8675,6 +9336,11 @@ public override SnapshotState Read(ref Utf8JsonReader reader, Type typeToConvert { result.Chat = root.Deserialize(AhpJsonTypeInfo.Get(options)); } + // SearchState also has a required `lifecycle`, so probe it before SessionState. + else if (root.TryGetProperty("query", out _) && root.TryGetProperty("results", out _)) + { + result.Search = root.Deserialize(AhpJsonTypeInfo.Get(options)); + } else if (root.TryGetProperty("lifecycle", out _)) { // SessionState is discriminated on its required `lifecycle` field. @@ -8723,6 +9389,7 @@ public override void Write(Utf8JsonWriter writer, SnapshotState value, JsonSeria if (value.Automations is not null) { JsonSerializer.Serialize(writer, value.Automations, AhpJsonTypeInfo.Get(options)); return; } if (value.Chat is not null) { JsonSerializer.Serialize(writer, value.Chat, AhpJsonTypeInfo.Get(options)); return; } if (value.Canvas is not null) { JsonSerializer.Serialize(writer, value.Canvas, AhpJsonTypeInfo.Get(options)); return; } + if (value.Search is not null) { JsonSerializer.Serialize(writer, value.Search, AhpJsonTypeInfo.Get(options)); return; } if (value.Session is not null) { JsonSerializer.Serialize(writer, value.Session, AhpJsonTypeInfo.Get(options)); return; } if (value.Terminal is not null) { JsonSerializer.Serialize(writer, value.Terminal, AhpJsonTypeInfo.Get(options)); return; } if (value.Changeset is not null) { JsonSerializer.Serialize(writer, value.Changeset, AhpJsonTypeInfo.Get(options)); return; } diff --git a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs index 4067f9f41..c3b557052 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -217,6 +217,15 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootTerminalsChangedAction value: actionType = value.Type; return true; + case SearchLifecycleChangedAction value: + actionType = value.Type; + return true; + case SearchQueryChangedAction value: + actionType = value.Type; + return true; + case SearchResultsChangedAction value: + actionType = value.Type; + return true; case SessionActiveClientRemovedAction value: actionType = value.Type; return true; diff --git a/clients/dotnet/src/AgentHostProtocol/Hosts/MultiHostStateMirror.cs b/clients/dotnet/src/AgentHostProtocol/Hosts/MultiHostStateMirror.cs index df13be267..baefc8849 100644 --- a/clients/dotnet/src/AgentHostProtocol/Hosts/MultiHostStateMirror.cs +++ b/clients/dotnet/src/AgentHostProtocol/Hosts/MultiHostStateMirror.cs @@ -24,6 +24,7 @@ public sealed class MultiHostStateMirror private readonly ConcurrentDictionary _canvases = new(); private readonly ConcurrentDictionary _terminals = new(); private readonly ConcurrentDictionary _changesets = new(); + private readonly ConcurrentDictionary _searches = new(); /// Stores for . public void PutRoot(HostId hostId, RootState root) @@ -102,6 +103,19 @@ public void PutChangeset(HostId hostId, string uri, ChangesetState state) public (ChangesetState? Value, bool Found) Changeset(HostId hostId, string uri) => _changesets.TryGetValue(new HostedResourceKey(hostId, uri), out var v) ? (v, true) : (default, false); + /// Stores a search snapshot under (hostId, uri). + public void PutSearch(HostId hostId, string uri, SearchState state) + { + Guard.ThrowIfNull(hostId, nameof(hostId)); + Guard.ThrowIfNull(uri, nameof(uri)); + Guard.ThrowIfNull(state, nameof(state)); + _searches[new HostedResourceKey(hostId, uri)] = state; + } + + /// Returns the search snapshot at (hostId, uri), or (default, false) if absent. + public (SearchState? Value, bool Found) Search(HostId hostId, string uri) => + _searches.TryGetValue(new HostedResourceKey(hostId, uri), out var v) ? (v, true) : (default, false); + /// Removes every snapshot belonging to . public void DropHost(HostId hostId) { @@ -111,6 +125,7 @@ public void DropHost(HostId hostId) foreach (var k in _canvases.Keys) if (k.HostId.Equals(hostId)) _canvases.TryRemove(k, out _); foreach (var k in _terminals.Keys) if (k.HostId.Equals(hostId)) _terminals.TryRemove(k, out _); foreach (var k in _changesets.Keys) if (k.HostId.Equals(hostId)) _changesets.TryRemove(k, out _); + foreach (var k in _searches.Keys) if (k.HostId.Equals(hostId)) _searches.TryRemove(k, out _); } /// Removes the snapshot at (hostId, uri) across every resource kind. @@ -122,5 +137,6 @@ public void DropResource(HostId hostId, string uri) _canvases.TryRemove(key, out _); _terminals.TryRemove(key, out _); _changesets.TryRemove(key, out _); + _searches.TryRemove(key, out _); } } diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index f8b00b7eb..76ab3ea30 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -2455,6 +2455,56 @@ public static ReduceOutcome ApplyToResourceWatch(ResourceWatchState state, State : ReduceOutcome.OutOfScope; } + // ─── Search Reducer ──────────────────────────────────────────────────── + + /// + /// Applies to the in + /// place. Returns for actions that + /// target a different state tree. + /// + public static ReduceOutcome ApplyToSearch(SearchState state, StateAction action) + { + Guard.ThrowIfNull(state, nameof(state)); + Guard.ThrowIfNull(action, nameof(action)); + switch (action.Value) + { + case SearchQueryChangedAction a: + { + state.Query = a.Query; + state.Lifecycle = new SearchLifecycleState(new SearchPendingLifecycleState()); + return ReduceOutcome.Applied; + } + case SearchResultsChangedAction a: + { + if (a.Replace != true) + { + if (a.Results.Count == 0) + { + return ReduceOutcome.NoOp; + } + + state.Results.AddRange(a.Results); + return ReduceOutcome.Applied; + } + + state.Results = new List(a.Results); + if (state.Lifecycle.Value is SearchPendingLifecycleState) + { + state.Lifecycle = new SearchLifecycleState(new SearchRunningLifecycleState()); + } + + return ReduceOutcome.Applied; + } + case SearchLifecycleChangedAction a: + { + state.Lifecycle = a.Lifecycle; + return ReduceOutcome.Applied; + } + default: + return ReduceOutcome.OutOfScope; + } + } + // ─── Annotations Reducer ─────────────────────────────────────────────── /// diff --git a/clients/dotnet/tests/AgentHostProtocol.Tests/FixtureDrivenReducerTests.cs b/clients/dotnet/tests/AgentHostProtocol.Tests/FixtureDrivenReducerTests.cs index 1299f7af6..71cf9d687 100644 --- a/clients/dotnet/tests/AgentHostProtocol.Tests/FixtureDrivenReducerTests.cs +++ b/clients/dotnet/tests/AgentHostProtocol.Tests/FixtureDrivenReducerTests.cs @@ -81,6 +81,9 @@ public void ReducerMatchesFixture(string name, string path) case "canvas": RunFixture(initial, expected, actions, Reducers.ApplyToCanvas); break; + case "search": + RunFixture(initial, expected, actions, Reducers.ApplyToSearch); + break; case "automation": RunFixture( initial, diff --git a/clients/dotnet/tests/AgentHostProtocol.Tests/MultiHostStateMirrorTests.cs b/clients/dotnet/tests/AgentHostProtocol.Tests/MultiHostStateMirrorTests.cs index b06898c08..f368c3c95 100644 --- a/clients/dotnet/tests/AgentHostProtocol.Tests/MultiHostStateMirrorTests.cs +++ b/clients/dotnet/tests/AgentHostProtocol.Tests/MultiHostStateMirrorTests.cs @@ -53,6 +53,41 @@ public void CanvasState_IsIsolatedAndDroppedWithItsResourceAndHost() Assert.Equal(new[] { false, false, true }, new[] { resourceFound, hostFound, otherFound }); } + [Fact] + public void SearchState_IsIsolatedAndDroppedWithItsResourceAndHost() + { + var mirror = new MultiHostStateMirror(); + const string uri = "ahp-search:/s1"; + SearchState State() => new() + { + Query = new SearchQuery + { + Text = "parseConfig", + Targets = new List { new(new SessionsSearchTarget()) }, + }, + Results = new List(), + Lifecycle = new SearchLifecycleState(new SearchPendingLifecycleState()), + }; + mirror.PutSearch("host-a", uri, State()); + mirror.PutSearch("host-b", uri, State()); + var (target, _) = mirror.Search("host-a", uri); + Reducers.ApplyToSearch(target!, new StateAction(new SearchLifecycleChangedAction + { + Type = ActionType.SearchLifecycleChanged, + Lifecycle = new SearchLifecycleState(new SearchCompletedLifecycleState { Reason = SearchCompletionReason.Exhausted }), + })); + var (retained, _) = mirror.Search("host-b", uri); + var targeted = new[] { target!.Lifecycle.Value is SearchCompletedLifecycleState, retained!.Lifecycle.Value is SearchCompletedLifecycleState }; + mirror.DropResource("host-a", uri); + var (_, resourceFound) = mirror.Search("host-a", uri); + mirror.PutSearch("host-a", uri, State()); + mirror.DropHost("host-a"); + var (_, hostFound) = mirror.Search("host-a", uri); + var (_, otherFound) = mirror.Search("host-b", uri); + Assert.Equal(new[] { true, false }, targeted); + Assert.Equal(new[] { false, false, true }, new[] { resourceFound, hostFound, otherFound }); + } + // A minimal-but-valid RootState carrying a distinguishing active-session // count so two hosts' roots are observably different snapshots. private static RootState Root(long activeSessions) => new() diff --git a/clients/go/ahp/multi_host_state_mirror.go b/clients/go/ahp/multi_host_state_mirror.go index 97bc5e46f..e94ec4bf1 100644 --- a/clients/go/ahp/multi_host_state_mirror.go +++ b/clients/go/ahp/multi_host_state_mirror.go @@ -35,6 +35,7 @@ type MultiHostStateMirror struct { automationCat map[string]ahptypes.AutomationState automation map[HostedResourceKey]ahptypes.AutomationEntry automationRun map[HostedResourceKey]ahptypes.AutomationRunState + search map[HostedResourceKey]ahptypes.SearchState } // NewMultiHostStateMirror returns an empty mirror. @@ -49,6 +50,7 @@ func NewMultiHostStateMirror() *MultiHostStateMirror { automationCat: make(map[string]ahptypes.AutomationState), automation: make(map[HostedResourceKey]ahptypes.AutomationEntry), automationRun: make(map[HostedResourceKey]ahptypes.AutomationRunState), + search: make(map[HostedResourceKey]ahptypes.SearchState), } } @@ -194,6 +196,21 @@ func (m *MultiHostStateMirror) AutomationRun(hostID string, uri ahptypes.URI) (a return v, ok } +// PutSearch stores a search snapshot under (hostID, uri). +func (m *MultiHostStateMirror) PutSearch(hostID string, uri ahptypes.URI, state ahptypes.SearchState) { + m.mu.Lock() + defer m.mu.Unlock() + m.search[HostedResourceKey{hostID, uri}] = state +} + +// Search returns the search snapshot at (hostID, uri), or (zero, false). +func (m *MultiHostStateMirror) Search(hostID string, uri ahptypes.URI) (ahptypes.SearchState, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + v, ok := m.search[HostedResourceKey{hostID, uri}] + return v, ok +} + // DropHost removes every snapshot belonging to hostID. Use when a // host is removed from the multi-host registry. func (m *MultiHostStateMirror) DropHost(hostID string) { @@ -236,6 +253,11 @@ func (m *MultiHostStateMirror) DropHost(hostID string) { delete(m.automationRun, k) } } + for k := range m.search { + if k.HostID == hostID { + delete(m.search, k) + } + } } // DropResource removes the snapshot at (hostID, uri) across every @@ -259,4 +281,5 @@ func (m *MultiHostStateMirror) DropResource(hostID string, uri ahptypes.URI) { delete(m.changes, k) delete(m.automation, k) delete(m.automationRun, k) + delete(m.search, k) } diff --git a/clients/go/ahp/multi_host_state_mirror_test.go b/clients/go/ahp/multi_host_state_mirror_test.go index 4aa6e589c..3fb4891d4 100644 --- a/clients/go/ahp/multi_host_state_mirror_test.go +++ b/clients/go/ahp/multi_host_state_mirror_test.go @@ -29,6 +29,30 @@ func TestMultiHostStateMirrorCanvasLifecycle(t *testing.T) { } } +func TestMultiHostStateMirrorSearchLifecycle(t *testing.T) { + mirror := NewMultiHostStateMirror() + uri := ahptypes.URI("ahp-search:/s1") + state := ahptypes.SearchState{ + Query: ahptypes.SearchQuery{Text: "parseConfig"}, + Results: []ahptypes.SearchResult{}, + Lifecycle: ahptypes.SearchLifecycleState{Value: &ahptypes.SearchPendingLifecycleState{ + Status: ahptypes.SearchLifecycleStatusPending, + }}, + } + mirror.PutSearch("host-a", uri, state) + mirror.PutSearch("host-b", uri, state) + mirror.DropResource("host-a", uri) + _, removed := mirror.Search("host-a", uri) + retained, found := mirror.Search("host-b", uri) + mirror.PutSearch("host-a", uri, state) + mirror.DropHost("host-a") + _, dropped := mirror.Search("host-a", uri) + _, otherHost := mirror.Search("host-b", uri) + if removed || !found || !reflect.DeepEqual(retained, state) || dropped || !otherHost { + t.Fatal("search state was not isolated or removed with its resource and host") + } +} + func TestMultiHostStateMirrorDropHostWithoutChangesets(t *testing.T) { mirror := NewMultiHostStateMirror() automationURI := ahptypes.URI("ahp-automation:/nightly") diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 0111cf477..a5ad3e526 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -2048,6 +2048,37 @@ func ApplyActionToResourceWatch(state *ahptypes.ResourceWatchState, action ahpty return ReduceOutcomeOutOfScope } +// ─── Search Reducer ──────────────────────────────────────────────────── + +// ApplyActionToSearch applies action to the [ahptypes.SearchState] in +// place. Returns [ReduceOutcomeOutOfScope] for actions that target a +// different state tree. +func ApplyActionToSearch(state *ahptypes.SearchState, action ahptypes.StateAction) ReduceOutcome { + switch a := action.Value.(type) { + case *ahptypes.SearchQueryChangedAction: + state.Query = a.Query + state.Lifecycle = ahptypes.SearchLifecycleState{Value: &ahptypes.SearchPendingLifecycleState{Status: ahptypes.SearchLifecycleStatusPending}} + return ReduceOutcomeApplied + case *ahptypes.SearchResultsChangedAction: + if a.Replace == nil || !*a.Replace { + if len(a.Results) == 0 { + return ReduceOutcomeNoOp + } + state.Results = append(state.Results, a.Results...) + return ReduceOutcomeApplied + } + state.Results = append([]ahptypes.SearchResult{}, a.Results...) + if _, pending := state.Lifecycle.Value.(*ahptypes.SearchPendingLifecycleState); pending { + state.Lifecycle = ahptypes.SearchLifecycleState{Value: &ahptypes.SearchRunningLifecycleState{Status: ahptypes.SearchLifecycleStatusRunning}} + } + return ReduceOutcomeApplied + case *ahptypes.SearchLifecycleChangedAction: + state.Lifecycle = a.Lifecycle + return ReduceOutcomeApplied + } + return ReduceOutcomeOutOfScope +} + // ApplyActionToAutomation applies an action to automation catalogue state. func ApplyActionToAutomation(state *ahptypes.AutomationState, action ahptypes.StateAction) ReduceOutcome { switch a := action.Value.(type) { diff --git a/clients/go/ahp/reducers_fixture_test.go b/clients/go/ahp/reducers_fixture_test.go index faf7905f9..f5d97136f 100644 --- a/clients/go/ahp/reducers_fixture_test.go +++ b/clients/go/ahp/reducers_fixture_test.go @@ -155,6 +155,8 @@ func TestFixtureDrivenReducerParity(t *testing.T) { runFixture[ahptypes.AnnotationsState](tt, fixture.Initial, fixture.Expected, actions, ApplyActionToAnnotations) case "resourceWatch": runFixture[ahptypes.ResourceWatchState](tt, fixture.Initial, fixture.Expected, actions, ApplyActionToResourceWatch) + case "search": + runFixture[ahptypes.SearchState](tt, fixture.Initial, fixture.Expected, actions, ApplyActionToSearch) case "automation": runFixture[ahptypes.AutomationState](tt, fixture.Initial, fixture.Expected, actions, ApplyActionToAutomation) case "automationRun": diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 60a3208c5..30c44d7a8 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -119,6 +119,9 @@ const ( ActionTypeTerminalCommandExecuted ActionType = "terminal/commandExecuted" ActionTypeTerminalCommandFinished ActionType = "terminal/commandFinished" ActionTypeResourceWatchChanged ActionType = "resourceWatch/changed" + ActionTypeSearchQueryChanged ActionType = "search/queryChanged" + ActionTypeSearchResultsChanged ActionType = "search/resultsChanged" + ActionTypeSearchLifecycleChanged ActionType = "search/lifecycleChanged" ActionTypeAutomationCreateRequested ActionType = "automation/createRequested" ActionTypeAutomationUpdateRequested ActionType = "automation/updateRequested" ActionTypeAutomationSet ActionType = "automation/set" @@ -1753,6 +1756,68 @@ type ResourceWatchChangedAction struct { Changes json.RawMessage `json:"changes"` } +// Replaces the search's query and restarts the search. +// +// Keeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to +// {@link SearchLifecycleStatus.Pending | pending}. The old results stay +// visible until the host replaces them, so the client does not flash an empty +// list. +// +// After the host applies this action, it stops the previous search and drops +// any of its results that it has not dispatched yet. The host MUST then +// dispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with +// `replace: true` before any other search action. The replacement can keep +// old results that still match the new query, and can be empty. If the new +// query is not valid, +// for example because it contains an invalid regular expression, the host +// replaces the results with an empty list and then changes the lifecycle to +// {@link SearchLifecycleStatus.Failed | failed}. +// +// Stability: 1.0 - Early development. +type SearchQueryChangedAction struct { + Type ActionType `json:"type"` + // The new query. + Query SearchQuery `json:"query"` +} + +// Adds results to {@link SearchState.results}, or replaces them. +// +// By default, the reducer appends `results`. Set `replace` to `true` to +// replace every result instead; if {@link SearchState.lifecycle} is +// {@link SearchLifecycleStatus.Pending | pending}, a replacement also changes +// it to {@link SearchLifecycleStatus.Running | running}. +// +// The host MUST dispatch a replacement first after a +// {@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also +// replace the results at other times, for example to re-rank them, to remove +// duplicates, or to update a completed search when a watched file changes. +// The host MUST NOT dispatch an empty `results` list unless `replace` is +// `true`. +// +// Stability: 1.0 - Early development. +type SearchResultsChangedAction struct { + Type ActionType `json:"type"` + // The results to append, in the order the host found them, or the replacement results. + Results []SearchResult `json:"results"` + // When `true`, replaces every result instead of appending. + Replace *bool `json:"replace,omitempty"` +} + +// Replaces {@link SearchState.lifecycle}. +// +// The host dispatches this to complete or fail a search, or to move a +// completed search back to {@link SearchLifecycleStatus.Running | running} when it +// searches again, for example after a watched file changes. The host MUST NOT +// change the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only +// {@link SearchQueryChangedAction | `search/queryChanged`} does that. +// +// Stability: 1.0 - Early development. +type SearchLifecycleChangedAction struct { + Type ActionType `json:"type"` + // The new lifecycle. + Lifecycle SearchLifecycleState `json:"lifecycle"` +} + // Ask the host to create a durable automation at a client-chosen resource. // // Clients may dispatch this action only when the host advertises its `create` @@ -1982,6 +2047,9 @@ func (*TerminalCommandDetectionAvailableAction) isStateAction() {} func (*TerminalCommandExecutedAction) isStateAction() {} func (*TerminalCommandFinishedAction) isStateAction() {} func (*ResourceWatchChangedAction) isStateAction() {} +func (*SearchQueryChangedAction) isStateAction() {} +func (*SearchResultsChangedAction) isStateAction() {} +func (*SearchLifecycleChangedAction) isStateAction() {} func (*AutomationCreateRequestedAction) isStateAction() {} func (*AutomationUpdateRequestedAction) isStateAction() {} func (*AutomationSetAction) isStateAction() {} @@ -2606,6 +2674,24 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value + case "search/queryChanged": + var value SearchQueryChangedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "search/resultsChanged": + var value SearchResultsChangedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "search/lifecycleChanged": + var value SearchLifecycleChangedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value case "automation/createRequested": var value AutomationCreateRequestedAction if err := json.Unmarshal(data, &value); err != nil { diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index 8db449b0f..20a0301a4 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -268,6 +268,11 @@ type InitializeResult struct { // // Stability: 1.0 - Early development. TcpConnections *TcpConnectionsCapability `json:"tcpConnections,omitempty"` + // Present when the host supports `createSearch`, which searches files, + // sessions, and chats and streams the results on an `ahp-search:` channel. + // + // Stability: 1.0 - Early development. + Search *SearchCapability `json:"search,omitempty"` // Present when chats in one session may be backed by different agent // providers (see {@link CreateChatParams.provider} and // {@link ChatState.provider}). @@ -1342,6 +1347,36 @@ type CreateResourceWatchResult struct { Channel URI `json:"channel"` } +// Starts a search on the host. +// +// The client chooses the channel URI and then subscribes to it to receive the +// search's {@link SearchState} and its results. The client replaces the query +// by dispatching {@link SearchQueryChangedAction | `search/queryChanged`}, +// and cancels the search by unsubscribing. +// +// The client MUST NOT send this command unless `InitializeResult.search` is +// present, and MUST NOT include a target whose kind is not listed in +// {@link SearchCapability.targets}. +// +// Stability: 1.0 - Early development. +type CreateSearchParams struct { + // Channel URI this command targets. + Channel URI `json:"channel"` + // Optional JSON-serializable metadata associated with this request. + // Receivers MUST ignore keys they do not understand. + Meta map[string]json.RawMessage `json:"_meta,omitempty"` + // What to search for and where. + Query SearchQuery `json:"query"` +} + +// Result of the `createSearch` command. +// +// An empty object on success. +// +// Stability: 1.0 - Early development. +type CreateSearchResult struct { +} + // Requests that the host load older historical turns into a chat state. // // The command result does not carry turns. Instead, before responding, the host diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index f3ac8c505..143d8dbb0 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -610,6 +610,63 @@ const ( AutomationRunOriginKindTrigger AutomationRunOriginKind = "trigger" ) +// Discriminant for {@link SearchTarget}. +// +// Stability: 1.0 - Early development. +type SearchTargetKind string + +const ( + // File paths. + SearchTargetKindFileNames SearchTargetKind = "fileNames" + // The text content of files. + SearchTargetKindFileText SearchTargetKind = "fileText" + // The host's sessions. + SearchTargetKindSessions SearchTargetKind = "sessions" + // The text of chat requests and responses. + SearchTargetKindChatMessages SearchTargetKind = "chatMessages" +) + +// Discriminant for {@link SearchResult}. +// +// Stability: 1.0 - Early development. +type SearchResultKind string + +const ( + SearchResultKindFileName SearchResultKind = "fileName" + SearchResultKindFileText SearchResultKind = "fileText" + SearchResultKindSession SearchResultKind = "session" + SearchResultKindChatMessage SearchResultKind = "chatMessage" +) + +// Lifecycle status of a search. +// +// Stability: 1.0 - Early development. +type SearchLifecycleStatus string + +const ( + // The query changed and the host has not replaced the results yet. + // {@link SearchState.results} belong to the previous query. + SearchLifecycleStatusPending SearchLifecycleStatus = "pending" + // The host is searching. + SearchLifecycleStatusRunning SearchLifecycleStatus = "running" + // The host found every result for the query. + SearchLifecycleStatusCompleted SearchLifecycleStatus = "completed" + // The search failed. + SearchLifecycleStatusFailed SearchLifecycleStatus = "failed" +) + +// Why a search completed. +// +// Stability: 1.0 - Early development. +type SearchCompletionReason string + +const ( + // The host searched every target. + SearchCompletionReasonExhausted SearchCompletionReason = "exhausted" + // The host stopped at the result limit. More results may exist. + SearchCompletionReasonLimitReached SearchCompletionReason = "limitReached" +) + // ─── Structs ────────────────────────────────────────────────────────── // Present when the host supports `createTcpConnection`. @@ -5403,6 +5460,313 @@ type AutomationRunState struct { Meta map[string]json.RawMessage `json:"_meta,omitempty"` } +// Present when the host supports `createSearch`. +// +// Stability: 1.0 - Early development. +type SearchCapability struct { + // The target kinds the host can search. A client MUST NOT send a + // {@link SearchTarget} whose kind is not listed here. + Targets []SearchTargetKind `json:"targets"` +} + +// What a search looks for and where. +// +// The client sends a query in `createSearch` and replaces it with +// {@link SearchQueryChangedAction | `search/queryChanged`}. +// +// Stability: 1.0 - Early development. +type SearchQuery struct { + // The text to search for. Its meaning depends on the target: see + // {@link SearchTarget}. An empty `text` matches nothing; the host completes + // the search with no results. + Text string `json:"text"` + // Match case. Defaults to `false`. + MatchCase *bool `json:"matchCase,omitempty"` + // Match only whole words. Defaults to `false`. + WholeWord *bool `json:"wholeWord,omitempty"` + // Treat `text` as a regular expression. Defaults to `false`. + IsRegex *bool `json:"isRegex,omitempty"` + // A hint that precise matching isn't expected, for example because the + // search powers a quick-find picker. The host MAY then match loosely, rank + // results by how well they match, and ignore {@link isRegex} and + // {@link wholeWord}. Defaults to `false`. + Fuzzy *bool `json:"fuzzy,omitempty"` + // Where to search. MUST contain at least one target. + Targets []SearchTarget `json:"targets"` + // The maximum number of results. The host MAY apply a lower limit, and + // completes the search with {@link SearchCompletionReason.LimitReached} + // when it reaches the limit that applies. + MaxResults *int64 `json:"maxResults,omitempty"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *SearchQuery) UnmarshalJSON(data []byte) error { + type wire SearchQuery + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "text", "matchCase", "wholeWord", "isRegex", "fuzzy", "targets", "maxResults") +} + +func (v SearchQuery) MarshalJSON() ([]byte, error) { + type wire SearchQuery + return marshalWithExtra(wire(v), v.Extra, "text", "matchCase", "wholeWord", "isRegex", "fuzzy", "targets", "maxResults") +} + +// Searches file paths under {@link FileSearchTargetBase.roots}. +// +// The host decides how to match {@link SearchQuery.text} against file paths, +// for example with fuzzy matching, and which query options apply. Results +// are {@link FileNameSearchResult}s. +// +// Stability: 1.0 - Early development. +type FileNamesSearchTarget struct { + // The folders to search. MUST contain at least one URI. + Roots []URI `json:"roots"` + // Glob patterns relative to a root. When present, only matching files are searched. + Includes []string `json:"includes,omitempty"` + // Glob patterns relative to a root. Matching files are not searched. + Excludes []string `json:"excludes,omitempty"` + // Also search files that the host's ignore rules, such as `.gitignore` + // files, would otherwise skip. Defaults to `false`. `excludes` still apply. + IncludeIgnored *bool `json:"includeIgnored,omitempty"` + Kind SearchTargetKind `json:"kind"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *FileNamesSearchTarget) UnmarshalJSON(data []byte) error { + type wire FileNamesSearchTarget + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "roots", "includes", "excludes", "includeIgnored", "kind") +} + +func (v FileNamesSearchTarget) MarshalJSON() ([]byte, error) { + type wire FileNamesSearchTarget + return marshalWithExtra(wire(v), v.Extra, "roots", "includes", "excludes", "includeIgnored", "kind") +} + +// Searches the text content of files under {@link FileSearchTargetBase.roots}. +// Results are {@link FileTextSearchResult}s. +// +// Stability: 1.0 - Early development. +type FileTextSearchTarget struct { + // The folders to search. MUST contain at least one URI. + Roots []URI `json:"roots"` + // Glob patterns relative to a root. When present, only matching files are searched. + Includes []string `json:"includes,omitempty"` + // Glob patterns relative to a root. Matching files are not searched. + Excludes []string `json:"excludes,omitempty"` + // Also search files that the host's ignore rules, such as `.gitignore` + // files, would otherwise skip. Defaults to `false`. `excludes` still apply. + IncludeIgnored *bool `json:"includeIgnored,omitempty"` + Kind SearchTargetKind `json:"kind"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *FileTextSearchTarget) UnmarshalJSON(data []byte) error { + type wire FileTextSearchTarget + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "roots", "includes", "excludes", "includeIgnored", "kind") +} + +func (v FileTextSearchTarget) MarshalJSON() ([]byte, error) { + type wire FileTextSearchTarget + return marshalWithExtra(wire(v), v.Extra, "roots", "includes", "excludes", "includeIgnored", "kind") +} + +// Searches the host's sessions, the same sessions that `listSessions` +// returns. The host decides which session content it matches, for example +// titles or requests. Results are {@link SessionSearchResult}s. +// +// Stability: 1.0 - Early development. +type SessionsSearchTarget struct { + Kind SearchTargetKind `json:"kind"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *SessionsSearchTarget) UnmarshalJSON(data []byte) error { + type wire SessionsSearchTarget + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind") +} + +func (v SessionsSearchTarget) MarshalJSON() ([]byte, error) { + type wire SessionsSearchTarget + return marshalWithExtra(wire(v), v.Extra, "kind") +} + +// Searches the visible text of chat requests and responses, including the +// responses of deferred turns. Results are +// {@link ChatMessageSearchResult}s. +// +// Stability: 1.0 - Early development. +type ChatMessagesSearchTarget struct { + Kind SearchTargetKind `json:"kind"` + // The chats to search. MUST contain at least one chat URI. + Chats []URI `json:"chats"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ChatMessagesSearchTarget) UnmarshalJSON(data []byte) error { + type wire ChatMessagesSearchTarget + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind", "chats") +} + +func (v ChatMessagesSearchTarget) MarshalJSON() ([]byte, error) { + type wire ChatMessagesSearchTarget + return marshalWithExtra(wire(v), v.Extra, "kind", "chats") +} + +// A matched span within {@link SearchMatch.text}: the half-open interval +// `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code +// units, as in {@link CompletionItem.rangeStart}. +// +// Stability: 1.0 - Early development. +type SearchHighlight struct { + // The start of the span. + RangeStart int64 `json:"rangeStart"` + // The end of the span, exclusive. MUST be greater than {@link rangeStart} + // and at most the length of {@link SearchMatch.text}. + RangeEnd int64 `json:"rangeEnd"` +} + +// The matched text of a result, with the matched spans highlighted. The host +// chooses how much text around the match to include. +// +// Stability: 1.0 - Early development. +type SearchMatch struct { + // The text to display. + Text string `json:"text"` + // The matched spans, in order. Spans MUST NOT overlap. + Highlights []SearchHighlight `json:"highlights"` +} + +// A file whose path matches. {@link SearchResultBase.resource} is the file; +// the match text is its path, usually relative to the root that contains it. +// +// Stability: 1.0 - Early development. +type FileNameSearchResult struct { + // The resource that contains the match. + Resource URI `json:"resource"` + // The text to display, with the matched spans highlighted. + Match SearchMatch `json:"match"` + // How well the result matches; higher is better. Scores have no fixed + // range, and are comparable across all results of one search. Clients + // SHOULD show results in descending score order. A host that does not rank + // results omits the score. + Score *float64 `json:"score,omitempty"` + Kind SearchResultKind `json:"kind"` +} + +// A match in the text of a file. {@link SearchResultBase.resource} is the +// file; the match text is the text around the match, usually its line. +// +// Stability: 1.0 - Early development. +type FileTextSearchResult struct { + // The resource that contains the match. + Resource URI `json:"resource"` + // The text to display, with the matched spans highlighted. + Match SearchMatch `json:"match"` + // How well the result matches; higher is better. Scores have no fixed + // range, and are comparable across all results of one search. Clients + // SHOULD show results in descending score order. A host that does not rank + // results omits the score. + Score *float64 `json:"score,omitempty"` + Kind SearchResultKind `json:"kind"` + // The location of the match in the file. + Range TextRange `json:"range"` +} + +// A session whose content matches. {@link SearchResultBase.resource} is the +// session URI. +// +// Stability: 1.0 - Early development. +type SessionSearchResult struct { + // The resource that contains the match. + Resource URI `json:"resource"` + // The text to display, with the matched spans highlighted. + Match SearchMatch `json:"match"` + // How well the result matches; higher is better. Scores have no fixed + // range, and are comparable across all results of one search. Clients + // SHOULD show results in descending score order. A host that does not rank + // results omits the score. + Score *float64 `json:"score,omitempty"` + Kind SearchResultKind `json:"kind"` + // The session's title. + Title string `json:"title"` +} + +// A match in a chat request or response. {@link SearchResultBase.resource} +// is the chat URI. +// +// Stability: 1.0 - Early development. +type ChatMessageSearchResult struct { + // The resource that contains the match. + Resource URI `json:"resource"` + // The text to display, with the matched spans highlighted. + Match SearchMatch `json:"match"` + // How well the result matches; higher is better. Scores have no fixed + // range, and are comparable across all results of one search. Clients + // SHOULD show results in descending score order. A host that does not rank + // results omits the score. + Score *float64 `json:"score,omitempty"` + Kind SearchResultKind `json:"kind"` + // The chat's title. + Title string `json:"title"` + // The ID of the turn that contains the match. + TurnId string `json:"turnId"` +} + +// The query changed and the host has not replaced the results yet. Clients +// MAY show the previous query's results differently, for example dimmed. +// +// Stability: 1.0 - Early development. +type SearchPendingLifecycleState struct { + Status SearchLifecycleStatus `json:"status"` +} + +// The host is searching and may add more results. +// +// Stability: 1.0 - Early development. +type SearchRunningLifecycleState struct { + Status SearchLifecycleStatus `json:"status"` +} + +// The host found every result for the query. A host that watches the +// searched files, sessions, or chats MAY still change the results later. +// +// Stability: 1.0 - Early development. +type SearchCompletedLifecycleState struct { + Status SearchLifecycleStatus `json:"status"` + // Why the search completed. + Reason SearchCompletionReason `json:"reason"` +} + +// The search failed. Results found before the failure remain in +// {@link SearchState.results}. +// +// Stability: 1.0 - Early development. +type SearchFailedLifecycleState struct { + Status SearchLifecycleStatus `json:"status"` + // Why the search failed, for example an invalid regular expression. + Error ErrorInfo `json:"error"` +} + +// Full state for one search, returned when a client subscribes to its +// `ahp-search:` URI. +// +// Stability: 1.0 - Early development. +type SearchState struct { + // The current query. + Query SearchQuery `json:"query"` + // Results in the order the host found them. Sort by + // {@link SearchResultBase.score} to rank them. While {@link lifecycle} is + // {@link SearchLifecycleStatus.Pending | pending}, these are results for the + // previous query. + Results []SearchResult `json:"results"` + // Where the search is in its lifecycle. + Lifecycle SearchLifecycleState `json:"lifecycle"` +} + // ─── Customization Enablement Union ─────────────────────────────────────── // CustomizationEnablement is a single explicit customization enablement decision. @@ -7339,6 +7703,249 @@ func (u AutomationRunLifecycle) MarshalJSON() ([]byte, error) { return json.Marshal(object) } +// SearchTarget is one place to search. +type SearchTarget struct { + Value isSearchTarget +} + +// isSearchTarget is the marker interface implemented by every +// concrete variant of SearchTarget. +type isSearchTarget interface{ isSearchTarget() } + +func (*FileNamesSearchTarget) isSearchTarget() {} +func (*FileTextSearchTarget) isSearchTarget() {} +func (*SessionsSearchTarget) isSearchTarget() {} +func (*ChatMessagesSearchTarget) isSearchTarget() {} + +// SearchTargetUnknown carries an unrecognized SearchTarget variant — typically a discriminator value introduced by a newer protocol version. The original JSON object is preserved verbatim so that re-encoding round-trips faithfully. +type SearchTargetUnknown struct { + Raw json.RawMessage +} + +func (*SearchTargetUnknown) isSearchTarget() {} + +// UnmarshalJSON decodes the variant indicated by the "kind" discriminator. +func (u *SearchTarget) UnmarshalJSON(data []byte) error { + disc, _, err := readDiscriminator(data, "kind") + if err != nil { + return err + } + switch disc { + case "fileNames": + var value FileNamesSearchTarget + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "fileText": + var value FileTextSearchTarget + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "sessions": + var value SessionsSearchTarget + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "chatMessages": + var value ChatMessagesSearchTarget + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + default: + raw := make(json.RawMessage, len(data)) + copy(raw, data) + u.Value = &SearchTargetUnknown{Raw: raw} + } + return nil +} + +// MarshalJSON encodes the active variant back to JSON. +func (u SearchTarget) MarshalJSON() ([]byte, error) { + if unk, ok := u.Value.(*SearchTargetUnknown); ok { + if len(unk.Raw) == 0 { + return []byte("null"), nil + } + return unk.Raw, nil + } + if u.Value == nil { + return []byte("null"), nil + } + return json.Marshal(u.Value) +} + +// SearchResult is one search match. +type SearchResult struct { + Value isSearchResult +} + +// isSearchResult is the marker interface implemented by every +// concrete variant of SearchResult. +type isSearchResult interface{ isSearchResult() } + +func (*FileNameSearchResult) isSearchResult() {} +func (*FileTextSearchResult) isSearchResult() {} +func (*SessionSearchResult) isSearchResult() {} +func (*ChatMessageSearchResult) isSearchResult() {} + +// SearchResultUnknown carries an unrecognized SearchResult variant — typically a discriminator value introduced by a newer protocol version. The original JSON object is preserved verbatim so that re-encoding round-trips faithfully. +type SearchResultUnknown struct { + Raw json.RawMessage +} + +func (*SearchResultUnknown) isSearchResult() {} + +// UnmarshalJSON decodes the variant indicated by the "kind" discriminator. +func (u *SearchResult) UnmarshalJSON(data []byte) error { + disc, _, err := readDiscriminator(data, "kind") + if err != nil { + return err + } + switch disc { + case "fileName": + var value FileNameSearchResult + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "fileText": + var value FileTextSearchResult + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "session": + var value SessionSearchResult + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "chatMessage": + var value ChatMessageSearchResult + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + default: + raw := make(json.RawMessage, len(data)) + copy(raw, data) + u.Value = &SearchResultUnknown{Raw: raw} + } + return nil +} + +// MarshalJSON encodes the active variant back to JSON. +func (u SearchResult) MarshalJSON() ([]byte, error) { + if unk, ok := u.Value.(*SearchResultUnknown); ok { + if len(unk.Raw) == 0 { + return []byte("null"), nil + } + return unk.Raw, nil + } + if u.Value == nil { + return []byte("null"), nil + } + return json.Marshal(u.Value) +} + +// SearchLifecycleState is the lifecycle of a search. +type SearchLifecycleState struct { + Value isSearchLifecycleState +} + +// isSearchLifecycleState is the marker interface implemented by every +// concrete variant of SearchLifecycleState. +type isSearchLifecycleState interface{ isSearchLifecycleState() } + +func (*SearchPendingLifecycleState) isSearchLifecycleState() {} +func (*SearchRunningLifecycleState) isSearchLifecycleState() {} +func (*SearchCompletedLifecycleState) isSearchLifecycleState() {} +func (*SearchFailedLifecycleState) isSearchLifecycleState() {} + +// SearchLifecycleStateUnknown carries an unrecognized SearchLifecycleState variant — typically a discriminator value introduced by a newer protocol version. The original JSON object is preserved verbatim so that re-encoding round-trips faithfully. +type SearchLifecycleStateUnknown struct { + Raw json.RawMessage +} + +func (*SearchLifecycleStateUnknown) isSearchLifecycleState() {} + +// UnmarshalJSON decodes the variant indicated by the "status" discriminator. +func (u *SearchLifecycleState) UnmarshalJSON(data []byte) error { + disc, _, err := readDiscriminator(data, "status") + if err != nil { + return err + } + switch disc { + case "pending": + var value SearchPendingLifecycleState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "running": + var value SearchRunningLifecycleState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "completed": + var value SearchCompletedLifecycleState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "failed": + var value SearchFailedLifecycleState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + default: + raw := make(json.RawMessage, len(data)) + copy(raw, data) + u.Value = &SearchLifecycleStateUnknown{Raw: raw} + } + return nil +} + +// MarshalJSON encodes the active variant back to JSON. +func (u SearchLifecycleState) MarshalJSON() ([]byte, error) { + if unk, ok := u.Value.(*SearchLifecycleStateUnknown); ok { + if len(unk.Raw) == 0 { + return []byte("null"), nil + } + return unk.Raw, nil + } + if u.Value == nil { + return []byte("null"), nil + } + data, err := json.Marshal(u.Value) + if err != nil { + return nil, err + } + var object map[string]json.RawMessage + if err := json.Unmarshal(data, &object); err != nil { + return nil, err + } + if object == nil { + return data, nil + } + switch u.Value.(type) { + case *SearchPendingLifecycleState: + object["status"] = json.RawMessage("\"pending\"") + case *SearchRunningLifecycleState: + object["status"] = json.RawMessage("\"running\"") + case *SearchCompletedLifecycleState: + object["status"] = json.RawMessage("\"completed\"") + case *SearchFailedLifecycleState: + object["status"] = json.RawMessage("\"failed\"") + } + return json.Marshal(object) +} + // MarshalJSON encodes the deferred turn with its `"isDeferred": true` marker. func (v DeferredTurn) MarshalJSON() ([]byte, error) { type wire DeferredTurn @@ -7516,11 +8123,11 @@ func (o ChatOrigin) MarshalJSON() ([]byte, error) { // SnapshotState is the state payload of a snapshot — root, session, // chat, canvas, terminal, changeset, resource-watch, annotations, automation catalogue, -// automation-run, or empty state. The active +// automation-run, search, or empty state. The active // variant is chosen by which pointer field is non-nil; UnmarshalJSON probes // for required fields in the canonical order -// (empty → automationRun → automations → session → chat → canvas → terminal → -// changeset → resourceWatch → annotations → root). An object with no members +// (empty → automationRun → automations → search → session → chat → canvas → +// terminal → changeset → resourceWatch → annotations → root). An object with no members // is an empty state, used by channels whose state has no fields. A state that // matches none of these, such as the state of a channel added in a later // protocol version, is kept as raw JSON in Unknown. @@ -7537,6 +8144,7 @@ type SnapshotState struct { Annotations *AnnotationsState `json:"-"` Automations *AutomationState `json:"-"` AutomationRun *AutomationRunState `json:"-"` + Search *SearchState `json:"-"` } // MarshalJSON encodes whichever variant is currently populated. @@ -7554,6 +8162,8 @@ func (s SnapshotState) MarshalJSON() ([]byte, error) { return json.Marshal(s.Chat) case s.Canvas != nil: return json.Marshal(s.Canvas) + case s.Search != nil: + return json.Marshal(s.Search) case s.Terminal != nil: return json.Marshal(s.Terminal) case s.Changeset != nil: @@ -7594,6 +8204,13 @@ func (s *SnapshotState) UnmarshalJSON(data []byte) error { return err } s.Automations = &v + // SearchState also has a required `lifecycle`, so probe it before SessionState. + case containsAll(probe, "query", "results"): + var v SearchState + if err := json.Unmarshal(data, &v); err != nil { + return err + } + s.Search = &v case containsAll(probe, "lifecycle"): var v SessionState if err := json.Unmarshal(data, &v); err != nil { diff --git a/clients/kotlin/AGENTS.md b/clients/kotlin/AGENTS.md index dab6b5f04..f90b0c44a 100644 --- a/clients/kotlin/AGENTS.md +++ b/clients/kotlin/AGENTS.md @@ -23,7 +23,7 @@ CI verifies the committed generated files match the output of `npm run generate: ## Library structure - `src/main/kotlin/com/microsoft/agenthostprotocol/Ahp.kt` — Hand-maintained entry point. Exposes the configured `kotlinx.serialization.json.Json` instance (`Ahp.json`) that consumers MUST use to encode/decode protocol messages. The custom `KSerializer`s for discriminated unions require a JSON-aware encoder/decoder, so generic `Json` instances may not work. -- `src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt` — Hand-written pure reducers (`rootReducer`, `sessionReducer`, `chatReducer`, `terminalReducer`, `changesetReducer`, `annotationsReducer`, `resourceWatchReducer`) ported from `types/channels-*/reducer.ts`, plus a small `Reducer` fun-interface and per-channel `object` wrappers. See [Reducers](#reducers) below. +- `src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt` — Hand-written pure reducers (`rootReducer`, `sessionReducer`, `chatReducer`, `terminalReducer`, `changesetReducer`, `annotationsReducer`, `resourceWatchReducer`, `searchReducer`) ported from `types/channels-*/reducer.ts`, plus a small `Reducer` fun-interface and per-channel `object` wrappers. See [Reducers](#reducers) below. - `src/main/kotlin/com/microsoft/agenthostprotocol/generated/` — Auto-generated wire types. - `build.gradle.kts` — Gradle build config. Sets `jvmTarget = JVM_1_8` (Android-friendly) with a JDK 17 toolchain. Configures the Vanniktech `maven-publish` plugin for Sonatype Central Portal publishing. Also wires the absolute path of `types/test-cases/reducers/` into the test JVM as the `ahp.reducerFixturesDir` system property so `FixtureDrivenReducerTest` can load fixtures regardless of cwd. - `gradle.properties` — Source of truth for the artifact's Maven coordinates (`GROUP`, `VERSION_NAME`) and POM metadata. @@ -147,6 +147,7 @@ public fun terminalReducer(state: TerminalState, action: StateAction): TerminalS public fun changesetReducer(state: ChangesetState, action: StateAction): ChangesetState public fun annotationsReducer(state: AnnotationsState, action: StateAction): AnnotationsState public fun resourceWatchReducer(state: ResourceWatchState, action: StateAction): ResourceWatchState +public fun searchReducer(state: SearchState, action: StateAction): SearchState public fun interface Reducer { public fun reduce(state: S, action: A): S } public object RootReducer : Reducer // delegates to rootReducer @@ -156,6 +157,7 @@ public object TerminalReducer : Reducer public object ChangesetReducer : Reducer public object AnnotationsReducer : Reducer public object ResourceWatchReducer : Reducer +public object SearchReducer : Reducer ``` Each reducer dispatches on the [`StateAction`] sealed interface and handles the action variants that belong to its channel. Actions belonging to other channels (or unknown `StateActionUnknown` variants returned by the wire-types decoder when the server sends a newer action type than this version of the client knows about) fall through to an `else -> state` no-op — this matches the forward-compatibility semantics of the canonical TypeScript and Swift reducers. diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index 3047adbb0..239aed5b9 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -21,10 +21,10 @@ import kotlinx.serialization.json.JsonPrimitive * * The companion top-level functions ([rootReducer], [sessionReducer], [chatReducer], [canvasReducer], * [terminalReducer], [changesetReducer], [annotationsReducer], [resourceWatchReducer], - * [automationReducer], and [automationRunReducer]) are the canonical implementations. + * [searchReducer], [automationReducer], and [automationRunReducer]) are the canonical implementations. * The object instances on this interface ([RootReducer], [SessionReducer], [ChatReducer], [CanvasReducer], * [TerminalReducer], [ChangesetReducer], [AnnotationsReducer], [ResourceWatchReducer], - * [AutomationReducer], and [AutomationRunReducer]) wrap them for use as values where an + * [SearchReducer], [AutomationReducer], and [AutomationRunReducer]) wrap them for use as values where an * instance is needed. */ public fun interface Reducer { @@ -79,6 +79,12 @@ public object ResourceWatchReducer : Reducer { resourceWatchReducer(state, action) } +/** Pure search reducer as a [Reducer] instance. Delegates to [searchReducer]. */ +public object SearchReducer : Reducer { + override fun reduce(state: SearchState, action: StateAction): SearchState = + searchReducer(state, action) +} + /** Pure automation reducer as a [Reducer] instance. Delegates to [automationReducer]. */ public object AutomationReducer : Reducer { override fun reduce(state: AutomationState, action: StateAction): AutomationState = @@ -2020,6 +2026,34 @@ public fun resourceWatchReducer(state: ResourceWatchState, action: StateAction): else -> state } +// ─── Search Reducer ───────────────────────────────────────────────────────── + +/** + * Pure reducer for [SearchState]. Handles the search-channel action variants; + * actions belonging to other channels (or unknown variants) return [state] + * unchanged. + */ +public fun searchReducer(state: SearchState, action: StateAction): SearchState = when (action) { + is StateActionSearchQueryChanged -> state.copy( + query = action.value.query, + lifecycle = SearchLifecycleStatePending(SearchPendingLifecycleState(status = SearchLifecycleStatus.PENDING)), + ) + is StateActionSearchResultsChanged -> if (action.value.replace != true) { + state.copy(results = state.results + action.value.results) + } else { + state.copy( + results = action.value.results, + lifecycle = if (state.lifecycle is SearchLifecycleStatePending) { + SearchLifecycleStateRunning(SearchRunningLifecycleState(status = SearchLifecycleStatus.RUNNING)) + } else { + state.lifecycle + }, + ) + } + is StateActionSearchLifecycleChanged -> state.copy(lifecycle = action.value.lifecycle) + else -> state +} + // ─── Automation Reducer ───────────────────────────────────────────────────── /** Pure reducer for [AutomationState]. Handles automation-channel action variants. */ diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 157007e09..60abc817a 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -129,6 +129,9 @@ value class ActionType(val rawValue: String) { val TERMINAL_COMMAND_EXECUTED: ActionType = ActionType("terminal/commandExecuted") val TERMINAL_COMMAND_FINISHED: ActionType = ActionType("terminal/commandFinished") val RESOURCE_WATCH_CHANGED: ActionType = ActionType("resourceWatch/changed") + val SEARCH_QUERY_CHANGED: ActionType = ActionType("search/queryChanged") + val SEARCH_RESULTS_CHANGED: ActionType = ActionType("search/resultsChanged") + val SEARCH_LIFECYCLE_CHANGED: ActionType = ActionType("search/lifecycleChanged") val AUTOMATION_CREATE_REQUESTED: ActionType = ActionType("automation/createRequested") val AUTOMATION_UPDATE_REQUESTED: ActionType = ActionType("automation/updateRequested") val AUTOMATION_SET: ActionType = ActionType("automation/set") @@ -1642,6 +1645,85 @@ data class ResourceWatchChangedAction( val changes: JsonElement ) +/** + * Replaces the search's query and restarts the search. + * + * Keeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to + * {@link SearchLifecycleStatus.Pending | pending}. The old results stay + * visible until the host replaces them, so the client does not flash an empty + * list. + * + * After the host applies this action, it stops the previous search and drops + * any of its results that it has not dispatched yet. The host MUST then + * dispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with + * `replace: true` before any other search action. The replacement can keep + * old results that still match the new query, and can be empty. If the new + * query is not valid, + * for example because it contains an invalid regular expression, the host + * replaces the results with an empty list and then changes the lifecycle to + * {@link SearchLifecycleStatus.Failed | failed}. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchQueryChangedAction( + val type: ActionType, + /** + * The new query. + */ + val query: SearchQuery +) + +/** + * Adds results to {@link SearchState.results}, or replaces them. + * + * By default, the reducer appends `results`. Set `replace` to `true` to + * replace every result instead; if {@link SearchState.lifecycle} is + * {@link SearchLifecycleStatus.Pending | pending}, a replacement also changes + * it to {@link SearchLifecycleStatus.Running | running}. + * + * The host MUST dispatch a replacement first after a + * {@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also + * replace the results at other times, for example to re-rank them, to remove + * duplicates, or to update a completed search when a watched file changes. + * The host MUST NOT dispatch an empty `results` list unless `replace` is + * `true`. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchResultsChangedAction( + val type: ActionType, + /** + * The results to append, in the order the host found them, or the replacement results. + */ + val results: List, + /** + * When `true`, replaces every result instead of appending. + */ + val replace: Boolean? = null +) + +/** + * Replaces {@link SearchState.lifecycle}. + * + * The host dispatches this to complete or fail a search, or to move a + * completed search back to {@link SearchLifecycleStatus.Running | running} when it + * searches again, for example after a watched file changes. The host MUST NOT + * change the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only + * {@link SearchQueryChangedAction | `search/queryChanged`} does that. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchLifecycleChangedAction( + val type: ActionType, + /** + * The new lifecycle. + */ + val lifecycle: SearchLifecycleState +) + @Serializable data class AutomationCreateRequestedAction( val type: ActionType, @@ -1903,6 +1985,9 @@ sealed interface StateAction @JvmInline value class StateActionTerminalCommandExecuted(val value: TerminalCommandExecutedAction) : StateAction @JvmInline value class StateActionTerminalCommandFinished(val value: TerminalCommandFinishedAction) : StateAction @JvmInline value class StateActionResourceWatchChanged(val value: ResourceWatchChangedAction) : StateAction +@JvmInline value class StateActionSearchQueryChanged(val value: SearchQueryChangedAction) : StateAction +@JvmInline value class StateActionSearchResultsChanged(val value: SearchResultsChangedAction) : StateAction +@JvmInline value class StateActionSearchLifecycleChanged(val value: SearchLifecycleChangedAction) : StateAction @JvmInline value class StateActionAutomationCreateRequested(val value: AutomationCreateRequestedAction) : StateAction @JvmInline value class StateActionAutomationUpdateRequested(val value: AutomationUpdateRequestedAction) : StateAction @JvmInline value class StateActionAutomationSet(val value: AutomationSetAction) : StateAction @@ -2027,6 +2112,9 @@ internal object StateActionSerializer : KSerializer { "terminal/commandExecuted" -> StateActionTerminalCommandExecuted(input.json.decodeFromJsonElement(TerminalCommandExecutedAction.serializer(), element)) "terminal/commandFinished" -> StateActionTerminalCommandFinished(input.json.decodeFromJsonElement(TerminalCommandFinishedAction.serializer(), element)) "resourceWatch/changed" -> StateActionResourceWatchChanged(input.json.decodeFromJsonElement(ResourceWatchChangedAction.serializer(), element)) + "search/queryChanged" -> StateActionSearchQueryChanged(input.json.decodeFromJsonElement(SearchQueryChangedAction.serializer(), element)) + "search/resultsChanged" -> StateActionSearchResultsChanged(input.json.decodeFromJsonElement(SearchResultsChangedAction.serializer(), element)) + "search/lifecycleChanged" -> StateActionSearchLifecycleChanged(input.json.decodeFromJsonElement(SearchLifecycleChangedAction.serializer(), element)) "automation/createRequested" -> StateActionAutomationCreateRequested(input.json.decodeFromJsonElement(AutomationCreateRequestedAction.serializer(), element)) "automation/updateRequested" -> StateActionAutomationUpdateRequested(input.json.decodeFromJsonElement(AutomationUpdateRequestedAction.serializer(), element)) "automation/set" -> StateActionAutomationSet(input.json.decodeFromJsonElement(AutomationSetAction.serializer(), element)) @@ -2144,6 +2232,9 @@ internal object StateActionSerializer : KSerializer { is StateActionTerminalCommandExecuted -> output.json.encodeToJsonElement(TerminalCommandExecutedAction.serializer(), value.value) is StateActionTerminalCommandFinished -> output.json.encodeToJsonElement(TerminalCommandFinishedAction.serializer(), value.value) is StateActionResourceWatchChanged -> output.json.encodeToJsonElement(ResourceWatchChangedAction.serializer(), value.value) + is StateActionSearchQueryChanged -> output.json.encodeToJsonElement(SearchQueryChangedAction.serializer(), value.value) + is StateActionSearchResultsChanged -> output.json.encodeToJsonElement(SearchResultsChangedAction.serializer(), value.value) + is StateActionSearchLifecycleChanged -> output.json.encodeToJsonElement(SearchLifecycleChangedAction.serializer(), value.value) is StateActionAutomationCreateRequested -> output.json.encodeToJsonElement(AutomationCreateRequestedAction.serializer(), value.value) is StateActionAutomationUpdateRequested -> output.json.encodeToJsonElement(AutomationUpdateRequestedAction.serializer(), value.value) is StateActionAutomationSet -> output.json.encodeToJsonElement(AutomationSetAction.serializer(), value.value) diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt index f12f81ddc..93708ea3a 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt @@ -526,6 +526,13 @@ data class InitializeResult( * Stability: 1.0 - Early development. */ val tcpConnections: TcpConnectionsCapability? = null, + /** + * Present when the host supports `createSearch`, which searches files, + * sessions, and chats and streams the results on an `ahp-search:` channel. + * + * Stability: 1.0 - Early development. + */ + val search: SearchCapability? = null, /** * Present when chats in one session may be backed by different agent * providers (see {@link CreateChatParams.provider} and @@ -1574,6 +1581,48 @@ data class CreateResourceWatchResult( val channel: String ) +/** + * Starts a search on the host. + * + * The client chooses the channel URI and then subscribes to it to receive the + * search's {@link SearchState} and its results. The client replaces the query + * by dispatching {@link SearchQueryChangedAction | `search/queryChanged`}, + * and cancels the search by unsubscribing. + * + * The client MUST NOT send this command unless `InitializeResult.search` is + * present, and MUST NOT include a target whose kind is not listed in + * {@link SearchCapability.targets}. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class CreateSearchParams( + /** + * Channel URI this command targets. + */ + val channel: String, + /** + * Optional JSON-serializable metadata associated with this request. + * Receivers MUST ignore keys they do not understand. + */ + @SerialName("_meta") + val meta: Map? = null, + /** + * What to search for and where. + */ + val query: SearchQuery +) + +/** + * Result of the `createSearch` command. + * + * An empty object on success. + * + * Stability: 1.0 - Early development. + */ +@Serializable +class CreateSearchResult + /** * Requests that the host load older historical turns into a chat state. * diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/State.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/State.generated.kt index 3851f1932..b7db214d7 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/State.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/State.generated.kt @@ -1293,6 +1293,139 @@ enum class AutomationRunOriginKind { TRIGGER } +/** + * Discriminant for {@link SearchTarget}. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = SearchTargetKindSerializer::class) +@JvmInline +value class SearchTargetKind(val rawValue: String) { + companion object { + /** + * File paths. + */ + val FILE_NAMES: SearchTargetKind = SearchTargetKind("fileNames") + /** + * The text content of files. + */ + val FILE_TEXT: SearchTargetKind = SearchTargetKind("fileText") + /** + * The host's sessions. + */ + val SESSIONS: SearchTargetKind = SearchTargetKind("sessions") + /** + * The text of chat requests and responses. + */ + val CHAT_MESSAGES: SearchTargetKind = SearchTargetKind("chatMessages") + } +} + +internal object SearchTargetKindSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("SearchTargetKind", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: SearchTargetKind) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): SearchTargetKind = + SearchTargetKind(decoder.decodeString()) +} + +/** + * Discriminant for {@link SearchResult}. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = SearchResultKindSerializer::class) +@JvmInline +value class SearchResultKind(val rawValue: String) { + companion object { + val FILE_NAME: SearchResultKind = SearchResultKind("fileName") + val FILE_TEXT: SearchResultKind = SearchResultKind("fileText") + val SESSION: SearchResultKind = SearchResultKind("session") + val CHAT_MESSAGE: SearchResultKind = SearchResultKind("chatMessage") + } +} + +internal object SearchResultKindSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("SearchResultKind", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: SearchResultKind) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): SearchResultKind = + SearchResultKind(decoder.decodeString()) +} + +/** + * Lifecycle status of a search. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = SearchLifecycleStatusSerializer::class) +@JvmInline +value class SearchLifecycleStatus(val rawValue: String) { + companion object { + /** + * The query changed and the host has not replaced the results yet. + * {@link SearchState.results} belong to the previous query. + */ + val PENDING: SearchLifecycleStatus = SearchLifecycleStatus("pending") + /** + * The host is searching. + */ + val RUNNING: SearchLifecycleStatus = SearchLifecycleStatus("running") + /** + * The host found every result for the query. + */ + val COMPLETED: SearchLifecycleStatus = SearchLifecycleStatus("completed") + /** + * The search failed. + */ + val FAILED: SearchLifecycleStatus = SearchLifecycleStatus("failed") + } +} + +internal object SearchLifecycleStatusSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("SearchLifecycleStatus", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: SearchLifecycleStatus) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): SearchLifecycleStatus = + SearchLifecycleStatus(decoder.decodeString()) +} + +/** + * Why a search completed. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = SearchCompletionReasonSerializer::class) +@JvmInline +value class SearchCompletionReason(val rawValue: String) { + companion object { + /** + * The host searched every target. + */ + val EXHAUSTED: SearchCompletionReason = SearchCompletionReason("exhausted") + /** + * The host stopped at the result limit. More results may exist. + */ + val LIMIT_REACHED: SearchCompletionReason = SearchCompletionReason("limitReached") + } +} + +internal object SearchCompletionReasonSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("SearchCompletionReason", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: SearchCompletionReason) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): SearchCompletionReason = + SearchCompletionReason(decoder.decodeString()) +} + // ─── State Types ──────────────────────────────────────────────────────────── /** @@ -6937,6 +7070,433 @@ data class AutomationRunState( val meta: Map? = null ) +/** + * Present when the host supports `createSearch`. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchCapability( + /** + * The target kinds the host can search. A client MUST NOT send a + * {@link SearchTarget} whose kind is not listed here. + */ + val targets: List +) + +/** + * What a search looks for and where. + * + * The client sends a query in `createSearch` and replaces it with + * {@link SearchQueryChangedAction | `search/queryChanged`}. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = SearchQuerySerializer::class) +data class SearchQuery( + /** + * The text to search for. Its meaning depends on the target: see + * {@link SearchTarget}. An empty `text` matches nothing; the host completes + * the search with no results. + */ + val text: String, + /** + * Match case. Defaults to `false`. + */ + val matchCase: Boolean? = null, + /** + * Match only whole words. Defaults to `false`. + */ + val wholeWord: Boolean? = null, + /** + * Treat `text` as a regular expression. Defaults to `false`. + */ + val isRegex: Boolean? = null, + /** + * A hint that precise matching isn't expected, for example because the + * search powers a quick-find picker. The host MAY then match loosely, rank + * results by how well they match, and ignore {@link isRegex} and + * {@link wholeWord}. Defaults to `false`. + */ + val fuzzy: Boolean? = null, + /** + * Where to search. MUST contain at least one target. + */ + val targets: List, + /** + * The maximum number of results. The host MAY apply a lower limit, and + * completes the search with {@link SearchCompletionReason.LimitReached} + * when it reaches the limit that applies. + */ + val maxResults: Long? = null, + @Transient + val extra: Map = emptyMap() +) + +internal object SearchQuerySerializer : UnknownMembersSerializer( + SearchQuery.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * Searches file paths under {@link FileSearchTargetBase.roots}. + * + * The host decides how to match {@link SearchQuery.text} against file paths, + * for example with fuzzy matching, and which query options apply. Results + * are {@link FileNameSearchResult}s. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = FileNamesSearchTargetSerializer::class) +data class FileNamesSearchTarget( + /** + * The folders to search. MUST contain at least one URI. + */ + val roots: List, + /** + * Glob patterns relative to a root. When present, only matching files are searched. + */ + val includes: List? = null, + /** + * Glob patterns relative to a root. Matching files are not searched. + */ + val excludes: List? = null, + /** + * Also search files that the host's ignore rules, such as `.gitignore` + * files, would otherwise skip. Defaults to `false`. `excludes` still apply. + */ + val includeIgnored: Boolean? = null, + val kind: SearchTargetKind, + @Transient + val extra: Map = emptyMap() +) + +internal object FileNamesSearchTargetSerializer : UnknownMembersSerializer( + FileNamesSearchTarget.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * Searches the text content of files under {@link FileSearchTargetBase.roots}. + * Results are {@link FileTextSearchResult}s. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = FileTextSearchTargetSerializer::class) +data class FileTextSearchTarget( + /** + * The folders to search. MUST contain at least one URI. + */ + val roots: List, + /** + * Glob patterns relative to a root. When present, only matching files are searched. + */ + val includes: List? = null, + /** + * Glob patterns relative to a root. Matching files are not searched. + */ + val excludes: List? = null, + /** + * Also search files that the host's ignore rules, such as `.gitignore` + * files, would otherwise skip. Defaults to `false`. `excludes` still apply. + */ + val includeIgnored: Boolean? = null, + val kind: SearchTargetKind, + @Transient + val extra: Map = emptyMap() +) + +internal object FileTextSearchTargetSerializer : UnknownMembersSerializer( + FileTextSearchTarget.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * Searches the host's sessions, the same sessions that `listSessions` + * returns. The host decides which session content it matches, for example + * titles or requests. Results are {@link SessionSearchResult}s. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = SessionsSearchTargetSerializer::class) +data class SessionsSearchTarget( + val kind: SearchTargetKind, + @Transient + val extra: Map = emptyMap() +) + +internal object SessionsSearchTargetSerializer : UnknownMembersSerializer( + SessionsSearchTarget.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * Searches the visible text of chat requests and responses, including the + * responses of deferred turns. Results are + * {@link ChatMessageSearchResult}s. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ChatMessagesSearchTargetSerializer::class) +data class ChatMessagesSearchTarget( + val kind: SearchTargetKind, + /** + * The chats to search. MUST contain at least one chat URI. + */ + val chats: List, + @Transient + val extra: Map = emptyMap() +) + +internal object ChatMessagesSearchTargetSerializer : UnknownMembersSerializer( + ChatMessagesSearchTarget.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * A matched span within {@link SearchMatch.text}: the half-open interval + * `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code + * units, as in {@link CompletionItem.rangeStart}. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchHighlight( + /** + * The start of the span. + */ + val rangeStart: Long, + /** + * The end of the span, exclusive. MUST be greater than {@link rangeStart} + * and at most the length of {@link SearchMatch.text}. + */ + val rangeEnd: Long +) + +/** + * The matched text of a result, with the matched spans highlighted. The host + * chooses how much text around the match to include. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchMatch( + /** + * The text to display. + */ + val text: String, + /** + * The matched spans, in order. Spans MUST NOT overlap. + */ + val highlights: List +) + +/** + * A file whose path matches. {@link SearchResultBase.resource} is the file; + * the match text is its path, usually relative to the root that contains it. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class FileNameSearchResult( + /** + * The resource that contains the match. + */ + val resource: String, + /** + * The text to display, with the matched spans highlighted. + */ + val match: SearchMatch, + /** + * How well the result matches; higher is better. Scores have no fixed + * range, and are comparable across all results of one search. Clients + * SHOULD show results in descending score order. A host that does not rank + * results omits the score. + */ + val score: Double? = null, + val kind: SearchResultKind +) + +/** + * A match in the text of a file. {@link SearchResultBase.resource} is the + * file; the match text is the text around the match, usually its line. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class FileTextSearchResult( + /** + * The resource that contains the match. + */ + val resource: String, + /** + * The text to display, with the matched spans highlighted. + */ + val match: SearchMatch, + /** + * How well the result matches; higher is better. Scores have no fixed + * range, and are comparable across all results of one search. Clients + * SHOULD show results in descending score order. A host that does not rank + * results omits the score. + */ + val score: Double? = null, + val kind: SearchResultKind, + /** + * The location of the match in the file. + */ + val range: TextRange +) + +/** + * A session whose content matches. {@link SearchResultBase.resource} is the + * session URI. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SessionSearchResult( + /** + * The resource that contains the match. + */ + val resource: String, + /** + * The text to display, with the matched spans highlighted. + */ + val match: SearchMatch, + /** + * How well the result matches; higher is better. Scores have no fixed + * range, and are comparable across all results of one search. Clients + * SHOULD show results in descending score order. A host that does not rank + * results omits the score. + */ + val score: Double? = null, + val kind: SearchResultKind, + /** + * The session's title. + */ + val title: String +) + +/** + * A match in a chat request or response. {@link SearchResultBase.resource} + * is the chat URI. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ChatMessageSearchResult( + /** + * The resource that contains the match. + */ + val resource: String, + /** + * The text to display, with the matched spans highlighted. + */ + val match: SearchMatch, + /** + * How well the result matches; higher is better. Scores have no fixed + * range, and are comparable across all results of one search. Clients + * SHOULD show results in descending score order. A host that does not rank + * results omits the score. + */ + val score: Double? = null, + val kind: SearchResultKind, + /** + * The chat's title. + */ + val title: String, + /** + * The ID of the turn that contains the match. + */ + val turnId: String +) + +/** + * The query changed and the host has not replaced the results yet. Clients + * MAY show the previous query's results differently, for example dimmed. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchPendingLifecycleState( + val status: SearchLifecycleStatus +) + +/** + * The host is searching and may add more results. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchRunningLifecycleState( + val status: SearchLifecycleStatus +) + +/** + * The host found every result for the query. A host that watches the + * searched files, sessions, or chats MAY still change the results later. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchCompletedLifecycleState( + val status: SearchLifecycleStatus, + /** + * Why the search completed. + */ + val reason: SearchCompletionReason +) + +/** + * The search failed. Results found before the failure remain in + * {@link SearchState.results}. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchFailedLifecycleState( + val status: SearchLifecycleStatus, + /** + * Why the search failed, for example an invalid regular expression. + */ + val error: ErrorInfo +) + +/** + * Full state for one search, returned when a client subscribes to its + * `ahp-search:` URI. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class SearchState( + /** + * The current query. + */ + val query: SearchQuery, + /** + * Results in the order the host found them. Sort by + * {@link SearchResultBase.score} to rank them. While {@link lifecycle} is + * {@link SearchLifecycleStatus.Pending | pending}, these are results for the + * previous query. + */ + val results: List, + /** + * Where the search is in its lifecycle. + */ + val lifecycle: SearchLifecycleState +) + // ─── Customization Enablement Union ───────────────────────────────────── /** @@ -8413,6 +8973,186 @@ internal object AutomationRunLifecycleSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("SearchTarget") + + override fun deserialize(decoder: Decoder): SearchTarget { + val input = decoder as? JsonDecoder + ?: error("SearchTarget can only be deserialized from JSON") + val element = input.decodeJsonElement() + val obj = element as? JsonObject + ?: error("Expected JsonObject for SearchTarget") + val discriminant = (obj["kind"] as? JsonPrimitive)?.content + ?: return SearchTargetUnknown(obj) + return when (discriminant) { + "fileNames" -> SearchTargetFileNames(input.json.decodeFromJsonElement(FileNamesSearchTarget.serializer(), element)) + "fileText" -> SearchTargetFileText(input.json.decodeFromJsonElement(FileTextSearchTarget.serializer(), element)) + "sessions" -> SearchTargetSessions(input.json.decodeFromJsonElement(SessionsSearchTarget.serializer(), element)) + "chatMessages" -> SearchTargetChatMessages(input.json.decodeFromJsonElement(ChatMessagesSearchTarget.serializer(), element)) + else -> SearchTargetUnknown(obj) + } + } + + override fun serialize(encoder: Encoder, value: SearchTarget) { + val output = encoder as? JsonEncoder + ?: error("SearchTarget can only be serialized to JSON") + val element: JsonElement = when (value) { + is SearchTargetFileNames -> output.json.encodeToJsonElement(FileNamesSearchTarget.serializer(), value.value) + is SearchTargetFileText -> output.json.encodeToJsonElement(FileTextSearchTarget.serializer(), value.value) + is SearchTargetSessions -> output.json.encodeToJsonElement(SessionsSearchTarget.serializer(), value.value) + is SearchTargetChatMessages -> output.json.encodeToJsonElement(ChatMessagesSearchTarget.serializer(), value.value) + is SearchTargetUnknown -> value.raw + } + output.encodeJsonElement(element) + } +} + +@Serializable(with = SearchResultSerializer::class) +sealed interface SearchResult + +@JvmInline +value class SearchResultFileName(val value: FileNameSearchResult) : SearchResult +@JvmInline +value class SearchResultFileText(val value: FileTextSearchResult) : SearchResult +@JvmInline +value class SearchResultSession(val value: SessionSearchResult) : SearchResult +@JvmInline +value class SearchResultChatMessage(val value: ChatMessageSearchResult) : SearchResult +/** + * Forward-compat catch-all for unknown SearchResult discriminators. + * + * Older clients may receive newer wire variants they don't recognise; capturing + * the raw `JsonObject` lets such payloads round-trip through the client unchanged. + * Reducers handle this variant conservatively on a per-union basis (typically + * as a no-op, but see `Reducers.kt` for the exact treatment). + */ +@JvmInline +value class SearchResultUnknown(val raw: JsonObject) : SearchResult + +internal object SearchResultSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("SearchResult") + + override fun deserialize(decoder: Decoder): SearchResult { + val input = decoder as? JsonDecoder + ?: error("SearchResult can only be deserialized from JSON") + val element = input.decodeJsonElement() + val obj = element as? JsonObject + ?: error("Expected JsonObject for SearchResult") + val discriminant = (obj["kind"] as? JsonPrimitive)?.content + ?: return SearchResultUnknown(obj) + return when (discriminant) { + "fileName" -> SearchResultFileName(input.json.decodeFromJsonElement(FileNameSearchResult.serializer(), element)) + "fileText" -> SearchResultFileText(input.json.decodeFromJsonElement(FileTextSearchResult.serializer(), element)) + "session" -> SearchResultSession(input.json.decodeFromJsonElement(SessionSearchResult.serializer(), element)) + "chatMessage" -> SearchResultChatMessage(input.json.decodeFromJsonElement(ChatMessageSearchResult.serializer(), element)) + else -> SearchResultUnknown(obj) + } + } + + override fun serialize(encoder: Encoder, value: SearchResult) { + val output = encoder as? JsonEncoder + ?: error("SearchResult can only be serialized to JSON") + val element: JsonElement = when (value) { + is SearchResultFileName -> output.json.encodeToJsonElement(FileNameSearchResult.serializer(), value.value) + is SearchResultFileText -> output.json.encodeToJsonElement(FileTextSearchResult.serializer(), value.value) + is SearchResultSession -> output.json.encodeToJsonElement(SessionSearchResult.serializer(), value.value) + is SearchResultChatMessage -> output.json.encodeToJsonElement(ChatMessageSearchResult.serializer(), value.value) + is SearchResultUnknown -> value.raw + } + output.encodeJsonElement(element) + } +} + +@Serializable(with = SearchLifecycleStateSerializer::class) +sealed interface SearchLifecycleState + +@JvmInline +value class SearchLifecycleStatePending(val value: SearchPendingLifecycleState) : SearchLifecycleState +@JvmInline +value class SearchLifecycleStateRunning(val value: SearchRunningLifecycleState) : SearchLifecycleState +@JvmInline +value class SearchLifecycleStateCompleted(val value: SearchCompletedLifecycleState) : SearchLifecycleState +@JvmInline +value class SearchLifecycleStateFailed(val value: SearchFailedLifecycleState) : SearchLifecycleState +/** + * Forward-compat catch-all for unknown SearchLifecycleState discriminators. + * + * Older clients may receive newer wire variants they don't recognise; capturing + * the raw `JsonObject` lets such payloads round-trip through the client unchanged. + * Reducers handle this variant conservatively on a per-union basis (typically + * as a no-op, but see `Reducers.kt` for the exact treatment). + */ +@JvmInline +value class SearchLifecycleStateUnknown(val raw: JsonObject) : SearchLifecycleState + +internal object SearchLifecycleStateSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("SearchLifecycleState") + + override fun deserialize(decoder: Decoder): SearchLifecycleState { + val input = decoder as? JsonDecoder + ?: error("SearchLifecycleState can only be deserialized from JSON") + val element = input.decodeJsonElement() + val obj = element as? JsonObject + ?: error("Expected JsonObject for SearchLifecycleState") + val discriminant = (obj["status"] as? JsonPrimitive)?.content + ?: return SearchLifecycleStateUnknown(obj) + return when (discriminant) { + "pending" -> SearchLifecycleStatePending(input.json.decodeFromJsonElement(SearchPendingLifecycleState.serializer(), element)) + "running" -> SearchLifecycleStateRunning(input.json.decodeFromJsonElement(SearchRunningLifecycleState.serializer(), element)) + "completed" -> SearchLifecycleStateCompleted(input.json.decodeFromJsonElement(SearchCompletedLifecycleState.serializer(), element)) + "failed" -> SearchLifecycleStateFailed(input.json.decodeFromJsonElement(SearchFailedLifecycleState.serializer(), element)) + else -> SearchLifecycleStateUnknown(obj) + } + } + + override fun serialize(encoder: Encoder, value: SearchLifecycleState) { + val output = encoder as? JsonEncoder + ?: error("SearchLifecycleState can only be serialized to JSON") + val element: JsonElement = when (value) { + is SearchLifecycleStatePending -> output.json.encodeToJsonElement(SearchPendingLifecycleState.serializer(), value.value) + is SearchLifecycleStateRunning -> output.json.encodeToJsonElement(SearchRunningLifecycleState.serializer(), value.value) + is SearchLifecycleStateCompleted -> output.json.encodeToJsonElement(SearchCompletedLifecycleState.serializer(), value.value) + is SearchLifecycleStateFailed -> output.json.encodeToJsonElement(SearchFailedLifecycleState.serializer(), value.value) + is SearchLifecycleStateUnknown -> value.raw + } + val encodedObject = element.jsonObject.toMutableMap() + val discriminant = when (value) { + is SearchLifecycleStatePending -> "pending" + is SearchLifecycleStateRunning -> "running" + is SearchLifecycleStateCompleted -> "completed" + is SearchLifecycleStateFailed -> "failed" + is SearchLifecycleStateUnknown -> null + } + if (discriminant != null) encodedObject["status"] = JsonPrimitive(discriminant) + output.encodeJsonElement(JsonObject(encodedObject)) + } +} + /** * A completed request/response cycle: either a {@link MaterializedTurn} with * its full response or a {@link DeferredTurn}, discriminated by `isDeferred`. @@ -8570,6 +9310,7 @@ sealed interface SnapshotState { @JvmInline value class Annotations(val value: AnnotationsState) : SnapshotState @JvmInline value class Automations(val value: AutomationState) : SnapshotState @JvmInline value class AutomationRun(val value: AutomationRunState) : SnapshotState + @JvmInline value class Search(val value: SearchState) : SnapshotState /** A state that this version does not recognize, kept as raw JSON so it re-encodes unchanged. */ @JvmInline value class Unknown(val raw: JsonObject) : SnapshotState } @@ -8586,7 +9327,9 @@ internal object SnapshotStateSerializer : KSerializer { ?: error("Expected JsonObject for SnapshotState") // Try the most distinctive shape first. AutomationRunState has required // `automation`, `origin`, and `sessions`; AutomationState has - // required `entries`; SessionState has required + // required `entries`; SearchState has required `query` + + // `results` (checked before session, because it also has a required + // `lifecycle`); SessionState has required // `lifecycle`; ChatState has required `turns`; ChangesetState has // required `status` + `files`; ResourceWatchState has required // `root` + `recursive`; AnnotationsState has required `annotations` @@ -8600,6 +9343,8 @@ internal object SnapshotStateSerializer : KSerializer { SnapshotState.AutomationRun(input.json.decodeFromJsonElement(AutomationRunState.serializer(), element)) obj.containsKey("entries") -> SnapshotState.Automations(input.json.decodeFromJsonElement(AutomationState.serializer(), element)) + obj.containsKey("query") && obj.containsKey("results") -> + SnapshotState.Search(input.json.decodeFromJsonElement(SearchState.serializer(), element)) obj.containsKey("lifecycle") -> SnapshotState.Session(input.json.decodeFromJsonElement(SessionState.serializer(), element)) obj.containsKey("turns") -> SnapshotState.Chat(input.json.decodeFromJsonElement(ChatState.serializer(), element)) obj.containsKey("instanceId") && obj.containsKey("extensionId") && obj.containsKey("canvasId") -> @@ -8633,6 +9378,7 @@ internal object SnapshotStateSerializer : KSerializer { is SnapshotState.Annotations -> output.json.encodeToJsonElement(AnnotationsState.serializer(), value.value) is SnapshotState.Automations -> output.json.encodeToJsonElement(AutomationState.serializer(), value.value) is SnapshotState.AutomationRun -> output.json.encodeToJsonElement(AutomationRunState.serializer(), value.value) + is SnapshotState.Search -> output.json.encodeToJsonElement(SearchState.serializer(), value.value) is SnapshotState.Unknown -> value.raw } output.encodeJsonElement(element) diff --git a/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/FixtureDrivenReducerTest.kt b/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/FixtureDrivenReducerTest.kt index 66e7b8a9a..d948a3a68 100644 --- a/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/FixtureDrivenReducerTest.kt +++ b/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/FixtureDrivenReducerTest.kt @@ -8,6 +8,7 @@ import com.microsoft.agenthostprotocol.generated.AutomationState import com.microsoft.agenthostprotocol.generated.AutomationRunState import com.microsoft.agenthostprotocol.generated.ResourceWatchState import com.microsoft.agenthostprotocol.generated.RootState +import com.microsoft.agenthostprotocol.generated.SearchState import com.microsoft.agenthostprotocol.generated.SessionState import com.microsoft.agenthostprotocol.generated.StateAction import com.microsoft.agenthostprotocol.generated.TerminalState @@ -213,6 +214,18 @@ class FixtureDrivenReducerTest { }, ) + "search" -> compareFixture( + file = file, + initial = initial, + expected = expected, + serializer = SearchState.serializer(), + run = { state -> + var s = state + for (action in actions) s = searchReducer(s, action) + s + }, + ) + "automation" -> compareFixture( file = file, initial = initial, diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 51086df48..1b97f6ada 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -20,11 +20,11 @@ use crate::state::{ ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ChatSummary, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, MaterializedTurn, McpAuthRequirement, McpServerState, - Message, ModelSelection, PendingMessageKind, ResponsePart, SessionActiveClient, - SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, - TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributor, - ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, ToolResultContent, Turn, - UsageInfo, + Message, ModelSelection, PendingMessageKind, ResponsePart, SearchLifecycleState, SearchQuery, + SearchResult, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, + TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, + ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, + ToolResultContent, Turn, UsageInfo, }; // ─── ActionType ────────────────────────────────────────────────────── @@ -132,6 +132,9 @@ pub enum ActionType { TerminalCommandExecuted, TerminalCommandFinished, ResourceWatchChanged, + SearchQueryChanged, + SearchResultsChanged, + SearchLifecycleChanged, AutomationCreateRequested, AutomationUpdateRequested, AutomationSet, @@ -303,6 +306,9 @@ impl serde::Serialize for ActionType { Self::TerminalCommandExecuted => serializer.serialize_str("terminal/commandExecuted"), Self::TerminalCommandFinished => serializer.serialize_str("terminal/commandFinished"), Self::ResourceWatchChanged => serializer.serialize_str("resourceWatch/changed"), + Self::SearchQueryChanged => serializer.serialize_str("search/queryChanged"), + Self::SearchResultsChanged => serializer.serialize_str("search/resultsChanged"), + Self::SearchLifecycleChanged => serializer.serialize_str("search/lifecycleChanged"), Self::AutomationCreateRequested => { serializer.serialize_str("automation/createRequested") } @@ -436,6 +442,9 @@ impl<'de> serde::Deserialize<'de> for ActionType { "terminal/commandExecuted" => Self::TerminalCommandExecuted, "terminal/commandFinished" => Self::TerminalCommandFinished, "resourceWatch/changed" => Self::ResourceWatchChanged, + "search/queryChanged" => Self::SearchQueryChanged, + "search/resultsChanged" => Self::SearchResultsChanged, + "search/lifecycleChanged" => Self::SearchLifecycleChanged, "automation/createRequested" => Self::AutomationCreateRequested, "automation/updateRequested" => Self::AutomationUpdateRequested, "automation/set" => Self::AutomationSet, @@ -2291,6 +2300,72 @@ pub struct ResourceWatchChangedAction { pub changes: AnyValue, } +/// Replaces the search's query and restarts the search. +/// +/// Keeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to +/// {@link SearchLifecycleStatus.Pending | pending}. The old results stay +/// visible until the host replaces them, so the client does not flash an empty +/// list. +/// +/// After the host applies this action, it stops the previous search and drops +/// any of its results that it has not dispatched yet. The host MUST then +/// dispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with +/// `replace: true` before any other search action. The replacement can keep +/// old results that still match the new query, and can be empty. If the new +/// query is not valid, +/// for example because it contains an invalid regular expression, the host +/// replaces the results with an empty list and then changes the lifecycle to +/// {@link SearchLifecycleStatus.Failed | failed}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchQueryChangedAction { + /// The new query. + pub query: SearchQuery, +} + +/// Adds results to {@link SearchState.results}, or replaces them. +/// +/// By default, the reducer appends `results`. Set `replace` to `true` to +/// replace every result instead; if {@link SearchState.lifecycle} is +/// {@link SearchLifecycleStatus.Pending | pending}, a replacement also changes +/// it to {@link SearchLifecycleStatus.Running | running}. +/// +/// The host MUST dispatch a replacement first after a +/// {@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also +/// replace the results at other times, for example to re-rank them, to remove +/// duplicates, or to update a completed search when a watched file changes. +/// The host MUST NOT dispatch an empty `results` list unless `replace` is +/// `true`. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchResultsChangedAction { + /// The results to append, in the order the host found them, or the replacement results. + pub results: Vec, + /// When `true`, replaces every result instead of appending. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub replace: Option, +} + +/// Replaces {@link SearchState.lifecycle}. +/// +/// The host dispatches this to complete or fail a search, or to move a +/// completed search back to {@link SearchLifecycleStatus.Running | running} when it +/// searches again, for example after a watched file changes. The host MUST NOT +/// change the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only +/// {@link SearchQueryChangedAction | `search/queryChanged`} does that. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchLifecycleChangedAction { + /// The new lifecycle. + pub lifecycle: SearchLifecycleState, +} + /// Ask the host to create a durable automation at a client-chosen resource. /// /// Clients may dispatch this action only when the host advertises its `create` @@ -2677,6 +2752,12 @@ pub enum StateAction { TerminalCommandFinished(TerminalCommandFinishedAction), #[serde(rename = "resourceWatch/changed")] ResourceWatchChanged(ResourceWatchChangedAction), + #[serde(rename = "search/queryChanged")] + SearchQueryChanged(SearchQueryChangedAction), + #[serde(rename = "search/resultsChanged")] + SearchResultsChanged(SearchResultsChangedAction), + #[serde(rename = "search/lifecycleChanged")] + SearchLifecycleChanged(SearchLifecycleChangedAction), #[serde(rename = "automation/createRequested")] AutomationCreateRequested(Box), #[serde(rename = "automation/updateRequested")] diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index c88924705..7593e8acb 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -18,8 +18,9 @@ use crate::state::{ AgentSelection, AutomationDefinition, AutomationSchedule, AutomationSessionTemplate, AutomationTrigger, AutomationTriggerDefinition, ChannelFlowControl, ChannelReceiveLimits, ContentRef, Message, MessageAttachment, ModelSelection, ResumedChannelSubscription, - SessionActiveClient, SessionConfigSchema, SessionSummary, SideChatSelection, Snapshot, - SnapshotState, TcpConnectionsCapability, TelemetryCapabilities, TerminalClaim, TextRange, Turn, + SearchCapability, SearchQuery, SessionActiveClient, SessionConfigSchema, SessionSummary, + SideChatSelection, Snapshot, SnapshotState, TcpConnectionsCapability, TelemetryCapabilities, + TerminalClaim, TextRange, Turn, }; // ─── Enums ──────────────────────────────────────────────────────────── @@ -445,6 +446,12 @@ pub struct InitializeResult { /// Stability: 1.0 - Early development. #[serde(default, skip_serializing_if = "Option::is_none")] pub tcp_connections: Option, + /// Present when the host supports `createSearch`, which searches files, + /// sessions, and chats and streams the results on an `ahp-search:` channel. + /// + /// Stability: 1.0 - Early development. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub search: Option, /// Present when chats in one session may be backed by different agent /// providers (see {@link CreateChatParams.provider} and /// {@link ChatState.provider}). @@ -1734,6 +1741,40 @@ pub struct CreateResourceWatchResult { pub channel: Uri, } +/// Starts a search on the host. +/// +/// The client chooses the channel URI and then subscribes to it to receive the +/// search's {@link SearchState} and its results. The client replaces the query +/// by dispatching {@link SearchQueryChangedAction | `search/queryChanged`}, +/// and cancels the search by unsubscribing. +/// +/// The client MUST NOT send this command unless `InitializeResult.search` is +/// present, and MUST NOT include a target whose kind is not listed in +/// {@link SearchCapability.targets}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateSearchParams { + /// Channel URI this command targets. + pub channel: Uri, + /// Optional JSON-serializable metadata associated with this request. + /// Receivers MUST ignore keys they do not understand. + #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] + pub meta: Option, + /// What to search for and where. + pub query: SearchQuery, +} + +/// Result of the `createSearch` command. +/// +/// An empty object on success. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateSearchResult {} + /// Requests that the host load older historical turns into a chat state. /// /// The command result does not carry turns. Instead, before responding, the host diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index cb76000f0..614226d92 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1620,6 +1620,187 @@ pub enum AutomationRunOriginKind { Trigger, } +/// Discriminant for {@link SearchTarget}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SearchTargetKind { + /// File paths. + FileNames, + /// The text content of files. + FileText, + /// The host's sessions. + Sessions, + /// The text of chat requests and responses. + ChatMessages, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for SearchTargetKind { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::FileNames => serializer.serialize_str("fileNames"), + Self::FileText => serializer.serialize_str("fileText"), + Self::Sessions => serializer.serialize_str("sessions"), + Self::ChatMessages => serializer.serialize_str("chatMessages"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for SearchTargetKind { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "fileNames" => Self::FileNames, + "fileText" => Self::FileText, + "sessions" => Self::Sessions, + "chatMessages" => Self::ChatMessages, + _ => Self::Unknown(raw), + }) + } +} + +/// Discriminant for {@link SearchResult}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SearchResultKind { + FileName, + FileText, + Session, + ChatMessage, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for SearchResultKind { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::FileName => serializer.serialize_str("fileName"), + Self::FileText => serializer.serialize_str("fileText"), + Self::Session => serializer.serialize_str("session"), + Self::ChatMessage => serializer.serialize_str("chatMessage"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for SearchResultKind { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "fileName" => Self::FileName, + "fileText" => Self::FileText, + "session" => Self::Session, + "chatMessage" => Self::ChatMessage, + _ => Self::Unknown(raw), + }) + } +} + +/// Lifecycle status of a search. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SearchLifecycleStatus { + /// The query changed and the host has not replaced the results yet. + /// {@link SearchState.results} belong to the previous query. + Pending, + /// The host is searching. + Running, + /// The host found every result for the query. + Completed, + /// The search failed. + Failed, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for SearchLifecycleStatus { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::Pending => serializer.serialize_str("pending"), + Self::Running => serializer.serialize_str("running"), + Self::Completed => serializer.serialize_str("completed"), + Self::Failed => serializer.serialize_str("failed"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for SearchLifecycleStatus { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "pending" => Self::Pending, + "running" => Self::Running, + "completed" => Self::Completed, + "failed" => Self::Failed, + _ => Self::Unknown(raw), + }) + } +} + +/// Why a search completed. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SearchCompletionReason { + /// The host searched every target. + Exhausted, + /// The host stopped at the result limit. More results may exist. + LimitReached, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for SearchCompletionReason { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::Exhausted => serializer.serialize_str("exhausted"), + Self::LimitReached => serializer.serialize_str("limitReached"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for SearchCompletionReason { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "exhausted" => Self::Exhausted, + "limitReached" => Self::LimitReached, + _ => Self::Unknown(raw), + }) + } +} + fn deserialize_extra_without_type<'de, D>( deserializer: D, ) -> Result, D::Error> @@ -6875,6 +7056,303 @@ pub struct AutomationRunState { pub meta: Option, } +/// Present when the host supports `createSearch`. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchCapability { + /// The target kinds the host can search. A client MUST NOT send a + /// {@link SearchTarget} whose kind is not listed here. + pub targets: Vec, +} + +/// What a search looks for and where. +/// +/// The client sends a query in `createSearch` and replaces it with +/// {@link SearchQueryChangedAction | `search/queryChanged`}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchQuery { + /// The text to search for. Its meaning depends on the target: see + /// {@link SearchTarget}. An empty `text` matches nothing; the host completes + /// the search with no results. + pub text: String, + /// Match case. Defaults to `false`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub match_case: Option, + /// Match only whole words. Defaults to `false`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub whole_word: Option, + /// Treat `text` as a regular expression. Defaults to `false`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_regex: Option, + /// A hint that precise matching isn't expected, for example because the + /// search powers a quick-find picker. The host MAY then match loosely, rank + /// results by how well they match, and ignore {@link isRegex} and + /// {@link wholeWord}. Defaults to `false`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fuzzy: Option, + /// Where to search. MUST contain at least one target. + pub targets: Vec, + /// The maximum number of results. The host MAY apply a lower limit, and + /// completes the search with {@link SearchCompletionReason.LimitReached} + /// when it reaches the limit that applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_results: Option, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten)] + pub extra: serde_json::Map, +} + +/// Searches file paths under {@link FileSearchTargetBase.roots}. +/// +/// The host decides how to match {@link SearchQuery.text} against file paths, +/// for example with fuzzy matching, and which query options apply. Results +/// are {@link FileNameSearchResult}s. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileNamesSearchTarget { + /// The folders to search. MUST contain at least one URI. + pub roots: Vec, + /// Glob patterns relative to a root. When present, only matching files are searched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub includes: Option>, + /// Glob patterns relative to a root. Matching files are not searched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub excludes: Option>, + /// Also search files that the host's ignore rules, such as `.gitignore` + /// files, would otherwise skip. Defaults to `false`. `excludes` still apply. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub include_ignored: Option, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// Searches the text content of files under {@link FileSearchTargetBase.roots}. +/// Results are {@link FileTextSearchResult}s. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileTextSearchTarget { + /// The folders to search. MUST contain at least one URI. + pub roots: Vec, + /// Glob patterns relative to a root. When present, only matching files are searched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub includes: Option>, + /// Glob patterns relative to a root. Matching files are not searched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub excludes: Option>, + /// Also search files that the host's ignore rules, such as `.gitignore` + /// files, would otherwise skip. Defaults to `false`. `excludes` still apply. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub include_ignored: Option, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// Searches the host's sessions, the same sessions that `listSessions` +/// returns. The host decides which session content it matches, for example +/// titles or requests. Results are {@link SessionSearchResult}s. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionsSearchTarget { + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// Searches the visible text of chat requests and responses, including the +/// responses of deferred turns. Results are +/// {@link ChatMessageSearchResult}s. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatMessagesSearchTarget { + /// The chats to search. MUST contain at least one chat URI. + pub chats: Vec, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// A matched span within {@link SearchMatch.text}: the half-open interval +/// `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code +/// units, as in {@link CompletionItem.rangeStart}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchHighlight { + /// The start of the span. + pub range_start: i64, + /// The end of the span, exclusive. MUST be greater than {@link rangeStart} + /// and at most the length of {@link SearchMatch.text}. + pub range_end: i64, +} + +/// The matched text of a result, with the matched spans highlighted. The host +/// chooses how much text around the match to include. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchMatch { + /// The text to display. + pub text: String, + /// The matched spans, in order. Spans MUST NOT overlap. + pub highlights: Vec, +} + +/// A file whose path matches. {@link SearchResultBase.resource} is the file; +/// the match text is its path, usually relative to the root that contains it. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileNameSearchResult { + /// The resource that contains the match. + pub resource: Uri, + /// The text to display, with the matched spans highlighted. + pub r#match: SearchMatch, + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub score: Option, +} + +/// A match in the text of a file. {@link SearchResultBase.resource} is the +/// file; the match text is the text around the match, usually its line. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileTextSearchResult { + /// The resource that contains the match. + pub resource: Uri, + /// The text to display, with the matched spans highlighted. + pub r#match: SearchMatch, + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub score: Option, + /// The location of the match in the file. + pub range: TextRange, +} + +/// A session whose content matches. {@link SearchResultBase.resource} is the +/// session URI. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSearchResult { + /// The resource that contains the match. + pub resource: Uri, + /// The text to display, with the matched spans highlighted. + pub r#match: SearchMatch, + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub score: Option, + /// The session's title. + pub title: String, +} + +/// A match in a chat request or response. {@link SearchResultBase.resource} +/// is the chat URI. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatMessageSearchResult { + /// The resource that contains the match. + pub resource: Uri, + /// The text to display, with the matched spans highlighted. + pub r#match: SearchMatch, + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub score: Option, + /// The chat's title. + pub title: String, + /// The ID of the turn that contains the match. + pub turn_id: String, +} + +/// The query changed and the host has not replaced the results yet. Clients +/// MAY show the previous query's results differently, for example dimmed. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchPendingLifecycleState {} + +/// The host is searching and may add more results. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchRunningLifecycleState {} + +/// The host found every result for the query. A host that watches the +/// searched files, sessions, or chats MAY still change the results later. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchCompletedLifecycleState { + /// Why the search completed. + pub reason: SearchCompletionReason, +} + +/// The search failed. Results found before the failure remain in +/// {@link SearchState.results}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchFailedLifecycleState { + /// Why the search failed, for example an invalid regular expression. + pub error: ErrorInfo, +} + +/// Full state for one search, returned when a client subscribes to its +/// `ahp-search:` URI. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchState { + /// The current query. + pub query: SearchQuery, + /// Results in the order the host found them. Sort by + /// {@link SearchResultBase.score} to rank them. While {@link lifecycle} is + /// {@link SearchLifecycleStatus.Pending | pending}, these are results for the + /// previous query. + pub results: Vec, + /// Where the search is in its lifecycle. + pub lifecycle: SearchLifecycleState, +} + // ─── Customization Enablement Union ─────────────────────────────────────── /// A single explicit customization enablement decision. @@ -7432,6 +7910,60 @@ pub enum AutomationRunLifecycle { Cancelled(AutomationCancelledRunLifecycle), } +/// One place to search. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind")] +pub enum SearchTarget { + #[serde(rename = "fileNames")] + FileNames(FileNamesSearchTarget), + #[serde(rename = "fileText")] + FileText(FileTextSearchTarget), + #[serde(rename = "sessions")] + Sessions(SessionsSearchTarget), + #[serde(rename = "chatMessages")] + ChatMessages(ChatMessagesSearchTarget), + /// Unknown or future variant — preserved as raw JSON for round-trip fidelity. + /// Reducers treat this as a no-op. + #[serde(untagged)] + Unknown(serde_json::Value), +} + +/// One search match. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind")] +pub enum SearchResult { + #[serde(rename = "fileName")] + FileName(FileNameSearchResult), + #[serde(rename = "fileText")] + FileText(FileTextSearchResult), + #[serde(rename = "session")] + Session(SessionSearchResult), + #[serde(rename = "chatMessage")] + ChatMessage(ChatMessageSearchResult), + /// Unknown or future variant — preserved as raw JSON for round-trip fidelity. + /// Reducers treat this as a no-op. + #[serde(untagged)] + Unknown(serde_json::Value), +} + +/// Lifecycle of a search. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "status")] +pub enum SearchLifecycleState { + #[serde(rename = "pending")] + Pending(SearchPendingLifecycleState), + #[serde(rename = "running")] + Running(SearchRunningLifecycleState), + #[serde(rename = "completed")] + Completed(SearchCompletedLifecycleState), + #[serde(rename = "failed")] + Failed(SearchFailedLifecycleState), + /// Unknown or future variant — preserved as raw JSON for round-trip fidelity. + /// Reducers treat this as a no-op. + #[serde(untagged)] + Unknown(serde_json::Value), +} + /// The state payload of a snapshot, selected by its resource's URI scheme. /// /// Standalone deserialization preserves any JSON value as Unknown. Use Snapshot @@ -7449,6 +7981,7 @@ pub enum SnapshotState { Annotations(Box), Automations(Box), AutomationRun(Box), + Search(Box), Root(Box), /// A state that this version does not recognize, kept as raw JSON so it /// re-encodes unchanged. @@ -7496,6 +8029,9 @@ impl SnapshotState { "ahp-automation-run" => serde_json::from_value::(value) .map(Box::new) .map(Self::AutomationRun), + "ahp-search" => serde_json::from_value::(value) + .map(Box::new) + .map(Self::Search), "ahp-tcp" => serde_json::from_value::(value).map(Self::Empty), "ahp-otlp" => serde_json::from_value::(value).map(Self::Empty), _ => Ok(Self::Unknown(value)), diff --git a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs index 3f895555c..2e1e91f55 100644 --- a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs @@ -40,14 +40,15 @@ use ahp_types::actions::ActionEnvelope; use ahp_types::common::ROOT_RESOURCE_URI; use ahp_types::state::{ AnnotationsState, AutomationEntry, AutomationRunState, AutomationState, CanvasState, - ChangesetState, ChatState, ResourceWatchState, RootState, SessionState, SnapshotState, - TerminalState, + ChangesetState, ChatState, ResourceWatchState, RootState, SearchState, SessionState, + SnapshotState, TerminalState, }; use crate::hosts::{HostId, HostSubscriptionEvent}; use crate::reducers::{ apply_action_to_automation, apply_action_to_automation_run, apply_action_to_canvas, - apply_action_to_chat, apply_action_to_root, apply_action_to_session, apply_action_to_terminal, + apply_action_to_chat, apply_action_to_root, apply_action_to_search, apply_action_to_session, + apply_action_to_terminal, }; use crate::SubscriptionEvent; @@ -102,6 +103,7 @@ pub struct MultiHostStateMirror { automation_catalogs: HashMap, automations: HashMap, automation_runs: HashMap, + searches: HashMap, } impl MultiHostStateMirror { @@ -165,6 +167,11 @@ impl MultiHostStateMirror { &self.automation_runs } + /// Borrow search states keyed by `(host_id, uri)`. + pub fn searches(&self) -> &HashMap { + &self.searches + } + /// Convenience: apply a [`HostSubscriptionEvent`] produced by /// [`crate::hosts::MultiHostClient::events`]. Action envelopes are /// routed through the reducer; non-action events (session-summary @@ -225,6 +232,10 @@ impl MultiHostStateMirror { apply_action_to_terminal(terminal, &envelope.action); return; } + if let Some(search) = self.searches.get_mut(&key) { + apply_action_to_search(search, &envelope.action); + return; + } if let Some(run) = self.automation_runs.get_mut(&key) { apply_action_to_automation_run(run, &envelope.action); } @@ -235,7 +246,7 @@ impl MultiHostStateMirror { /// Seed the mirror from a [`Snapshot`](ahp_types::state::Snapshot) /// scoped to `host` — root, session, terminal, changeset, - /// resource-watch, annotations, automation, or automation-run as the + /// resource-watch, annotations, automation, automation-run, or search as the /// snapshot's `state` discriminator dictates. pub fn apply_snapshot(&mut self, host: &HostId, snapshot: &ahp_types::state::Snapshot) { let key = HostedResourceKey::new(host.clone(), snapshot.resource.clone()); @@ -275,12 +286,15 @@ impl MultiHostStateMirror { SnapshotState::AutomationRun(state) => { self.automation_runs.insert(key, state.as_ref().clone()); } + SnapshotState::Search(state) => { + self.searches.insert(key, state.as_ref().clone()); + } } } /// Drop every slot keyed under `host` — root state, sessions, /// terminals, changesets, resource watches, annotations, automations, - /// and automation runs. + /// automation runs, and searches. pub fn reset_host(&mut self, host: &HostId) { self.root_states.remove(host); self.sessions.retain(|key, _| &key.host_id != host); @@ -293,6 +307,7 @@ impl MultiHostStateMirror { self.automation_catalogs.remove(host); self.automations.retain(|key, _| &key.host_id != host); self.automation_runs.retain(|key, _| &key.host_id != host); + self.searches.retain(|key, _| &key.host_id != host); } /// Drop every host's state. @@ -308,6 +323,7 @@ impl MultiHostStateMirror { self.automation_catalogs.clear(); self.automations.clear(); self.automation_runs.clear(); + self.searches.clear(); } fn replace_automations(&mut self, host: &HostId, automations: Vec) { diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 83ea77892..058a6553e 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -62,7 +62,8 @@ use ahp_types::state::{ ChatState, ChildCustomization, ConfirmationOption, Customization, CustomizationEnablement, ErrorResponsePart, InputRequestResponsePart, MaterializedTurn, McpServerCustomization, McpServerStartingState, McpServerState, McpServerStoppedState, PendingMessage, - PendingMessageKind, ResourceWatchState, ResponsePart, RootState, SessionInputRequest, + PendingMessageKind, ResourceWatchState, ResponsePart, RootState, SearchLifecycleState, + SearchPendingLifecycleState, SearchRunningLifecycleState, SearchState, SessionInputRequest, SessionLifecycle, SessionState, SessionStatus, TerminalCommandPart, TerminalContentPart, TerminalExitedLifecycleState, TerminalLifecycleState, TerminalState, TerminalUnclassifiedPart, ToolCallAuthRequiredState, ToolCallCancellationReason, ToolCallCancelledState, @@ -2269,6 +2270,38 @@ pub fn apply_action_to_resource_watch( } } +// ─── Search Reducer ─────────────────────────────────────────────────── + +/// Apply a [`StateAction`] to a [`SearchState`] in place. +pub fn apply_action_to_search(state: &mut SearchState, action: &StateAction) -> ReduceOutcome { + match action { + StateAction::SearchQueryChanged(a) => { + state.query = a.query.clone(); + state.lifecycle = SearchLifecycleState::Pending(SearchPendingLifecycleState {}); + ReduceOutcome::Applied + } + StateAction::SearchResultsChanged(a) => { + if a.replace != Some(true) { + if a.results.is_empty() { + return ReduceOutcome::NoOp; + } + state.results.extend(a.results.iter().cloned()); + return ReduceOutcome::Applied; + } + state.results = a.results.clone(); + if matches!(state.lifecycle, SearchLifecycleState::Pending(_)) { + state.lifecycle = SearchLifecycleState::Running(SearchRunningLifecycleState {}); + } + ReduceOutcome::Applied + } + StateAction::SearchLifecycleChanged(a) => { + state.lifecycle = a.lifecycle.clone(); + ReduceOutcome::Applied + } + _ => ReduceOutcome::OutOfScope, + } +} + /// Apply a [`StateAction`] to an [`AutomationState`] in place. pub fn apply_action_to_automation( state: &mut AutomationState, @@ -2871,6 +2904,14 @@ mod tests { &file_name, description, ), + "search" => run_fixture::( + initial, + expected, + &parsed_actions, + apply_action_to_search, + &file_name, + description, + ), "automation" => run_fixture::( initial, expected, diff --git a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs index 5c33c6795..2c79446d9 100644 --- a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs @@ -12,12 +12,14 @@ use ahp::hosts::{HostId, HostSubscriptionEvent}; use ahp::{HostedResourceKey, MultiHostStateMirror, SubscriptionEvent}; use ahp_types::actions::{ ActionEnvelope, CanvasStateChangedAction, RootActiveSessionsChangedAction, - RootAgentsChangedAction, SessionTitleChangedAction, StateAction, + RootAgentsChangedAction, SearchLifecycleChangedAction, SessionTitleChangedAction, StateAction, }; use ahp_types::common::ROOT_RESOURCE_URI; use ahp_types::state::{ - AgentInfo, CanvasState, RootState, SessionLifecycle, SessionState, SessionStatus, - SessionSummary, Snapshot, SnapshotState, + AgentInfo, CanvasState, RootState, SearchCompletedLifecycleState, SearchCompletionReason, + SearchLifecycleState, SearchPendingLifecycleState, SearchQuery, SearchState, SearchTarget, + SessionLifecycle, SessionState, SessionStatus, SessionSummary, SessionsSearchTarget, Snapshot, + SnapshotState, }; fn agent(provider: &str) -> AgentInfo { @@ -215,6 +217,72 @@ fn canvases_are_reduced_and_reset_per_host() { ); } +#[test] +fn searches_are_reduced_and_reset_per_host() { + let mut mirror = MultiHostStateMirror::new(); + let uri = "ahp-search:/s1"; + let alpha = HostId::new("alpha"); + let beta = HostId::new("beta"); + let snapshot = Snapshot { + resource: uri.into(), + state: SnapshotState::Search(Box::new(SearchState { + query: SearchQuery { + text: "parseConfig".into(), + match_case: None, + whole_word: None, + is_regex: None, + fuzzy: None, + targets: vec![SearchTarget::Sessions(SessionsSearchTarget { + extra: Default::default(), + })], + max_results: None, + extra: Default::default(), + }, + results: vec![], + lifecycle: SearchLifecycleState::Pending(SearchPendingLifecycleState {}), + })), + from_seq: 1, + }; + mirror.apply_snapshot(&alpha, &snapshot); + mirror.apply_snapshot(&beta, &snapshot); + mirror.apply_envelope( + &alpha, + &ActionEnvelope { + channel: uri.into(), + action: StateAction::SearchLifecycleChanged(SearchLifecycleChangedAction { + lifecycle: SearchLifecycleState::Completed(SearchCompletedLifecycleState { + reason: SearchCompletionReason::Exhausted, + }), + }), + server_seq: 2, + origin: None, + rejection_reason: None, + }, + ); + let alpha_key = HostedResourceKey::new(alpha.clone(), uri); + let beta_key = HostedResourceKey::new(beta, uri); + let targeted = ( + matches!( + mirror.searches()[&alpha_key].lifecycle, + SearchLifecycleState::Completed(_) + ), + matches!( + mirror.searches()[&beta_key].lifecycle, + SearchLifecycleState::Completed(_) + ), + ); + mirror.reset_host(&alpha); + let reset = ( + mirror.searches().contains_key(&alpha_key), + mirror.searches().contains_key(&beta_key), + ); + mirror.reset(); + assert_eq!( + (targeted, reset, mirror.searches().is_empty()), + ((true, false), (false, true), true), + ); +} + #[test] fn root_states_are_isolated_per_host() { let mut mirror = MultiHostStateMirror::new(); diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift index 09cbbcf54..171a9f920 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift @@ -48,6 +48,7 @@ public let clientDispatchableActions: Set = [ "terminal/claimed", "terminal/titleChanged", "terminal/cleared", + "search/queryChanged", "automation/createRequested", "automation/updateRequested", "automation/removed", @@ -101,6 +102,7 @@ public func isClientDispatchable(_ action: StateAction) -> Bool { .terminalClaimed, .terminalTitleChanged, .terminalCleared, + .searchQueryChanged, .automationCreateRequested, .automationUpdateRequested, .automationRemoved, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index b1967ec29..c1781aaba 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -106,6 +106,9 @@ public enum ActionType: Codable, Sendable, Equatable { case terminalCommandExecuted case terminalCommandFinished case resourceWatchChanged + case searchQueryChanged + case searchResultsChanged + case searchLifecycleChanged case automationCreateRequested case automationUpdateRequested case automationSet @@ -222,6 +225,9 @@ public enum ActionType: Codable, Sendable, Equatable { case "terminal/commandExecuted": self = .terminalCommandExecuted case "terminal/commandFinished": self = .terminalCommandFinished case "resourceWatch/changed": self = .resourceWatchChanged + case "search/queryChanged": self = .searchQueryChanged + case "search/resultsChanged": self = .searchResultsChanged + case "search/lifecycleChanged": self = .searchLifecycleChanged case "automation/createRequested": self = .automationCreateRequested case "automation/updateRequested": self = .automationUpdateRequested case "automation/set": self = .automationSet @@ -338,6 +344,9 @@ public enum ActionType: Codable, Sendable, Equatable { case .terminalCommandExecuted: try container.encode("terminal/commandExecuted") case .terminalCommandFinished: try container.encode("terminal/commandFinished") case .resourceWatchChanged: try container.encode("resourceWatch/changed") + case .searchQueryChanged: try container.encode("search/queryChanged") + case .searchResultsChanged: try container.encode("search/resultsChanged") + case .searchLifecycleChanged: try container.encode("search/lifecycleChanged") case .automationCreateRequested: try container.encode("automation/createRequested") case .automationUpdateRequested: try container.encode("automation/updateRequested") case .automationSet: try container.encode("automation/set") @@ -2504,6 +2513,94 @@ public struct ResourceWatchChangedAction: Codable, Sendable, Equatable { } } +/// Replaces the search's query and restarts the search. +/// +/// Keeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to +/// {@link SearchLifecycleStatus.Pending | pending}. The old results stay +/// visible until the host replaces them, so the client does not flash an empty +/// list. +/// +/// After the host applies this action, it stops the previous search and drops +/// any of its results that it has not dispatched yet. The host MUST then +/// dispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with +/// `replace: true` before any other search action. The replacement can keep +/// old results that still match the new query, and can be empty. If the new +/// query is not valid, +/// for example because it contains an invalid regular expression, the host +/// replaces the results with an empty list and then changes the lifecycle to +/// {@link SearchLifecycleStatus.Failed | failed}. +/// +/// Stability: 1.0 - Early development. +public struct SearchQueryChangedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The new query. + public var query: SearchQuery + + public init( + type: ActionType, + query: SearchQuery + ) { + self.type = type + self.query = query + } +} + +/// Adds results to {@link SearchState.results}, or replaces them. +/// +/// By default, the reducer appends `results`. Set `replace` to `true` to +/// replace every result instead; if {@link SearchState.lifecycle} is +/// {@link SearchLifecycleStatus.Pending | pending}, a replacement also changes +/// it to {@link SearchLifecycleStatus.Running | running}. +/// +/// The host MUST dispatch a replacement first after a +/// {@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also +/// replace the results at other times, for example to re-rank them, to remove +/// duplicates, or to update a completed search when a watched file changes. +/// The host MUST NOT dispatch an empty `results` list unless `replace` is +/// `true`. +/// +/// Stability: 1.0 - Early development. +public struct SearchResultsChangedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The results to append, in the order the host found them, or the replacement results. + public var results: [SearchResult] + /// When `true`, replaces every result instead of appending. + public var replace: Bool? + + public init( + type: ActionType, + results: [SearchResult], + replace: Bool? = nil + ) { + self.type = type + self.results = results + self.replace = replace + } +} + +/// Replaces {@link SearchState.lifecycle}. +/// +/// The host dispatches this to complete or fail a search, or to move a +/// completed search back to {@link SearchLifecycleStatus.Running | running} when it +/// searches again, for example after a watched file changes. The host MUST NOT +/// change the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only +/// {@link SearchQueryChangedAction | `search/queryChanged`} does that. +/// +/// Stability: 1.0 - Early development. +public struct SearchLifecycleChangedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The new lifecycle. + public var lifecycle: SearchLifecycleState + + public init( + type: ActionType, + lifecycle: SearchLifecycleState + ) { + self.type = type + self.lifecycle = lifecycle + } +} + public struct AutomationCreateRequestedAction: Codable, Sendable, Equatable { public var type: ActionType /// Client-chosen `ahp-automation:` URI that becomes {@link AutomationEntry.resource}. @@ -2803,6 +2900,9 @@ public enum StateAction: Codable, Sendable, Equatable { case terminalCommandExecuted(TerminalCommandExecutedAction) case terminalCommandFinished(TerminalCommandFinishedAction) case resourceWatchChanged(ResourceWatchChangedAction) + case searchQueryChanged(SearchQueryChangedAction) + case searchResultsChanged(SearchResultsChangedAction) + case searchLifecycleChanged(SearchLifecycleChangedAction) case automationCreateRequested(AutomationCreateRequestedAction) case automationUpdateRequested(AutomationUpdateRequestedAction) case automationSet(AutomationSetAction) @@ -3024,6 +3124,12 @@ public enum StateAction: Codable, Sendable, Equatable { self = .terminalCommandFinished(try TerminalCommandFinishedAction(from: decoder)) case "resourceWatch/changed": self = .resourceWatchChanged(try ResourceWatchChangedAction(from: decoder)) + case "search/queryChanged": + self = .searchQueryChanged(try SearchQueryChangedAction(from: decoder)) + case "search/resultsChanged": + self = .searchResultsChanged(try SearchResultsChangedAction(from: decoder)) + case "search/lifecycleChanged": + self = .searchLifecycleChanged(try SearchLifecycleChangedAction(from: decoder)) case "automation/createRequested": self = .automationCreateRequested(try AutomationCreateRequestedAction(from: decoder)) case "automation/updateRequested": @@ -3149,6 +3255,9 @@ public enum StateAction: Codable, Sendable, Equatable { case .terminalCommandExecuted(let v): try v.encode(to: encoder) case .terminalCommandFinished(let v): try v.encode(to: encoder) case .resourceWatchChanged(let v): try v.encode(to: encoder) + case .searchQueryChanged(let v): try v.encode(to: encoder) + case .searchResultsChanged(let v): try v.encode(to: encoder) + case .searchLifecycleChanged(let v): try v.encode(to: encoder) case .automationCreateRequested(let v): try v.encode(to: encoder) case .automationUpdateRequested(let v): try v.encode(to: encoder) case .automationSet(let v): try v.encode(to: encoder) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 4112710ba..15e4ad6cb 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -484,6 +484,11 @@ public struct InitializeResult: Codable, Sendable, Equatable { /// /// Stability: 1.0 - Early development. public var tcpConnections: TcpConnectionsCapability? + /// Present when the host supports `createSearch`, which searches files, + /// sessions, and chats and streams the results on an `ahp-search:` channel. + /// + /// Stability: 1.0 - Early development. + public var search: SearchCapability? /// Present when chats in one session may be backed by different agent /// providers (see {@link CreateChatParams.provider} and /// {@link ChatState.provider}). @@ -505,6 +510,7 @@ public struct InitializeResult: Codable, Sendable, Equatable { case telemetry case automations case tcpConnections + case search case multipleChatProviders } @@ -521,6 +527,7 @@ public struct InitializeResult: Codable, Sendable, Equatable { telemetry: TelemetryCapabilities? = nil, automations: AutomationCapabilities? = nil, tcpConnections: TcpConnectionsCapability? = nil, + search: SearchCapability? = nil, multipleChatProviders: MultipleChatProvidersCapability? = nil ) { self.protocolVersion = protocolVersion @@ -535,6 +542,7 @@ public struct InitializeResult: Codable, Sendable, Equatable { self.telemetry = telemetry self.automations = automations self.tcpConnections = tcpConnections + self.search = search self.multipleChatProviders = multipleChatProviders } } @@ -1962,6 +1970,57 @@ public struct CreateResourceWatchResult: Codable, Sendable, Equatable { } } +/// Starts a search on the host. +/// +/// The client chooses the channel URI and then subscribes to it to receive the +/// search's {@link SearchState} and its results. The client replaces the query +/// by dispatching {@link SearchQueryChangedAction | `search/queryChanged`}, +/// and cancels the search by unsubscribing. +/// +/// The client MUST NOT send this command unless `InitializeResult.search` is +/// present, and MUST NOT include a target whose kind is not listed in +/// {@link SearchCapability.targets}. +/// +/// Stability: 1.0 - Early development. +public struct CreateSearchParams: Codable, Sendable, Equatable { + /// Channel URI this command targets. + public var channel: String + /// Optional JSON-serializable metadata associated with this request. + /// Receivers MUST ignore keys they do not understand. + public var meta: [String: AnyCodable]? + /// What to search for and where. + public var query: SearchQuery + + enum CodingKeys: String, CodingKey { + case channel + case meta = "_meta" + case query + } + + public init( + channel: String, + meta: [String: AnyCodable]? = nil, + query: SearchQuery + ) { + self.channel = channel + self.meta = meta + self.query = query + } +} + +/// Result of the `createSearch` command. +/// +/// An empty object on success. +/// +/// Stability: 1.0 - Early development. +public struct CreateSearchResult: Codable, Sendable, Equatable { + + public init( + + ) { + } +} + /// Requests that the host load older historical turns into a chat state. /// /// The command result does not carry turns. Instead, before responding, the host @@ -3081,6 +3140,11 @@ extension CreateResourceWatchParams: AHPCommand { public static let method = "createResourceWatch" } +extension CreateSearchParams: AHPCommand { + public typealias Result = CreateSearchResult + public static let method = "createSearch" +} + extension ListSessionsParams: AHPCommand { public typealias Result = ListSessionsResult public static let method = "listSessions" diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index bddcd7af1..b1843d38b 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1204,6 +1204,151 @@ public enum AutomationRunOriginKind: String, Codable, Sendable { case trigger = "trigger" } +/// Discriminant for {@link SearchTarget}. +/// +/// Stability: 1.0 - Early development. +public enum SearchTargetKind: Codable, Sendable, Equatable { + /// File paths. + case fileNames + /// The text content of files. + case fileText + /// The host's sessions. + case sessions + /// The text of chat requests and responses. + case chatMessages + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "fileNames": self = .fileNames + case "fileText": self = .fileText + case "sessions": self = .sessions + case "chatMessages": self = .chatMessages + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .fileNames: try container.encode("fileNames") + case .fileText: try container.encode("fileText") + case .sessions: try container.encode("sessions") + case .chatMessages: try container.encode("chatMessages") + case .unknown(let raw): try container.encode(raw) + } + } +} + +/// Discriminant for {@link SearchResult}. +/// +/// Stability: 1.0 - Early development. +public enum SearchResultKind: Codable, Sendable, Equatable { + case fileName + case fileText + case session + case chatMessage + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "fileName": self = .fileName + case "fileText": self = .fileText + case "session": self = .session + case "chatMessage": self = .chatMessage + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .fileName: try container.encode("fileName") + case .fileText: try container.encode("fileText") + case .session: try container.encode("session") + case .chatMessage: try container.encode("chatMessage") + case .unknown(let raw): try container.encode(raw) + } + } +} + +/// Lifecycle status of a search. +/// +/// Stability: 1.0 - Early development. +public enum SearchLifecycleStatus: Codable, Sendable, Equatable { + /// The query changed and the host has not replaced the results yet. + /// {@link SearchState.results} belong to the previous query. + case pending + /// The host is searching. + case running + /// The host found every result for the query. + case completed + /// The search failed. + case failed + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "pending": self = .pending + case "running": self = .running + case "completed": self = .completed + case "failed": self = .failed + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .pending: try container.encode("pending") + case .running: try container.encode("running") + case .completed: try container.encode("completed") + case .failed: try container.encode("failed") + case .unknown(let raw): try container.encode(raw) + } + } +} + +/// Why a search completed. +/// +/// Stability: 1.0 - Early development. +public enum SearchCompletionReason: Codable, Sendable, Equatable { + /// The host searched every target. + case exhausted + /// The host stopped at the result limit. More results may exist. + case limitReached + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "exhausted": self = .exhausted + case "limitReached": self = .limitReached + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .exhausted: try container.encode("exhausted") + case .limitReached: try container.encode("limitReached") + case .unknown(let raw): try container.encode(raw) + } + } +} + // MARK: - State Types /// Present when the host supports `createTcpConnection`. @@ -8855,6 +9000,574 @@ public struct AutomationRunState: Codable, Sendable, Equatable { } } +/// Present when the host supports `createSearch`. +/// +/// Stability: 1.0 - Early development. +public struct SearchCapability: Codable, Sendable, Equatable { + /// The target kinds the host can search. A client MUST NOT send a + /// {@link SearchTarget} whose kind is not listed here. + public var targets: [SearchTargetKind] + + public init( + targets: [SearchTargetKind] + ) { + self.targets = targets + } +} + +/// What a search looks for and where. +/// +/// The client sends a query in `createSearch` and replaces it with +/// {@link SearchQueryChangedAction | `search/queryChanged`}. +/// +/// Stability: 1.0 - Early development. +public struct SearchQuery: Codable, Sendable, Equatable { + /// The text to search for. Its meaning depends on the target: see + /// {@link SearchTarget}. An empty `text` matches nothing; the host completes + /// the search with no results. + public var text: String + /// Match case. Defaults to `false`. + public var matchCase: Bool? + /// Match only whole words. Defaults to `false`. + public var wholeWord: Bool? + /// Treat `text` as a regular expression. Defaults to `false`. + public var isRegex: Bool? + /// A hint that precise matching isn't expected, for example because the + /// search powers a quick-find picker. The host MAY then match loosely, rank + /// results by how well they match, and ignore {@link isRegex} and + /// {@link wholeWord}. Defaults to `false`. + public var fuzzy: Bool? + /// Where to search. MUST contain at least one target. + public var targets: [SearchTarget] + /// The maximum number of results. The host MAY apply a lower limit, and + /// completes the search with {@link SearchCompletionReason.LimitReached} + /// when it reaches the limit that applies. + public var maxResults: Int? + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case text + case matchCase + case wholeWord + case isRegex + case fuzzy + case targets + case maxResults + } + + public init( + text: String, + matchCase: Bool? = nil, + wholeWord: Bool? = nil, + isRegex: Bool? = nil, + fuzzy: Bool? = nil, + targets: [SearchTarget], + maxResults: Int? = nil, + extra: [String: AnyCodable] = [:] + ) { + self.text = text + self.matchCase = matchCase + self.wholeWord = wholeWord + self.isRegex = isRegex + self.fuzzy = fuzzy + self.targets = targets + self.maxResults = maxResults + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.text = try container.decode(String.self, forKey: .text) + self.matchCase = try container.decodeIfPresent(Bool.self, forKey: .matchCase) + self.wholeWord = try container.decodeIfPresent(Bool.self, forKey: .wholeWord) + self.isRegex = try container.decodeIfPresent(Bool.self, forKey: .isRegex) + self.fuzzy = try container.decodeIfPresent(Bool.self, forKey: .fuzzy) + self.targets = try container.decode([SearchTarget].self, forKey: .targets) + self.maxResults = try container.decodeIfPresent(Int.self, forKey: .maxResults) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.text, forKey: .text) + try container.encodeIfPresent(self.matchCase, forKey: .matchCase) + try container.encodeIfPresent(self.wholeWord, forKey: .wholeWord) + try container.encodeIfPresent(self.isRegex, forKey: .isRegex) + try container.encodeIfPresent(self.fuzzy, forKey: .fuzzy) + try container.encode(self.targets, forKey: .targets) + try container.encodeIfPresent(self.maxResults, forKey: .maxResults) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// Searches file paths under {@link FileSearchTargetBase.roots}. +/// +/// The host decides how to match {@link SearchQuery.text} against file paths, +/// for example with fuzzy matching, and which query options apply. Results +/// are {@link FileNameSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public struct FileNamesSearchTarget: Codable, Sendable, Equatable { + /// The folders to search. MUST contain at least one URI. + public var roots: [String] + /// Glob patterns relative to a root. When present, only matching files are searched. + public var includes: [String]? + /// Glob patterns relative to a root. Matching files are not searched. + public var excludes: [String]? + /// Also search files that the host's ignore rules, such as `.gitignore` + /// files, would otherwise skip. Defaults to `false`. `excludes` still apply. + public var includeIgnored: Bool? + public var kind: SearchTargetKind + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case roots + case includes + case excludes + case includeIgnored + case kind + } + + public init( + roots: [String], + includes: [String]? = nil, + excludes: [String]? = nil, + includeIgnored: Bool? = nil, + kind: SearchTargetKind, + extra: [String: AnyCodable] = [:] + ) { + self.roots = roots + self.includes = includes + self.excludes = excludes + self.includeIgnored = includeIgnored + self.kind = kind + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.roots = try container.decode([String].self, forKey: .roots) + self.includes = try container.decodeIfPresent([String].self, forKey: .includes) + self.excludes = try container.decodeIfPresent([String].self, forKey: .excludes) + self.includeIgnored = try container.decodeIfPresent(Bool.self, forKey: .includeIgnored) + self.kind = try container.decode(SearchTargetKind.self, forKey: .kind) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.roots, forKey: .roots) + try container.encodeIfPresent(self.includes, forKey: .includes) + try container.encodeIfPresent(self.excludes, forKey: .excludes) + try container.encodeIfPresent(self.includeIgnored, forKey: .includeIgnored) + try container.encode(self.kind, forKey: .kind) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// Searches the text content of files under {@link FileSearchTargetBase.roots}. +/// Results are {@link FileTextSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public struct FileTextSearchTarget: Codable, Sendable, Equatable { + /// The folders to search. MUST contain at least one URI. + public var roots: [String] + /// Glob patterns relative to a root. When present, only matching files are searched. + public var includes: [String]? + /// Glob patterns relative to a root. Matching files are not searched. + public var excludes: [String]? + /// Also search files that the host's ignore rules, such as `.gitignore` + /// files, would otherwise skip. Defaults to `false`. `excludes` still apply. + public var includeIgnored: Bool? + public var kind: SearchTargetKind + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case roots + case includes + case excludes + case includeIgnored + case kind + } + + public init( + roots: [String], + includes: [String]? = nil, + excludes: [String]? = nil, + includeIgnored: Bool? = nil, + kind: SearchTargetKind, + extra: [String: AnyCodable] = [:] + ) { + self.roots = roots + self.includes = includes + self.excludes = excludes + self.includeIgnored = includeIgnored + self.kind = kind + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.roots = try container.decode([String].self, forKey: .roots) + self.includes = try container.decodeIfPresent([String].self, forKey: .includes) + self.excludes = try container.decodeIfPresent([String].self, forKey: .excludes) + self.includeIgnored = try container.decodeIfPresent(Bool.self, forKey: .includeIgnored) + self.kind = try container.decode(SearchTargetKind.self, forKey: .kind) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.roots, forKey: .roots) + try container.encodeIfPresent(self.includes, forKey: .includes) + try container.encodeIfPresent(self.excludes, forKey: .excludes) + try container.encodeIfPresent(self.includeIgnored, forKey: .includeIgnored) + try container.encode(self.kind, forKey: .kind) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// Searches the host's sessions, the same sessions that `listSessions` +/// returns. The host decides which session content it matches, for example +/// titles or requests. Results are {@link SessionSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public struct SessionsSearchTarget: Codable, Sendable, Equatable { + public var kind: SearchTargetKind + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + public init( + kind: SearchTargetKind, + extra: [String: AnyCodable] = [:] + ) { + self.kind = kind + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.kind = try container.decode(SearchTargetKind.self, forKey: .kind) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.kind, forKey: .kind) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// Searches the visible text of chat requests and responses, including the +/// responses of deferred turns. Results are +/// {@link ChatMessageSearchResult}s. +/// +/// Stability: 1.0 - Early development. +public struct ChatMessagesSearchTarget: Codable, Sendable, Equatable { + public var kind: SearchTargetKind + /// The chats to search. MUST contain at least one chat URI. + public var chats: [String] + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case kind + case chats + } + + public init( + kind: SearchTargetKind, + chats: [String], + extra: [String: AnyCodable] = [:] + ) { + self.kind = kind + self.chats = chats + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.kind = try container.decode(SearchTargetKind.self, forKey: .kind) + self.chats = try container.decode([String].self, forKey: .chats) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.kind, forKey: .kind) + try container.encode(self.chats, forKey: .chats) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// A matched span within {@link SearchMatch.text}: the half-open interval +/// `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code +/// units, as in {@link CompletionItem.rangeStart}. +/// +/// Stability: 1.0 - Early development. +public struct SearchHighlight: Codable, Sendable, Equatable { + /// The start of the span. + public var rangeStart: Int + /// The end of the span, exclusive. MUST be greater than {@link rangeStart} + /// and at most the length of {@link SearchMatch.text}. + public var rangeEnd: Int + + public init( + rangeStart: Int, + rangeEnd: Int + ) { + self.rangeStart = rangeStart + self.rangeEnd = rangeEnd + } +} + +/// The matched text of a result, with the matched spans highlighted. The host +/// chooses how much text around the match to include. +/// +/// Stability: 1.0 - Early development. +public struct SearchMatch: Codable, Sendable, Equatable { + /// The text to display. + public var text: String + /// The matched spans, in order. Spans MUST NOT overlap. + public var highlights: [SearchHighlight] + + public init( + text: String, + highlights: [SearchHighlight] + ) { + self.text = text + self.highlights = highlights + } +} + +/// A file whose path matches. {@link SearchResultBase.resource} is the file; +/// the match text is its path, usually relative to the root that contains it. +/// +/// Stability: 1.0 - Early development. +public struct FileNameSearchResult: Codable, Sendable, Equatable { + /// The resource that contains the match. + public var resource: String + /// The text to display, with the matched spans highlighted. + public var match: SearchMatch + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + public var score: Double? + public var kind: SearchResultKind + + public init( + resource: String, + match: SearchMatch, + score: Double? = nil, + kind: SearchResultKind + ) { + self.resource = resource + self.match = match + self.score = score + self.kind = kind + } +} + +/// A match in the text of a file. {@link SearchResultBase.resource} is the +/// file; the match text is the text around the match, usually its line. +/// +/// Stability: 1.0 - Early development. +public struct FileTextSearchResult: Codable, Sendable, Equatable { + /// The resource that contains the match. + public var resource: String + /// The text to display, with the matched spans highlighted. + public var match: SearchMatch + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + public var score: Double? + public var kind: SearchResultKind + /// The location of the match in the file. + public var range: TextRange + + public init( + resource: String, + match: SearchMatch, + score: Double? = nil, + kind: SearchResultKind, + range: TextRange + ) { + self.resource = resource + self.match = match + self.score = score + self.kind = kind + self.range = range + } +} + +/// A session whose content matches. {@link SearchResultBase.resource} is the +/// session URI. +/// +/// Stability: 1.0 - Early development. +public struct SessionSearchResult: Codable, Sendable, Equatable { + /// The resource that contains the match. + public var resource: String + /// The text to display, with the matched spans highlighted. + public var match: SearchMatch + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + public var score: Double? + public var kind: SearchResultKind + /// The session's title. + public var title: String + + public init( + resource: String, + match: SearchMatch, + score: Double? = nil, + kind: SearchResultKind, + title: String + ) { + self.resource = resource + self.match = match + self.score = score + self.kind = kind + self.title = title + } +} + +/// A match in a chat request or response. {@link SearchResultBase.resource} +/// is the chat URI. +/// +/// Stability: 1.0 - Early development. +public struct ChatMessageSearchResult: Codable, Sendable, Equatable { + /// The resource that contains the match. + public var resource: String + /// The text to display, with the matched spans highlighted. + public var match: SearchMatch + /// How well the result matches; higher is better. Scores have no fixed + /// range, and are comparable across all results of one search. Clients + /// SHOULD show results in descending score order. A host that does not rank + /// results omits the score. + public var score: Double? + public var kind: SearchResultKind + /// The chat's title. + public var title: String + /// The ID of the turn that contains the match. + public var turnId: String + + public init( + resource: String, + match: SearchMatch, + score: Double? = nil, + kind: SearchResultKind, + title: String, + turnId: String + ) { + self.resource = resource + self.match = match + self.score = score + self.kind = kind + self.title = title + self.turnId = turnId + } +} + +/// The query changed and the host has not replaced the results yet. Clients +/// MAY show the previous query's results differently, for example dimmed. +/// +/// Stability: 1.0 - Early development. +public struct SearchPendingLifecycleState: Codable, Sendable, Equatable { + public var status: SearchLifecycleStatus + + public init( + status: SearchLifecycleStatus + ) { + self.status = status + } +} + +/// The host is searching and may add more results. +/// +/// Stability: 1.0 - Early development. +public struct SearchRunningLifecycleState: Codable, Sendable, Equatable { + public var status: SearchLifecycleStatus + + public init( + status: SearchLifecycleStatus + ) { + self.status = status + } +} + +/// The host found every result for the query. A host that watches the +/// searched files, sessions, or chats MAY still change the results later. +/// +/// Stability: 1.0 - Early development. +public struct SearchCompletedLifecycleState: Codable, Sendable, Equatable { + public var status: SearchLifecycleStatus + /// Why the search completed. + public var reason: SearchCompletionReason + + public init( + status: SearchLifecycleStatus, + reason: SearchCompletionReason + ) { + self.status = status + self.reason = reason + } +} + +/// The search failed. Results found before the failure remain in +/// {@link SearchState.results}. +/// +/// Stability: 1.0 - Early development. +public struct SearchFailedLifecycleState: Codable, Sendable, Equatable { + public var status: SearchLifecycleStatus + /// Why the search failed, for example an invalid regular expression. + public var error: ErrorInfo + + public init( + status: SearchLifecycleStatus, + error: ErrorInfo + ) { + self.status = status + self.error = error + } +} + +/// Full state for one search, returned when a client subscribes to its +/// `ahp-search:` URI. +/// +/// Stability: 1.0 - Early development. +public struct SearchState: Codable, Sendable, Equatable { + /// The current query. + public var query: SearchQuery + /// Results in the order the host found them. Sort by + /// {@link SearchResultBase.score} to rank them. While {@link lifecycle} is + /// {@link SearchLifecycleStatus.Pending | pending}, these are results for the + /// previous query. + public var results: [SearchResult] + /// Where the search is in its lifecycle. + public var lifecycle: SearchLifecycleState + + public init( + query: SearchQuery, + results: [SearchResult], + lifecycle: SearchLifecycleState + ) { + self.query = query + self.results = results + self.lifecycle = lifecycle + } +} + // MARK: - Customization Enablement Union /// A single explicit customization enablement decision. @@ -10297,6 +11010,146 @@ public enum AutomationRunLifecycle: Codable, Sendable, Equatable { } } +public enum SearchTarget: Codable, Sendable, Equatable { + case fileNames(FileNamesSearchTarget) + case fileText(FileTextSearchTarget) + case sessions(SessionsSearchTarget) + case chatMessages(ChatMessagesSearchTarget) + /// Unknown or future discriminant; the raw payload is preserved + /// and re-encoded verbatim for forward-compatibility. + case unknown(AnyCodable) + + private enum DiscriminantKey: String, CodingKey { + case discriminant = "kind" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: DiscriminantKey.self) + guard let discriminant = try container.decodeIfPresent(String.self, forKey: .discriminant) else { + self = .unknown(try AnyCodable(from: decoder)) + return + } + switch discriminant { + case "fileNames": + self = .fileNames(try FileNamesSearchTarget(from: decoder)) + case "fileText": + self = .fileText(try FileTextSearchTarget(from: decoder)) + case "sessions": + self = .sessions(try SessionsSearchTarget(from: decoder)) + case "chatMessages": + self = .chatMessages(try ChatMessagesSearchTarget(from: decoder)) + default: + self = .unknown(try AnyCodable(from: decoder)) + } + } + + public func encode(to encoder: Encoder) throws { + switch self { + case .fileNames(let value): try value.encode(to: encoder) + case .fileText(let value): try value.encode(to: encoder) + case .sessions(let value): try value.encode(to: encoder) + case .chatMessages(let value): try value.encode(to: encoder) + case .unknown(let value): try value.encode(to: encoder) + } + } +} + +public enum SearchResult: Codable, Sendable, Equatable { + case fileName(FileNameSearchResult) + case fileText(FileTextSearchResult) + case session(SessionSearchResult) + case chatMessage(ChatMessageSearchResult) + /// Unknown or future discriminant; the raw payload is preserved + /// and re-encoded verbatim for forward-compatibility. + case unknown(AnyCodable) + + private enum DiscriminantKey: String, CodingKey { + case discriminant = "kind" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: DiscriminantKey.self) + guard let discriminant = try container.decodeIfPresent(String.self, forKey: .discriminant) else { + self = .unknown(try AnyCodable(from: decoder)) + return + } + switch discriminant { + case "fileName": + self = .fileName(try FileNameSearchResult(from: decoder)) + case "fileText": + self = .fileText(try FileTextSearchResult(from: decoder)) + case "session": + self = .session(try SessionSearchResult(from: decoder)) + case "chatMessage": + self = .chatMessage(try ChatMessageSearchResult(from: decoder)) + default: + self = .unknown(try AnyCodable(from: decoder)) + } + } + + public func encode(to encoder: Encoder) throws { + switch self { + case .fileName(let value): try value.encode(to: encoder) + case .fileText(let value): try value.encode(to: encoder) + case .session(let value): try value.encode(to: encoder) + case .chatMessage(let value): try value.encode(to: encoder) + case .unknown(let value): try value.encode(to: encoder) + } + } +} + +public enum SearchLifecycleState: Codable, Sendable, Equatable { + case pending(SearchPendingLifecycleState) + case running(SearchRunningLifecycleState) + case completed(SearchCompletedLifecycleState) + case failed(SearchFailedLifecycleState) + /// Unknown or future discriminant; the raw payload is preserved + /// and re-encoded verbatim for forward-compatibility. + case unknown(AnyCodable) + + private enum DiscriminantKey: String, CodingKey { + case discriminant = "status" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: DiscriminantKey.self) + guard let discriminant = try container.decodeIfPresent(String.self, forKey: .discriminant) else { + self = .unknown(try AnyCodable(from: decoder)) + return + } + switch discriminant { + case "pending": + self = .pending(try SearchPendingLifecycleState(from: decoder)) + case "running": + self = .running(try SearchRunningLifecycleState(from: decoder)) + case "completed": + self = .completed(try SearchCompletedLifecycleState(from: decoder)) + case "failed": + self = .failed(try SearchFailedLifecycleState(from: decoder)) + default: + self = .unknown(try AnyCodable(from: decoder)) + } + } + + public func encode(to encoder: Encoder) throws { + switch self { + case .pending(var value): + value.status = .pending + try value.encode(to: encoder) + case .running(var value): + value.status = .running + try value.encode(to: encoder) + case .completed(var value): + value.status = .completed + try value.encode(to: encoder) + case .failed(var value): + value.status = .failed + try value.encode(to: encoder) + case .unknown(let value): try value.encode(to: encoder) + } + } +} + public enum ToolResultContent: Codable, Sendable, Equatable { case text(ToolResultTextContent) case embeddedResource(ToolResultEmbeddedResourceContent) @@ -10367,6 +11220,7 @@ public enum SnapshotState: Codable, Sendable, Equatable { case annotations(AnnotationsState) case automations(AutomationState) case automationRun(AutomationRunState) + case search(SearchState) /// A state that this version does not recognize, kept as raw JSON so it /// re-encodes unchanged. case unknown(AnyCodable) @@ -10389,6 +11243,7 @@ public enum SnapshotState: Codable, Sendable, Equatable { case "ahp-resource-watch": return .resourceWatch(try ResourceWatchState(from: decoder)) case "ahp-annotations": return .annotations(try AnnotationsState(from: decoder)) case "ahp-automation-run": return .automationRun(try AutomationRunState(from: decoder)) + case "ahp-search": return .search(try SearchState(from: decoder)) case "ahp-tcp": return .empty(try EmptyState(from: decoder)) case "ahp-otlp": return .empty(try EmptyState(from: decoder)) default: return .unknown(try AnyCodable(from: decoder)) @@ -10408,6 +11263,7 @@ public enum SnapshotState: Codable, Sendable, Equatable { case .annotations(let state): try state.encode(to: encoder) case .automations(let state): try state.encode(to: encoder) case .automationRun(let state): try state.encode(to: encoder) + case .search(let state): try state.encode(to: encoder) case .unknown(let raw): try raw.encode(to: encoder) } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index 184d61f34..f750f6f1e 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -1309,6 +1309,33 @@ public func canvasReducer(state: CanvasState, action: StateAction) -> CanvasStat return a.canvas } +// MARK: - Search Reducer + +/// Pure reducer for search state. Handles the `search/*` actions. +public func searchReducer(state: SearchState, action: StateAction) -> SearchState { + var next = state + switch action { + case .searchQueryChanged(let a): + next.query = a.query + next.lifecycle = .pending(SearchPendingLifecycleState(status: .pending)) + case .searchResultsChanged(let a): + guard a.replace == true else { + guard !a.results.isEmpty else { return state } + next.results.append(contentsOf: a.results) + return next + } + next.results = a.results + if case .pending = state.lifecycle { + next.lifecycle = .running(SearchRunningLifecycleState(status: .running)) + } + case .searchLifecycleChanged(let a): + next.lifecycle = a.lifecycle + default: + return state + } + return next +} + // MARK: - Terminal Reducer /// Pure reducer for terminal state. Handles all terminal-scoped actions. diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/AHPStateMirror.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/AHPStateMirror.swift index 89d1e537c..e3b936784 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/AHPStateMirror.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/AHPStateMirror.swift @@ -23,6 +23,7 @@ public actor AHPStateMirror { public private(set) var automationCatalog = AutomationState(entries: []) public private(set) var automations: [String: AutomationEntry] = [:] public private(set) var automationRuns: [String: AutomationRunState] = [:] + public private(set) var searches: [String: SearchState] = [:] public init() {} @@ -55,6 +56,10 @@ public actor AHPStateMirror { canvases[channel] = canvasReducer(state: canvas, action: action) return } + if channel.hasPrefix("ahp-search:"), let search = searches[channel] { + searches[channel] = searchReducer(state: search, action: action) + return + } if channel.hasPrefix("ahp-terminal:"), var terminal = terminals[channel] { terminal = terminalReducer(state: terminal, action: action) terminals[channel] = terminal @@ -115,6 +120,8 @@ public actor AHPStateMirror { rebuildAutomationIndex() case .automationRun(let state): automationRuns[snapshot.resource] = state + case .search(let state): + searches[snapshot.resource] = state } } @@ -139,5 +146,6 @@ public actor AHPStateMirror { automationCatalog = AutomationState(entries: []) automations.removeAll() automationRuns.removeAll() + searches.removeAll() } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/MultiHostStateMirror.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/MultiHostStateMirror.swift index 64a896434..082873bfa 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/MultiHostStateMirror.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocolClient/MultiHostStateMirror.swift @@ -53,6 +53,7 @@ public actor MultiHostStateMirror { public private(set) var automationCatalogs: [HostId: AutomationState] = [:] public private(set) var automations: [HostedResourceKey: AutomationEntry] = [:] public private(set) var automationRuns: [HostedResourceKey: AutomationRunState] = [:] + public private(set) var searches: [HostedResourceKey: SearchState] = [:] public init() {} @@ -95,6 +96,10 @@ public actor MultiHostStateMirror { canvases[key] = canvasReducer(state: canvas, action: action) return } + if channel.hasPrefix("ahp-search:"), let search = searches[key] { + searches[key] = searchReducer(state: search, action: action) + return + } if channel.hasPrefix("ahp-terminal:"), var terminal = terminals[key] { terminal = terminalReducer(state: terminal, action: action) terminals[key] = terminal @@ -158,6 +163,8 @@ public actor MultiHostStateMirror { setAutomationCatalog(host: host, catalog: state) case .automationRun(let state): automationRuns[key] = state + case .search(let state): + searches[key] = state } } @@ -174,6 +181,7 @@ public actor MultiHostStateMirror { automationCatalogs.removeValue(forKey: host) automations = automations.filter { $0.key.hostId != host } automationRuns = automationRuns.filter { $0.key.hostId != host } + searches = searches.filter { $0.key.hostId != host } } /// Reset every host's state. @@ -189,6 +197,7 @@ public actor MultiHostStateMirror { automationCatalogs.removeAll() automations.removeAll() automationRuns.removeAll() + searches.removeAll() } private func setAutomationCatalog(host: HostId, catalog: AutomationState) { diff --git a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/AHPStateMirrorTests.swift b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/AHPStateMirrorTests.swift index 3e6c0683c..23097ad27 100644 --- a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/AHPStateMirrorTests.swift +++ b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/AHPStateMirrorTests.swift @@ -69,6 +69,29 @@ final class AHPStateMirrorTests: XCTestCase { XCTAssertTrue(remaining.isEmpty) } + func testSearchQueryChangeKeepsResultsAndResetsLifecycle() async { + let mirror = AHPStateMirror() + let resource = "ahp-search:/s1" + let initial = SearchState( + query: SearchQuery(text: "parseConfig", targets: [.sessions(SessionsSearchTarget(kind: .sessions))]), + results: [], + lifecycle: .completed(SearchCompletedLifecycleState(status: .completed, reason: .exhausted)) + ) + await mirror.applySnapshot(Snapshot(resource: resource, state: .search(initial), fromSeq: 1)) + let next = SearchQuery(text: "loadConfig", targets: [.sessions(SessionsSearchTarget(kind: .sessions))]) + await mirror.apply(ActionEnvelope( + channel: resource, + action: .searchQueryChanged(SearchQueryChangedAction(type: .searchQueryChanged, query: next)), + serverSeq: 2 + )) + let changed = await mirror.searches + await mirror.reset() + let remaining = await mirror.searches + XCTAssertEqual(changed[resource]?.query.text, "loadConfig") + XCTAssertEqual(changed[resource]?.lifecycle, .pending(SearchPendingLifecycleState(status: .pending))) + XCTAssertTrue(remaining.isEmpty) + } + func testApplySnapshotSeedsRootState() async { let mirror = AHPStateMirror() let agents = [ diff --git a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/MultiHostStateMirrorTests.swift b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/MultiHostStateMirrorTests.swift index a4be792ff..4a78daf48 100644 --- a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/MultiHostStateMirrorTests.swift +++ b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/MultiHostStateMirrorTests.swift @@ -68,6 +68,39 @@ final class MultiHostStateMirrorTests: XCTestCase { XCTAssertTrue(remaining.isEmpty) } + func testSearchUpdatesAndResetAreIsolatedPerHost() async { + let mirror = MultiHostStateMirror() + let resource = "ahp-search:/s1" + let initial = SearchState( + query: SearchQuery(text: "parseConfig", targets: [.sessions(SessionsSearchTarget(kind: .sessions))]), + results: [], + lifecycle: .pending(SearchPendingLifecycleState(status: .pending)) + ) + let snapshot = Snapshot(resource: resource, state: .search(initial), fromSeq: 1) + await mirror.applySnapshot(host: "alpha", snapshot: snapshot) + await mirror.applySnapshot(host: "beta", snapshot: snapshot) + await mirror.apply(host: "alpha", envelope: ActionEnvelope( + channel: resource, + action: .searchLifecycleChanged(SearchLifecycleChangedAction( + type: .searchLifecycleChanged, + lifecycle: .completed(SearchCompletedLifecycleState(status: .completed, reason: .exhausted)) + )), + serverSeq: 2 + )) + let targeted = await mirror.searches + await mirror.reset(host: "alpha") + let afterReset = await mirror.searches + await mirror.reset() + let remaining = await mirror.searches + let alphaKey = HostedResourceKey(hostId: "alpha", uri: resource) + let betaKey = HostedResourceKey(hostId: "beta", uri: resource) + XCTAssertEqual(targeted[alphaKey]?.lifecycle, .completed(SearchCompletedLifecycleState(status: .completed, reason: .exhausted))) + XCTAssertEqual(targeted[betaKey]?.lifecycle, .pending(SearchPendingLifecycleState(status: .pending))) + XCTAssertNil(afterReset[alphaKey]) + XCTAssertNotNil(afterReset[betaKey]) + XCTAssertTrue(remaining.isEmpty) + } + // MARK: - root_states_are_isolated_per_host func testRootStatesAreIsolatedPerHost() async { diff --git a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolTests/FixtureDrivenReducerTests.swift b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolTests/FixtureDrivenReducerTests.swift index 2b216d639..3bd0d075f 100644 --- a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolTests/FixtureDrivenReducerTests.swift +++ b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolTests/FixtureDrivenReducerTests.swift @@ -196,6 +196,10 @@ final class FixtureDrivenReducerTests: XCTestCase { try compareFixture(file: file, fixture: fixture, stateType: CanvasState.self) { state in actions.reduce(state) { canvasReducer(state: $0, action: $1) } } + case "search": + try compareFixture(file: file, fixture: fixture, stateType: SearchState.self) { state in + actions.reduce(state) { searchReducer(state: $0, action: $1) } + } case "annotations": try compareFixture(file: file, fixture: fixture, stateType: AnnotationsState.self) { state in actions.reduce(state) { annotationsReducer(state: $0, action: $1) } diff --git a/clients/typescript/src/client/hosts/state-mirror.ts b/clients/typescript/src/client/hosts/state-mirror.ts index 4e5292e14..c724852e9 100644 --- a/clients/typescript/src/client/hosts/state-mirror.ts +++ b/clients/typescript/src/client/hosts/state-mirror.ts @@ -35,6 +35,7 @@ import type { AutomationAction, AutomationRunAction, RootAction, + SearchAction, SessionAction, TerminalAction, } from '../../types/action-origin.generated.js'; @@ -45,6 +46,7 @@ import type { SessionState } from '../../types/channels-session/state.js'; import type { TerminalState } from '../../types/channels-terminal/state.js'; import type { AutomationEntry, AutomationState } from '../../types/channels-automation/state.js'; import type { AutomationRunState } from '../../types/channels-automation-run/state.js'; +import type { SearchState } from '../../types/channels-search/state.js'; import { changesetReducer } from '../../types/channels-changeset/reducer.js'; import { canvasReducer } from '../../types/channels-canvas/reducer.js'; import { rootReducer } from '../../types/channels-root/reducer.js'; @@ -52,6 +54,7 @@ import { sessionReducer } from '../../types/channels-session/reducer.js'; import { terminalReducer } from '../../types/channels-terminal/reducer.js'; import { automationReducer } from '../../types/channels-automation/reducer.js'; import { automationRunReducer } from '../../types/channels-automation-run/reducer.js'; +import { searchReducer } from '../../types/channels-search/reducer.js'; import { ROOT_RESOURCE_URI, type HostId, type HostSubscriptionEvent } from './types.js'; import { isCanvasState } from '../canvas-state.js'; @@ -112,6 +115,7 @@ export class MultiHostStateMirror { private readonly automationCatalogsMap = new Map(); private readonly automationsMap = new Map(); private readonly automationRunsMap = new Map(); + private readonly searchesMap = new Map(); /** All known root states keyed by host. */ get rootStates(): ReadonlyMap { @@ -152,6 +156,11 @@ export class MultiHostStateMirror { return this.automationRunsMap; } + /** Searches keyed by `hostedResourceKey(hostId, uri)`. */ + get searches(): ReadonlyMap { + return this.searchesMap; + } + /** Look up the root state for `hostId`. */ getRoot(hostId: HostId): RootState | undefined { @@ -182,6 +191,11 @@ export class MultiHostStateMirror { return this.automationsMap.get(hostedResourceKey(hostId, uri)); } + /** Look up a search by `(hostId, uri)`. */ + getSearch(hostId: HostId, uri: URI): SearchState | undefined { + return this.searchesMap.get(hostedResourceKey(hostId, uri)); + } + /** * Convenience: apply a {@link HostSubscriptionEvent} produced by * {@link MultiHostClient.events}. Action envelopes are routed through @@ -250,6 +264,13 @@ export class MultiHostStateMirror { this.automationRunsMap.set(key, automationRunReducer(current, action as AutomationRunAction)); return; } + if (channel.startsWith('ahp-search:')) { + const key = hostedResourceKey(hostId, channel); + const current = this.searchesMap.get(key); + if (!current) return; + this.searchesMap.set(key, searchReducer(current, action as SearchAction)); + return; + } } /** @@ -291,6 +312,10 @@ export class MultiHostStateMirror { this.automationRunsMap.set(key, snapshot.state as AutomationRunState); return; } + if (resource.startsWith('ahp-search:')) { + this.searchesMap.set(key, snapshot.state as SearchState); + return; + } } /** Drop every slot keyed under `hostId` — root, sessions, terminals, changesets. */ @@ -316,6 +341,9 @@ export class MultiHostStateMirror { for (const key of this.automationRunsMap.keys()) { if (key.startsWith(prefix)) this.automationRunsMap.delete(key); } + for (const key of this.searchesMap.keys()) { + if (key.startsWith(prefix)) this.searchesMap.delete(key); + } } /** Drop every host's state. */ @@ -328,6 +356,7 @@ export class MultiHostStateMirror { this.automationCatalogsMap.clear(); this.automationsMap.clear(); this.automationRunsMap.clear(); + this.searchesMap.clear(); } private setAutomationCatalog(hostId: HostId, state: AutomationState): void { diff --git a/clients/typescript/src/client/state-mirror.ts b/clients/typescript/src/client/state-mirror.ts index 1d4ca9954..c1bf9a033 100644 --- a/clients/typescript/src/client/state-mirror.ts +++ b/clients/typescript/src/client/state-mirror.ts @@ -2,8 +2,8 @@ * Convenience reducer-driven state store, mirroring the Swift * `AHPStateMirror` and the Rust reducers example. * - * Tracks root, session, canvas, terminal, changeset, automation catalogue, and - * automation-run state. Apply {@link Snapshot}s and {@link ActionEnvelope}s and + * Tracks root, session, canvas, terminal, changeset, automation catalogue, + * automation-run, and search state. Apply {@link Snapshot}s and {@link ActionEnvelope}s and * the mirror keeps those resources up to date via the generated reducers. * * Useful for simple clients. Larger apps will usually keep their own @@ -19,6 +19,7 @@ import type { AutomationAction, AutomationRunAction, RootAction, + SearchAction, SessionAction, TerminalAction, } from '../types/action-origin.generated.js'; @@ -29,6 +30,7 @@ import type { SessionState } from '../types/channels-session/state.js'; import type { TerminalState } from '../types/channels-terminal/state.js'; import type { AutomationEntry, AutomationState } from '../types/channels-automation/state.js'; import type { AutomationRunState } from '../types/channels-automation-run/state.js'; +import type { SearchState } from '../types/channels-search/state.js'; import { changesetReducer } from '../types/channels-changeset/reducer.js'; import { canvasReducer } from '../types/channels-canvas/reducer.js'; import { rootReducer } from '../types/channels-root/reducer.js'; @@ -36,6 +38,7 @@ import { sessionReducer } from '../types/channels-session/reducer.js'; import { terminalReducer } from '../types/channels-terminal/reducer.js'; import { automationReducer } from '../types/channels-automation/reducer.js'; import { automationRunReducer } from '../types/channels-automation-run/reducer.js'; +import { searchReducer } from '../types/channels-search/reducer.js'; import { isCanvasState } from './canvas-state.js'; const ROOT_URI = 'ahp-root://' as const; @@ -54,6 +57,7 @@ export class AhpStateMirror { private automationCatalogState: AutomationState = INITIAL_AUTOMATION_CATALOG; private readonly automationsMap = new Map(); private readonly automationRunsMap = new Map(); + private readonly searchesMap = new Map(); /** Current root state. */ get root(): RootState { @@ -94,6 +98,11 @@ export class AhpStateMirror { return this.automationRunsMap; } + /** All known searches keyed by their channel URI. */ + get searches(): ReadonlyMap { + return this.searchesMap; + } + /** Look up a session by URI. */ getSession(uri: URI): SessionState | undefined { @@ -114,6 +123,11 @@ export class AhpStateMirror { return this.automationsMap.get(uri); } + /** Look up a search by its channel URI. */ + getSearch(uri: URI): SearchState | undefined { + return this.searchesMap.get(uri); + } + /** * Apply a server snapshot, replacing the state for the resource the * snapshot covers. @@ -151,6 +165,10 @@ export class AhpStateMirror { this.automationRunsMap.set(resource, snapshot.state as AutomationRunState); return; } + if (resource.startsWith('ahp-search:')) { + this.searchesMap.set(resource, snapshot.state as SearchState); + return; + } } /** @@ -204,6 +222,12 @@ export class AhpStateMirror { this.automationRunsMap.set(channel, automationRunReducer(current, action as AutomationRunAction)); return; } + if (channel.startsWith('ahp-search:')) { + const current = this.searchesMap.get(channel); + if (!current) return; + this.searchesMap.set(channel, searchReducer(current, action as SearchAction)); + return; + } } private setAutomationCatalog(state: AutomationState): void { diff --git a/clients/typescript/test/client.test.ts b/clients/typescript/test/client.test.ts index 8b4611ea7..3905c01b4 100644 --- a/clients/typescript/test/client.test.ts +++ b/clients/typescript/test/client.test.ts @@ -44,6 +44,7 @@ import { AutomationOperation, type AutomationEntry } from '../src/types/channels import { MessageKind } from '../src/types/channels-chat/state.js'; import { SessionLifecycle, SessionStatus } from '../src/types/channels-session/state.js'; import type { CanvasState } from '../src/types/channels-canvas/state.js'; +import { SearchCompletionReason, SearchLifecycleStatus, SearchTargetKind, type SearchState } from '../src/types/channels-search/state.js'; import type { Snapshot } from '../src/types/common/state.js'; const ROOT = 'ahp-root://' as const; @@ -223,6 +224,30 @@ test('state mirror replaces and clears live canvas sources', () => { }); }); +test('state mirror reduces search actions on search channels', () => { + const mirror = new AhpStateMirror(); + const resource = 'ahp-search:/s1'; + const initial: SearchState = { + query: { text: 'parseConfig', targets: [{ kind: SearchTargetKind.Sessions }] }, + results: [], + lifecycle: { status: SearchLifecycleStatus.Pending }, + }; + mirror.applySnapshot({ resource, state: initial, fromSeq: 1 }); + mirror.apply({ + channel: resource, + serverSeq: 2, + origin: undefined, + action: { + type: ActionType.SearchLifecycleChanged, + lifecycle: { status: SearchLifecycleStatus.Completed, reason: SearchCompletionReason.Exhausted }, + }, + }); + assert.deepEqual(mirror.getSearch(resource), { + ...initial, + lifecycle: { status: SearchLifecycleStatus.Completed, reason: SearchCompletionReason.Exhausted }, + }); +}); + test('state mirror rejects a non-canvas snapshot on a canvas channel', () => { const mirror = new AhpStateMirror(); assert.throws(() => mirror.applySnapshot({ diff --git a/clients/typescript/test/hosts.test.ts b/clients/typescript/test/hosts.test.ts index 2cb33fc4b..91cdb01f9 100644 --- a/clients/typescript/test/hosts.test.ts +++ b/clients/typescript/test/hosts.test.ts @@ -57,6 +57,7 @@ import { import { PROTOCOL_VERSION } from '../src/types/version/registry.js'; import { SessionLifecycle, SessionStatus } from '../src/types/channels-session/state.js'; import type { CanvasState } from '../src/types/channels-canvas/state.js'; +import { SearchCompletionReason, SearchLifecycleStatus, SearchTargetKind, type SearchState } from '../src/types/channels-search/state.js'; import { ActionType, type ActionEnvelope } from '../src/types/common/actions.js'; const ROOT = 'ahp-root://' as const; @@ -410,6 +411,39 @@ test('MultiHostStateMirror isolates canvas updates and clears canvas state on re }); }); +test('MultiHostStateMirror isolates search updates and clears search state on reset', () => { + const mirror = new MultiHostStateMirror(); + const resource = 'ahp-search:/s1'; + const initial: SearchState = { + query: { text: 'parseConfig', targets: [{ kind: SearchTargetKind.Sessions }] }, + results: [], + lifecycle: { status: SearchLifecycleStatus.Pending }, + }; + mirror.applySnapshot('host-a', { resource, state: initial, fromSeq: 1 }); + mirror.applySnapshot('host-b', { resource, state: initial, fromSeq: 1 }); + mirror.applyEnvelope('host-a', { + channel: resource, + serverSeq: 2, + origin: undefined, + action: { + type: ActionType.SearchLifecycleChanged, + lifecycle: { status: SearchLifecycleStatus.Completed, reason: SearchCompletionReason.LimitReached }, + }, + }); + const updated = mirror.getSearch('host-a', resource)?.lifecycle; + mirror.resetHost('host-a'); + const afterHostReset = { + removed: mirror.getSearch('host-a', resource), + retained: mirror.getSearch('host-b', resource), + }; + mirror.reset(); + assert.deepEqual({ updated, afterHostReset, remaining: mirror.searches.size }, { + updated: { status: SearchLifecycleStatus.Completed, reason: SearchCompletionReason.LimitReached }, + afterHostReset: { removed: undefined, retained: initial }, + remaining: 0, + }); +}); + test('MultiHostStateMirror.resetHost drops every keyed state for that host', () => { const mirror = new MultiHostStateMirror(); mirror.applySnapshot('host-a', { resource: ROOT, state: { agents: [] }, fromSeq: 0 }); diff --git a/docs/.changes/20261124-completion-range-integers.json b/docs/.changes/20261124-completion-range-integers.json new file mode 100644 index 000000000..1d568e938 --- /dev/null +++ b/docs/.changes/20261124-completion-range-integers.json @@ -0,0 +1,5 @@ +{ + "type": "changed", + "message": "`CompletionItem.rangeStart` and `rangeEnd` are now typed as integers in the JSON Schema, with minimums of 0 and 1.", + "targets": ["spec"] +} diff --git a/docs/.changes/20261124-search-channel.json b/docs/.changes/20261124-search-channel.json new file mode 100644 index 000000000..b7ed14908 --- /dev/null +++ b/docs/.changes/20261124-search-channel.json @@ -0,0 +1,4 @@ +{ + "type": "added", + "message": "Experimental `ahp-search:` channel: `createSearch` searches file names, file text, sessions, and chat messages and streams scored, highlighted results into `SearchState`. Clients change the query with `search/queryChanged` (results stay visible while the lifecycle is `pending`) and cancel by unsubscribing; hosts append or replace results with `search/resultsChanged` and report progress with `search/lifecycleChanged`." +} diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index cdc4a6f4e..54b7002f3 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -104,6 +104,7 @@ export default withMermaid(defineConfigWithTheme({ { text: 'Automation Run Channel', link: '/specification/automation-run-channel' }, { text: 'Terminal Channel', link: '/specification/terminal-channel' }, { text: 'TCP Channel', link: '/specification/tcp-channel' }, + { text: 'Search Channel', link: '/specification/search-channel' }, { text: 'Resource Watch Channel', link: '/specification/resource-watch-channel' }, { text: 'Telemetry Channel', link: '/specification/telemetry-channel' }, ], @@ -127,6 +128,7 @@ export default withMermaid(defineConfigWithTheme({ { text: 'Canvas Channel', link: '/reference/canvas' }, { text: 'Terminal Channel', link: '/reference/terminal' }, { text: 'TCP Channel', link: '/reference/tcp' }, + { text: 'Search Channel', link: '/reference/search' }, { text: 'Changeset Channel', link: '/reference/changeset' }, { text: 'Annotations Channel', link: '/reference/annotations' }, { text: 'Automation Catalogue Channel', link: '/reference/automation' }, diff --git a/docs/specification/overview.md b/docs/specification/overview.md index 5653ac9d4..3f64307ca 100644 --- a/docs/specification/overview.md +++ b/docs/specification/overview.md @@ -87,6 +87,7 @@ The specification is organised around the **channels** that AHP exposes — each - **[Chat Channel](/specification/chat-channel)** — `ahp-chat:/` — per-chat conversation state: turns, streaming, tool calls, pending messages, input requests, and changesets. - **[Terminal Channel](/specification/terminal-channel)** — per-terminal pty state, data flow, claims, command detection. - **[TCP Channel](/specification/tcp-channel)** — `ahp-tcp:` — experimental forwarding of a TCP connection that the host opens on its network. +- **[Search Channel](/specification/search-channel)** — `ahp-search:` — experimental search over files, sessions, and chats, with streamed results. - **[Telemetry Channel](/specification/telemetry-channel)** — `ahp-otlp:` — OpenTelemetry logs, traces, and metrics emitted by the agent host. - **[Versioning](/specification/versioning)** — Protocol version negotiation and compatibility. - **[Common Types](/reference/common)** — Cross-cutting types, base command/notification shapes, and JSON-RPC wire types. @@ -95,6 +96,7 @@ The specification is organised around the **channels** that AHP exposes — each - **[Chat Channel Reference](/reference/chat)** — `ChatState`, chat actions, and chat commands. - **[Terminal Channel Reference](/reference/terminal)** — `TerminalState`, terminal actions, and terminal commands. - **[TCP Channel Reference](/reference/tcp)** — `createTcpConnection` and TCP notifications. +- **[Search Channel Reference](/reference/search)** — `SearchState`, search actions, and `createSearch`. - **[Changeset Channel Reference](/reference/changeset)** — `ChangesetState`, changeset actions, and changeset commands. - **[Annotations Channel Reference](/reference/annotations)** — `AnnotationsState` and annotations actions. - **[Automation Catalogue Channel Reference](/reference/automation)** — `AutomationState`, automation actions, and automation commands. diff --git a/docs/specification/search-channel.md b/docs/specification/search-channel.md new file mode 100644 index 000000000..af6c240e6 --- /dev/null +++ b/docs/specification/search-channel.md @@ -0,0 +1,215 @@ +# Search Channel + + + +A search channel runs one search on the host and streams its results into the +channel's state. One search can look in file names, file contents, session +titles, and chat messages at the same time. The client can change the query +while the search runs, and cancels the search by unsubscribing. + +## Capability + +A host that supports search includes `search` in the `initialize` result. It +lists the kinds of target that the host can search: + +```json +{ "search": { "targets": ["fileNames", "fileText", "sessions", "chatMessages"] } } +``` + +A client MUST NOT send `createSearch` unless this member is present, and MUST +NOT include a target whose kind is not listed. + +## Starting a Search + +The client chooses a URI for the new channel and sends `createSearch` with a +query: + +```json +{ + "jsonrpc": "2.0", + "id": 40, + "method": "createSearch", + "params": { + "channel": "ahp-search:/q1", + "query": { + "text": "parseConfig", + "matchCase": true, + "targets": [ + { "kind": "fileText", "roots": ["file:///workspace"], "excludes": ["**/dist/**"] }, + { "kind": "sessions" }, + { "kind": "chatMessages", "chats": ["ahp-chat:/c1"] } + ], + "maxResults": 500 + } + } +} +``` + +On success, the result is an empty object (`{}`). On failure, the host returns +one of these errors: + +| Error | Cause | +|---|---| +| `InvalidParams` | The query is not valid. For example, a target kind is not supported or a regular expression is invalid. | +| `PermissionDenied` | The client is not permitted to search a root or chat. | +| `AlreadyExists` | The channel URI is already in use. The host MUST NOT replace the existing search. | + +The client then subscribes to the channel. A new search starts with no +results and a `running` lifecycle. If the client does not +subscribe within a time limit that the host chooses, the host stops the search +and releases the channel. + +## Query + +| Member | Meaning | +|---|---| +| `text` | The text to search for. An empty `text` matches nothing. | +| `matchCase` | Match case. Defaults to `false`. | +| `wholeWord` | Match only whole words. Defaults to `false`. | +| `isRegex` | Treat `text` as a regular expression. Defaults to `false`. | +| `fuzzy` | A hint that precise matching isn't expected, for example in a quick-find picker. The host MAY then match loosely and ignore `isRegex` and `wholeWord`. Defaults to `false`. | +| `targets` | Where to search. At least one target. | +| `maxResults` | The maximum number of results. The host MAY apply a lower limit. | + +Each target has a `kind`: + +| Kind | Searches | Members | +|---|---|---| +| `fileNames` | File paths under `roots`. The host decides how to match `text` against paths, for example with fuzzy matching, and which query options apply. | `roots`, `includes`, `excludes`, `includeIgnored` | +| `fileText` | The text content of files under `roots` | `roots`, `includes`, `excludes`, `includeIgnored` | +| `sessions` | The host's sessions, the same sessions that `listSessions` returns. The host decides which session content it matches, for example titles or requests. | none | +| `chatMessages` | The visible text of chat requests and responses, including the responses of [deferred turns](/specification/chat-channel#deferred-turns) | `chats`: the chats to search. At least one chat URI. | + +`includes` and `excludes` are glob patterns relative to a root. By default, the +host skips files that its ignore rules, such as `.gitignore` files, exclude. +Set `includeIgnored` to search them as well; `excludes` still apply. + +## State + +The channel's state is a `SearchState`: + +```typescript +SearchState { + query: SearchQuery + results: SearchResult[] + lifecycle: SearchLifecycleState +} +``` + +Each result is one match. Every result has the `resource` that contains the +match, a `match` with the text to display, and an optional `score`. +`match.highlights` are the matched spans of `match.text`. Each span is the +half-open interval `[rangeStart, rangeEnd)` of UTF-16 code unit offsets, as in +completion items. The host chooses how much text around the match to include +in `match.text`. + +| Result kind | `resource` | Other members | +|---|---|---| +| `fileName` | The file | none. `match.text` is the file's path. | +| `fileText` | The file | `range`: the location of the match in the file, as a `TextRange` | +| `session` | The session URI | `title`: the session's title | +| `chatMessage` | The chat URI | `title` (the chat's title) and `turnId` | + +`score` is a number with no fixed range; higher is better. Scores are +comparable across all results of one search, so a client can show results of every kind in one +ranked list. Results are stored in the order the host found them; clients +SHOULD sort them by descending score. A host that does not rank results omits +the score. + +To open a `chatMessage` result, the client subscribes to the chat and locates +the turn with `turnId`. If that turn is deferred, the client reads it with +`fetchDeferredTurns`. + +### Lifecycle + +`lifecycle` is a union discriminated by `status`: + +| Status | Meaning | Other members | +|---|---|---| +| `pending` | The query changed and the host has not replaced the results yet. `results` belong to the previous query; clients MAY show them dimmed. | none | +| `running` | The host is searching and may add results. | none | +| `completed` | The host found every result for the query. | `reason`: `exhausted` (every target was searched) or `limitReached` (the host stopped at the result limit) | +| `failed` | The search failed. Results found before the failure remain. | `error` | + +`completed` and `failed` are not final. A host that watches the searched +files, sessions, or chats MAY change the results of a completed search, or move +it back to `running` and search again. + +## Actions + +| Action | Dispatched by | Effect | +|---|---|---| +| `search/queryChanged` | Client | Replaces `query`, keeps `results`, and sets `lifecycle` to `pending`. The host restarts the search. | +| `search/resultsChanged` | Host | Appends `results`. With `replace: true`, replaces every result instead; the replacement may be empty, and a `pending` lifecycle becomes `running`. | +| `search/lifecycleChanged` | Host | Replaces `lifecycle`, for example to complete or fail the search. | + +The host MUST NOT dispatch an empty `results` list unless `replace` is `true`, +and MUST NOT change the lifecycle to `pending`; only `search/queryChanged` does +that. A host MAY replace the results at any time, for example to re-rank them, +to remove duplicates, or to update a completed search when a watched file +changes. + +## Changing the Query + +To change the query, for example as the user types, the client dispatches +`search/queryChanged` with the full new query. The reducer keeps the old +results and sets the lifecycle to `pending`, so the list does not flash empty +while the host restarts the search. + +After the host applies `search/queryChanged`, it stops the previous search and +drops any of its results that it has not dispatched yet. It MUST then dispatch +`search/resultsChanged` with `replace: true` before any other search action. The replacement can +keep the old results that still match the new query, for example when the user +narrows `pars` to `parse`, or it can be empty. Results for the old query that +the host dispatched before it applied the change are replaced along with the +rest. + +If the new query is not valid, for example because it contains an invalid +regular expression, the host accepts the action, replaces the results with an +empty list, and then changes the lifecycle to +`failed`. The client can show the error next to the query. + +```mermaid +sequenceDiagram + autonumber + participant C as Client + participant H as Host + + C->>H: createSearch { channel: "ahp-search:/q1", query: { text: "pars", ... } } + H-->>C: {} + C->>H: subscribe { channel: "ahp-search:/q1" } + H-->>C: { snapshot: { state: { query, results: [], lifecycle: { status: "running" } } } } + H-->>C: action search/resultsChanged (append) + C->>H: dispatchAction search/queryChanged { query: { text: "parseConfig", ... } } + H-->>C: action search/queryChanged (lifecycle: pending) + H-->>C: action search/resultsChanged { replace: true } (old results that still match; lifecycle: running) + H-->>C: action search/resultsChanged (append) + H-->>C: action search/lifecycleChanged { status: "completed", reason: "exhausted" } + C->>H: unsubscribe { channel: "ahp-search:/q1" } + Note over H: search released +``` + +## Cancelling a Search + +The client cancels a search by sending `unsubscribe` for its channel. When the +last subscriber unsubscribes, the host stops the search and releases the +channel. + +A completed search keeps its state until the client unsubscribes. The client +can change the query of a completed search to start it again. + +## Connection Loss + +When the AHP connection closes, the host MAY keep a search for a period of time +that it chooses, so that a client can resume it with `reconnect` or +`subscribe`. Once the host releases a search, `reconnect` lists the channel in +`missing`, and `subscribe` fails. To search again, the client sends +`createSearch`. + +## Security + +A host applies the same access rules to a search as to the operations that +would reach the same data: `resourceRead` for files, and `listSessions` and +`subscribe` for sessions and chats. A host does not need to track which +sessions or chats a particular client has seen. A host SHOULD limit the number +of searches for each client and the work that each search does. diff --git a/docs/specification/subscriptions.md b/docs/specification/subscriptions.md index 5832deef1..dd8621457 100644 --- a/docs/specification/subscriptions.md +++ b/docs/specification/subscriptions.md @@ -30,6 +30,7 @@ All channels use the same `subscribe` and `unsubscribe` messages. | `ahp-canvas:/` | `CanvasState` | Experimental. One canvas. The URI is listed in `ChatState.canvases`. See [Canvas Channel](/reference/canvas). | | `ahp-terminal:/` | `TerminalState` | One terminal. See [Terminal Channel](/specification/terminal-channel). | | `ahp-tcp:/` | `EmptyState` | Experimental. One TCP connection that the host opened with `createTcpConnection`. Private to the client that created it. See [TCP Channel](/specification/tcp-channel). | +| `ahp-search:/` | `SearchState` | Experimental. One search that a client started with `createSearch`. See [Search Channel](/specification/search-channel). | | `ahp-changeset:/` | `ChangesetState` | One changeset. The client builds the URI from the `Changeset.uriTemplate` of a session or chat. | | `ahp-resource-watch:/` | `ResourceWatchState` | One file watch. The URI is returned by `createResourceWatch`. | | `ahp-otlp:` | `EmptyState` | OpenTelemetry logs, traces, or metrics. The URIs are listed in `InitializeResult.telemetry`. See [Telemetry Channel](/specification/telemetry-channel). | @@ -57,6 +58,7 @@ route any message using only its `method` and `params.channel`. | `moveChat` | The URI of the chat to move | | `createTerminal`, `disposeTerminal` | The terminal URI. For `createTerminal`, this is the URI of the new terminal. | | `createTcpConnection` | The URI of the new TCP channel | +| `createSearch` | The URI of the new search channel | | `invokeChangesetOperation` | The changeset URI | | `subscribe`, `unsubscribe` | The URI of the channel being subscribed to or released | | `dispatchAction`, `action` | The URI of the channel that the action changes | diff --git a/docs/specification/versioning.md b/docs/specification/versioning.md index 68c52d168..6fb9d00fc 100644 --- a/docs/specification/versioning.md +++ b/docs/specification/versioning.md @@ -42,6 +42,7 @@ protocol or package version numbers. | [Canvas](/reference/canvas) | **1 - Experimental** | | [Terminal](/specification/terminal-channel) | **2 - Stable** | | [TCP](/specification/tcp-channel) | **1.0 - Early development** | +| [Search](/specification/search-channel) | **1.0 - Early development** | | [Changeset](/reference/changeset) | **1.2 - Release candidate** | | [Annotations](/reference/annotations) | **1.1 - Active development** | | [Telemetry](/specification/telemetry-channel) | **2 - Stable** | diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 4199e1146..57ef8a323 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -2617,6 +2617,64 @@ "type" ] }, + "SearchQueryChangedAction": { + "type": "object", + "description": "Replaces the search's query and restarts the search.\n\nKeeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to\n{@link SearchLifecycleStatus.Pending | pending}. The old results stay\nvisible until the host replaces them, so the client does not flash an empty\nlist.\n\nAfter the host applies this action, it stops the previous search and drops\nany of its results that it has not dispatched yet. The host MUST then\ndispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with\n`replace: true` before any other search action. The replacement can keep\nold results that still match the new query, and can be empty. If the new\nquery is not valid,\nfor example because it contains an invalid regular expression, the host\nreplaces the results with an empty list and then changes the lifecycle to\n{@link SearchLifecycleStatus.Failed | failed}.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/queryChanged" + }, + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The new query." + } + }, + "required": [ + "type", + "query" + ] + }, + "SearchResultsChangedAction": { + "type": "object", + "description": "Adds results to {@link SearchState.results}, or replaces them.\n\nBy default, the reducer appends `results`. Set `replace` to `true` to\nreplace every result instead; if {@link SearchState.lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, a replacement also changes\nit to {@link SearchLifecycleStatus.Running | running}.\n\nThe host MUST dispatch a replacement first after a\n{@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also\nreplace the results at other times, for example to re-rank them, to remove\nduplicates, or to update a completed search when a watched file changes.\nThe host MUST NOT dispatch an empty `results` list unless `replace` is\n`true`.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/resultsChanged" + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "The results to append, in the order the host found them, or the replacement results." + }, + "replace": { + "type": "boolean", + "description": "When `true`, replaces every result instead of appending." + } + }, + "required": [ + "type", + "results" + ] + }, + "SearchLifecycleChangedAction": { + "type": "object", + "description": "Replaces {@link SearchState.lifecycle}.\n\nThe host dispatches this to complete or fail a search, or to move a\ncompleted search back to {@link SearchLifecycleStatus.Running | running} when it\nsearches again, for example after a watched file changes. The host MUST NOT\nchange the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only\n{@link SearchQueryChangedAction | `search/queryChanged`} does that.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/lifecycleChanged" + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "The new lifecycle." + } + }, + "required": [ + "type", + "lifecycle" + ] + }, "ChatToolCallConfirmedAction": { "oneOf": [ { @@ -3260,6 +3318,9 @@ { "$ref": "#/$defs/AutomationRunState" }, + { + "$ref": "#/$defs/SearchState" + }, { "$ref": "#/$defs/EmptyState" } @@ -8990,6 +9051,477 @@ "description": "Present when the host supports `createTcpConnection`.\n\nA client creates a connection with `createTcpConnection`, then subscribes to\nits channel with windowed delivery. A TCP channel's state is an\n{@link EmptyState}; its data is sent in `tcp/data` and `tcp/eof`\nnotifications. TCP connections do not survive the loss of the AHP connection.\n\nStability: 1.0 - Early development.", "properties": {} }, + "SearchCapability": { + "type": "object", + "description": "Present when the host supports `createSearch`.\n\nStability: 1.0 - Early development.", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTargetKind" + }, + "description": "The target kinds the host can search. A client MUST NOT send a\n{@link SearchTarget} whose kind is not listed here." + } + }, + "required": [ + "targets" + ] + }, + "SearchQuery": { + "type": "object", + "description": "What a search looks for and where.\n\nThe client sends a query in `createSearch` and replaces it with\n{@link SearchQueryChangedAction | `search/queryChanged`}.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to search for. Its meaning depends on the target: see\n{@link SearchTarget}. An empty `text` matches nothing; the host completes\nthe search with no results." + }, + "matchCase": { + "type": "boolean", + "description": "Match case. Defaults to `false`." + }, + "wholeWord": { + "type": "boolean", + "description": "Match only whole words. Defaults to `false`." + }, + "isRegex": { + "type": "boolean", + "description": "Treat `text` as a regular expression. Defaults to `false`." + }, + "fuzzy": { + "type": "boolean", + "description": "A hint that precise matching isn't expected, for example because the\nsearch powers a quick-find picker. The host MAY then match loosely, rank\nresults by how well they match, and ignore {@link isRegex} and\n{@link wholeWord}. Defaults to `false`." + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTarget" + }, + "description": "Where to search. MUST contain at least one target." + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results. The host MAY apply a lower limit, and\ncompletes the search with {@link SearchCompletionReason.LimitReached}\nwhen it reaches the limit that applies.", + "minimum": 1 + } + }, + "required": [ + "text", + "targets" + ] + }, + "FileSearchTargetBase": { + "type": "object", + "description": "Shared fields for file search targets.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + } + }, + "required": [ + "roots" + ] + }, + "FileNamesSearchTarget": { + "type": "object", + "description": "Searches file paths under {@link FileSearchTargetBase.roots}.\n\nThe host decides how to match {@link SearchQuery.text} against file paths,\nfor example with fuzzy matching, and which query options apply. Results\nare {@link FileNameSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileNames" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "FileTextSearchTarget": { + "type": "object", + "description": "Searches the text content of files under {@link FileSearchTargetBase.roots}.\nResults are {@link FileTextSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileText" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "SessionsSearchTarget": { + "type": "object", + "description": "Searches the host's sessions, the same sessions that `listSessions`\nreturns. The host decides which session content it matches, for example\ntitles or requests. Results are {@link SessionSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "sessions" + } + }, + "required": [ + "kind" + ] + }, + "ChatMessagesSearchTarget": { + "type": "object", + "description": "Searches the visible text of chat requests and responses, including the\nresponses of deferred turns. Results are\n{@link ChatMessageSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "chatMessages" + }, + "chats": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The chats to search. MUST contain at least one chat URI." + } + }, + "required": [ + "kind", + "chats" + ] + }, + "SearchHighlight": { + "type": "object", + "description": "A matched span within {@link SearchMatch.text}: the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits, as in {@link CompletionItem.rangeStart}.\n\nStability: 1.0 - Early development.", + "properties": { + "rangeStart": { + "type": "integer", + "description": "The start of the span.", + "minimum": 0 + }, + "rangeEnd": { + "type": "integer", + "description": "The end of the span, exclusive. MUST be greater than {@link rangeStart}\nand at most the length of {@link SearchMatch.text}.", + "minimum": 1 + } + }, + "required": [ + "rangeStart", + "rangeEnd" + ] + }, + "SearchMatch": { + "type": "object", + "description": "The matched text of a result, with the matched spans highlighted. The host\nchooses how much text around the match to include.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to display." + }, + "highlights": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchHighlight" + }, + "description": "The matched spans, in order. Spans MUST NOT overlap." + } + }, + "required": [ + "text", + "highlights" + ] + }, + "SearchResultBase": { + "type": "object", + "description": "Shared fields for search results. Each result is one match.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + } + }, + "required": [ + "resource", + "match" + ] + }, + "FileNameSearchResult": { + "type": "object", + "description": "A file whose path matches. {@link SearchResultBase.resource} is the file;\nthe match text is its path, usually relative to the root that contains it.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileName" + } + }, + "required": [ + "resource", + "match", + "kind" + ] + }, + "FileTextSearchResult": { + "type": "object", + "description": "A match in the text of a file. {@link SearchResultBase.resource} is the\nfile; the match text is the text around the match, usually its line.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileText" + }, + "range": { + "$ref": "#/$defs/TextRange", + "description": "The location of the match in the file." + } + }, + "required": [ + "resource", + "match", + "kind", + "range" + ] + }, + "SessionSearchResult": { + "type": "object", + "description": "A session whose content matches. {@link SearchResultBase.resource} is the\nsession URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "session" + }, + "title": { + "type": "string", + "description": "The session's title." + } + }, + "required": [ + "resource", + "match", + "kind", + "title" + ] + }, + "ChatMessageSearchResult": { + "type": "object", + "description": "A match in a chat request or response. {@link SearchResultBase.resource}\nis the chat URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "chatMessage" + }, + "title": { + "type": "string", + "description": "The chat's title." + }, + "turnId": { + "type": "string", + "description": "The ID of the turn that contains the match." + } + }, + "required": [ + "resource", + "match", + "kind", + "title", + "turnId" + ] + }, + "SearchPendingLifecycleState": { + "type": "object", + "description": "The query changed and the host has not replaced the results yet. Clients\nMAY show the previous query's results differently, for example dimmed.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "pending" + } + }, + "required": [ + "status" + ] + }, + "SearchRunningLifecycleState": { + "type": "object", + "description": "The host is searching and may add more results.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "running" + } + }, + "required": [ + "status" + ] + }, + "SearchCompletedLifecycleState": { + "type": "object", + "description": "The host found every result for the query. A host that watches the\nsearched files, sessions, or chats MAY still change the results later.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "completed" + }, + "reason": { + "$ref": "#/$defs/SearchCompletionReason", + "description": "Why the search completed." + } + }, + "required": [ + "status", + "reason" + ] + }, + "SearchFailedLifecycleState": { + "type": "object", + "description": "The search failed. Results found before the failure remain in\n{@link SearchState.results}.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "failed" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Why the search failed, for example an invalid regular expression." + } + }, + "required": [ + "status", + "error" + ] + }, + "SearchState": { + "type": "object", + "description": "Full state for one search, returned when a client subscribes to its\n`ahp-search:` URI.\n\nStability: 1.0 - Early development.", + "properties": { + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The current query." + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "Results in the order the host found them. Sort by\n{@link SearchResultBase.score} to rank them. While {@link lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, these are results for the\nprevious query." + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "Where the search is in its lifecycle." + } + }, + "required": [ + "query", + "results", + "lifecycle" + ] + }, "StringOrMarkdown": { "oneOf": [ { @@ -9585,6 +10117,57 @@ ], "description": "Discriminated lifecycle of an automation run." }, + "SearchTarget": { + "oneOf": [ + { + "$ref": "#/$defs/FileNamesSearchTarget" + }, + { + "$ref": "#/$defs/FileTextSearchTarget" + }, + { + "$ref": "#/$defs/SessionsSearchTarget" + }, + { + "$ref": "#/$defs/ChatMessagesSearchTarget" + } + ], + "description": "One place to search." + }, + "SearchResult": { + "oneOf": [ + { + "$ref": "#/$defs/FileNameSearchResult" + }, + { + "$ref": "#/$defs/FileTextSearchResult" + }, + { + "$ref": "#/$defs/SessionSearchResult" + }, + { + "$ref": "#/$defs/ChatMessageSearchResult" + } + ], + "description": "One search match." + }, + "SearchLifecycleState": { + "oneOf": [ + { + "$ref": "#/$defs/SearchPendingLifecycleState" + }, + { + "$ref": "#/$defs/SearchRunningLifecycleState" + }, + { + "$ref": "#/$defs/SearchCompletedLifecycleState" + }, + { + "$ref": "#/$defs/SearchFailedLifecycleState" + } + ], + "description": "Discriminated lifecycle of a search." + }, "StateAction": { "description": "Discriminated union of all state actions.", "oneOf": [ @@ -9888,6 +10471,15 @@ { "$ref": "#/$defs/ResourceWatchChangedAction" }, + { + "$ref": "#/$defs/SearchQueryChangedAction" + }, + { + "$ref": "#/$defs/SearchResultsChangedAction" + }, + { + "$ref": "#/$defs/SearchLifecycleChangedAction" + }, { "$ref": "#/$defs/AutomationCreateRequestedAction" }, @@ -10102,6 +10694,24 @@ ], "type": "string", "description": "Operations the host currently permits for an automation.\n\nThe list on {@link AutomationEntry.operations} is authoritative and may\nchange over time. Clients MUST NOT infer permission from capabilities alone:\ncapabilities describe what the host implementation can support, while\noperations describe what is allowed for this particular automation now." + }, + "SearchTargetKind": { + "enum": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ], + "type": "string", + "description": "Discriminant for {@link SearchTarget}." + }, + "SearchCompletionReason": { + "enum": [ + "exhausted", + "limitReached" + ], + "type": "string", + "description": "Why a search completed." } } } diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 7fdda1e0f..6aa8892d6 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -209,6 +209,10 @@ "$ref": "#/$defs/TcpConnectionsCapability", "description": "Present when the host supports `createTcpConnection`, which opens a TCP\nconnection on the host's network for the client to forward.\n\nStability: 1.0 - Early development." }, + "search": { + "$ref": "#/$defs/SearchCapability", + "description": "Present when the host supports `createSearch`, which searches files,\nsessions, and chats and streams the results on an `ahp-search:` channel.\n\nStability: 1.0 - Early development." + }, "multipleChatProviders": { "$ref": "#/$defs/MultipleChatProvidersCapability", "description": "Present when chats in one session may be backed by different agent\nproviders (see {@link CreateChatParams.provider} and\n{@link ChatState.provider}).\nClients MUST NOT send `CreateChatParams.provider` without it.\n\nStability: 1.0 - Early development." @@ -1427,12 +1431,14 @@ "description": "The text inserted into the input when this item is accepted." }, "rangeStart": { - "type": "number", - "description": "If defined, the start of the range in the input's `text` that is replaced\nby `insertText`. The range is the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits.\n\nWhen omitted, the client SHOULD insert `insertText` at the cursor.\n\nNote: this range refers to positions in the *current* input. The\nattachment's own `rangeStart`/`rangeEnd` (when present) refer to\npositions in the final {@link Message.text} after the item is\naccepted." + "type": "integer", + "description": "If defined, the start of the range in the input's `text` that is replaced\nby `insertText`. The range is the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits.\n\nWhen omitted, the client SHOULD insert `insertText` at the cursor.\n\nNote: this range refers to positions in the *current* input. The\nattachment's own `rangeStart`/`rangeEnd` (when present) refer to\npositions in the final {@link Message.text} after the item is\naccepted.", + "minimum": 0 }, "rangeEnd": { - "type": "number", - "description": "The end of the range in the input's `text` that is replaced by\n`insertText`. See {@link rangeStart}." + "type": "integer", + "description": "The end of the range in the input's `text` that is replaced by\n`insertText`. See {@link rangeStart}.", + "minimum": 1 }, "attachment": { "$ref": "#/$defs/MessageAttachment", @@ -2030,6 +2036,34 @@ "description": "Result of the `createTcpConnection` command.\n\nAn empty object on success.\n\nStability: 1.0 - Early development.", "properties": {} }, + "CreateSearchParams": { + "type": "object", + "description": "Starts a search on the host.\n\nThe client chooses the channel URI and then subscribes to it to receive the\nsearch's {@link SearchState} and its results. The client replaces the query\nby dispatching {@link SearchQueryChangedAction | `search/queryChanged`},\nand cancels the search by unsubscribing.\n\nThe client MUST NOT send this command unless `InitializeResult.search` is\npresent, and MUST NOT include a target whose kind is not listed in\n{@link SearchCapability.targets}.\n\nStability: 1.0 - Early development.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "The client-chosen URI for the new channel, for example `ahp-search:/`." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "What to search for and where." + } + }, + "required": [ + "channel", + "query" + ] + }, + "CreateSearchResult": { + "type": "object", + "description": "Result of the `createSearch` command.\n\nAn empty object on success.\n\nStability: 1.0 - Early development.", + "properties": {} + }, "ReconnectResult": { "oneOf": [ { @@ -2634,6 +2668,9 @@ { "$ref": "#/$defs/AutomationRunState" }, + { + "$ref": "#/$defs/SearchState" + }, { "$ref": "#/$defs/EmptyState" } @@ -8364,6 +8401,477 @@ "description": "Present when the host supports `createTcpConnection`.\n\nA client creates a connection with `createTcpConnection`, then subscribes to\nits channel with windowed delivery. A TCP channel's state is an\n{@link EmptyState}; its data is sent in `tcp/data` and `tcp/eof`\nnotifications. TCP connections do not survive the loss of the AHP connection.\n\nStability: 1.0 - Early development.", "properties": {} }, + "SearchCapability": { + "type": "object", + "description": "Present when the host supports `createSearch`.\n\nStability: 1.0 - Early development.", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTargetKind" + }, + "description": "The target kinds the host can search. A client MUST NOT send a\n{@link SearchTarget} whose kind is not listed here." + } + }, + "required": [ + "targets" + ] + }, + "SearchQuery": { + "type": "object", + "description": "What a search looks for and where.\n\nThe client sends a query in `createSearch` and replaces it with\n{@link SearchQueryChangedAction | `search/queryChanged`}.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to search for. Its meaning depends on the target: see\n{@link SearchTarget}. An empty `text` matches nothing; the host completes\nthe search with no results." + }, + "matchCase": { + "type": "boolean", + "description": "Match case. Defaults to `false`." + }, + "wholeWord": { + "type": "boolean", + "description": "Match only whole words. Defaults to `false`." + }, + "isRegex": { + "type": "boolean", + "description": "Treat `text` as a regular expression. Defaults to `false`." + }, + "fuzzy": { + "type": "boolean", + "description": "A hint that precise matching isn't expected, for example because the\nsearch powers a quick-find picker. The host MAY then match loosely, rank\nresults by how well they match, and ignore {@link isRegex} and\n{@link wholeWord}. Defaults to `false`." + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTarget" + }, + "description": "Where to search. MUST contain at least one target." + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results. The host MAY apply a lower limit, and\ncompletes the search with {@link SearchCompletionReason.LimitReached}\nwhen it reaches the limit that applies.", + "minimum": 1 + } + }, + "required": [ + "text", + "targets" + ] + }, + "FileSearchTargetBase": { + "type": "object", + "description": "Shared fields for file search targets.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + } + }, + "required": [ + "roots" + ] + }, + "FileNamesSearchTarget": { + "type": "object", + "description": "Searches file paths under {@link FileSearchTargetBase.roots}.\n\nThe host decides how to match {@link SearchQuery.text} against file paths,\nfor example with fuzzy matching, and which query options apply. Results\nare {@link FileNameSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileNames" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "FileTextSearchTarget": { + "type": "object", + "description": "Searches the text content of files under {@link FileSearchTargetBase.roots}.\nResults are {@link FileTextSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileText" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "SessionsSearchTarget": { + "type": "object", + "description": "Searches the host's sessions, the same sessions that `listSessions`\nreturns. The host decides which session content it matches, for example\ntitles or requests. Results are {@link SessionSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "sessions" + } + }, + "required": [ + "kind" + ] + }, + "ChatMessagesSearchTarget": { + "type": "object", + "description": "Searches the visible text of chat requests and responses, including the\nresponses of deferred turns. Results are\n{@link ChatMessageSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "chatMessages" + }, + "chats": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The chats to search. MUST contain at least one chat URI." + } + }, + "required": [ + "kind", + "chats" + ] + }, + "SearchHighlight": { + "type": "object", + "description": "A matched span within {@link SearchMatch.text}: the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits, as in {@link CompletionItem.rangeStart}.\n\nStability: 1.0 - Early development.", + "properties": { + "rangeStart": { + "type": "integer", + "description": "The start of the span.", + "minimum": 0 + }, + "rangeEnd": { + "type": "integer", + "description": "The end of the span, exclusive. MUST be greater than {@link rangeStart}\nand at most the length of {@link SearchMatch.text}.", + "minimum": 1 + } + }, + "required": [ + "rangeStart", + "rangeEnd" + ] + }, + "SearchMatch": { + "type": "object", + "description": "The matched text of a result, with the matched spans highlighted. The host\nchooses how much text around the match to include.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to display." + }, + "highlights": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchHighlight" + }, + "description": "The matched spans, in order. Spans MUST NOT overlap." + } + }, + "required": [ + "text", + "highlights" + ] + }, + "SearchResultBase": { + "type": "object", + "description": "Shared fields for search results. Each result is one match.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + } + }, + "required": [ + "resource", + "match" + ] + }, + "FileNameSearchResult": { + "type": "object", + "description": "A file whose path matches. {@link SearchResultBase.resource} is the file;\nthe match text is its path, usually relative to the root that contains it.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileName" + } + }, + "required": [ + "resource", + "match", + "kind" + ] + }, + "FileTextSearchResult": { + "type": "object", + "description": "A match in the text of a file. {@link SearchResultBase.resource} is the\nfile; the match text is the text around the match, usually its line.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileText" + }, + "range": { + "$ref": "#/$defs/TextRange", + "description": "The location of the match in the file." + } + }, + "required": [ + "resource", + "match", + "kind", + "range" + ] + }, + "SessionSearchResult": { + "type": "object", + "description": "A session whose content matches. {@link SearchResultBase.resource} is the\nsession URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "session" + }, + "title": { + "type": "string", + "description": "The session's title." + } + }, + "required": [ + "resource", + "match", + "kind", + "title" + ] + }, + "ChatMessageSearchResult": { + "type": "object", + "description": "A match in a chat request or response. {@link SearchResultBase.resource}\nis the chat URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "chatMessage" + }, + "title": { + "type": "string", + "description": "The chat's title." + }, + "turnId": { + "type": "string", + "description": "The ID of the turn that contains the match." + } + }, + "required": [ + "resource", + "match", + "kind", + "title", + "turnId" + ] + }, + "SearchPendingLifecycleState": { + "type": "object", + "description": "The query changed and the host has not replaced the results yet. Clients\nMAY show the previous query's results differently, for example dimmed.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "pending" + } + }, + "required": [ + "status" + ] + }, + "SearchRunningLifecycleState": { + "type": "object", + "description": "The host is searching and may add more results.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "running" + } + }, + "required": [ + "status" + ] + }, + "SearchCompletedLifecycleState": { + "type": "object", + "description": "The host found every result for the query. A host that watches the\nsearched files, sessions, or chats MAY still change the results later.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "completed" + }, + "reason": { + "$ref": "#/$defs/SearchCompletionReason", + "description": "Why the search completed." + } + }, + "required": [ + "status", + "reason" + ] + }, + "SearchFailedLifecycleState": { + "type": "object", + "description": "The search failed. Results found before the failure remain in\n{@link SearchState.results}.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "failed" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Why the search failed, for example an invalid regular expression." + } + }, + "required": [ + "status", + "error" + ] + }, + "SearchState": { + "type": "object", + "description": "Full state for one search, returned when a client subscribes to its\n`ahp-search:` URI.\n\nStability: 1.0 - Early development.", + "properties": { + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The current query." + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "Results in the order the host found them. Sort by\n{@link SearchResultBase.score} to rank them. While {@link lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, these are results for the\nprevious query." + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "Where the search is in its lifecycle." + } + }, + "required": [ + "query", + "results", + "lifecycle" + ] + }, "ActionOrigin": { "type": "object", "description": "Identifies the client that originally dispatched an action.", @@ -10976,6 +11484,64 @@ "type" ] }, + "SearchQueryChangedAction": { + "type": "object", + "description": "Replaces the search's query and restarts the search.\n\nKeeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to\n{@link SearchLifecycleStatus.Pending | pending}. The old results stay\nvisible until the host replaces them, so the client does not flash an empty\nlist.\n\nAfter the host applies this action, it stops the previous search and drops\nany of its results that it has not dispatched yet. The host MUST then\ndispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with\n`replace: true` before any other search action. The replacement can keep\nold results that still match the new query, and can be empty. If the new\nquery is not valid,\nfor example because it contains an invalid regular expression, the host\nreplaces the results with an empty list and then changes the lifecycle to\n{@link SearchLifecycleStatus.Failed | failed}.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/queryChanged" + }, + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The new query." + } + }, + "required": [ + "type", + "query" + ] + }, + "SearchResultsChangedAction": { + "type": "object", + "description": "Adds results to {@link SearchState.results}, or replaces them.\n\nBy default, the reducer appends `results`. Set `replace` to `true` to\nreplace every result instead; if {@link SearchState.lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, a replacement also changes\nit to {@link SearchLifecycleStatus.Running | running}.\n\nThe host MUST dispatch a replacement first after a\n{@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also\nreplace the results at other times, for example to re-rank them, to remove\nduplicates, or to update a completed search when a watched file changes.\nThe host MUST NOT dispatch an empty `results` list unless `replace` is\n`true`.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/resultsChanged" + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "The results to append, in the order the host found them, or the replacement results." + }, + "replace": { + "type": "boolean", + "description": "When `true`, replaces every result instead of appending." + } + }, + "required": [ + "type", + "results" + ] + }, + "SearchLifecycleChangedAction": { + "type": "object", + "description": "Replaces {@link SearchState.lifecycle}.\n\nThe host dispatches this to complete or fail a search, or to move a\ncompleted search back to {@link SearchLifecycleStatus.Running | running} when it\nsearches again, for example after a watched file changes. The host MUST NOT\nchange the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only\n{@link SearchQueryChangedAction | `search/queryChanged`} does that.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/lifecycleChanged" + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "The new lifecycle." + } + }, + "required": [ + "type", + "lifecycle" + ] + }, "URI": { "type": "string", "description": "A URI string (e.g. `ahp-root://`, `ahp-session:/`, or `ahp-chat:/`)." @@ -11290,6 +11856,15 @@ { "$ref": "#/$defs/ResourceWatchChangedAction" }, + { + "$ref": "#/$defs/SearchQueryChangedAction" + }, + { + "$ref": "#/$defs/SearchResultsChangedAction" + }, + { + "$ref": "#/$defs/SearchLifecycleChangedAction" + }, { "$ref": "#/$defs/AutomationCreateRequestedAction" }, @@ -12130,6 +12705,75 @@ ], "description": "Discriminated lifecycle of an automation run." }, + "SearchTargetKind": { + "enum": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ], + "type": "string", + "description": "Discriminant for {@link SearchTarget}." + }, + "SearchTarget": { + "oneOf": [ + { + "$ref": "#/$defs/FileNamesSearchTarget" + }, + { + "$ref": "#/$defs/FileTextSearchTarget" + }, + { + "$ref": "#/$defs/SessionsSearchTarget" + }, + { + "$ref": "#/$defs/ChatMessagesSearchTarget" + } + ], + "description": "One place to search." + }, + "SearchCompletionReason": { + "enum": [ + "exhausted", + "limitReached" + ], + "type": "string", + "description": "Why a search completed." + }, + "SearchResult": { + "oneOf": [ + { + "$ref": "#/$defs/FileNameSearchResult" + }, + { + "$ref": "#/$defs/FileTextSearchResult" + }, + { + "$ref": "#/$defs/SessionSearchResult" + }, + { + "$ref": "#/$defs/ChatMessageSearchResult" + } + ], + "description": "One search match." + }, + "SearchLifecycleState": { + "oneOf": [ + { + "$ref": "#/$defs/SearchPendingLifecycleState" + }, + { + "$ref": "#/$defs/SearchRunningLifecycleState" + }, + { + "$ref": "#/$defs/SearchCompletedLifecycleState" + }, + { + "$ref": "#/$defs/SearchFailedLifecycleState" + } + ], + "description": "Discriminated lifecycle of a search." + }, "ChatToolCallConfirmedAction": { "oneOf": [ { diff --git a/schema/errors.schema.json b/schema/errors.schema.json index e07b4c571..0ee8929c9 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -602,6 +602,9 @@ { "$ref": "#/$defs/AutomationRunState" }, + { + "$ref": "#/$defs/SearchState" + }, { "$ref": "#/$defs/EmptyState" } @@ -6332,6 +6335,477 @@ "description": "Present when the host supports `createTcpConnection`.\n\nA client creates a connection with `createTcpConnection`, then subscribes to\nits channel with windowed delivery. A TCP channel's state is an\n{@link EmptyState}; its data is sent in `tcp/data` and `tcp/eof`\nnotifications. TCP connections do not survive the loss of the AHP connection.\n\nStability: 1.0 - Early development.", "properties": {} }, + "SearchCapability": { + "type": "object", + "description": "Present when the host supports `createSearch`.\n\nStability: 1.0 - Early development.", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTargetKind" + }, + "description": "The target kinds the host can search. A client MUST NOT send a\n{@link SearchTarget} whose kind is not listed here." + } + }, + "required": [ + "targets" + ] + }, + "SearchQuery": { + "type": "object", + "description": "What a search looks for and where.\n\nThe client sends a query in `createSearch` and replaces it with\n{@link SearchQueryChangedAction | `search/queryChanged`}.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to search for. Its meaning depends on the target: see\n{@link SearchTarget}. An empty `text` matches nothing; the host completes\nthe search with no results." + }, + "matchCase": { + "type": "boolean", + "description": "Match case. Defaults to `false`." + }, + "wholeWord": { + "type": "boolean", + "description": "Match only whole words. Defaults to `false`." + }, + "isRegex": { + "type": "boolean", + "description": "Treat `text` as a regular expression. Defaults to `false`." + }, + "fuzzy": { + "type": "boolean", + "description": "A hint that precise matching isn't expected, for example because the\nsearch powers a quick-find picker. The host MAY then match loosely, rank\nresults by how well they match, and ignore {@link isRegex} and\n{@link wholeWord}. Defaults to `false`." + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTarget" + }, + "description": "Where to search. MUST contain at least one target." + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results. The host MAY apply a lower limit, and\ncompletes the search with {@link SearchCompletionReason.LimitReached}\nwhen it reaches the limit that applies.", + "minimum": 1 + } + }, + "required": [ + "text", + "targets" + ] + }, + "FileSearchTargetBase": { + "type": "object", + "description": "Shared fields for file search targets.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + } + }, + "required": [ + "roots" + ] + }, + "FileNamesSearchTarget": { + "type": "object", + "description": "Searches file paths under {@link FileSearchTargetBase.roots}.\n\nThe host decides how to match {@link SearchQuery.text} against file paths,\nfor example with fuzzy matching, and which query options apply. Results\nare {@link FileNameSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileNames" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "FileTextSearchTarget": { + "type": "object", + "description": "Searches the text content of files under {@link FileSearchTargetBase.roots}.\nResults are {@link FileTextSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileText" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "SessionsSearchTarget": { + "type": "object", + "description": "Searches the host's sessions, the same sessions that `listSessions`\nreturns. The host decides which session content it matches, for example\ntitles or requests. Results are {@link SessionSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "sessions" + } + }, + "required": [ + "kind" + ] + }, + "ChatMessagesSearchTarget": { + "type": "object", + "description": "Searches the visible text of chat requests and responses, including the\nresponses of deferred turns. Results are\n{@link ChatMessageSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "chatMessages" + }, + "chats": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The chats to search. MUST contain at least one chat URI." + } + }, + "required": [ + "kind", + "chats" + ] + }, + "SearchHighlight": { + "type": "object", + "description": "A matched span within {@link SearchMatch.text}: the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits, as in {@link CompletionItem.rangeStart}.\n\nStability: 1.0 - Early development.", + "properties": { + "rangeStart": { + "type": "integer", + "description": "The start of the span.", + "minimum": 0 + }, + "rangeEnd": { + "type": "integer", + "description": "The end of the span, exclusive. MUST be greater than {@link rangeStart}\nand at most the length of {@link SearchMatch.text}.", + "minimum": 1 + } + }, + "required": [ + "rangeStart", + "rangeEnd" + ] + }, + "SearchMatch": { + "type": "object", + "description": "The matched text of a result, with the matched spans highlighted. The host\nchooses how much text around the match to include.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to display." + }, + "highlights": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchHighlight" + }, + "description": "The matched spans, in order. Spans MUST NOT overlap." + } + }, + "required": [ + "text", + "highlights" + ] + }, + "SearchResultBase": { + "type": "object", + "description": "Shared fields for search results. Each result is one match.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + } + }, + "required": [ + "resource", + "match" + ] + }, + "FileNameSearchResult": { + "type": "object", + "description": "A file whose path matches. {@link SearchResultBase.resource} is the file;\nthe match text is its path, usually relative to the root that contains it.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileName" + } + }, + "required": [ + "resource", + "match", + "kind" + ] + }, + "FileTextSearchResult": { + "type": "object", + "description": "A match in the text of a file. {@link SearchResultBase.resource} is the\nfile; the match text is the text around the match, usually its line.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileText" + }, + "range": { + "$ref": "#/$defs/TextRange", + "description": "The location of the match in the file." + } + }, + "required": [ + "resource", + "match", + "kind", + "range" + ] + }, + "SessionSearchResult": { + "type": "object", + "description": "A session whose content matches. {@link SearchResultBase.resource} is the\nsession URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "session" + }, + "title": { + "type": "string", + "description": "The session's title." + } + }, + "required": [ + "resource", + "match", + "kind", + "title" + ] + }, + "ChatMessageSearchResult": { + "type": "object", + "description": "A match in a chat request or response. {@link SearchResultBase.resource}\nis the chat URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "chatMessage" + }, + "title": { + "type": "string", + "description": "The chat's title." + }, + "turnId": { + "type": "string", + "description": "The ID of the turn that contains the match." + } + }, + "required": [ + "resource", + "match", + "kind", + "title", + "turnId" + ] + }, + "SearchPendingLifecycleState": { + "type": "object", + "description": "The query changed and the host has not replaced the results yet. Clients\nMAY show the previous query's results differently, for example dimmed.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "pending" + } + }, + "required": [ + "status" + ] + }, + "SearchRunningLifecycleState": { + "type": "object", + "description": "The host is searching and may add more results.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "running" + } + }, + "required": [ + "status" + ] + }, + "SearchCompletedLifecycleState": { + "type": "object", + "description": "The host found every result for the query. A host that watches the\nsearched files, sessions, or chats MAY still change the results later.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "completed" + }, + "reason": { + "$ref": "#/$defs/SearchCompletionReason", + "description": "Why the search completed." + } + }, + "required": [ + "status", + "reason" + ] + }, + "SearchFailedLifecycleState": { + "type": "object", + "description": "The search failed. Results found before the failure remain in\n{@link SearchState.results}.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "failed" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Why the search failed, for example an invalid regular expression." + } + }, + "required": [ + "status", + "error" + ] + }, + "SearchState": { + "type": "object", + "description": "Full state for one search, returned when a client subscribes to its\n`ahp-search:` URI.\n\nStability: 1.0 - Early development.", + "properties": { + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The current query." + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "Results in the order the host found them. Sort by\n{@link SearchResultBase.score} to rank them. While {@link lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, these are results for the\nprevious query." + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "Where the search is in its lifecycle." + } + }, + "required": [ + "query", + "results", + "lifecycle" + ] + }, "BaseParams": { "type": "object", "description": "Base shape every command's params extends.\n\n`channel` identifies the channel the command targets, mirroring the\n`channel` field on every protocol notification. For commands that operate\non a specific channel (a session, terminal, or changeset), `channel` is\nthat channel's URI. For commands that are connection-level rather than\nchannel-scoped (e.g. {@link InitializeParams | `initialize`},\n{@link PingParams | `ping`}, {@link ListSessionsParams | `listSessions`},\nthe `resource*` filesystem commands, and {@link AuthenticateParams |\n`authenticate`}), the params type narrows `channel` to the literal\nroot URI `'ahp-root://'`.\n\nThis invariant lets implementations route every incoming message —\nrequest, response, or notification — by inspecting `params.channel`\nwithout needing to know the per-method param shape.", @@ -6536,6 +7010,10 @@ "$ref": "#/$defs/TcpConnectionsCapability", "description": "Present when the host supports `createTcpConnection`, which opens a TCP\nconnection on the host's network for the client to forward.\n\nStability: 1.0 - Early development." }, + "search": { + "$ref": "#/$defs/SearchCapability", + "description": "Present when the host supports `createSearch`, which searches files,\nsessions, and chats and streams the results on an `ahp-search:` channel.\n\nStability: 1.0 - Early development." + }, "multipleChatProviders": { "$ref": "#/$defs/MultipleChatProvidersCapability", "description": "Present when chats in one session may be backed by different agent\nproviders (see {@link CreateChatParams.provider} and\n{@link ChatState.provider}).\nClients MUST NOT send `CreateChatParams.provider` without it.\n\nStability: 1.0 - Early development." @@ -7754,12 +8232,14 @@ "description": "The text inserted into the input when this item is accepted." }, "rangeStart": { - "type": "number", - "description": "If defined, the start of the range in the input's `text` that is replaced\nby `insertText`. The range is the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits.\n\nWhen omitted, the client SHOULD insert `insertText` at the cursor.\n\nNote: this range refers to positions in the *current* input. The\nattachment's own `rangeStart`/`rangeEnd` (when present) refer to\npositions in the final {@link Message.text} after the item is\naccepted." + "type": "integer", + "description": "If defined, the start of the range in the input's `text` that is replaced\nby `insertText`. The range is the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits.\n\nWhen omitted, the client SHOULD insert `insertText` at the cursor.\n\nNote: this range refers to positions in the *current* input. The\nattachment's own `rangeStart`/`rangeEnd` (when present) refer to\npositions in the final {@link Message.text} after the item is\naccepted.", + "minimum": 0 }, "rangeEnd": { - "type": "number", - "description": "The end of the range in the input's `text` that is replaced by\n`insertText`. See {@link rangeStart}." + "type": "integer", + "description": "The end of the range in the input's `text` that is replaced by\n`insertText`. See {@link rangeStart}.", + "minimum": 1 }, "attachment": { "$ref": "#/$defs/MessageAttachment", @@ -8357,6 +8837,34 @@ "description": "Result of the `createTcpConnection` command.\n\nAn empty object on success.\n\nStability: 1.0 - Early development.", "properties": {} }, + "CreateSearchParams": { + "type": "object", + "description": "Starts a search on the host.\n\nThe client chooses the channel URI and then subscribes to it to receive the\nsearch's {@link SearchState} and its results. The client replaces the query\nby dispatching {@link SearchQueryChangedAction | `search/queryChanged`},\nand cancels the search by unsubscribing.\n\nThe client MUST NOT send this command unless `InitializeResult.search` is\npresent, and MUST NOT include a target whose kind is not listed in\n{@link SearchCapability.targets}.\n\nStability: 1.0 - Early development.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "The client-chosen URI for the new channel, for example `ahp-search:/`." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "What to search for and where." + } + }, + "required": [ + "channel", + "query" + ] + }, + "CreateSearchResult": { + "type": "object", + "description": "Result of the `createSearch` command.\n\nAn empty object on success.\n\nStability: 1.0 - Early development.", + "properties": {} + }, "URI": { "type": "string", "description": "A URI string (e.g. `ahp-root://`, `ahp-session:/`, or `ahp-chat:/`)." @@ -9138,6 +9646,75 @@ ], "description": "Discriminated lifecycle of an automation run." }, + "SearchTargetKind": { + "enum": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ], + "type": "string", + "description": "Discriminant for {@link SearchTarget}." + }, + "SearchTarget": { + "oneOf": [ + { + "$ref": "#/$defs/FileNamesSearchTarget" + }, + { + "$ref": "#/$defs/FileTextSearchTarget" + }, + { + "$ref": "#/$defs/SessionsSearchTarget" + }, + { + "$ref": "#/$defs/ChatMessagesSearchTarget" + } + ], + "description": "One place to search." + }, + "SearchCompletionReason": { + "enum": [ + "exhausted", + "limitReached" + ], + "type": "string", + "description": "Why a search completed." + }, + "SearchResult": { + "oneOf": [ + { + "$ref": "#/$defs/FileNameSearchResult" + }, + { + "$ref": "#/$defs/FileTextSearchResult" + }, + { + "$ref": "#/$defs/SessionSearchResult" + }, + { + "$ref": "#/$defs/ChatMessageSearchResult" + } + ], + "description": "One search match." + }, + "SearchLifecycleState": { + "oneOf": [ + { + "$ref": "#/$defs/SearchPendingLifecycleState" + }, + { + "$ref": "#/$defs/SearchRunningLifecycleState" + }, + { + "$ref": "#/$defs/SearchCompletedLifecycleState" + }, + { + "$ref": "#/$defs/SearchFailedLifecycleState" + } + ], + "description": "Discriminated lifecycle of a search." + }, "PathStyle": { "enum": [ "posix", @@ -9475,6 +10052,15 @@ { "$ref": "#/$defs/ResourceWatchChangedAction" }, + { + "$ref": "#/$defs/SearchQueryChangedAction" + }, + { + "$ref": "#/$defs/SearchResultsChangedAction" + }, + { + "$ref": "#/$defs/SearchLifecycleChangedAction" + }, { "$ref": "#/$defs/AutomationCreateRequestedAction" }, @@ -11859,6 +12445,64 @@ "changes" ] }, + "SearchQueryChangedAction": { + "type": "object", + "description": "Replaces the search's query and restarts the search.\n\nKeeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to\n{@link SearchLifecycleStatus.Pending | pending}. The old results stay\nvisible until the host replaces them, so the client does not flash an empty\nlist.\n\nAfter the host applies this action, it stops the previous search and drops\nany of its results that it has not dispatched yet. The host MUST then\ndispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with\n`replace: true` before any other search action. The replacement can keep\nold results that still match the new query, and can be empty. If the new\nquery is not valid,\nfor example because it contains an invalid regular expression, the host\nreplaces the results with an empty list and then changes the lifecycle to\n{@link SearchLifecycleStatus.Failed | failed}.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/queryChanged" + }, + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The new query." + } + }, + "required": [ + "type", + "query" + ] + }, + "SearchResultsChangedAction": { + "type": "object", + "description": "Adds results to {@link SearchState.results}, or replaces them.\n\nBy default, the reducer appends `results`. Set `replace` to `true` to\nreplace every result instead; if {@link SearchState.lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, a replacement also changes\nit to {@link SearchLifecycleStatus.Running | running}.\n\nThe host MUST dispatch a replacement first after a\n{@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also\nreplace the results at other times, for example to re-rank them, to remove\nduplicates, or to update a completed search when a watched file changes.\nThe host MUST NOT dispatch an empty `results` list unless `replace` is\n`true`.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/resultsChanged" + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "The results to append, in the order the host found them, or the replacement results." + }, + "replace": { + "type": "boolean", + "description": "When `true`, replaces every result instead of appending." + } + }, + "required": [ + "type", + "results" + ] + }, + "SearchLifecycleChangedAction": { + "type": "object", + "description": "Replaces {@link SearchState.lifecycle}.\n\nThe host dispatches this to complete or fail a search, or to move a\ncompleted search back to {@link SearchLifecycleStatus.Running | running} when it\nsearches again, for example after a watched file changes. The host MUST NOT\nchange the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only\n{@link SearchQueryChangedAction | `search/queryChanged`} does that.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "search/lifecycleChanged" + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "The new lifecycle." + } + }, + "required": [ + "type", + "lifecycle" + ] + }, "AutomationCreateRequestedAction": { "type": "object", "description": "Ask the host to create a durable automation at a client-chosen resource.\n\nClients may dispatch this action only when the host advertises its `create`\nautomation capability. {@link AutomationCreateRequestedAction.resource |\n`resource`} MUST use the `ahp-automation:` scheme and MUST NOT already\nidentify an unrelated automation.\n\nThis side-effect request leaves optimistic catalogue state unchanged. The\nhost validates trigger ids and configuration, normalizes event-trigger\ntitles and descriptions, captures any\n{@link AutomationSessionTemplate.customizations | session customizations}\nfrom the dispatching client, persists the definition, then publishes the\nauthoritative result with {@link AutomationSetAction | `automation/set`}.\nRejections leave the catalogue unchanged.", diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index d0ad18bc7..07c95e72d 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -904,6 +904,9 @@ { "$ref": "#/$defs/AutomationRunState" }, + { + "$ref": "#/$defs/SearchState" + }, { "$ref": "#/$defs/EmptyState" } @@ -6634,6 +6637,477 @@ "description": "Present when the host supports `createTcpConnection`.\n\nA client creates a connection with `createTcpConnection`, then subscribes to\nits channel with windowed delivery. A TCP channel's state is an\n{@link EmptyState}; its data is sent in `tcp/data` and `tcp/eof`\nnotifications. TCP connections do not survive the loss of the AHP connection.\n\nStability: 1.0 - Early development.", "properties": {} }, + "SearchCapability": { + "type": "object", + "description": "Present when the host supports `createSearch`.\n\nStability: 1.0 - Early development.", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTargetKind" + }, + "description": "The target kinds the host can search. A client MUST NOT send a\n{@link SearchTarget} whose kind is not listed here." + } + }, + "required": [ + "targets" + ] + }, + "SearchQuery": { + "type": "object", + "description": "What a search looks for and where.\n\nThe client sends a query in `createSearch` and replaces it with\n{@link SearchQueryChangedAction | `search/queryChanged`}.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to search for. Its meaning depends on the target: see\n{@link SearchTarget}. An empty `text` matches nothing; the host completes\nthe search with no results." + }, + "matchCase": { + "type": "boolean", + "description": "Match case. Defaults to `false`." + }, + "wholeWord": { + "type": "boolean", + "description": "Match only whole words. Defaults to `false`." + }, + "isRegex": { + "type": "boolean", + "description": "Treat `text` as a regular expression. Defaults to `false`." + }, + "fuzzy": { + "type": "boolean", + "description": "A hint that precise matching isn't expected, for example because the\nsearch powers a quick-find picker. The host MAY then match loosely, rank\nresults by how well they match, and ignore {@link isRegex} and\n{@link wholeWord}. Defaults to `false`." + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTarget" + }, + "description": "Where to search. MUST contain at least one target." + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results. The host MAY apply a lower limit, and\ncompletes the search with {@link SearchCompletionReason.LimitReached}\nwhen it reaches the limit that applies.", + "minimum": 1 + } + }, + "required": [ + "text", + "targets" + ] + }, + "FileSearchTargetBase": { + "type": "object", + "description": "Shared fields for file search targets.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + } + }, + "required": [ + "roots" + ] + }, + "FileNamesSearchTarget": { + "type": "object", + "description": "Searches file paths under {@link FileSearchTargetBase.roots}.\n\nThe host decides how to match {@link SearchQuery.text} against file paths,\nfor example with fuzzy matching, and which query options apply. Results\nare {@link FileNameSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileNames" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "FileTextSearchTarget": { + "type": "object", + "description": "Searches the text content of files under {@link FileSearchTargetBase.roots}.\nResults are {@link FileTextSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileText" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "SessionsSearchTarget": { + "type": "object", + "description": "Searches the host's sessions, the same sessions that `listSessions`\nreturns. The host decides which session content it matches, for example\ntitles or requests. Results are {@link SessionSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "sessions" + } + }, + "required": [ + "kind" + ] + }, + "ChatMessagesSearchTarget": { + "type": "object", + "description": "Searches the visible text of chat requests and responses, including the\nresponses of deferred turns. Results are\n{@link ChatMessageSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "chatMessages" + }, + "chats": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The chats to search. MUST contain at least one chat URI." + } + }, + "required": [ + "kind", + "chats" + ] + }, + "SearchHighlight": { + "type": "object", + "description": "A matched span within {@link SearchMatch.text}: the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits, as in {@link CompletionItem.rangeStart}.\n\nStability: 1.0 - Early development.", + "properties": { + "rangeStart": { + "type": "integer", + "description": "The start of the span.", + "minimum": 0 + }, + "rangeEnd": { + "type": "integer", + "description": "The end of the span, exclusive. MUST be greater than {@link rangeStart}\nand at most the length of {@link SearchMatch.text}.", + "minimum": 1 + } + }, + "required": [ + "rangeStart", + "rangeEnd" + ] + }, + "SearchMatch": { + "type": "object", + "description": "The matched text of a result, with the matched spans highlighted. The host\nchooses how much text around the match to include.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to display." + }, + "highlights": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchHighlight" + }, + "description": "The matched spans, in order. Spans MUST NOT overlap." + } + }, + "required": [ + "text", + "highlights" + ] + }, + "SearchResultBase": { + "type": "object", + "description": "Shared fields for search results. Each result is one match.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + } + }, + "required": [ + "resource", + "match" + ] + }, + "FileNameSearchResult": { + "type": "object", + "description": "A file whose path matches. {@link SearchResultBase.resource} is the file;\nthe match text is its path, usually relative to the root that contains it.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileName" + } + }, + "required": [ + "resource", + "match", + "kind" + ] + }, + "FileTextSearchResult": { + "type": "object", + "description": "A match in the text of a file. {@link SearchResultBase.resource} is the\nfile; the match text is the text around the match, usually its line.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileText" + }, + "range": { + "$ref": "#/$defs/TextRange", + "description": "The location of the match in the file." + } + }, + "required": [ + "resource", + "match", + "kind", + "range" + ] + }, + "SessionSearchResult": { + "type": "object", + "description": "A session whose content matches. {@link SearchResultBase.resource} is the\nsession URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "session" + }, + "title": { + "type": "string", + "description": "The session's title." + } + }, + "required": [ + "resource", + "match", + "kind", + "title" + ] + }, + "ChatMessageSearchResult": { + "type": "object", + "description": "A match in a chat request or response. {@link SearchResultBase.resource}\nis the chat URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "chatMessage" + }, + "title": { + "type": "string", + "description": "The chat's title." + }, + "turnId": { + "type": "string", + "description": "The ID of the turn that contains the match." + } + }, + "required": [ + "resource", + "match", + "kind", + "title", + "turnId" + ] + }, + "SearchPendingLifecycleState": { + "type": "object", + "description": "The query changed and the host has not replaced the results yet. Clients\nMAY show the previous query's results differently, for example dimmed.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "pending" + } + }, + "required": [ + "status" + ] + }, + "SearchRunningLifecycleState": { + "type": "object", + "description": "The host is searching and may add more results.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "running" + } + }, + "required": [ + "status" + ] + }, + "SearchCompletedLifecycleState": { + "type": "object", + "description": "The host found every result for the query. A host that watches the\nsearched files, sessions, or chats MAY still change the results later.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "completed" + }, + "reason": { + "$ref": "#/$defs/SearchCompletionReason", + "description": "Why the search completed." + } + }, + "required": [ + "status", + "reason" + ] + }, + "SearchFailedLifecycleState": { + "type": "object", + "description": "The search failed. Results found before the failure remain in\n{@link SearchState.results}.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "failed" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Why the search failed, for example an invalid regular expression." + } + }, + "required": [ + "status", + "error" + ] + }, + "SearchState": { + "type": "object", + "description": "Full state for one search, returned when a client subscribes to its\n`ahp-search:` URI.\n\nStability: 1.0 - Early development.", + "properties": { + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The current query." + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "Results in the order the host found them. Sort by\n{@link SearchResultBase.score} to rank them. While {@link lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, these are results for the\nprevious query." + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "Where the search is in its lifecycle." + } + }, + "required": [ + "query", + "results", + "lifecycle" + ] + }, "URI": { "type": "string", "description": "A URI string (e.g. `ahp-root://`, `ahp-session:/`, or `ahp-chat:/`)." @@ -7422,6 +7896,75 @@ } ], "description": "Discriminated lifecycle of an automation run." + }, + "SearchTargetKind": { + "enum": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ], + "type": "string", + "description": "Discriminant for {@link SearchTarget}." + }, + "SearchTarget": { + "oneOf": [ + { + "$ref": "#/$defs/FileNamesSearchTarget" + }, + { + "$ref": "#/$defs/FileTextSearchTarget" + }, + { + "$ref": "#/$defs/SessionsSearchTarget" + }, + { + "$ref": "#/$defs/ChatMessagesSearchTarget" + } + ], + "description": "One place to search." + }, + "SearchCompletionReason": { + "enum": [ + "exhausted", + "limitReached" + ], + "type": "string", + "description": "Why a search completed." + }, + "SearchResult": { + "oneOf": [ + { + "$ref": "#/$defs/FileNameSearchResult" + }, + { + "$ref": "#/$defs/FileTextSearchResult" + }, + { + "$ref": "#/$defs/SessionSearchResult" + }, + { + "$ref": "#/$defs/ChatMessageSearchResult" + } + ], + "description": "One search match." + }, + "SearchLifecycleState": { + "oneOf": [ + { + "$ref": "#/$defs/SearchPendingLifecycleState" + }, + { + "$ref": "#/$defs/SearchRunningLifecycleState" + }, + { + "$ref": "#/$defs/SearchCompletedLifecycleState" + }, + { + "$ref": "#/$defs/SearchFailedLifecycleState" + } + ], + "description": "Discriminated lifecycle of a search." } } } diff --git a/schema/state.schema.json b/schema/state.schema.json index 35d20f752..4d8855fc5 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -513,6 +513,9 @@ { "$ref": "#/$defs/AutomationRunState" }, + { + "$ref": "#/$defs/SearchState" + }, { "$ref": "#/$defs/EmptyState" } @@ -6243,6 +6246,477 @@ "description": "Present when the host supports `createTcpConnection`.\n\nA client creates a connection with `createTcpConnection`, then subscribes to\nits channel with windowed delivery. A TCP channel's state is an\n{@link EmptyState}; its data is sent in `tcp/data` and `tcp/eof`\nnotifications. TCP connections do not survive the loss of the AHP connection.\n\nStability: 1.0 - Early development.", "properties": {} }, + "SearchCapability": { + "type": "object", + "description": "Present when the host supports `createSearch`.\n\nStability: 1.0 - Early development.", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTargetKind" + }, + "description": "The target kinds the host can search. A client MUST NOT send a\n{@link SearchTarget} whose kind is not listed here." + } + }, + "required": [ + "targets" + ] + }, + "SearchQuery": { + "type": "object", + "description": "What a search looks for and where.\n\nThe client sends a query in `createSearch` and replaces it with\n{@link SearchQueryChangedAction | `search/queryChanged`}.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to search for. Its meaning depends on the target: see\n{@link SearchTarget}. An empty `text` matches nothing; the host completes\nthe search with no results." + }, + "matchCase": { + "type": "boolean", + "description": "Match case. Defaults to `false`." + }, + "wholeWord": { + "type": "boolean", + "description": "Match only whole words. Defaults to `false`." + }, + "isRegex": { + "type": "boolean", + "description": "Treat `text` as a regular expression. Defaults to `false`." + }, + "fuzzy": { + "type": "boolean", + "description": "A hint that precise matching isn't expected, for example because the\nsearch powers a quick-find picker. The host MAY then match loosely, rank\nresults by how well they match, and ignore {@link isRegex} and\n{@link wholeWord}. Defaults to `false`." + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchTarget" + }, + "description": "Where to search. MUST contain at least one target." + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results. The host MAY apply a lower limit, and\ncompletes the search with {@link SearchCompletionReason.LimitReached}\nwhen it reaches the limit that applies.", + "minimum": 1 + } + }, + "required": [ + "text", + "targets" + ] + }, + "FileSearchTargetBase": { + "type": "object", + "description": "Shared fields for file search targets.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + } + }, + "required": [ + "roots" + ] + }, + "FileNamesSearchTarget": { + "type": "object", + "description": "Searches file paths under {@link FileSearchTargetBase.roots}.\n\nThe host decides how to match {@link SearchQuery.text} against file paths,\nfor example with fuzzy matching, and which query options apply. Results\nare {@link FileNameSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileNames" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "FileTextSearchTarget": { + "type": "object", + "description": "Searches the text content of files under {@link FileSearchTargetBase.roots}.\nResults are {@link FileTextSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The folders to search. MUST contain at least one URI." + }, + "includes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. When present, only matching files are searched." + }, + "excludes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Glob patterns relative to a root. Matching files are not searched." + }, + "includeIgnored": { + "type": "boolean", + "description": "Also search files that the host's ignore rules, such as `.gitignore`\nfiles, would otherwise skip. Defaults to `false`. `excludes` still apply." + }, + "kind": { + "const": "fileText" + } + }, + "required": [ + "roots", + "kind" + ] + }, + "SessionsSearchTarget": { + "type": "object", + "description": "Searches the host's sessions, the same sessions that `listSessions`\nreturns. The host decides which session content it matches, for example\ntitles or requests. Results are {@link SessionSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "sessions" + } + }, + "required": [ + "kind" + ] + }, + "ChatMessagesSearchTarget": { + "type": "object", + "description": "Searches the visible text of chat requests and responses, including the\nresponses of deferred turns. Results are\n{@link ChatMessageSearchResult}s.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "chatMessages" + }, + "chats": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "The chats to search. MUST contain at least one chat URI." + } + }, + "required": [ + "kind", + "chats" + ] + }, + "SearchHighlight": { + "type": "object", + "description": "A matched span within {@link SearchMatch.text}: the half-open interval\n`[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code\nunits, as in {@link CompletionItem.rangeStart}.\n\nStability: 1.0 - Early development.", + "properties": { + "rangeStart": { + "type": "integer", + "description": "The start of the span.", + "minimum": 0 + }, + "rangeEnd": { + "type": "integer", + "description": "The end of the span, exclusive. MUST be greater than {@link rangeStart}\nand at most the length of {@link SearchMatch.text}.", + "minimum": 1 + } + }, + "required": [ + "rangeStart", + "rangeEnd" + ] + }, + "SearchMatch": { + "type": "object", + "description": "The matched text of a result, with the matched spans highlighted. The host\nchooses how much text around the match to include.\n\nStability: 1.0 - Early development.", + "properties": { + "text": { + "type": "string", + "description": "The text to display." + }, + "highlights": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchHighlight" + }, + "description": "The matched spans, in order. Spans MUST NOT overlap." + } + }, + "required": [ + "text", + "highlights" + ] + }, + "SearchResultBase": { + "type": "object", + "description": "Shared fields for search results. Each result is one match.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + } + }, + "required": [ + "resource", + "match" + ] + }, + "FileNameSearchResult": { + "type": "object", + "description": "A file whose path matches. {@link SearchResultBase.resource} is the file;\nthe match text is its path, usually relative to the root that contains it.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileName" + } + }, + "required": [ + "resource", + "match", + "kind" + ] + }, + "FileTextSearchResult": { + "type": "object", + "description": "A match in the text of a file. {@link SearchResultBase.resource} is the\nfile; the match text is the text around the match, usually its line.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "fileText" + }, + "range": { + "$ref": "#/$defs/TextRange", + "description": "The location of the match in the file." + } + }, + "required": [ + "resource", + "match", + "kind", + "range" + ] + }, + "SessionSearchResult": { + "type": "object", + "description": "A session whose content matches. {@link SearchResultBase.resource} is the\nsession URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "session" + }, + "title": { + "type": "string", + "description": "The session's title." + } + }, + "required": [ + "resource", + "match", + "kind", + "title" + ] + }, + "ChatMessageSearchResult": { + "type": "object", + "description": "A match in a chat request or response. {@link SearchResultBase.resource}\nis the chat URI.\n\nStability: 1.0 - Early development.", + "properties": { + "resource": { + "$ref": "#/$defs/URI", + "description": "The resource that contains the match." + }, + "match": { + "$ref": "#/$defs/SearchMatch", + "description": "The text to display, with the matched spans highlighted." + }, + "score": { + "type": "number", + "description": "How well the result matches; higher is better. Scores have no fixed\nrange, and are comparable across all results of one search. Clients\nSHOULD show results in descending score order. A host that does not rank\nresults omits the score." + }, + "kind": { + "const": "chatMessage" + }, + "title": { + "type": "string", + "description": "The chat's title." + }, + "turnId": { + "type": "string", + "description": "The ID of the turn that contains the match." + } + }, + "required": [ + "resource", + "match", + "kind", + "title", + "turnId" + ] + }, + "SearchPendingLifecycleState": { + "type": "object", + "description": "The query changed and the host has not replaced the results yet. Clients\nMAY show the previous query's results differently, for example dimmed.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "pending" + } + }, + "required": [ + "status" + ] + }, + "SearchRunningLifecycleState": { + "type": "object", + "description": "The host is searching and may add more results.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "running" + } + }, + "required": [ + "status" + ] + }, + "SearchCompletedLifecycleState": { + "type": "object", + "description": "The host found every result for the query. A host that watches the\nsearched files, sessions, or chats MAY still change the results later.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "completed" + }, + "reason": { + "$ref": "#/$defs/SearchCompletionReason", + "description": "Why the search completed." + } + }, + "required": [ + "status", + "reason" + ] + }, + "SearchFailedLifecycleState": { + "type": "object", + "description": "The search failed. Results found before the failure remain in\n{@link SearchState.results}.\n\nStability: 1.0 - Early development.", + "properties": { + "status": { + "const": "failed" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Why the search failed, for example an invalid regular expression." + } + }, + "required": [ + "status", + "error" + ] + }, + "SearchState": { + "type": "object", + "description": "Full state for one search, returned when a client subscribes to its\n`ahp-search:` URI.\n\nStability: 1.0 - Early development.", + "properties": { + "query": { + "$ref": "#/$defs/SearchQuery", + "description": "The current query." + }, + "results": { + "type": "array", + "items": { + "$ref": "#/$defs/SearchResult" + }, + "description": "Results in the order the host found them. Sort by\n{@link SearchResultBase.score} to rank them. While {@link lifecycle} is\n{@link SearchLifecycleStatus.Pending | pending}, these are results for the\nprevious query." + }, + "lifecycle": { + "$ref": "#/$defs/SearchLifecycleState", + "description": "Where the search is in its lifecycle." + } + }, + "required": [ + "query", + "results", + "lifecycle" + ] + }, "StringOrMarkdown": { "oneOf": [ { @@ -6838,6 +7312,57 @@ ], "description": "Discriminated lifecycle of an automation run." }, + "SearchTarget": { + "oneOf": [ + { + "$ref": "#/$defs/FileNamesSearchTarget" + }, + { + "$ref": "#/$defs/FileTextSearchTarget" + }, + { + "$ref": "#/$defs/SessionsSearchTarget" + }, + { + "$ref": "#/$defs/ChatMessagesSearchTarget" + } + ], + "description": "One place to search." + }, + "SearchResult": { + "oneOf": [ + { + "$ref": "#/$defs/FileNameSearchResult" + }, + { + "$ref": "#/$defs/FileTextSearchResult" + }, + { + "$ref": "#/$defs/SessionSearchResult" + }, + { + "$ref": "#/$defs/ChatMessageSearchResult" + } + ], + "description": "One search match." + }, + "SearchLifecycleState": { + "oneOf": [ + { + "$ref": "#/$defs/SearchPendingLifecycleState" + }, + { + "$ref": "#/$defs/SearchRunningLifecycleState" + }, + { + "$ref": "#/$defs/SearchCompletedLifecycleState" + }, + { + "$ref": "#/$defs/SearchFailedLifecycleState" + } + ], + "description": "Discriminated lifecycle of a search." + }, "URI": { "type": "string", "description": "A URI string (e.g. `ahp-root://`, `ahp-session:/`, or `ahp-chat:/`)." @@ -7023,6 +7548,24 @@ ], "type": "string", "description": "Operations the host currently permits for an automation.\n\nThe list on {@link AutomationEntry.operations} is authoritative and may\nchange over time. Clients MUST NOT infer permission from capabilities alone:\ncapabilities describe what the host implementation can support, while\noperations describe what is allowed for this particular automation now." + }, + "SearchTargetKind": { + "enum": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ], + "type": "string", + "description": "Discriminant for {@link SearchTarget}." + }, + "SearchCompletionReason": { + "enum": [ + "exhausted", + "limitReached" + ], + "type": "string", + "description": "Why a search completed." } } } diff --git a/scripts/find-protocol-sources.ts b/scripts/find-protocol-sources.ts index 7ab1e3899..1d0beddef 100644 --- a/scripts/find-protocol-sources.ts +++ b/scripts/find-protocol-sources.ts @@ -28,6 +28,7 @@ export const PROTOCOL_SOURCE_DIRS: readonly string[] = [ 'channels-automation', 'channels-automation-run', 'channels-tcp', + 'channels-search', ]; /** diff --git a/scripts/generate-action-origin.ts b/scripts/generate-action-origin.ts index f25c2ecb9..847609f8e 100644 --- a/scripts/generate-action-origin.ts +++ b/scripts/generate-action-origin.ts @@ -17,7 +17,7 @@ const GENERATED_HEADER = `// Generated from types/actions.ts — do not edit // Run \`npm run generate\` to regenerate. `; -type ActionScope = 'root' | 'session' | 'chat' | 'canvas' | 'terminal' | 'changeset' | 'annotations' | 'resourceWatch' | 'automation' | 'automationRun'; +type ActionScope = 'root' | 'session' | 'chat' | 'canvas' | 'terminal' | 'changeset' | 'annotations' | 'resourceWatch' | 'search' | 'automation' | 'automationRun'; interface ActionInfo { /** The interface name (e.g. 'RootAgentsChangedAction') */ @@ -156,6 +156,7 @@ export function readActionOrigins(project: Project): ActionInfo[] { : category === 'Changeset Actions' ? 'changeset' : category === 'Annotations Actions' ? 'annotations' : category === 'Resource Watch Actions' ? 'resourceWatch' + : category === 'Search Actions' ? 'search' : category === 'Automation Actions' ? 'automation' : category === 'Automation Run Actions' ? 'automationRun' : 'session'; @@ -217,6 +218,7 @@ export function generateActionOrigin(project: Project, outDir: string): void { const changesetActions = actions.filter(a => a.scope === 'changeset'); const annotationsActions = actions.filter(a => a.scope === 'annotations'); const resourceWatchActions = actions.filter(a => a.scope === 'resourceWatch'); + const searchActions = actions.filter(a => a.scope === 'search'); const automationActions = actions.filter(a => a.scope === 'automation'); const automationRunActions = actions.filter(a => a.scope === 'automationRun'); const clientRootActions = rootActions.filter(a => a.isClientDispatchable); @@ -235,6 +237,8 @@ export function generateActionOrigin(project: Project, outDir: string): void { const serverAnnotationsActions = annotationsActions.filter(a => !a.isClientDispatchable); const clientResourceWatchActions = resourceWatchActions.filter(a => a.isClientDispatchable); const serverResourceWatchActions = resourceWatchActions.filter(a => !a.isClientDispatchable); + const clientSearchActions = searchActions.filter(a => a.isClientDispatchable); + const serverSearchActions = searchActions.filter(a => !a.isClientDispatchable); const clientAutomationActions = automationActions.filter(a => a.isClientDispatchable); const serverAutomationActions = automationActions.filter(a => !a.isClientDispatchable); const clientAutomationRunActions = automationRunActions.filter(a => a.isClientDispatchable); @@ -509,6 +513,25 @@ export function generateActionOrigin(project: Project, outDir: string): void { lines.push(`;`); lines.push(``); + // SearchAction + for (const [name, doc, list] of [ + ['SearchAction', 'Union of all search-scoped actions.', searchActions], + ['ClientSearchAction', 'Union of search actions that clients may dispatch.', clientSearchActions], + ['ServerSearchAction', 'Union of search actions that only the server may produce.', serverSearchActions], + ] as const) { + lines.push(`/** ${doc} */`); + lines.push(`export type ${name} =`); + if (list.length === 0) { + lines.push(` never`); + } else { + for (const a of list) { + lines.push(` | ${a.name}`); + } + } + lines.push(`;`); + lines.push(``); + } + // AutomationAction lines.push(`/** Union of all automation-scoped actions. */`); lines.push(`export type AutomationAction =`); diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index aee23b49d..f03690e66 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -791,6 +791,8 @@ const STATE_ENUMS = [ 'AutomationDisableConditionKind', 'AutomationTargetKind', 'AutomationRunStatus', 'AutomationRunOriginKind', + 'SearchTargetKind', 'SearchResultKind', + 'SearchLifecycleStatus', 'SearchCompletionReason', ]; // `mutable: true` marks the STATE types the reducers mutate in place — these @@ -972,6 +974,23 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'AutomationCancelledRunLifecycle' }, { name: 'AutomationRunSummary' }, { name: 'AutomationRunState', mutable: true }, + { name: 'SearchCapability' }, + { name: 'SearchQuery' }, + { name: 'FileNamesSearchTarget' }, + { name: 'FileTextSearchTarget' }, + { name: 'SessionsSearchTarget' }, + { name: 'ChatMessagesSearchTarget' }, + { name: 'SearchHighlight' }, + { name: 'SearchMatch' }, + { name: 'FileNameSearchResult' }, + { name: 'FileTextSearchResult' }, + { name: 'SessionSearchResult' }, + { name: 'ChatMessageSearchResult' }, + { name: 'SearchPendingLifecycleState' }, + { name: 'SearchRunningLifecycleState' }, + { name: 'SearchCompletedLifecycleState' }, + { name: 'SearchFailedLifecycleState' }, + { name: 'SearchState', mutable: true }, ]; const RESPONSE_PART_UNION: UnionConfig = { @@ -1485,6 +1504,45 @@ const AUTOMATION_RUN_LIFECYCLE_UNION: UnionConfig = { ], }; +const SEARCH_TARGET_UNION: UnionConfig = { + name: 'SearchTarget', + discriminantField: 'kind', + doc: 'SearchTarget is one place to search.', + variants: [ + { variantName: 'FileNames', innerType: 'FileNamesSearchTarget', wireValue: 'fileNames' }, + { variantName: 'FileText', innerType: 'FileTextSearchTarget', wireValue: 'fileText' }, + { variantName: 'Sessions', innerType: 'SessionsSearchTarget', wireValue: 'sessions' }, + { variantName: 'ChatMessages', innerType: 'ChatMessagesSearchTarget', wireValue: 'chatMessages' }, + ], + unknown: true, +}; + +const SEARCH_RESULT_UNION: UnionConfig = { + name: 'SearchResult', + discriminantField: 'kind', + doc: 'SearchResult is one search match.', + variants: [ + { variantName: 'FileName', innerType: 'FileNameSearchResult', wireValue: 'fileName' }, + { variantName: 'FileText', innerType: 'FileTextSearchResult', wireValue: 'fileText' }, + { variantName: 'Session', innerType: 'SessionSearchResult', wireValue: 'session' }, + { variantName: 'ChatMessage', innerType: 'ChatMessageSearchResult', wireValue: 'chatMessage' }, + ], + unknown: true, +}; + +const SEARCH_LIFECYCLE_UNION: UnionConfig = { + name: 'SearchLifecycleState', + discriminantField: 'status', + doc: 'SearchLifecycleState is the lifecycle of a search.', + variants: [ + { variantName: 'Pending', innerType: 'SearchPendingLifecycleState', wireValue: 'pending' }, + { variantName: 'Running', innerType: 'SearchRunningLifecycleState', wireValue: 'running' }, + { variantName: 'Completed', innerType: 'SearchCompletedLifecycleState', wireValue: 'completed' }, + { variantName: 'Failed', innerType: 'SearchFailedLifecycleState', wireValue: 'failed' }, + ], + unknown: true, +}; + function generateCustomizationEnablementUnionCs(project: Project): string { const extra = aliasPreservesUnknownMembers(project, 'CustomizationEnablement') ? ' [JsonExtensionData]\n public Dictionary? Extra { get; set; }\n' @@ -1546,9 +1604,9 @@ function generateSnapshotState(): string { return `/// /// SnapshotState is the state payload of a snapshot — root, session, /// chat, canvas, terminal, changeset, resource-watch, annotations, automation catalogue, - /// automation-run, or empty state. Read + /// automation-run, search, or empty state. Read /// probes for distinctive fields in an order where no probe shadows another -/// (empty → chat → session → canvas → terminal → changeset → resource-watch → annotations → root). +/// (empty → chat → search → session → canvas → terminal → changeset → resource-watch → annotations → root). /// An object with no members is an empty state, used by channels whose state has no fields. /// [JsonConverter(typeof(SnapshotStateConverter))] @@ -1587,6 +1645,9 @@ public sealed class SnapshotState /// Automation run state variant, when populated. public AutomationRunState? AutomationRun { get; set; } + /// Search state variant, when populated. + public SearchState? Search { get; set; } + /// /// A state that this version does not recognize, such as the state of a channel /// added in a later protocol version. Kept as raw JSON so it re-encodes unchanged. @@ -1621,6 +1682,11 @@ internal sealed class SnapshotStateConverter : JsonConverter { result.Chat = root.Deserialize(AhpJsonTypeInfo.Get(options)); } + // SearchState also has a required \`lifecycle\`, so probe it before SessionState. + else if (root.TryGetProperty("query", out _) && root.TryGetProperty("results", out _)) + { + result.Search = root.Deserialize(AhpJsonTypeInfo.Get(options)); + } else if (root.TryGetProperty("lifecycle", out _)) { // SessionState is discriminated on its required \`lifecycle\` field. @@ -1669,6 +1735,7 @@ internal sealed class SnapshotStateConverter : JsonConverter if (value.Automations is not null) { JsonSerializer.Serialize(writer, value.Automations, AhpJsonTypeInfo.Get(options)); return; } if (value.Chat is not null) { JsonSerializer.Serialize(writer, value.Chat, AhpJsonTypeInfo.Get(options)); return; } if (value.Canvas is not null) { JsonSerializer.Serialize(writer, value.Canvas, AhpJsonTypeInfo.Get(options)); return; } + if (value.Search is not null) { JsonSerializer.Serialize(writer, value.Search, AhpJsonTypeInfo.Get(options)); return; } if (value.Session is not null) { JsonSerializer.Serialize(writer, value.Session, AhpJsonTypeInfo.Get(options)); return; } if (value.Terminal is not null) { JsonSerializer.Serialize(writer, value.Terminal, AhpJsonTypeInfo.Get(options)); return; } if (value.Changeset is not null) { JsonSerializer.Serialize(writer, value.Changeset, AhpJsonTypeInfo.Get(options)); return; } @@ -1724,6 +1791,7 @@ function generateStateFile(project: Project): string { TERMINAL_LIFECYCLE_STATE_UNION, SESSION_ORIGIN_UNION, AUTOMATION_TRIGGER_UNION, AUTOMATION_DISABLE_CONDITION_UNION, AUTOMATION_TARGET_UNION, AUTOMATION_RUN_ORIGIN_UNION, AUTOMATION_RUN_LIFECYCLE_UNION, + SEARCH_TARGET_UNION, SEARCH_RESULT_UNION, SEARCH_LIFECYCLE_UNION, ]) { lines.push(generateDiscriminatedUnion(project, u)); lines.push(''); @@ -1861,6 +1929,9 @@ const ACTION_VARIANTS: { type: string; variantName: string; tsInterface: string { type: 'terminal/commandExecuted', variantName: 'TerminalCommandExecuted', tsInterface: 'TerminalCommandExecutedAction' }, { type: 'terminal/commandFinished', variantName: 'TerminalCommandFinished', tsInterface: 'TerminalCommandFinishedAction' }, { type: 'resourceWatch/changed', variantName: 'ResourceWatchChanged', tsInterface: 'ResourceWatchChangedAction' }, + { type: 'search/queryChanged', variantName: 'SearchQueryChanged', tsInterface: 'SearchQueryChangedAction' }, + { type: 'search/resultsChanged', variantName: 'SearchResultsChanged', tsInterface: 'SearchResultsChangedAction' }, + { type: 'search/lifecycleChanged', variantName: 'SearchLifecycleChanged', tsInterface: 'SearchLifecycleChangedAction' }, { type: 'annotations/set', variantName: 'AnnotationsSet', tsInterface: 'AnnotationsSetAction' }, { type: 'annotations/removed', variantName: 'AnnotationsRemoved', tsInterface: 'AnnotationsRemovedAction' }, { type: 'annotations/entrySet', variantName: 'AnnotationsEntrySet', tsInterface: 'AnnotationsEntrySetAction' }, @@ -2473,6 +2544,7 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: str { name: 'ResourceMkdirParams' }, { name: 'ResourceMkdirResult' }, { name: 'ResourceRequestParams' }, { name: 'ResourceRequestResult' }, { name: 'CreateResourceWatchParams' }, { name: 'CreateResourceWatchResult' }, + { name: 'CreateSearchParams' }, { name: 'CreateSearchResult' }, { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, @@ -3045,6 +3117,10 @@ function checkExhaustiveness(project: Project): void { 'AutomationTarget', 'AutomationRunOrigin', 'AutomationRunLifecycle', 'SessionInputRequest', 'BackgroundWork', 'ToolCallConfirmationState', 'ToolCallRiskAssessment', + 'SearchTarget', 'SearchResult', 'SearchLifecycleState', + // FileSearchTargetBase / SearchResultBase are base interfaces flattened into + // their variant records via `extends`. + 'FileSearchTargetBase', 'SearchResultBase', 'ReconnectResult', 'AuthRequiredErrorData', 'PermissionDeniedErrorData', 'UnsupportedProtocolVersionErrorData', 'AhpError', 'AhpErrorDetailsMap', 'AhpErrorCode', 'AhpErrorCodeWithData', diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index a5006bf74..b8be359c3 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -179,6 +179,7 @@ function mapType(tsType: string): string { tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | EmptyState' || + tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | SearchState | EmptyState' || tsType === 'RootState | SessionState | ChatState | TerminalState | ChangesetState' || tsType === 'RootState | SessionState | ChatState | TerminalState | ChangesetState | AnnotationsState' ) { @@ -767,6 +768,8 @@ const STATE_ENUMS = [ 'AutomationDisableConditionKind', 'AutomationTargetKind', 'AutomationRunStatus', 'AutomationRunOriginKind', + 'SearchTargetKind', 'SearchResultKind', + 'SearchLifecycleStatus', 'SearchCompletionReason', ]; const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: string; omitProps?: string[] }[] = [ @@ -945,6 +948,23 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'AutomationCancelledRunLifecycle' }, { name: 'AutomationRunSummary' }, { name: 'AutomationRunState' }, + { name: 'SearchCapability' }, + { name: 'SearchQuery' }, + { name: 'FileNamesSearchTarget' }, + { name: 'FileTextSearchTarget' }, + { name: 'SessionsSearchTarget' }, + { name: 'ChatMessagesSearchTarget' }, + { name: 'SearchHighlight' }, + { name: 'SearchMatch' }, + { name: 'FileNameSearchResult' }, + { name: 'FileTextSearchResult' }, + { name: 'SessionSearchResult' }, + { name: 'ChatMessageSearchResult' }, + { name: 'SearchPendingLifecycleState' }, + { name: 'SearchRunningLifecycleState' }, + { name: 'SearchCompletedLifecycleState' }, + { name: 'SearchFailedLifecycleState' }, + { name: 'SearchState' }, ]; const RESPONSE_PART_UNION: UnionConfig = { @@ -1262,6 +1282,46 @@ const AUTOMATION_RUN_LIFECYCLE_UNION: UnionConfig = { injectDiscriminantOnMarshal: true, }; +const SEARCH_TARGET_UNION: UnionConfig = { + name: 'SearchTarget', + discriminantField: 'kind', + doc: 'SearchTarget is one place to search.', + variants: [ + { variantName: 'FileNames', innerType: 'FileNamesSearchTarget', wireValue: 'fileNames' }, + { variantName: 'FileText', innerType: 'FileTextSearchTarget', wireValue: 'fileText' }, + { variantName: 'Sessions', innerType: 'SessionsSearchTarget', wireValue: 'sessions' }, + { variantName: 'ChatMessages', innerType: 'ChatMessagesSearchTarget', wireValue: 'chatMessages' }, + ], + unknown: true, +}; + +const SEARCH_RESULT_UNION: UnionConfig = { + name: 'SearchResult', + discriminantField: 'kind', + doc: 'SearchResult is one search match.', + variants: [ + { variantName: 'FileName', innerType: 'FileNameSearchResult', wireValue: 'fileName' }, + { variantName: 'FileText', innerType: 'FileTextSearchResult', wireValue: 'fileText' }, + { variantName: 'Session', innerType: 'SessionSearchResult', wireValue: 'session' }, + { variantName: 'ChatMessage', innerType: 'ChatMessageSearchResult', wireValue: 'chatMessage' }, + ], + unknown: true, +}; + +const SEARCH_LIFECYCLE_UNION: UnionConfig = { + name: 'SearchLifecycleState', + discriminantField: 'status', + doc: 'SearchLifecycleState is the lifecycle of a search.', + variants: [ + { variantName: 'Pending', innerType: 'SearchPendingLifecycleState', wireValue: 'pending' }, + { variantName: 'Running', innerType: 'SearchRunningLifecycleState', wireValue: 'running' }, + { variantName: 'Completed', innerType: 'SearchCompletedLifecycleState', wireValue: 'completed' }, + { variantName: 'Failed', innerType: 'SearchFailedLifecycleState', wireValue: 'failed' }, + ], + unknown: true, + injectDiscriminantOnMarshal: true, +}; + /** * `Turn = MaterializedTurn | DeferredTurn` is discriminated by the boolean * `isDeferred`, which the string-discriminant union emitter cannot express: @@ -1451,11 +1511,11 @@ func (o ChatOrigin) MarshalJSON() ([]byte, error) { function generateSnapshotState(): string { return `// SnapshotState is the state payload of a snapshot — root, session, // chat, canvas, terminal, changeset, resource-watch, annotations, automation catalogue, -// automation-run, or empty state. The active +// automation-run, search, or empty state. The active // variant is chosen by which pointer field is non-nil; UnmarshalJSON probes // for required fields in the canonical order -// (empty → automationRun → automations → session → chat → canvas → terminal → -// changeset → resourceWatch → annotations → root). An object with no members +// (empty → automationRun → automations → search → session → chat → canvas → +// terminal → changeset → resourceWatch → annotations → root). An object with no members // is an empty state, used by channels whose state has no fields. A state that // matches none of these, such as the state of a channel added in a later // protocol version, is kept as raw JSON in Unknown. @@ -1472,6 +1532,7 @@ type SnapshotState struct { \tAnnotations *AnnotationsState \`json:"-"\` \tAutomations *AutomationState \`json:"-"\` \tAutomationRun *AutomationRunState \`json:"-"\` +\tSearch *SearchState \`json:"-"\` } // MarshalJSON encodes whichever variant is currently populated. @@ -1489,6 +1550,8 @@ func (s SnapshotState) MarshalJSON() ([]byte, error) { \t\treturn json.Marshal(s.Chat) \tcase s.Canvas != nil: \t\treturn json.Marshal(s.Canvas) +\tcase s.Search != nil: +\t\treturn json.Marshal(s.Search) \tcase s.Terminal != nil: \t\treturn json.Marshal(s.Terminal) \tcase s.Changeset != nil: @@ -1529,6 +1592,13 @@ func (s *SnapshotState) UnmarshalJSON(data []byte) error { \t\t\treturn err \t\t} \t\ts.Automations = &v +\t// SearchState also has a required \`lifecycle\`, so probe it before SessionState. +\tcase containsAll(probe, "query", "results"): +\t\tvar v SearchState +\t\tif err := json.Unmarshal(data, &v); err != nil { +\t\t\treturn err +\t\t} +\t\ts.Search = &v \tcase containsAll(probe, "lifecycle"): \t\tvar v SessionState \t\tif err := json.Unmarshal(data, &v); err != nil { @@ -1713,6 +1783,12 @@ function generateStateFile(project: Project): string { lines.push(''); lines.push(generateDiscriminatedUnion(project, AUTOMATION_RUN_LIFECYCLE_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_TARGET_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_RESULT_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_LIFECYCLE_UNION)); + lines.push(''); lines.push(generateTurnUnion()); lines.push(''); lines.push(generateChatOriginGo()); @@ -1830,6 +1906,9 @@ const ACTION_VARIANTS: { { type: 'terminal/commandExecuted', variantName: 'TerminalCommandExecuted', tsInterface: 'TerminalCommandExecutedAction' }, { type: 'terminal/commandFinished', variantName: 'TerminalCommandFinished', tsInterface: 'TerminalCommandFinishedAction' }, { type: 'resourceWatch/changed', variantName: 'ResourceWatchChanged', tsInterface: 'ResourceWatchChangedAction' }, + { type: 'search/queryChanged', variantName: 'SearchQueryChanged', tsInterface: 'SearchQueryChangedAction' }, + { type: 'search/resultsChanged', variantName: 'SearchResultsChanged', tsInterface: 'SearchResultsChangedAction' }, + { type: 'search/lifecycleChanged', variantName: 'SearchLifecycleChanged', tsInterface: 'SearchLifecycleChangedAction' }, { type: 'automation/createRequested', variantName: 'AutomationCreateRequested', tsInterface: 'AutomationCreateRequestedAction' }, { type: 'automation/updateRequested', variantName: 'AutomationUpdateRequested', tsInterface: 'AutomationUpdateRequestedAction' }, { type: 'automation/set', variantName: 'AutomationSet', tsInterface: 'AutomationSetAction' }, @@ -1979,6 +2058,7 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: str { name: 'ResourceMkdirParams' }, { name: 'ResourceMkdirResult' }, { name: 'ResourceRequestParams' }, { name: 'ResourceRequestResult' }, { name: 'CreateResourceWatchParams' }, { name: 'CreateResourceWatchResult' }, + { name: 'CreateSearchParams' }, { name: 'CreateSearchResult' }, { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, @@ -2679,6 +2759,11 @@ function checkExhaustiveness(project: Project): void { 'TerminalLifecycleState', 'SessionInputRequest', 'BackgroundWork', + 'SearchTarget', + 'SearchResult', + 'SearchLifecycleState', + 'FileSearchTargetBase', + 'SearchResultBase', 'ToolCallConfirmationState', 'ReconnectResult', 'SessionOrigin', diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index 88697f9ac..c0f43d7e9 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -160,6 +160,7 @@ function mapType(tsType: string): string { tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | EmptyState' || + tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | SearchState | EmptyState' || tsType === 'RootState | SessionState | ChatState' || tsType === 'RootState | SessionState | ChatState | TerminalState' || tsType === 'RootState | SessionState | ChatState | TerminalState | ChangesetState' || @@ -900,6 +901,7 @@ sealed interface SnapshotState { @JvmInline value class Annotations(val value: AnnotationsState) : SnapshotState @JvmInline value class Automations(val value: AutomationState) : SnapshotState @JvmInline value class AutomationRun(val value: AutomationRunState) : SnapshotState + @JvmInline value class Search(val value: SearchState) : SnapshotState /** A state that this version does not recognize, kept as raw JSON so it re-encodes unchanged. */ @JvmInline value class Unknown(val raw: JsonObject) : SnapshotState } @@ -916,7 +918,9 @@ internal object SnapshotStateSerializer : KSerializer { ?: error("Expected JsonObject for SnapshotState") // Try the most distinctive shape first. AutomationRunState has required // \`automation\`, \`origin\`, and \`sessions\`; AutomationState has - // required \`entries\`; SessionState has required + // required \`entries\`; SearchState has required \`query\` + + // \`results\` (checked before session, because it also has a required + // \`lifecycle\`); SessionState has required // \`lifecycle\`; ChatState has required \`turns\`; ChangesetState has // required \`status\` + \`files\`; ResourceWatchState has required // \`root\` + \`recursive\`; AnnotationsState has required \`annotations\` @@ -930,6 +934,8 @@ internal object SnapshotStateSerializer : KSerializer { SnapshotState.AutomationRun(input.json.decodeFromJsonElement(AutomationRunState.serializer(), element)) obj.containsKey("entries") -> SnapshotState.Automations(input.json.decodeFromJsonElement(AutomationState.serializer(), element)) + obj.containsKey("query") && obj.containsKey("results") -> + SnapshotState.Search(input.json.decodeFromJsonElement(SearchState.serializer(), element)) obj.containsKey("lifecycle") -> SnapshotState.Session(input.json.decodeFromJsonElement(SessionState.serializer(), element)) obj.containsKey("turns") -> SnapshotState.Chat(input.json.decodeFromJsonElement(ChatState.serializer(), element)) obj.containsKey("instanceId") && obj.containsKey("extensionId") && obj.containsKey("canvasId") -> @@ -963,6 +969,7 @@ internal object SnapshotStateSerializer : KSerializer { is SnapshotState.Annotations -> output.json.encodeToJsonElement(AnnotationsState.serializer(), value.value) is SnapshotState.Automations -> output.json.encodeToJsonElement(AutomationState.serializer(), value.value) is SnapshotState.AutomationRun -> output.json.encodeToJsonElement(AutomationRunState.serializer(), value.value) + is SnapshotState.Search -> output.json.encodeToJsonElement(SearchState.serializer(), value.value) is SnapshotState.Unknown -> value.raw } output.encodeJsonElement(element) @@ -1118,6 +1125,8 @@ const STATE_ENUMS = [ 'AutomationDisableConditionKind', 'AutomationTargetKind', 'AutomationRunStatus', 'AutomationRunOriginKind', + 'SearchTargetKind', 'SearchResultKind', + 'SearchLifecycleStatus', 'SearchCompletionReason', ]; const STATE_STRUCTS = [ @@ -1195,6 +1204,12 @@ const STATE_STRUCTS = [ 'AutomationCompletedRunLifecycle', 'AutomationFailedRunLifecycle', 'AutomationCancelledRunLifecycle', 'AutomationRunSummary', 'AutomationRunState', + 'SearchCapability', 'SearchQuery', + 'FileNamesSearchTarget', 'FileTextSearchTarget', 'SessionsSearchTarget', 'ChatMessagesSearchTarget', + 'SearchHighlight', 'SearchMatch', + 'FileNameSearchResult', 'FileTextSearchResult', 'SessionSearchResult', 'ChatMessageSearchResult', + 'SearchPendingLifecycleState', 'SearchRunningLifecycleState', 'SearchCompletedLifecycleState', 'SearchFailedLifecycleState', + 'SearchState', ]; const RESPONSE_PART_UNION: UnionConfig = { @@ -1542,6 +1557,43 @@ const AUTOMATION_RUN_LIFECYCLE_UNION: UnionConfig = { injectDiscriminantOnSerialize: true, }; +const SEARCH_TARGET_UNION: UnionConfig = { + name: 'SearchTarget', + discriminantField: 'kind', + variants: [ + { caseName: 'FileNames', structName: 'FileNamesSearchTarget', discriminantValue: 'fileNames' }, + { caseName: 'FileText', structName: 'FileTextSearchTarget', discriminantValue: 'fileText' }, + { caseName: 'Sessions', structName: 'SessionsSearchTarget', discriminantValue: 'sessions' }, + { caseName: 'ChatMessages', structName: 'ChatMessagesSearchTarget', discriminantValue: 'chatMessages' }, + ], + unknown: true, +}; + +const SEARCH_RESULT_UNION: UnionConfig = { + name: 'SearchResult', + discriminantField: 'kind', + variants: [ + { caseName: 'FileName', structName: 'FileNameSearchResult', discriminantValue: 'fileName' }, + { caseName: 'FileText', structName: 'FileTextSearchResult', discriminantValue: 'fileText' }, + { caseName: 'Session', structName: 'SessionSearchResult', discriminantValue: 'session' }, + { caseName: 'ChatMessage', structName: 'ChatMessageSearchResult', discriminantValue: 'chatMessage' }, + ], + unknown: true, +}; + +const SEARCH_LIFECYCLE_UNION: UnionConfig = { + name: 'SearchLifecycleState', + discriminantField: 'status', + variants: [ + { caseName: 'Pending', structName: 'SearchPendingLifecycleState', discriminantValue: 'pending' }, + { caseName: 'Running', structName: 'SearchRunningLifecycleState', discriminantValue: 'running' }, + { caseName: 'Completed', structName: 'SearchCompletedLifecycleState', discriminantValue: 'completed' }, + { caseName: 'Failed', structName: 'SearchFailedLifecycleState', discriminantValue: 'failed' }, + ], + unknown: true, + injectDiscriminantOnSerialize: true, +}; + function generateStateFile(project: Project): string { const lines: string[] = [ GENERATED_HEADER.replace('package ', '@file:OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)\n\npackage '), @@ -1643,6 +1695,12 @@ function generateStateFile(project: Project): string { lines.push(''); lines.push(generateDiscriminatedUnion(project, AUTOMATION_RUN_LIFECYCLE_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_TARGET_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_RESULT_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_LIFECYCLE_UNION)); + lines.push(''); lines.push(generateTurnKotlin(project)); lines.push(''); lines.push(generateToolResultContentUnion()); @@ -1756,6 +1814,9 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'terminal/commandExecuted', caseName: 'TerminalCommandExecuted', tsInterface: 'TerminalCommandExecutedAction' }, { type: 'terminal/commandFinished', caseName: 'TerminalCommandFinished', tsInterface: 'TerminalCommandFinishedAction' }, { type: 'resourceWatch/changed', caseName: 'ResourceWatchChanged', tsInterface: 'ResourceWatchChangedAction' }, + { type: 'search/queryChanged', caseName: 'SearchQueryChanged', tsInterface: 'SearchQueryChangedAction' }, + { type: 'search/resultsChanged', caseName: 'SearchResultsChanged', tsInterface: 'SearchResultsChangedAction' }, + { type: 'search/lifecycleChanged', caseName: 'SearchLifecycleChanged', tsInterface: 'SearchLifecycleChangedAction' }, { type: 'automation/createRequested', caseName: 'AutomationCreateRequested', tsInterface: 'AutomationCreateRequestedAction' }, { type: 'automation/updateRequested', caseName: 'AutomationUpdateRequested', tsInterface: 'AutomationUpdateRequestedAction' }, { type: 'automation/set', caseName: 'AutomationSet', tsInterface: 'AutomationSetAction' }, @@ -1955,6 +2016,7 @@ const COMMAND_STRUCTS = [ 'ResourceMkdirParams', 'ResourceMkdirResult', 'ResourceRequestParams', 'ResourceRequestResult', 'CreateResourceWatchParams', 'CreateResourceWatchResult', + 'CreateSearchParams', 'CreateSearchResult', 'FetchTurnsParams', 'FetchTurnsResult', 'FetchDeferredTurnsParams', 'FetchDeferredTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', @@ -2626,6 +2688,11 @@ function checkExhaustiveness(project: Project): void { 'TerminalLifecycleState', // TERMINAL_LIFECYCLE_STATE_UNION discriminated union 'SessionInputRequest', // SESSION_INPUT_REQUEST_UNION discriminated union 'BackgroundWork', // BACKGROUND_WORK_UNION discriminated union + 'SearchTarget', // SEARCH_TARGET_UNION discriminated union + 'SearchResult', // SEARCH_RESULT_UNION discriminated union + 'SearchLifecycleState', // SEARCH_LIFECYCLE_UNION discriminated union + 'FileSearchTargetBase', // base interface, flattened into the file search target data classes via `extends` + 'SearchResultBase', // base interface, flattened into the search result data classes via `extends` 'ToolCallConfirmationState', // TOOL_CALL_CONFIRMATION_STATE_UNION discriminated union 'ChildCustomizationType', // TS subset alias of CustomizationType; consumers reuse CustomizationType 'CustomizationLoadState', // CUSTOMIZATION_LOAD_STATE_UNION discriminated union diff --git a/scripts/generate-markdown.ts b/scripts/generate-markdown.ts index f513924cc..39001cae8 100644 --- a/scripts/generate-markdown.ts +++ b/scripts/generate-markdown.ts @@ -77,6 +77,7 @@ const DIR_TO_PAGE: Record = { 'channels-automation': 'automation', 'channels-automation-run': 'automation-run', 'channels-tcp': 'tcp', + 'channels-search': 'search', }; /** @@ -1207,6 +1208,31 @@ function generateTcpChannelPage(project: Project): string { return lines.join('\n'); } +function generateSearchChannelPage(project: Project): string { + currentPage = 'search'; + const stateSf = findChannelSourceFile(project, 'channels-search', 'state.ts'); + const actionsSf = findChannelSourceFile(project, 'channels-search', 'actions.ts'); + const commandsSf = findChannelSourceFile(project, 'channels-search', 'commands.ts'); + const lines: string[] = [GENERATED_HEADER, '# Search Channel\n', stabilityIndex(stateSf)]; + lines.push('Reference for `ahp-search:/` channels, which stream the results of a search over files, sessions, and chats. See the [Search Channel specification](/specification/search-channel).\n'); + lines.push(schemaLink('state.schema.json')); + if (stateSf) { + lines.push('## State Types\n'); + lines.push(emitStateTypesSection([stateSf])); + } + if (actionsSf) { + lines.push('## Actions\n'); + lines.push(schemaLink('actions.schema.json')); + lines.push(emitActionsSection([actionsSf])); + } + if (commandsSf) { + lines.push('## Commands\n'); + lines.push(schemaLink('commands.schema.json')); + lines.push(emitCommandsSection(project, [commandsSf])); + } + return lines.join('\n'); +} + // ─── Error Codes Page ──────────────────────────────────────────────────────── function generateErrorCodesPage(project: Project): string { @@ -1484,6 +1510,7 @@ export function generateMarkdownDocs(project: Project, outDir: string): void { { filename: 'resource-watch.md', generator: generateResourceWatchChannelPage }, { filename: 'otlp.md', generator: generateOtlpChannelPage }, { filename: 'tcp.md', generator: generateTcpChannelPage }, + { filename: 'search.md', generator: generateSearchChannelPage }, { filename: 'automation.md', generator: generateAutomationChannelPage }, { filename: 'automation-run.md', generator: generateAutomationRunChannelPage }, { filename: 'mcp.md', generator: generateMcpChannelPage }, diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 5d8e5347b..5637bdc08 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -171,6 +171,7 @@ function mapType(tsType: string, propName?: string, containerName?: string): str || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | EmptyState' + || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | SearchState | EmptyState' || tsType === 'RootState | SessionState | ChatState' || tsType === 'RootState | SessionState | ChatState | TerminalState' || tsType === 'RootState | SessionState | ChatState | TerminalState | ChangesetState' @@ -863,6 +864,8 @@ const STATE_ENUMS = [ 'AutomationDisableConditionKind', 'AutomationTargetKind', 'AutomationRunStatus', 'AutomationRunOriginKind', + 'SearchTargetKind', 'SearchResultKind', + 'SearchLifecycleStatus', 'SearchCompletionReason', ]; /** @@ -1045,6 +1048,23 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'AutomationCancelledRunLifecycle', omitDiscriminants: true }, { name: 'AutomationRunSummary' }, { name: 'AutomationRunState' }, + { name: 'SearchCapability' }, + { name: 'SearchQuery' }, + { name: 'FileNamesSearchTarget', omitDiscriminants: true }, + { name: 'FileTextSearchTarget', omitDiscriminants: true }, + { name: 'SessionsSearchTarget', omitDiscriminants: true }, + { name: 'ChatMessagesSearchTarget', omitDiscriminants: true }, + { name: 'SearchHighlight' }, + { name: 'SearchMatch' }, + { name: 'FileNameSearchResult', omitDiscriminants: true }, + { name: 'FileTextSearchResult', omitDiscriminants: true }, + { name: 'SessionSearchResult', omitDiscriminants: true }, + { name: 'ChatMessageSearchResult', omitDiscriminants: true }, + { name: 'SearchPendingLifecycleState', omitDiscriminants: true }, + { name: 'SearchRunningLifecycleState', omitDiscriminants: true }, + { name: 'SearchCompletedLifecycleState', omitDiscriminants: true }, + { name: 'SearchFailedLifecycleState', omitDiscriminants: true }, + { name: 'SearchState' }, ]; const RESPONSE_PART_UNION: UnionConfig = { @@ -1361,6 +1381,45 @@ const AUTOMATION_RUN_LIFECYCLE_UNION: UnionConfig = { ], }; +const SEARCH_TARGET_UNION: UnionConfig = { + name: 'SearchTarget', + discriminantField: 'kind', + doc: 'One place to search.', + variants: [ + { variantName: 'FileNames', innerType: 'FileNamesSearchTarget', wireValue: 'fileNames' }, + { variantName: 'FileText', innerType: 'FileTextSearchTarget', wireValue: 'fileText' }, + { variantName: 'Sessions', innerType: 'SessionsSearchTarget', wireValue: 'sessions' }, + { variantName: 'ChatMessages', innerType: 'ChatMessagesSearchTarget', wireValue: 'chatMessages' }, + ], + unknown: true, +}; + +const SEARCH_RESULT_UNION: UnionConfig = { + name: 'SearchResult', + discriminantField: 'kind', + doc: 'One search match.', + variants: [ + { variantName: 'FileName', innerType: 'FileNameSearchResult', wireValue: 'fileName' }, + { variantName: 'FileText', innerType: 'FileTextSearchResult', wireValue: 'fileText' }, + { variantName: 'Session', innerType: 'SessionSearchResult', wireValue: 'session' }, + { variantName: 'ChatMessage', innerType: 'ChatMessageSearchResult', wireValue: 'chatMessage' }, + ], + unknown: true, +}; + +const SEARCH_LIFECYCLE_UNION: UnionConfig = { + name: 'SearchLifecycleState', + discriminantField: 'status', + doc: 'Lifecycle of a search.', + variants: [ + { variantName: 'Pending', innerType: 'SearchPendingLifecycleState', wireValue: 'pending' }, + { variantName: 'Running', innerType: 'SearchRunningLifecycleState', wireValue: 'running' }, + { variantName: 'Completed', innerType: 'SearchCompletedLifecycleState', wireValue: 'completed' }, + { variantName: 'Failed', innerType: 'SearchFailedLifecycleState', wireValue: 'failed' }, + ], + unknown: true, +}; + function generateChatOrigin(project: Project): string { const originKind = findEnum(project, 'ChatOriginKind'); if (!originKind) throw new Error('ChatOriginKind enum not found'); @@ -1432,6 +1491,7 @@ pub enum SnapshotState { Annotations(Box), Automations(Box), AutomationRun(Box), + Search(Box), Root(Box), /// A state that this version does not recognize, kept as raw JSON so it /// re-encodes unchanged. @@ -1701,6 +1761,12 @@ where D: serde::Deserializer<'de>, lines.push(''); lines.push(generateDiscriminatedUnion(project, AUTOMATION_RUN_LIFECYCLE_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_TARGET_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_RESULT_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_LIFECYCLE_UNION)); + lines.push(''); lines.push(generateSnapshotState()); lines.push(''); @@ -1817,6 +1883,9 @@ const ACTION_VARIANTS: { { type: 'terminal/commandExecuted', variantName: 'TerminalCommandExecuted', tsInterface: 'TerminalCommandExecutedAction' }, { type: 'terminal/commandFinished', variantName: 'TerminalCommandFinished', tsInterface: 'TerminalCommandFinishedAction' }, { type: 'resourceWatch/changed', variantName: 'ResourceWatchChanged', tsInterface: 'ResourceWatchChangedAction' }, + { type: 'search/queryChanged', variantName: 'SearchQueryChanged', tsInterface: 'SearchQueryChangedAction' }, + { type: 'search/resultsChanged', variantName: 'SearchResultsChanged', tsInterface: 'SearchResultsChangedAction' }, + { type: 'search/lifecycleChanged', variantName: 'SearchLifecycleChanged', tsInterface: 'SearchLifecycleChangedAction' }, { type: 'automation/createRequested', variantName: 'AutomationCreateRequested', tsInterface: 'AutomationCreateRequestedAction', boxed: true }, { type: 'automation/updateRequested', variantName: 'AutomationUpdateRequested', tsInterface: 'AutomationUpdateRequestedAction', boxed: true }, { type: 'automation/set', variantName: 'AutomationSet', tsInterface: 'AutomationSetAction', boxed: true }, @@ -1903,7 +1972,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, MaterializedTurn, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, MaterializedTurn, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary, SearchQuery, SearchLifecycleState, SearchResult};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); @@ -2047,6 +2116,7 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: s { name: 'ResourceMkdirParams' }, { name: 'ResourceMkdirResult' }, { name: 'ResourceRequestParams' }, { name: 'ResourceRequestResult' }, { name: 'CreateResourceWatchParams' }, { name: 'CreateResourceWatchResult' }, + { name: 'CreateSearchParams' }, { name: 'CreateSearchResult' }, { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget', omitDiscriminants: true }, @@ -2107,7 +2177,7 @@ function generateCommandsFile(project: Project): string { lines.push('#[allow(unused_imports)]'); lines.push('use crate::actions::{ActionEnvelope, StateAction};'); lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentSelection, AutomationDefinition, AutomationSchedule, AutomationSessionTemplate, AutomationTrigger, AutomationTriggerDefinition, ChannelFlowControl, ChannelReceiveLimits, ContentRef, Message, MessageAttachment, ModelSelection, ResumedChannelSubscription, SessionActiveClient, SessionConfigSchema, SessionSummary, SideChatSelection, Snapshot, SnapshotState, TcpConnectionsCapability, TelemetryCapabilities, TerminalClaim, TextRange, Turn};'); + lines.push('use crate::state::{AgentSelection, AutomationDefinition, AutomationSchedule, AutomationSessionTemplate, AutomationTrigger, AutomationTriggerDefinition, ChannelFlowControl, ChannelReceiveLimits, ContentRef, Message, MessageAttachment, ModelSelection, ResumedChannelSubscription, SessionActiveClient, SessionConfigSchema, SessionSummary, SideChatSelection, Snapshot, SnapshotState, SearchCapability, SearchQuery, TcpConnectionsCapability, TelemetryCapabilities, TerminalClaim, TextRange, Turn};'); lines.push(''); lines.push('// ─── Enums ────────────────────────────────────────────────────────────\n'); @@ -2649,6 +2719,11 @@ function checkExhaustiveness(project: Project): void { 'TerminalLifecycleState', // TERMINAL_LIFECYCLE_STATE_UNION discriminated union 'SessionInputRequest', // SESSION_INPUT_REQUEST_UNION discriminated union 'BackgroundWork', // BACKGROUND_WORK_UNION discriminated union + 'SearchTarget', // SEARCH_TARGET_UNION discriminated union + 'SearchResult', // SEARCH_RESULT_UNION discriminated union + 'SearchLifecycleState', // SEARCH_LIFECYCLE_UNION discriminated union + 'FileSearchTargetBase', // base interface, flattened into the file search target structs via `extends` + 'SearchResultBase', // base interface, flattened into the search result structs via `extends` 'ToolCallConfirmationState', // TOOL_CALL_CONFIRMATION_STATE_UNION discriminated union 'ReconnectResult', 'SessionOrigin', diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 3fa420480..4e8853817 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -129,6 +129,7 @@ function mapType(tsType: string, propName?: string, containerName?: string): str || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState' || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | EmptyState' + || tsType === 'RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | SearchState | EmptyState' || tsType === 'RootState | SessionState | ChatState' || tsType === 'RootState | SessionState | ChatState | TerminalState' || tsType === 'RootState | SessionState | ChatState | TerminalState | ChangesetState' @@ -741,6 +742,8 @@ const STATE_ENUMS = [ 'AutomationDisableConditionKind', 'AutomationTargetKind', 'AutomationRunStatus', 'AutomationRunOriginKind', + 'SearchTargetKind', 'SearchResultKind', + 'SearchLifecycleStatus', 'SearchCompletionReason', ]; const STATE_STRUCTS = [ @@ -818,6 +821,12 @@ const STATE_STRUCTS = [ 'AutomationCompletedRunLifecycle', 'AutomationFailedRunLifecycle', 'AutomationCancelledRunLifecycle', 'AutomationRunSummary', 'AutomationRunState', + 'SearchCapability', 'SearchQuery', + 'FileNamesSearchTarget', 'FileTextSearchTarget', 'SessionsSearchTarget', 'ChatMessagesSearchTarget', + 'SearchHighlight', 'SearchMatch', + 'FileNameSearchResult', 'FileTextSearchResult', 'SessionSearchResult', 'ChatMessageSearchResult', + 'SearchPendingLifecycleState', 'SearchRunningLifecycleState', 'SearchCompletedLifecycleState', 'SearchFailedLifecycleState', + 'SearchState', ]; const RESPONSE_PART_UNION: UnionConfig = { @@ -1052,6 +1061,46 @@ const BACKGROUND_WORK_UNION: UnionConfig = { ], }; +const SEARCH_TARGET_UNION: UnionConfig = { + name: 'SearchTarget', + discriminantField: 'kind', + // Open union: future protocol versions may add new search target kinds. + allowUnknown: true, + variants: [ + { caseName: 'fileNames', structName: 'FileNamesSearchTarget', discriminantValue: 'fileNames' }, + { caseName: 'fileText', structName: 'FileTextSearchTarget', discriminantValue: 'fileText' }, + { caseName: 'sessions', structName: 'SessionsSearchTarget', discriminantValue: 'sessions' }, + { caseName: 'chatMessages', structName: 'ChatMessagesSearchTarget', discriminantValue: 'chatMessages' }, + ], +}; + +const SEARCH_RESULT_UNION: UnionConfig = { + name: 'SearchResult', + discriminantField: 'kind', + // Open union: future protocol versions may add new search result kinds. + allowUnknown: true, + variants: [ + { caseName: 'fileName', structName: 'FileNameSearchResult', discriminantValue: 'fileName' }, + { caseName: 'fileText', structName: 'FileTextSearchResult', discriminantValue: 'fileText' }, + { caseName: 'session', structName: 'SessionSearchResult', discriminantValue: 'session' }, + { caseName: 'chatMessage', structName: 'ChatMessageSearchResult', discriminantValue: 'chatMessage' }, + ], +}; + +const SEARCH_LIFECYCLE_UNION: UnionConfig = { + name: 'SearchLifecycleState', + discriminantField: 'status', + // Open union: future protocol versions may add new search statuses. + allowUnknown: true, + variants: [ + { caseName: 'pending', structName: 'SearchPendingLifecycleState', discriminantValue: 'pending' }, + { caseName: 'running', structName: 'SearchRunningLifecycleState', discriminantValue: 'running' }, + { caseName: 'completed', structName: 'SearchCompletedLifecycleState', discriminantValue: 'completed' }, + { caseName: 'failed', structName: 'SearchFailedLifecycleState', discriminantValue: 'failed' }, + ], + injectDiscriminantOnEncode: true, +}; + function generateToolResultContentUnion(): string { return `public enum ToolResultContent: Codable, Sendable, Equatable { case text(ToolResultTextContent) @@ -1185,6 +1234,7 @@ public enum SnapshotState: Codable, Sendable, Equatable { case annotations(AnnotationsState) case automations(AutomationState) case automationRun(AutomationRunState) + case search(SearchState) /// A state that this version does not recognize, kept as raw JSON so it /// re-encodes unchanged. case unknown(AnyCodable) @@ -1215,6 +1265,7 @@ ${branches} case .annotations(let state): try state.encode(to: encoder) case .automations(let state): try state.encode(to: encoder) case .automationRun(let state): try state.encode(to: encoder) + case .search(let state): try state.encode(to: encoder) case .unknown(let raw): try raw.encode(to: encoder) } } @@ -1572,6 +1623,12 @@ function generateStateFile(project: Project): string { lines.push(''); lines.push(generateDiscriminatedUnion(project, AUTOMATION_RUN_LIFECYCLE_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_TARGET_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_RESULT_UNION)); + lines.push(''); + lines.push(generateDiscriminatedUnion(project, SEARCH_LIFECYCLE_UNION)); + lines.push(''); lines.push(generateToolResultContentUnion()); lines.push(''); lines.push(generateSnapshotState()); @@ -1684,6 +1741,9 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'terminal/commandExecuted', caseName: 'terminalCommandExecuted', tsInterface: 'TerminalCommandExecutedAction' }, { type: 'terminal/commandFinished', caseName: 'terminalCommandFinished', tsInterface: 'TerminalCommandFinishedAction' }, { type: 'resourceWatch/changed', caseName: 'resourceWatchChanged', tsInterface: 'ResourceWatchChangedAction' }, + { type: 'search/queryChanged', caseName: 'searchQueryChanged', tsInterface: 'SearchQueryChangedAction' }, + { type: 'search/resultsChanged', caseName: 'searchResultsChanged', tsInterface: 'SearchResultsChangedAction' }, + { type: 'search/lifecycleChanged', caseName: 'searchLifecycleChanged', tsInterface: 'SearchLifecycleChangedAction' }, { type: 'automation/createRequested', caseName: 'automationCreateRequested', tsInterface: 'AutomationCreateRequestedAction' }, { type: 'automation/updateRequested', caseName: 'automationUpdateRequested', tsInterface: 'AutomationUpdateRequestedAction' }, { type: 'automation/set', caseName: 'automationSet', tsInterface: 'AutomationSetAction' }, @@ -1921,6 +1981,7 @@ const COMMAND_STRUCTS = [ 'ResourceMkdirParams', 'ResourceMkdirResult', 'ResourceRequestParams', 'ResourceRequestResult', 'CreateResourceWatchParams', 'CreateResourceWatchResult', + 'CreateSearchParams', 'CreateSearchResult', 'FetchTurnsParams', 'FetchTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', @@ -2762,6 +2823,11 @@ function checkExhaustiveness(project: Project): void { 'TerminalLifecycleState', // TERMINAL_LIFECYCLE_STATE_UNION discriminated union 'SessionInputRequest', // SESSION_INPUT_REQUEST_UNION discriminated union 'BackgroundWork', // BACKGROUND_WORK_UNION discriminated union + 'SearchTarget', // SEARCH_TARGET_UNION discriminated union + 'SearchResult', // SEARCH_RESULT_UNION discriminated union + 'SearchLifecycleState', // SEARCH_LIFECYCLE_UNION discriminated union + 'FileSearchTargetBase', // base interface, flattened into the file search target structs via `extends` + 'SearchResultBase', // base interface, flattened into the search result structs via `extends` 'ToolCallConfirmationState', // TOOL_CALL_CONFIRMATION_STATE_UNION discriminated union 'AuthRequiredErrorData', // emitted by generateErrorsFile() 'PermissionDeniedErrorData', // emitted by generateErrorsFile() diff --git a/scripts/read-stability.test.ts b/scripts/read-stability.test.ts index d35248e3d..fd1eca00d 100644 --- a/scripts/read-stability.test.ts +++ b/scripts/read-stability.test.ts @@ -113,7 +113,7 @@ test('native client docs preserve declaration and entrypoint stability', () => { ['clients/dotnet/src/AgentHostProtocol.Abstractions/Generated', 'Commands.generated.cs', 'Notifications.generated.cs'], ]; for (const [directory, commands, notifications] of clients) { - for (const [file, expected] of [[commands, 18], [notifications, 6]] as const) { + for (const [file, expected] of [[commands, 21], [notifications, 6]] as const) { const content = readFileSync(resolve(root, directory, file), 'utf8'); assert.equal(content.split(marker).length - 1, expected, `${directory}/${file}`); } diff --git a/scripts/snapshot-channels.ts b/scripts/snapshot-channels.ts index 0623f8b38..ad94c3e91 100644 --- a/scripts/snapshot-channels.ts +++ b/scripts/snapshot-channels.ts @@ -15,6 +15,7 @@ export const SNAPSHOT_CHANNELS = [ { scheme: 'ahp-resource-watch', variant: 'ResourceWatch', type: 'ResourceWatchState' }, { scheme: 'ahp-annotations', variant: 'Annotations', type: 'AnnotationsState' }, { scheme: 'ahp-automation-run', variant: 'AutomationRun', type: 'AutomationRunState' }, + { scheme: 'ahp-search', variant: 'Search', type: 'SearchState' }, { scheme: 'ahp-tcp', variant: 'Empty', type: 'EmptyState' }, { scheme: 'ahp-otlp', variant: 'Empty', type: 'EmptyState' }, ] as const; diff --git a/types/action-origin.generated.ts b/types/action-origin.generated.ts index 1168405c9..1e227ab92 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -103,6 +103,9 @@ import type { TerminalCommandExecutedAction, TerminalCommandFinishedAction, ResourceWatchChangedAction, + SearchQueryChangedAction, + SearchResultsChangedAction, + SearchLifecycleChangedAction, AutomationCreateRequestedAction, AutomationUpdateRequestedAction, AutomationSetAction, @@ -417,6 +420,24 @@ export type ServerResourceWatchAction = | ResourceWatchChangedAction ; +/** Union of all search-scoped actions. */ +export type SearchAction = + | SearchQueryChangedAction + | SearchResultsChangedAction + | SearchLifecycleChangedAction +; + +/** Union of search actions that clients may dispatch. */ +export type ClientSearchAction = + | SearchQueryChangedAction +; + +/** Union of search actions that only the server may produce. */ +export type ServerSearchAction = + | SearchResultsChangedAction + | SearchLifecycleChangedAction +; + /** Union of all automation-scoped actions. */ export type AutomationAction = | AutomationCreateRequestedAction @@ -566,6 +587,9 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.TerminalCommandExecuted]: false, [ActionType.TerminalCommandFinished]: false, [ActionType.ResourceWatchChanged]: false, + [ActionType.SearchQueryChanged]: true, + [ActionType.SearchResultsChanged]: false, + [ActionType.SearchLifecycleChanged]: false, [ActionType.AutomationCreateRequested]: true, [ActionType.AutomationUpdateRequested]: true, [ActionType.AutomationSet]: false, diff --git a/types/actions.ts b/types/actions.ts index 184714927..aa1c7dbdb 100644 --- a/types/actions.ts +++ b/types/actions.ts @@ -16,5 +16,6 @@ export * from './channels-terminal/actions.js'; export * from './channels-changeset/actions.js'; export * from './channels-annotations/actions.js'; export * from './channels-resource-watch/actions.js'; +export * from './channels-search/actions.js'; export * from './channels-automation/actions.js'; export * from './channels-automation-run/actions.js'; diff --git a/types/channels-search/actions.ts b/types/channels-search/actions.ts new file mode 100644 index 000000000..6f3889c4c --- /dev/null +++ b/types/channels-search/actions.ts @@ -0,0 +1,83 @@ +/** + * Search Channel Actions — Mutations of an `ahp-search:` channel's state. + * + * @module channels-search/actions + */ + +import { ActionType } from '../common/actions.js'; +import type { SearchLifecycleState, SearchQuery, SearchResult } from './state.js'; + +/** + * Replaces the search's query and restarts the search. + * + * Keeps {@link SearchState.results} and sets {@link SearchState.lifecycle} to + * {@link SearchLifecycleStatus.Pending | pending}. The old results stay + * visible until the host replaces them, so the client does not flash an empty + * list. + * + * After the host applies this action, it stops the previous search and drops + * any of its results that it has not dispatched yet. The host MUST then + * dispatch {@link SearchResultsChangedAction | `search/resultsChanged`} with + * `replace: true` before any other search action. The replacement can keep + * old results that still match the new query, and can be empty. If the new + * query is not valid, + * for example because it contains an invalid regular expression, the host + * replaces the results with an empty list and then changes the lifecycle to + * {@link SearchLifecycleStatus.Failed | failed}. + * + * @category Search Actions + * @version 1 + * @stability 1.0 + * @clientDispatchable + */ +export interface SearchQueryChangedAction { + type: ActionType.SearchQueryChanged; + /** The new query. */ + query: SearchQuery; +} + +/** + * Adds results to {@link SearchState.results}, or replaces them. + * + * By default, the reducer appends `results`. Set `replace` to `true` to + * replace every result instead; if {@link SearchState.lifecycle} is + * {@link SearchLifecycleStatus.Pending | pending}, a replacement also changes + * it to {@link SearchLifecycleStatus.Running | running}. + * + * The host MUST dispatch a replacement first after a + * {@link SearchQueryChangedAction | `search/queryChanged`}. It MAY also + * replace the results at other times, for example to re-rank them, to remove + * duplicates, or to update a completed search when a watched file changes. + * The host MUST NOT dispatch an empty `results` list unless `replace` is + * `true`. + * + * @category Search Actions + * @version 1 + * @stability 1.0 + */ +export interface SearchResultsChangedAction { + type: ActionType.SearchResultsChanged; + /** The results to append, in the order the host found them, or the replacement results. */ + results: SearchResult[]; + /** When `true`, replaces every result instead of appending. */ + replace?: boolean; +} + +/** + * Replaces {@link SearchState.lifecycle}. + * + * The host dispatches this to complete or fail a search, or to move a + * completed search back to {@link SearchLifecycleStatus.Running | running} when it + * searches again, for example after a watched file changes. The host MUST NOT + * change the lifecycle to {@link SearchLifecycleStatus.Pending | pending}; only + * {@link SearchQueryChangedAction | `search/queryChanged`} does that. + * + * @category Search Actions + * @version 1 + * @stability 1.0 + */ +export interface SearchLifecycleChangedAction { + type: ActionType.SearchLifecycleChanged; + /** The new lifecycle. */ + lifecycle: SearchLifecycleState; +} diff --git a/types/channels-search/commands.ts b/types/channels-search/commands.ts new file mode 100644 index 000000000..980338669 --- /dev/null +++ b/types/channels-search/commands.ts @@ -0,0 +1,67 @@ +/** + * Search Channel Commands — `createSearch`. + * + * @module channels-search/commands + */ + +import type { URI } from '../common/state.js'; +import type { BaseParams } from '../common/commands.js'; +import type { SearchQuery } from './state.js'; + +/** + * Starts a search on the host. + * + * The client chooses the channel URI and then subscribes to it to receive the + * search's {@link SearchState} and its results. The client replaces the query + * by dispatching {@link SearchQueryChangedAction | `search/queryChanged`}, + * and cancels the search by unsubscribing. + * + * The client MUST NOT send this command unless `InitializeResult.search` is + * present, and MUST NOT include a target whose kind is not listed in + * {@link SearchCapability.targets}. + * + * @category Search Commands + * @method createSearch + * @direction Client → Server + * @messageType Request + * @version 1 + * @stability 1.0 + * @throws `InvalidParams` (`-32602`) if the query is not valid, for example because a target kind is not supported or a regular expression is invalid. + * @throws `PermissionDenied` (`-32009`) if the client is not permitted to search a root or chat. + * @throws `AlreadyExists` (`-32010`) if the channel URI is already in use. + * @see {@link /specification/search-channel | Search Channel} + * @example + * ```jsonc + * // Client → Server + * { "jsonrpc": "2.0", "id": 40, "method": "createSearch", + * "params": { + * "channel": "ahp-search:/5f0c…", + * "query": { + * "text": "parseConfig", + * "targets": [ + * { "kind": "fileText", "roots": ["file:///workspace"] }, + * { "kind": "chatMessages", "chats": ["ahp-chat:/c1"] } + * ] + * } + * } } + * + * // Server → Client + * { "jsonrpc": "2.0", "id": 40, "result": {} } + * ``` + */ +export interface CreateSearchParams extends BaseParams { + /** The client-chosen URI for the new channel, for example `ahp-search:/`. */ + channel: URI; + /** What to search for and where. */ + query: SearchQuery; +} + +/** + * Result of the `createSearch` command. + * + * An empty object on success. + * + * @category Search Commands + * @stability 1.0 + */ +export interface CreateSearchResult {} diff --git a/types/channels-search/reducer.ts b/types/channels-search/reducer.ts new file mode 100644 index 000000000..94c27588e --- /dev/null +++ b/types/channels-search/reducer.ts @@ -0,0 +1,37 @@ +/** + * Search Channel Reducer — Pure reducer for `SearchState`. + * + * @module channels-search/reducer + */ + +import { ActionType } from '../common/actions.js'; +import { SearchLifecycleStatus, type SearchState } from './state.js'; +import type { SearchAction } from '../action-origin.generated.js'; +import { softAssertNever } from '../common/reducer-helpers.js'; + +/** + * Pure reducer for search state. Handles every {@link SearchAction} variant. + */ +export function searchReducer(state: SearchState, action: SearchAction, log?: (msg: string) => void): SearchState { + switch (action.type) { + case ActionType.SearchQueryChanged: + return { ...state, query: action.query, lifecycle: { status: SearchLifecycleStatus.Pending } }; + + case ActionType.SearchResultsChanged: + if (!action.replace) { + return { ...state, results: [...state.results, ...action.results] }; + } + return { + ...state, + results: action.results, + lifecycle: state.lifecycle.status === SearchLifecycleStatus.Pending ? { status: SearchLifecycleStatus.Running } : state.lifecycle, + }; + + case ActionType.SearchLifecycleChanged: + return { ...state, lifecycle: action.lifecycle }; + + default: + softAssertNever(action, log); + return state; + } +} diff --git a/types/channels-search/state.ts b/types/channels-search/state.ts new file mode 100644 index 000000000..d51da0033 --- /dev/null +++ b/types/channels-search/state.ts @@ -0,0 +1,434 @@ +/** + * Search Channel State Types — Per-search state exposed on `ahp-search:` + * channels. + * + * Stability: 1.0 - Early development + * + * @module channels-search/state + */ + +import type { ErrorInfo, TextRange, URI } from '../common/state.js'; + +// ─── Capability ────────────────────────────────────────────────────────────── + +/** + * Present when the host supports `createSearch`. + * + * @category Search Types + * @stability 1.0 + * @see {@link /specification/search-channel | Search Channel} + */ +export interface SearchCapability { + /** + * The target kinds the host can search. A client MUST NOT send a + * {@link SearchTarget} whose kind is not listed here. + */ + targets: SearchTargetKind[]; +} + +// ─── Query ─────────────────────────────────────────────────────────────────── + +/** + * What a search looks for and where. + * + * The client sends a query in `createSearch` and replaces it with + * {@link SearchQueryChangedAction | `search/queryChanged`}. + * + * @category Search Types + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface SearchQuery { + /** + * The text to search for. Its meaning depends on the target: see + * {@link SearchTarget}. An empty `text` matches nothing; the host completes + * the search with no results. + */ + text: string; + /** Match case. Defaults to `false`. */ + matchCase?: boolean; + /** Match only whole words. Defaults to `false`. */ + wholeWord?: boolean; + /** Treat `text` as a regular expression. Defaults to `false`. */ + isRegex?: boolean; + /** + * A hint that precise matching isn't expected, for example because the + * search powers a quick-find picker. The host MAY then match loosely, rank + * results by how well they match, and ignore {@link isRegex} and + * {@link wholeWord}. Defaults to `false`. + */ + fuzzy?: boolean; + /** Where to search. MUST contain at least one target. */ + targets: SearchTarget[]; + /** + * The maximum number of results. The host MAY apply a lower limit, and + * completes the search with {@link SearchCompletionReason.LimitReached} + * when it reaches the limit that applies. + * @integer + * @minimum 1 + */ + maxResults?: number; +} + +/** + * Discriminant for {@link SearchTarget}. + * + * @category Search Types + * @stability 1.0 + * @nonexhaustive + */ +export const enum SearchTargetKind { + /** File paths. */ + FileNames = 'fileNames', + /** The text content of files. */ + FileText = 'fileText', + /** The host's sessions. */ + Sessions = 'sessions', + /** The text of chat requests and responses. */ + ChatMessages = 'chatMessages', +} + +/** + * Shared fields for file search targets. + * + * @category Search Types + * @stability 1.0 + */ +export interface FileSearchTargetBase { + /** The folders to search. MUST contain at least one URI. */ + roots: URI[]; + /** Glob patterns relative to a root. When present, only matching files are searched. */ + includes?: string[]; + /** Glob patterns relative to a root. Matching files are not searched. */ + excludes?: string[]; + /** + * Also search files that the host's ignore rules, such as `.gitignore` + * files, would otherwise skip. Defaults to `false`. `excludes` still apply. + */ + includeIgnored?: boolean; +} + +/** + * Searches file paths under {@link FileSearchTargetBase.roots}. + * + * The host decides how to match {@link SearchQuery.text} against file paths, + * for example with fuzzy matching, and which query options apply. Results + * are {@link FileNameSearchResult}s. + * + * @category Search Types + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface FileNamesSearchTarget extends FileSearchTargetBase { + kind: SearchTargetKind.FileNames; +} + +/** + * Searches the text content of files under {@link FileSearchTargetBase.roots}. + * Results are {@link FileTextSearchResult}s. + * + * @category Search Types + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface FileTextSearchTarget extends FileSearchTargetBase { + kind: SearchTargetKind.FileText; +} + +/** + * Searches the host's sessions, the same sessions that `listSessions` + * returns. The host decides which session content it matches, for example + * titles or requests. Results are {@link SessionSearchResult}s. + * + * @category Search Types + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface SessionsSearchTarget { + kind: SearchTargetKind.Sessions; +} + +/** + * Searches the visible text of chat requests and responses, including the + * responses of deferred turns. Results are + * {@link ChatMessageSearchResult}s. + * + * @category Search Types + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface ChatMessagesSearchTarget { + kind: SearchTargetKind.ChatMessages; + /** The chats to search. MUST contain at least one chat URI. */ + chats: URI[]; +} + +/** + * One place to search. + * + * @category Search Types + * @stability 1.0 + */ +export type SearchTarget = + | FileNamesSearchTarget + | FileTextSearchTarget + | SessionsSearchTarget + | ChatMessagesSearchTarget; + +// ─── Results ───────────────────────────────────────────────────────────────── + +/** + * A matched span within {@link SearchMatch.text}: the half-open interval + * `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code + * units, as in {@link CompletionItem.rangeStart}. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchHighlight { + /** + * The start of the span. + * @integer + * @minimum 0 + */ + rangeStart: number; + /** + * The end of the span, exclusive. MUST be greater than {@link rangeStart} + * and at most the length of {@link SearchMatch.text}. + * @integer + * @minimum 1 + */ + rangeEnd: number; +} + +/** + * The matched text of a result, with the matched spans highlighted. The host + * chooses how much text around the match to include. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchMatch { + /** The text to display. */ + text: string; + /** The matched spans, in order. Spans MUST NOT overlap. */ + highlights: SearchHighlight[]; +} + +/** + * Discriminant for {@link SearchResult}. + * + * @category Search Types + * @stability 1.0 + * @nonexhaustive + */ +export const enum SearchResultKind { + FileName = 'fileName', + FileText = 'fileText', + Session = 'session', + ChatMessage = 'chatMessage', +} + +/** + * Shared fields for search results. Each result is one match. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchResultBase { + /** The resource that contains the match. */ + resource: URI; + /** The text to display, with the matched spans highlighted. */ + match: SearchMatch; + /** + * How well the result matches; higher is better. Scores have no fixed + * range, and are comparable across all results of one search. Clients + * SHOULD show results in descending score order. A host that does not rank + * results omits the score. + * @format float + */ + score?: number; +} + +/** + * A file whose path matches. {@link SearchResultBase.resource} is the file; + * the match text is its path, usually relative to the root that contains it. + * + * @category Search Types + * @stability 1.0 + */ +export interface FileNameSearchResult extends SearchResultBase { + kind: SearchResultKind.FileName; +} + +/** + * A match in the text of a file. {@link SearchResultBase.resource} is the + * file; the match text is the text around the match, usually its line. + * + * @category Search Types + * @stability 1.0 + */ +export interface FileTextSearchResult extends SearchResultBase { + kind: SearchResultKind.FileText; + /** The location of the match in the file. */ + range: TextRange; +} + +/** + * A session whose content matches. {@link SearchResultBase.resource} is the + * session URI. + * + * @category Search Types + * @stability 1.0 + */ +export interface SessionSearchResult extends SearchResultBase { + kind: SearchResultKind.Session; + /** The session's title. */ + title: string; +} + +/** + * A match in a chat request or response. {@link SearchResultBase.resource} + * is the chat URI. + * + * @category Search Types + * @stability 1.0 + */ +export interface ChatMessageSearchResult extends SearchResultBase { + kind: SearchResultKind.ChatMessage; + /** The chat's title. */ + title: string; + /** The ID of the turn that contains the match. */ + turnId: string; +} + +/** + * One search match. + * + * @category Search Types + * @stability 1.0 + */ +export type SearchResult = + | FileNameSearchResult + | FileTextSearchResult + | SessionSearchResult + | ChatMessageSearchResult; + +// ─── Lifecycle ─────────────────────────────────────────────────────────────── + +/** + * Lifecycle status of a search. + * + * @category Search Types + * @stability 1.0 + * @nonexhaustive + */ +export const enum SearchLifecycleStatus { + /** + * The query changed and the host has not replaced the results yet. + * {@link SearchState.results} belong to the previous query. + */ + Pending = 'pending', + /** The host is searching. */ + Running = 'running', + /** The host found every result for the query. */ + Completed = 'completed', + /** The search failed. */ + Failed = 'failed', +} + +/** + * Why a search completed. + * + * @category Search Types + * @stability 1.0 + * @nonexhaustive + */ +export const enum SearchCompletionReason { + /** The host searched every target. */ + Exhausted = 'exhausted', + /** The host stopped at the result limit. More results may exist. */ + LimitReached = 'limitReached', +} + +/** + * The query changed and the host has not replaced the results yet. Clients + * MAY show the previous query's results differently, for example dimmed. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchPendingLifecycleState { + status: SearchLifecycleStatus.Pending; +} + +/** + * The host is searching and may add more results. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchRunningLifecycleState { + status: SearchLifecycleStatus.Running; +} + +/** + * The host found every result for the query. A host that watches the + * searched files, sessions, or chats MAY still change the results later. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchCompletedLifecycleState { + status: SearchLifecycleStatus.Completed; + /** Why the search completed. */ + reason: SearchCompletionReason; +} + +/** + * The search failed. Results found before the failure remain in + * {@link SearchState.results}. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchFailedLifecycleState { + status: SearchLifecycleStatus.Failed; + /** Why the search failed, for example an invalid regular expression. */ + error: ErrorInfo; +} + +/** + * Discriminated lifecycle of a search. + * + * @category Search Types + * @stability 1.0 + */ +export type SearchLifecycleState = + | SearchPendingLifecycleState + | SearchRunningLifecycleState + | SearchCompletedLifecycleState + | SearchFailedLifecycleState; + +// ─── State ─────────────────────────────────────────────────────────────────── + +/** + * Full state for one search, returned when a client subscribes to its + * `ahp-search:` URI. + * + * @category Search Types + * @stability 1.0 + */ +export interface SearchState { + /** The current query. */ + query: SearchQuery; + /** + * Results in the order the host found them. Sort by + * {@link SearchResultBase.score} to rank them. While {@link lifecycle} is + * {@link SearchLifecycleStatus.Pending | pending}, these are results for the + * previous query. + */ + results: SearchResult[]; + /** Where the search is in its lifecycle. */ + lifecycle: SearchLifecycleState; +} diff --git a/types/channels-session/commands.ts b/types/channels-session/commands.ts index 3a65660ff..ceefb1ab0 100644 --- a/types/channels-session/commands.ts +++ b/types/channels-session/commands.ts @@ -274,12 +274,18 @@ export interface CompletionItem { * attachment's own `rangeStart`/`rangeEnd` (when present) refer to * positions in the final {@link Message.text} after the item is * accepted. + * + * @integer + * @minimum 0 */ rangeStart?: number; /** * The end of the range in the input's `text` that is replaced by * `insertText`. See {@link rangeStart}. + * + * @integer + * @minimum 1 */ rangeEnd?: number; diff --git a/types/commands.ts b/types/commands.ts index 3bfd44073..881b8bf7b 100644 --- a/types/commands.ts +++ b/types/commands.ts @@ -14,5 +14,6 @@ export * from './channels-chat/commands.js'; export * from './channels-terminal/commands.js'; export * from './channels-changeset/commands.js'; export * from './channels-resource-watch/commands.js'; +export * from './channels-search/commands.js'; export * from './channels-automation/commands.js'; export * from './channels-tcp/commands.js'; diff --git a/types/common/actions.ts b/types/common/actions.ts index 1bb7f1590..4b8fd269b 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -131,6 +131,11 @@ import type { import type { ResourceWatchChangedAction, } from '../channels-resource-watch/actions.js'; +import type { + SearchQueryChangedAction, + SearchResultsChangedAction, + SearchLifecycleChangedAction, +} from '../channels-search/actions.js'; import type { AutomationCreateRequestedAction, AutomationRemovedAction, @@ -254,6 +259,9 @@ export const enum ActionType { TerminalCommandExecuted = 'terminal/commandExecuted', TerminalCommandFinished = 'terminal/commandFinished', ResourceWatchChanged = 'resourceWatch/changed', + SearchQueryChanged = 'search/queryChanged', + SearchResultsChanged = 'search/resultsChanged', + SearchLifecycleChanged = 'search/lifecycleChanged', AutomationCreateRequested = 'automation/createRequested', AutomationUpdateRequested = 'automation/updateRequested', AutomationSet = 'automation/set', @@ -399,6 +407,9 @@ export type StateAction = | TerminalCommandExecutedAction | TerminalCommandFinishedAction | ResourceWatchChangedAction + | SearchQueryChangedAction + | SearchResultsChangedAction + | SearchLifecycleChangedAction | AutomationCreateRequestedAction | AutomationUpdateRequestedAction | AutomationSetAction diff --git a/types/common/commands.ts b/types/common/commands.ts index 7da1b08d2..d0535dbee 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -30,6 +30,7 @@ import type { } from '../channels-automation/state.js'; import type { TelemetryCapabilities } from '../channels-otlp/state.js'; import type { TcpConnectionsCapability } from '../channels-tcp/state.js'; +import type { SearchCapability } from '../channels-search/state.js'; // ─── BaseParams ────────────────────────────────────────────────────────────── @@ -376,6 +377,13 @@ export interface InitializeResult { * @see {@link /specification/tcp-channel | TCP Channel} */ tcpConnections?: TcpConnectionsCapability; + /** + * Present when the host supports `createSearch`, which searches files, + * sessions, and chats and streams the results on an `ahp-search:` channel. + * @stability 1.0 + * @see {@link /specification/search-channel | Search Channel} + */ + search?: SearchCapability; /** * Present when chats in one session may be backed by different agent * providers (see {@link CreateChatParams.provider} and diff --git a/types/common/messages.ts b/types/common/messages.ts index fa2ce4ace..cd304c172 100644 --- a/types/common/messages.ts +++ b/types/common/messages.ts @@ -104,6 +104,7 @@ import type { import type { AhpError } from './errors.js'; import type { TcpDataParams, TcpEofParams, TcpResetParams } from '../channels-tcp/notifications.js'; import type { CreateTcpConnectionParams, CreateTcpConnectionResult } from '../channels-tcp/commands.js'; +import type { CreateSearchParams, CreateSearchResult } from '../channels-search/commands.js'; // ─── JSON-RPC Base Types ───────────────────────────────────────────────────── @@ -180,6 +181,7 @@ export interface CommandMap { 'createTerminal': { params: CreateTerminalParams; result: null }; 'disposeTerminal': { params: DisposeTerminalParams; result: null }; 'createResourceWatch': { params: CreateResourceWatchParams; result: CreateResourceWatchResult }; + 'createSearch': { params: CreateSearchParams; result: CreateSearchResult }; 'listSessions': { params: ListSessionsParams; result: ListSessionsResult }; 'resourceRead': { params: ResourceReadParams; result: ResourceReadResult }; 'resourceWrite': { params: ResourceWriteParams; result: ResourceWriteResult }; diff --git a/types/common/state.ts b/types/common/state.ts index 310537e5e..4616d900d 100644 --- a/types/common/state.ts +++ b/types/common/state.ts @@ -17,6 +17,7 @@ import type { ChatState } from '../channels-chat/state.js'; import type { CanvasState } from '../channels-canvas/state.js'; import type { AutomationState } from '../channels-automation/state.js'; import type { AutomationRunState } from '../channels-automation-run/state.js'; +import type { SearchState } from '../channels-search/state.js'; // ─── Type Aliases ──────────────────────────────────────────────────────────── @@ -466,7 +467,7 @@ export interface Snapshot { * new kinds of state; a client MUST NOT fail on a state that it does not * recognize, and ignores that snapshot. */ - state: RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | EmptyState; + state: RootState | SessionState | TerminalState | ChangesetState | ResourceWatchState | AnnotationsState | ChatState | CanvasState | AutomationState | AutomationRunState | SearchState | EmptyState; /** The `serverSeq` at which this snapshot was taken. Subsequent actions will have `serverSeq > fromSeq`. */ fromSeq: number; } diff --git a/types/index.ts b/types/index.ts index cd083a862..e26b7cc43 100644 --- a/types/index.ts +++ b/types/index.ts @@ -31,6 +31,7 @@ export { changesetReducer, annotationsReducer, resourceWatchReducer, + searchReducer, automationReducer, automationRunReducer, isClientDispatchable, diff --git a/types/messages.test.ts b/types/messages.test.ts index 4d2f22b3c..356ea6955 100644 --- a/types/messages.test.ts +++ b/types/messages.test.ts @@ -34,6 +34,7 @@ function readChannelSources(baseName: string): string { 'channels-changeset', 'channels-annotations', 'channels-resource-watch', + 'channels-search', 'channels-otlp', 'channels-tcp', 'channels-automation', diff --git a/types/reducers.test.ts b/types/reducers.test.ts index c641b63b8..91bdd29f6 100644 --- a/types/reducers.test.ts +++ b/types/reducers.test.ts @@ -26,13 +26,14 @@ import { changesetReducer, annotationsReducer, resourceWatchReducer, + searchReducer, automationReducer, automationRunReducer, isClientDispatchable, } from './reducers.js'; import { IS_CLIENT_DISPATCHABLE } from './action-origin.generated.js'; import { ActionType } from './actions.js'; -import type { RootState, SessionState, ChatState, CanvasState, TerminalState, ChangesetState, AnnotationsState, ResourceWatchState, AutomationState, AutomationRunState } from './state.js'; +import type { RootState, SessionState, ChatState, CanvasState, TerminalState, ChangesetState, AnnotationsState, ResourceWatchState, SearchState, AutomationState, AutomationRunState } from './state.js'; import { CustomizationType, McpServerStatus, @@ -62,6 +63,7 @@ function readChannelSources(baseName: string): string { 'channels-changeset', 'channels-annotations', 'channels-resource-watch', + 'channels-search', 'channels-automation', 'channels-automation-run', ]; @@ -79,11 +81,11 @@ function readChannelSources(baseName: string): string { // ─── Fixture Loading ───────────────────────────────────────────────────────── -type FixtureState = RootState | SessionState | ChatState | CanvasState | TerminalState | ChangesetState | AnnotationsState | ResourceWatchState | AutomationState | AutomationRunState; +type FixtureState = RootState | SessionState | ChatState | CanvasState | TerminalState | ChangesetState | AnnotationsState | ResourceWatchState | SearchState | AutomationState | AutomationRunState; interface Fixture { description: string; - reducer: 'root' | 'session' | 'chat' | 'canvas' | 'terminal' | 'changeset' | 'annotations' | 'resourceWatch' | 'automation' | 'automationRun'; + reducer: 'root' | 'session' | 'chat' | 'canvas' | 'terminal' | 'changeset' | 'annotations' | 'resourceWatch' | 'search' | 'automation' | 'automationRun'; initial: FixtureState; actions: unknown[]; expected: FixtureState; @@ -135,6 +137,8 @@ describe('reducer fixtures', () => { state = annotationsReducer(state as AnnotationsState, action as any); } else if (fixture.reducer === 'resourceWatch') { state = resourceWatchReducer(state as ResourceWatchState, action as any); + } else if (fixture.reducer === 'search') { + state = searchReducer(state as SearchState, action as any); } else if (fixture.reducer === 'automation') { state = automationReducer(state as AutomationState, action as any); } else if (fixture.reducer === 'automationRun') { diff --git a/types/reducers.ts b/types/reducers.ts index a7a011a5e..675c6cb59 100644 --- a/types/reducers.ts +++ b/types/reducers.ts @@ -13,6 +13,7 @@ export { terminalReducer } from './channels-terminal/reducer.js'; export { changesetReducer } from './channels-changeset/reducer.js'; export { annotationsReducer } from './channels-annotations/reducer.js'; export { resourceWatchReducer } from './channels-resource-watch/reducer.js'; +export { searchReducer } from './channels-search/reducer.js'; export { automationReducer } from './channels-automation/reducer.js'; export { automationRunReducer } from './channels-automation-run/reducer.js'; export { softAssertNever, isClientDispatchable } from './common/reducer-helpers.js'; diff --git a/types/state.ts b/types/state.ts index 762329ffc..2f31f78c0 100644 --- a/types/state.ts +++ b/types/state.ts @@ -17,6 +17,7 @@ export * from './channels-changeset/state.js'; export * from './channels-annotations/state.js'; export * from './channels-otlp/state.js'; export * from './channels-resource-watch/state.js'; +export * from './channels-search/state.js'; export * from './channels-automation/state.js'; export * from './channels-automation-run/state.js'; export * from './channels-tcp/state.js'; diff --git a/types/test-cases/reducers/340-search-resultschanged-appends.json b/types/test-cases/reducers/340-search-resultschanged-appends.json new file mode 100644 index 000000000..ad3c0089d --- /dev/null +++ b/types/test-cases/reducers/340-search-resultschanged-appends.json @@ -0,0 +1,141 @@ +{ + "description": "search/resultsChanged without replace appends results in order", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "running" + } + }, + "actions": [ + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ] + } + ], + "expected": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + }, + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "lifecycle": { + "status": "running" + } + } +} diff --git a/types/test-cases/reducers/341-search-lifecyclechanged-completed.json b/types/test-cases/reducers/341-search-lifecyclechanged-completed.json new file mode 100644 index 000000000..773bc12d1 --- /dev/null +++ b/types/test-cases/reducers/341-search-lifecyclechanged-completed.json @@ -0,0 +1,96 @@ +{ + "description": "search/lifecycleChanged completes a search with its reason", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "running" + } + }, + "actions": [ + { + "type": "search/lifecycleChanged", + "lifecycle": { + "status": "completed", + "reason": "limitReached" + } + } + ], + "expected": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "completed", + "reason": "limitReached" + } + } +} diff --git a/types/test-cases/reducers/342-search-lifecyclechanged-failed-keeps-results.json b/types/test-cases/reducers/342-search-lifecyclechanged-failed-keeps-results.json new file mode 100644 index 000000000..9258b0964 --- /dev/null +++ b/types/test-cases/reducers/342-search-lifecyclechanged-failed-keeps-results.json @@ -0,0 +1,102 @@ +{ + "description": "search/lifecycleChanged to failed keeps earlier results", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "running" + } + }, + "actions": [ + { + "type": "search/lifecycleChanged", + "lifecycle": { + "status": "failed", + "error": { + "errorType": "timeout", + "message": "Search timed out" + } + } + } + ], + "expected": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "failed", + "error": { + "errorType": "timeout", + "message": "Search timed out" + } + } + } +} diff --git a/types/test-cases/reducers/343-search-querychanged-keeps-pending-results.json b/types/test-cases/reducers/343-search-querychanged-keeps-pending-results.json new file mode 100644 index 000000000..6ae38ef8b --- /dev/null +++ b/types/test-cases/reducers/343-search-querychanged-keeps-pending-results.json @@ -0,0 +1,151 @@ +{ + "description": "search/queryChanged replaces the query, keeps results, and sets the lifecycle to pending", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + }, + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "lifecycle": { + "status": "completed", + "reason": "exhausted" + } + }, + "actions": [ + { + "type": "search/queryChanged", + "query": { + "text": "parseConfigFile", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + } + } + ], + "expected": { + "query": { + "text": "parseConfigFile", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + }, + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "lifecycle": { + "status": "pending" + } + } +} diff --git a/types/test-cases/reducers/344-search-querychanged-then-resultschanged.json b/types/test-cases/reducers/344-search-querychanged-then-resultschanged.json new file mode 100644 index 000000000..6daeee4e7 --- /dev/null +++ b/types/test-cases/reducers/344-search-querychanged-then-resultschanged.json @@ -0,0 +1,218 @@ +{ + "description": "a replacing search/resultsChanged after search/queryChanged replaces results and moves pending to running, then appends add more", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + }, + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "lifecycle": { + "status": "running" + } + }, + "actions": [ + { + "type": "search/queryChanged", + "query": { + "text": "parseConfigFile", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + } + }, + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "replace": true + }, + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/c.ts", + "match": { + "text": "parseConfigFile(path)", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 15 + } + ] + }, + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 15 + } + }, + "score": 0.75 + } + ] + }, + { + "type": "search/lifecycleChanged", + "lifecycle": { + "status": "completed", + "reason": "exhausted" + } + } + ], + "expected": { + "query": { + "text": "parseConfigFile", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + }, + { + "kind": "fileText", + "resource": "file:///workspace/c.ts", + "match": { + "text": "parseConfigFile(path)", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 15 + } + ] + }, + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 15 + } + }, + "score": 0.75 + } + ], + "lifecycle": { + "status": "completed", + "reason": "exhausted" + } + } +} diff --git a/types/test-cases/reducers/345-search-resultschanged-keeps-completed.json b/types/test-cases/reducers/345-search-resultschanged-keeps-completed.json new file mode 100644 index 000000000..3e451d0ea --- /dev/null +++ b/types/test-cases/reducers/345-search-resultschanged-keeps-completed.json @@ -0,0 +1,191 @@ +{ + "description": "a replacing search/resultsChanged on a completed search replaces results and keeps the lifecycle", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + }, + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "lifecycle": { + "status": "completed", + "reason": "exhausted" + } + }, + "actions": [ + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + }, + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "replace": true + } + ], + "expected": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + }, + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "completed", + "reason": "exhausted" + } + } +} diff --git a/types/test-cases/reducers/346-search-lifecyclechanged-reruns.json b/types/test-cases/reducers/346-search-lifecyclechanged-reruns.json new file mode 100644 index 000000000..b68fa4460 --- /dev/null +++ b/types/test-cases/reducers/346-search-lifecyclechanged-reruns.json @@ -0,0 +1,148 @@ +{ + "description": "search/lifecycleChanged moves a completed search back to running and appended results follow", + "reducer": "search", + "initial": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "completed", + "reason": "exhausted" + } + }, + "actions": [ + { + "type": "search/lifecycleChanged", + "lifecycle": { + "status": "running" + } + }, + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ] + } + ], + "expected": { + "query": { + "text": "parseConfig", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + }, + { + "kind": "fileText", + "resource": "file:///workspace/b.ts", + "match": { + "text": "const x = parseConfig(raw);", + "highlights": [ + { + "rangeStart": 10, + "rangeEnd": 21 + } + ] + }, + "range": { + "start": { + "line": 4, + "character": 10 + }, + "end": { + "line": 4, + "character": 21 + } + }, + "score": 0.5 + } + ], + "lifecycle": { + "status": "running" + } + } +} diff --git a/types/test-cases/round-trips/110-search-completed-snapshot.json b/types/test-cases/round-trips/110-search-completed-snapshot.json new file mode 100644 index 000000000..85df17f97 --- /dev/null +++ b/types/test-cases/round-trips/110-search-completed-snapshot.json @@ -0,0 +1,242 @@ +{ + "name": "search-completed-snapshot", + "group": "A", + "description": "A completed search snapshot preserves its query, every target and result kind, and the completed lifecycle.", + "type": "Snapshot", + "input": { + "resource": "ahp-search:/q1", + "state": { + "query": { + "text": "parseConfig", + "matchCase": true, + "wholeWord": true, + "targets": [ + { + "kind": "fileNames", + "roots": [ + "file:///workspace" + ], + "includeIgnored": true + }, + { + "kind": "fileText", + "roots": [ + "file:///workspace", + "file:///other" + ], + "includes": [ + "src/**" + ], + "excludes": [ + "**/dist/**" + ] + }, + { + "kind": "sessions" + }, + { + "kind": "chatMessages", + "chats": [ + "ahp-chat:/c1" + ] + } + ], + "maxResults": 4 + }, + "results": [ + { + "kind": "fileName", + "resource": "file:///workspace/src/parseConfig.ts", + "match": { + "text": "src/parseConfig.ts", + "highlights": [ + { + "rangeStart": 4, + "rangeEnd": 15 + } + ] + }, + "score": 0.5 + }, + { + "kind": "fileText", + "resource": "file:///workspace/src/index.ts", + "match": { + "text": "export function parseConfig(raw: string) {", + "highlights": [ + { + "rangeStart": 16, + "rangeEnd": 27 + } + ] + }, + "range": { + "start": { + "line": 11, + "character": 16 + }, + "end": { + "line": 11, + "character": 27 + } + }, + "score": 0.75 + }, + { + "kind": "session", + "resource": "ahp-session:/s1", + "match": { + "text": "Fix parseConfig crash", + "highlights": [ + { + "rangeStart": 4, + "rangeEnd": 15 + } + ] + }, + "title": "Fix parseConfig crash" + }, + { + "kind": "chatMessage", + "resource": "ahp-chat:/c1", + "match": { + "text": "\u2026the bug is in parseConfig when\u2026", + "highlights": [ + { + "rangeStart": 15, + "rangeEnd": 26 + } + ] + }, + "title": "Fix parseConfig crash", + "turnId": "t45", + "score": 0.25 + } + ], + "lifecycle": { + "status": "completed", + "reason": "limitReached" + } + }, + "fromSeq": 7 + }, + "acceptableOutputs": [ + { + "resource": "ahp-search:/q1", + "state": { + "query": { + "text": "parseConfig", + "matchCase": true, + "wholeWord": true, + "targets": [ + { + "kind": "fileNames", + "roots": [ + "file:///workspace" + ], + "includeIgnored": true + }, + { + "kind": "fileText", + "roots": [ + "file:///workspace", + "file:///other" + ], + "includes": [ + "src/**" + ], + "excludes": [ + "**/dist/**" + ] + }, + { + "kind": "sessions" + }, + { + "kind": "chatMessages", + "chats": [ + "ahp-chat:/c1" + ] + } + ], + "maxResults": 4 + }, + "results": [ + { + "kind": "fileName", + "resource": "file:///workspace/src/parseConfig.ts", + "match": { + "text": "src/parseConfig.ts", + "highlights": [ + { + "rangeStart": 4, + "rangeEnd": 15 + } + ] + }, + "score": 0.5 + }, + { + "kind": "fileText", + "resource": "file:///workspace/src/index.ts", + "match": { + "text": "export function parseConfig(raw: string) {", + "highlights": [ + { + "rangeStart": 16, + "rangeEnd": 27 + } + ] + }, + "range": { + "start": { + "line": 11, + "character": 16 + }, + "end": { + "line": 11, + "character": 27 + } + }, + "score": 0.75 + }, + { + "kind": "session", + "resource": "ahp-session:/s1", + "match": { + "text": "Fix parseConfig crash", + "highlights": [ + { + "rangeStart": 4, + "rangeEnd": 15 + } + ] + }, + "title": "Fix parseConfig crash" + }, + { + "kind": "chatMessage", + "resource": "ahp-chat:/c1", + "match": { + "text": "\u2026the bug is in parseConfig when\u2026", + "highlights": [ + { + "rangeStart": 15, + "rangeEnd": 26 + } + ] + }, + "title": "Fix parseConfig crash", + "turnId": "t45", + "score": 0.25 + } + ], + "lifecycle": { + "status": "completed", + "reason": "limitReached" + } + }, + "fromSeq": 7 + } + ] +} diff --git a/types/test-cases/round-trips/111-search-failed-snapshot.json b/types/test-cases/round-trips/111-search-failed-snapshot.json new file mode 100644 index 000000000..cd57c2419 --- /dev/null +++ b/types/test-cases/round-trips/111-search-failed-snapshot.json @@ -0,0 +1,60 @@ +{ + "name": "search-failed-snapshot", + "group": "A", + "description": "A failed search snapshot preserves its failed lifecycle and error.", + "type": "Snapshot", + "input": { + "resource": "ahp-search:/q2", + "state": { + "query": { + "text": "(unclosed", + "isRegex": true, + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [], + "lifecycle": { + "status": "failed", + "error": { + "errorType": "invalidRegex", + "message": "Unterminated group" + } + } + }, + "fromSeq": 2 + }, + "acceptableOutputs": [ + { + "resource": "ahp-search:/q2", + "state": { + "query": { + "text": "(unclosed", + "isRegex": true, + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [], + "lifecycle": { + "status": "failed", + "error": { + "errorType": "invalidRegex", + "message": "Unterminated group" + } + } + }, + "fromSeq": 2 + } + ] +} diff --git a/types/test-cases/round-trips/112-search-querychanged-action.json b/types/test-cases/round-trips/112-search-querychanged-action.json new file mode 100644 index 000000000..6e56d1ac0 --- /dev/null +++ b/types/test-cases/round-trips/112-search-querychanged-action.json @@ -0,0 +1,38 @@ +{ + "name": "search-querychanged-action", + "group": "A", + "description": "The client-dispatched search/queryChanged action preserves the replacement query, including the fuzzy hint.", + "type": "StateAction", + "input": { + "type": "search/queryChanged", + "query": { + "text": "parseConf", + "fuzzy": true, + "targets": [ + { + "kind": "fileNames", + "roots": [ + "file:///workspace" + ] + } + ] + } + }, + "acceptableOutputs": [ + { + "type": "search/queryChanged", + "query": { + "text": "parseConf", + "fuzzy": true, + "targets": [ + { + "kind": "fileNames", + "roots": [ + "file:///workspace" + ] + } + ] + } + } + ] +} diff --git a/types/test-cases/round-trips/113-search-resultschanged-append-action.json b/types/test-cases/round-trips/113-search-resultschanged-append-action.json new file mode 100644 index 000000000..977aae0c5 --- /dev/null +++ b/types/test-cases/round-trips/113-search-resultschanged-append-action.json @@ -0,0 +1,66 @@ +{ + "name": "search-resultschanged-append-action", + "group": "A", + "description": "The search/resultsChanged action without replace preserves a batch of typed results.", + "type": "StateAction", + "input": { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/src/index.ts", + "match": { + "text": "export function parseConfig(raw: string) {", + "highlights": [ + { + "rangeStart": 16, + "rangeEnd": 27 + } + ] + }, + "range": { + "start": { + "line": 11, + "character": 16 + }, + "end": { + "line": 11, + "character": 27 + } + }, + "score": 0.75 + } + ] + }, + "acceptableOutputs": [ + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/src/index.ts", + "match": { + "text": "export function parseConfig(raw: string) {", + "highlights": [ + { + "rangeStart": 16, + "rangeEnd": 27 + } + ] + }, + "range": { + "start": { + "line": 11, + "character": 16 + }, + "end": { + "line": 11, + "character": 27 + } + }, + "score": 0.75 + } + ] + } + ] +} diff --git a/types/test-cases/round-trips/114-initialize-search-capability.json b/types/test-cases/round-trips/114-initialize-search-capability.json new file mode 100644 index 000000000..6fa1bd2b5 --- /dev/null +++ b/types/test-cases/round-trips/114-initialize-search-capability.json @@ -0,0 +1,50 @@ +{ + "name": "initialize-search-capability", + "group": "A", + "description": "InitializeResult preserves the search capability and its supported target kinds.", + "type": "InitializeResult", + "input": { + "protocolVersion": "1.2.0", + "serverSeq": 7, + "snapshots": [ + { + "resource": "ahp-root://", + "state": { + "agents": [] + }, + "fromSeq": 7 + } + ], + "search": { + "targets": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ] + } + }, + "acceptableOutputs": [ + { + "protocolVersion": "1.2.0", + "serverSeq": 7, + "snapshots": [ + { + "resource": "ahp-root://", + "state": { + "agents": [] + }, + "fromSeq": 7 + } + ], + "search": { + "targets": [ + "fileNames", + "fileText", + "sessions", + "chatMessages" + ] + } + } + ] +} diff --git a/types/test-cases/round-trips/115-search-resultschanged-replace-action.json b/types/test-cases/round-trips/115-search-resultschanged-replace-action.json new file mode 100644 index 000000000..16395c680 --- /dev/null +++ b/types/test-cases/round-trips/115-search-resultschanged-replace-action.json @@ -0,0 +1,68 @@ +{ + "name": "search-resultschanged-replace-action", + "group": "A", + "description": "The search/resultsChanged action preserves replace and its replacement results.", + "type": "StateAction", + "input": { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/c.ts", + "match": { + "text": "parseConfigFile(path)", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 15 + } + ] + }, + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 15 + } + }, + "score": 0.75 + } + ], + "replace": true + }, + "acceptableOutputs": [ + { + "type": "search/resultsChanged", + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/c.ts", + "match": { + "text": "parseConfigFile(path)", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 15 + } + ] + }, + "range": { + "start": { + "line": 2, + "character": 0 + }, + "end": { + "line": 2, + "character": 15 + } + }, + "score": 0.75 + } + ], + "replace": true + } + ] +} diff --git a/types/test-cases/round-trips/116-search-pending-snapshot.json b/types/test-cases/round-trips/116-search-pending-snapshot.json new file mode 100644 index 000000000..be3741dc3 --- /dev/null +++ b/types/test-cases/round-trips/116-search-pending-snapshot.json @@ -0,0 +1,98 @@ +{ + "name": "search-pending-snapshot", + "group": "A", + "description": "A pending search snapshot preserves the previous query's results.", + "type": "Snapshot", + "input": { + "resource": "ahp-search:/q3", + "state": { + "query": { + "text": "parseConfigFile", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "pending" + } + }, + "fromSeq": 12 + }, + "acceptableOutputs": [ + { + "resource": "ahp-search:/q3", + "state": { + "query": { + "text": "parseConfigFile", + "targets": [ + { + "kind": "fileText", + "roots": [ + "file:///workspace" + ] + } + ] + }, + "results": [ + { + "kind": "fileText", + "resource": "file:///workspace/a.ts", + "match": { + "text": "parseConfig()", + "highlights": [ + { + "rangeStart": 0, + "rangeEnd": 11 + } + ] + }, + "range": { + "start": { + "line": 0, + "character": 0 + }, + "end": { + "line": 0, + "character": 11 + } + } + } + ], + "lifecycle": { + "status": "pending" + } + }, + "fromSeq": 12 + } + ] +} diff --git a/types/test-cases/round-trips/117-search-lifecyclechanged-action.json b/types/test-cases/round-trips/117-search-lifecyclechanged-action.json new file mode 100644 index 000000000..cf9d1417f --- /dev/null +++ b/types/test-cases/round-trips/117-search-lifecyclechanged-action.json @@ -0,0 +1,28 @@ +{ + "name": "search-lifecyclechanged-action", + "group": "A", + "description": "The search/lifecycleChanged action preserves a failed lifecycle with its error.", + "type": "StateAction", + "input": { + "type": "search/lifecycleChanged", + "lifecycle": { + "status": "failed", + "error": { + "errorType": "permissionDenied", + "message": "Access to file:///other was revoked" + } + } + }, + "acceptableOutputs": [ + { + "type": "search/lifecycleChanged", + "lifecycle": { + "status": "failed", + "error": { + "errorType": "permissionDenied", + "message": "Access to file:///other was revoked" + } + } + } + ] +} diff --git a/types/version/message-checks.ts b/types/version/message-checks.ts index eed5692fc..6fa9e55fe 100644 --- a/types/version/message-checks.ts +++ b/types/version/message-checks.ts @@ -64,6 +64,7 @@ type _ExpectedCommands = | 'createTerminal' | 'disposeTerminal' | 'createResourceWatch' + | 'createSearch' | 'listSessions' | 'resourceRead' | 'resourceWrite' diff --git a/types/version/registry.ts b/types/version/registry.ts index 09acef16e..b19027d6a 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -199,6 +199,9 @@ export const ACTION_INTRODUCED_IN: { readonly [K in StateAction['type']]: string [ActionType.TerminalCommandExecuted]: '0.1.0', [ActionType.TerminalCommandFinished]: '0.1.0', [ActionType.ResourceWatchChanged]: '0.2.0', + [ActionType.SearchQueryChanged]: '1.2.0', + [ActionType.SearchResultsChanged]: '1.2.0', + [ActionType.SearchLifecycleChanged]: '1.2.0', [ActionType.AutomationCreateRequested]: '0.8.0', [ActionType.AutomationUpdateRequested]: '0.8.0', [ActionType.AutomationSet]: '0.8.0',