From 6c2218f3e054f0056cab70de753baece30cc4ff1 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 16:48:58 -0800 Subject: [PATCH 1/3] chat: add read-only transcript navigation and search Let clients list prompt previews, read a contiguous window by turn ID, and locate matching text without extending the live subscription. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Actions.generated.cs | 2 +- .../Generated/Commands.generated.cs | 176 +++++++++++- .../JsonSerializerContext.generated.cs | 10 + .../Generated/State.generated.cs | 6 + .../TypesRoundTripFixtures.cs | 12 + clients/go/ahptypes/actions.generated.go | 2 +- clients/go/ahptypes/commands.generated.go | 136 +++++++++- clients/go/ahptypes/roundtrip_fixture_test.go | 24 ++ clients/go/ahptypes/state.generated.go | 4 + .../generated/Commands.generated.kt | 201 ++++++++++++++ .../generated/Messages.generated.kt | 9 + .../generated/State.generated.kt | 6 + .../agenthostprotocol/RoundTripCorpusTest.kt | 12 + clients/rust/crates/ahp-types/src/actions.rs | 2 +- clients/rust/crates/ahp-types/src/commands.rs | 170 +++++++++++- clients/rust/crates/ahp-types/src/state.rs | 5 + .../ahp-types/tests/roundtrip_corpus.rs | 12 +- clients/rust/crates/ahp/src/reducers.rs | 1 + .../Generated/Commands.generated.swift | 250 ++++++++++++++++++ .../Generated/Messages.generated.swift | 12 + .../Generated/State.generated.swift | 7 + .../TypesRoundTripFixtureTests.swift | 12 + .../typescript/test/types-round-trip.test.ts | 11 +- .../20261119-chat-history-navigation.json | 4 + docs/specification/chat-channel.md | 50 +++- docs/specification/subscriptions.md | 4 +- schema/actions.schema.json | 6 +- schema/commands.schema.json | 240 ++++++++++++++++- schema/errors.schema.json | 240 ++++++++++++++++- schema/notifications.schema.json | 4 + schema/state.schema.json | 4 + scripts/generate-csharp.ts | 5 +- scripts/generate-go.ts | 5 +- scripts/generate-json-schema.test.ts | 38 ++- scripts/generate-json-schema.ts | 17 +- scripts/generate-kotlin.ts | 14 +- scripts/generate-rust.ts | 5 +- scripts/generate-swift.ts | 17 +- types/channels-chat/actions.ts | 2 +- types/channels-chat/commands.ts | 173 +++++++++++- types/channels-chat/state.ts | 6 + types/channels-session/commands.ts | 2 +- types/common/messages.ts | 9 + .../100-chat-history-navigation-snapshot.json | 16 ++ .../101-list-chat-turns-params.json | 8 + .../102-list-chat-turns-result.json | 14 + .../103-read-chat-turns-params.json | 8 + .../104-read-chat-turns-result.json | 16 ++ .../105-search-chat-turns-params.json | 8 + .../106-search-chat-turns-result.json | 8 + types/version/message-checks.ts | 3 + 51 files changed, 1974 insertions(+), 34 deletions(-) create mode 100644 docs/.changes/20261119-chat-history-navigation.json create mode 100644 types/test-cases/round-trips/100-chat-history-navigation-snapshot.json create mode 100644 types/test-cases/round-trips/101-list-chat-turns-params.json create mode 100644 types/test-cases/round-trips/102-list-chat-turns-result.json create mode 100644 types/test-cases/round-trips/103-read-chat-turns-params.json create mode 100644 types/test-cases/round-trips/104-read-chat-turns-result.json create mode 100644 types/test-cases/round-trips/105-search-chat-turns-params.json create mode 100644 types/test-cases/round-trips/106-search-chat-turns-result.json diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 394577de9..8a36438c3 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -1976,7 +1976,7 @@ public sealed record ChatTruncatedAction /// Loads older completed turns into this chat's state. /// /// Hosts dispatch this before responding to `fetchTurns`, and before applying -/// any operation that references a turn older than the currently loaded window. +/// any state-changing operation that references a turn older than the currently loaded window. /// `turns` is ordered oldest-first and is prepended to the current `turns` /// window. `turnsNextCursor` replaces the state's cursor; omit it when all /// retained turns are now loaded. diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 1b015b8cc..0822cd202 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -125,6 +125,31 @@ public override void Write(Utf8JsonWriter writer, ChatMoveDestinationKind value, => writer.WriteStringValue(value.Value); } +/// Which contiguous window of completed turns to read, relative to an anchor. +[JsonConverter(typeof(WireEnumConverter))] +public enum ChatTurnReadDirection +{ + /// Include the anchor and nearby turns. + [WireValue("around")] + Around, + /// Immediately preceding turns, excluding the anchor. + [WireValue("before")] + Before, + /// Immediately following turns, excluding the anchor. + [WireValue("after")] + After, +} + +/// The searchable side of a completed turn. +[JsonConverter(typeof(WireEnumConverter))] +public enum ChatTurnMatchKind +{ + [WireValue("request")] + Request, + [WireValue("response")] + Response, +} + /// Native filesystem path grammar used by a host environment. [JsonConverter(typeof(WireEnumConverter))] public enum PathStyle @@ -1804,7 +1829,7 @@ public sealed record CreateResourceWatchResult /// channel's `turns` state, ahead of the already-loaded window, and update or /// clear `turnsNextCursor`. /// -/// Before applying any operation that references a turn outside the currently +/// Before applying any state-changing operation that references a turn outside the currently /// loaded window, the host MUST eagerly load enough older turns into state for /// that operation to reduce against valid state. public sealed record FetchTurnsParams @@ -1832,6 +1857,155 @@ public sealed record FetchTurnsResult { } +/// A prompt in the retained history, identified by its turn rather than its position. +public sealed record ChatTurnIndexEntry +{ + /// Stable identifier of the completed turn in this chat. + public required string TurnId { get; init; } + + /// First nonempty trimmed prompt line, or empty string. If truncated, the + /// 80 Unicode scalar values include the trailing ellipsis. + public required string Preview { get; init; } + + /// The turn's ISO 8601 start time, if known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StartedAt { get; init; } +} + +/// Lists every visible non-system prompt in retained turns, oldest first, across pages. +/// Requires `ChatState.historyNavigation`. Does not load turns into state. +public sealed record ListChatTurnsParams +{ + /// Chat URI. + 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; } + + /// Maximum entries in the page; defaults to 100. The host may return fewer. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? Limit { get; init; } + + /// Opaque index cursor for this chat; omit to start at the oldest eligible prompt. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Cursor { get; init; } +} + +/// One chronological page of the prompt index. +public sealed record ListChatTurnsResult +{ + /// Continue this index after the last entry; absent at the end of the index. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? NextCursor { get; init; } + + /// One entry per eligible prompt in transcript order. + public required List Items { get; init; } +} + +/// Reads a byte-bounded window of completed turns directly, without changing +/// any subscription or fetching intervening pages. Requires +/// `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). +public sealed record ReadChatTurnsParams +{ + /// Chat URI. + 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; } + + /// Identifier of the retained completed turn anchoring the window. + public required string TurnId { get; init; } + + /// Defaults to `around`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ChatTurnReadDirection? Direction { get; init; } + + /// Maximum number of whole turns, including the anchor for `around`; defaults to 10. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? Limit { get; init; } +} + +/// A contiguous slice of the transcript, not a chat snapshot or a state update. +public sealed record ReadChatTurnsResult +{ + /// Whole turns in chronological order for all three directions. + public required List Turns { get; init; } + + /// Whether retained completed turns precede this window. + public bool HasBefore { get; init; } + + /// Whether retained completed turns follow this window. + public bool HasAfter { get; init; } +} + +/// A match locator, not a snippet, text offset, or response-part identifier. +public sealed record ChatTurnMatch +{ + public required string TurnId { get; init; } + + public ChatTurnMatchKind Kind { get; init; } + + /// Zero-based index of this nonempty match in forward text order on this + /// side of the turn, for the same query and flags. + public long Occurrence { get; init; } +} + +/// Searches visible request and response text in retained completed turns. +/// Returns match locators newest first, independently of the subscription. +/// Requires `ChatState.historyNavigation`. +public sealed record SearchChatTurnsParams +{ + /// Chat URI. + 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; } + + /// Maximum matches in the page; defaults to 100. The host may return fewer. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? Limit { get; init; } + + /// Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Cursor { get; init; } + + /// Nonempty literal text, or a pattern when `isRegex` is true. + public required string Query { get; init; } + + /// Case-sensitive matching; defaults to false. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? MatchCase { get; init; } + + /// Require whole-word matches; defaults to false. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? WholeWord { get; init; } + + /// Treat the query as a regular expression; defaults to false. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? IsRegex { get; init; } +} + +/// One page of match locators, which may end within a turn or side. +public sealed record SearchChatTurnsResult +{ + /// Resume after the last result or scanned position. A bounded scan may + /// return no matches with an advancing cursor; only absence means done. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? NextCursor { get; init; } + + /// Match locators in reverse transcript order. + public required List Items { get; init; } +} + /// Stop receiving updates for a channel. public sealed record UnsubscribeParams { diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 6af2ed4fd..ac3caded7 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -197,6 +197,10 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ChatTruncatedAction))] [JsonSerializable(typeof(ChatTurnCancelledAction))] [JsonSerializable(typeof(ChatTurnCompleteAction))] +[JsonSerializable(typeof(ChatTurnIndexEntry))] +[JsonSerializable(typeof(ChatTurnMatch))] +[JsonSerializable(typeof(ChatTurnMatchKind))] +[JsonSerializable(typeof(ChatTurnReadDirection))] [JsonSerializable(typeof(ChatTurnResumeAction))] [JsonSerializable(typeof(ChatTurnsLoadedAction))] [JsonSerializable(typeof(ChatTurnStartedAction))] @@ -272,6 +276,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(JsonRpcSuccessResponse))] [JsonSerializable(typeof(ListAutomationTriggerDefinitionsParams))] [JsonSerializable(typeof(ListAutomationTriggerDefinitionsResult))] +[JsonSerializable(typeof(ListChatTurnsParams))] +[JsonSerializable(typeof(ListChatTurnsResult))] [JsonSerializable(typeof(ListSessionsParams))] [JsonSerializable(typeof(ListSessionsResult))] [JsonSerializable(typeof(MarkdownResponsePart))] @@ -318,6 +324,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ProjectInfo))] [JsonSerializable(typeof(PromptCustomization))] [JsonSerializable(typeof(ProtectedResourceMetadata))] +[JsonSerializable(typeof(ReadChatTurnsParams))] +[JsonSerializable(typeof(ReadChatTurnsResult))] [JsonSerializable(typeof(ReasoningResponsePart))] [JsonSerializable(typeof(ReconnectParams))] [JsonSerializable(typeof(ReconnectReplayResult))] @@ -363,6 +371,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RuleCustomization))] [JsonSerializable(typeof(RunAutomationParams))] [JsonSerializable(typeof(RunAutomationResult))] +[JsonSerializable(typeof(SearchChatTurnsParams))] +[JsonSerializable(typeof(SearchChatTurnsResult))] [JsonSerializable(typeof(SessionActiveClient))] [JsonSerializable(typeof(SessionActiveClientRemovedAction))] [JsonSerializable(typeof(SessionActiveClientSetAction))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 3be11f1f2..51d768ab4 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2643,6 +2643,12 @@ public sealed class ChatState /// Completed turns public required List Turns { get; set; } + /// When true, the host supports `listChatTurns`, `readChatTurns`, and + /// `searchChatTurns` over this chat's retained history, independently of + /// the subscription window. Absent or false means unsupported. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? HistoryNavigation { get; set; } + /// Cursor for loading older completed turns into this chat state. /// /// Presence means `turns` is a tail window and more historical turns are diff --git a/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs b/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs index 447313763..b4bbb9193 100644 --- a/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs +++ b/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs @@ -166,6 +166,18 @@ private static (object decoded, string reencoded) DecodeAndReencode(string type, return Wrap(Ser.Deserialize(inputJson)); case "CreateChatParams": return Wrap(Ser.Deserialize(inputJson)); + case "ListChatTurnsParams": + return Wrap(Ser.Deserialize(inputJson)); + case "ListChatTurnsResult": + return Wrap(Ser.Deserialize(inputJson)); + case "ReadChatTurnsParams": + return Wrap(Ser.Deserialize(inputJson)); + case "ReadChatTurnsResult": + return Wrap(Ser.Deserialize(inputJson)); + case "SearchChatTurnsParams": + return Wrap(Ser.Deserialize(inputJson)); + case "SearchChatTurnsResult": + return Wrap(Ser.Deserialize(inputJson)); case "Snapshot": return Wrap(Ser.Deserialize(inputJson)); case "SubscribeParams": diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index cfb71a816..60b75df3b 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -974,7 +974,7 @@ type ChatTruncatedAction struct { // Loads older completed turns into this chat's state. // // Hosts dispatch this before responding to `fetchTurns`, and before applying -// any operation that references a turn older than the currently loaded window. +// any state-changing operation that references a turn older than the currently loaded window. // `turns` is ordered oldest-first and is prepended to the current `turns` // window. `turnsNextCursor` replaces the state's cursor; omit it when all // retained turns are now loaded. diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index 94be6ada1..d49cff660 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -43,6 +43,26 @@ const ( ChatMoveDestinationKindNewSession ChatMoveDestinationKind = "newSession" ) +// Which contiguous window of completed turns to read, relative to an anchor. +type ChatTurnReadDirection string + +const ( + // Include the anchor and nearby turns. + ChatTurnReadDirectionAround ChatTurnReadDirection = "around" + // Immediately preceding turns, excluding the anchor. + ChatTurnReadDirectionBefore ChatTurnReadDirection = "before" + // Immediately following turns, excluding the anchor. + ChatTurnReadDirectionAfter ChatTurnReadDirection = "after" +) + +// The searchable side of a completed turn. +type ChatTurnMatchKind string + +const ( + ChatTurnMatchKindRequest ChatTurnMatchKind = "request" + ChatTurnMatchKindResponse ChatTurnMatchKind = "response" +) + // Native filesystem path grammar used by a host environment. type PathStyle string @@ -1287,7 +1307,7 @@ type CreateResourceWatchResult struct { // channel's `turns` state, ahead of the already-loaded window, and update or // clear `turnsNextCursor`. // -// Before applying any operation that references a turn outside the currently +// Before applying any state-changing operation that references a turn outside the currently // loaded window, the host MUST eagerly load enough older turns into state for // that operation to reduce against valid state. type FetchTurnsParams struct { @@ -1308,6 +1328,120 @@ type FetchTurnsParams struct { type FetchTurnsResult struct { } +// A prompt in the retained history, identified by its turn rather than its position. +type ChatTurnIndexEntry struct { + // Stable identifier of the completed turn in this chat. + TurnId string `json:"turnId"` + // First nonempty trimmed prompt line, or empty string. If truncated, the + // 80 Unicode scalar values include the trailing ellipsis. + Preview string `json:"preview"` + // The turn's ISO 8601 start time, if known. + StartedAt *string `json:"startedAt,omitempty"` +} + +// Lists every visible non-system prompt in retained turns, oldest first, across pages. +// Requires `ChatState.historyNavigation`. Does not load turns into state. +type ListChatTurnsParams 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"` + // Maximum number of entries to return in this page. The server SHOULD respect + // this bound but MAY return fewer entries and MAY impose its own upper cap. + // Omit to let the server choose the page size. + Limit *int64 `json:"limit,omitempty"` + // Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + // Omit to fetch the first page. Cursors are server-defined and MUST be treated + // as opaque — do not parse, modify, or persist them across connections. An + // unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + Cursor *string `json:"cursor,omitempty"` +} + +// One chronological page of the prompt index. +type ListChatTurnsResult struct { + // Opaque cursor for the next page. Present when more entries exist beyond the + // returned page; absent signals the end of the collection. Pass it back as + // {@link PaginatedParams.cursor} to fetch the following page. + NextCursor *string `json:"nextCursor,omitempty"` + // One entry per eligible prompt in transcript order. + Items []ChatTurnIndexEntry `json:"items"` +} + +// Reads a byte-bounded window of completed turns directly, without changing +// any subscription or fetching intervening pages. Requires +// `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). +type ReadChatTurnsParams 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"` + // Identifier of the retained completed turn anchoring the window. + TurnId string `json:"turnId"` + // Defaults to `around`. + Direction *ChatTurnReadDirection `json:"direction,omitempty"` + // Maximum number of whole turns, including the anchor for `around`; defaults to 10. + Limit *int64 `json:"limit,omitempty"` +} + +// A contiguous slice of the transcript, not a chat snapshot or a state update. +type ReadChatTurnsResult struct { + // Whole turns in chronological order for all three directions. + Turns []Turn `json:"turns"` + // Whether retained completed turns precede this window. + HasBefore bool `json:"hasBefore"` + // Whether retained completed turns follow this window. + HasAfter bool `json:"hasAfter"` +} + +// A match locator, not a snippet, text offset, or response-part identifier. +type ChatTurnMatch struct { + TurnId string `json:"turnId"` + Kind ChatTurnMatchKind `json:"kind"` + // Zero-based index of this nonempty match in forward text order on this + // side of the turn, for the same query and flags. + Occurrence int64 `json:"occurrence"` +} + +// Searches visible request and response text in retained completed turns. +// Returns match locators newest first, independently of the subscription. +// Requires `ChatState.historyNavigation`. +type SearchChatTurnsParams 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"` + // Maximum number of entries to return in this page. The server SHOULD respect + // this bound but MAY return fewer entries and MAY impose its own upper cap. + // Omit to let the server choose the page size. + Limit *int64 `json:"limit,omitempty"` + // Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + // Omit to fetch the first page. Cursors are server-defined and MUST be treated + // as opaque — do not parse, modify, or persist them across connections. An + // unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + Cursor *string `json:"cursor,omitempty"` + // Nonempty literal text, or a pattern when `isRegex` is true. + Query string `json:"query"` + // Case-sensitive matching; defaults to false. + MatchCase *bool `json:"matchCase,omitempty"` + // Require whole-word matches; defaults to false. + WholeWord *bool `json:"wholeWord,omitempty"` + // Treat the query as a regular expression; defaults to false. + IsRegex *bool `json:"isRegex,omitempty"` +} + +// One page of match locators, which may end within a turn or side. +type SearchChatTurnsResult struct { + // Opaque cursor for the next page. Present when more entries exist beyond the + // returned page; absent signals the end of the collection. Pass it back as + // {@link PaginatedParams.cursor} to fetch the following page. + NextCursor *string `json:"nextCursor,omitempty"` + // Match locators in reverse transcript order. + Items []ChatTurnMatch `json:"items"` +} + // Stop receiving updates for a channel. type UnsubscribeParams struct { // Channel URI to unsubscribe from diff --git a/clients/go/ahptypes/roundtrip_fixture_test.go b/clients/go/ahptypes/roundtrip_fixture_test.go index c8442d822..c6ec5ea0c 100644 --- a/clients/go/ahptypes/roundtrip_fixture_test.go +++ b/clients/go/ahptypes/roundtrip_fixture_test.go @@ -262,6 +262,30 @@ func decodeAndReencode(t *testing.T, name, typ, inputJSON string) string { var v CreateChatParams dec(&v) return enc(&v) + case "ListChatTurnsParams": + var v ListChatTurnsParams + dec(&v) + return enc(&v) + case "ListChatTurnsResult": + var v ListChatTurnsResult + dec(&v) + return enc(&v) + case "ReadChatTurnsParams": + var v ReadChatTurnsParams + dec(&v) + return enc(&v) + case "ReadChatTurnsResult": + var v ReadChatTurnsResult + dec(&v) + return enc(&v) + case "SearchChatTurnsParams": + var v SearchChatTurnsParams + dec(&v) + return enc(&v) + case "SearchChatTurnsResult": + var v SearchChatTurnsResult + dec(&v) + return enc(&v) case "ChatSource": var v ChatSource dec(&v) diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 127394dd7..237ac6688 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1522,6 +1522,10 @@ type ChatState struct { Config *ChatConfigState `json:"config,omitempty"` // Completed turns Turns []Turn `json:"turns"` + // When true, the host supports `listChatTurns`, `readChatTurns`, and + // `searchChatTurns` over this chat's retained history, independently of + // the subscription window. Absent or false means unsupported. + HistoryNavigation *bool `json:"historyNavigation,omitempty"` // Cursor for loading older completed turns into this chat state. // // Presence means `turns` is a tail window and more historical turns are 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 80e23fac8..abea80936 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 @@ -89,6 +89,39 @@ internal object ChatMoveDestinationKindSerializer : KSerializer? = null, + /** + * Maximum number of entries to return in this page. The server SHOULD respect + * this bound but MAY return fewer entries and MAY impose its own upper cap. + * Omit to let the server choose the page size. + */ + val limit: Long? = null, + /** + * Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + * Omit to fetch the first page. Cursors are server-defined and MUST be treated + * as opaque — do not parse, modify, or persist them across connections. An + * unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + */ + val cursor: String? = null +) + +@Serializable +data class ListChatTurnsResult( + /** + * Opaque cursor for the next page. Present when more entries exist beyond the + * returned page; absent signals the end of the collection. Pass it back as + * {@link PaginatedParams.cursor} to fetch the following page. + */ + val nextCursor: String? = null, + /** + * One entry per eligible prompt in transcript order. + */ + val items: List +) + +@Serializable +data class ReadChatTurnsParams( + /** + * 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, + /** + * Identifier of the retained completed turn anchoring the window. + */ + val turnId: String, + /** + * Defaults to `around`. + */ + val direction: ChatTurnReadDirection? = null, + /** + * Maximum number of whole turns, including the anchor for `around`; defaults to 10. + */ + val limit: Long? = null +) + +@Serializable +data class ReadChatTurnsResult( + /** + * Whole turns in chronological order for all three directions. + */ + val turns: List, + /** + * Whether retained completed turns precede this window. + */ + val hasBefore: Boolean, + /** + * Whether retained completed turns follow this window. + */ + val hasAfter: Boolean +) + +@Serializable +data class ChatTurnMatch( + val turnId: String, + val kind: ChatTurnMatchKind, + /** + * Zero-based index of this nonempty match in forward text order on this + * side of the turn, for the same query and flags. + */ + val occurrence: Long +) + +@Serializable +data class SearchChatTurnsParams( + /** + * 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, + /** + * Maximum number of entries to return in this page. The server SHOULD respect + * this bound but MAY return fewer entries and MAY impose its own upper cap. + * Omit to let the server choose the page size. + */ + val limit: Long? = null, + /** + * Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + * Omit to fetch the first page. Cursors are server-defined and MUST be treated + * as opaque — do not parse, modify, or persist them across connections. An + * unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + */ + val cursor: String? = null, + /** + * Nonempty literal text, or a pattern when `isRegex` is true. + */ + val query: String, + /** + * Case-sensitive matching; defaults to false. + */ + val matchCase: Boolean? = null, + /** + * Require whole-word matches; defaults to false. + */ + val wholeWord: Boolean? = null, + /** + * Treat the query as a regular expression; defaults to false. + */ + val isRegex: Boolean? = null +) + +@Serializable +data class SearchChatTurnsResult( + /** + * Opaque cursor for the next page. Present when more entries exist beyond the + * returned page; absent signals the end of the collection. Pass it back as + * {@link PaginatedParams.cursor} to fetch the following page. + */ + val nextCursor: String? = null, + /** + * Match locators in reverse transcript order. + */ + val items: List +) + @Serializable data class UnsubscribeParams( /** diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt index 3209e3e15..9aa4e5c3f 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt @@ -131,6 +131,15 @@ object AhpCommands { fun fetchTurns(id: Long, params: FetchTurnsParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "fetchTurns", params = params) + fun listChatTurns(id: Long, params: ListChatTurnsParams): JsonRpcRequest = + JsonRpcRequest(id = id, method = "listChatTurns", params = params) + + fun readChatTurns(id: Long, params: ReadChatTurnsParams): JsonRpcRequest = + JsonRpcRequest(id = id, method = "readChatTurns", params = params) + + fun searchChatTurns(id: Long, params: SearchChatTurnsParams): JsonRpcRequest = + JsonRpcRequest(id = id, method = "searchChatTurns", params = params) + fun authenticate(id: Long, params: AuthenticateParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "authenticate", params = params) 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 8210c2a51..c5f0fcb29 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 @@ -1983,6 +1983,12 @@ data class ChatState( * Completed turns */ val turns: List, + /** + * When true, the host supports `listChatTurns`, `readChatTurns`, and + * `searchChatTurns` over this chat's retained history, independently of + * the subscription window. Absent or false means unsupported. + */ + val historyNavigation: Boolean? = null, /** * Cursor for loading older completed turns into this chat state. * diff --git a/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt b/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt index 38b1b7f3c..047e00640 100644 --- a/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt +++ b/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt @@ -33,6 +33,12 @@ import com.microsoft.agenthostprotocol.generated.AuthenticateParams import com.microsoft.agenthostprotocol.generated.ChangesetOperationTarget import com.microsoft.agenthostprotocol.generated.ChatSource import com.microsoft.agenthostprotocol.generated.CreateChatParams +import com.microsoft.agenthostprotocol.generated.ListChatTurnsParams +import com.microsoft.agenthostprotocol.generated.ListChatTurnsResult +import com.microsoft.agenthostprotocol.generated.ReadChatTurnsParams +import com.microsoft.agenthostprotocol.generated.ReadChatTurnsResult +import com.microsoft.agenthostprotocol.generated.SearchChatTurnsParams +import com.microsoft.agenthostprotocol.generated.SearchChatTurnsResult import com.microsoft.agenthostprotocol.generated.Customization import com.microsoft.agenthostprotocol.generated.Implementation import com.microsoft.agenthostprotocol.generated.InitializeResult @@ -268,6 +274,12 @@ class RoundTripCorpusTest { "Implementation" -> rt(Implementation.serializer()) "InitializeResult" -> rt(InitializeResult.serializer()) "CreateChatParams" -> rt(CreateChatParams.serializer()) + "ListChatTurnsParams" -> rt(ListChatTurnsParams.serializer()) + "ListChatTurnsResult" -> rt(ListChatTurnsResult.serializer()) + "ReadChatTurnsParams" -> rt(ReadChatTurnsParams.serializer()) + "ReadChatTurnsResult" -> rt(ReadChatTurnsResult.serializer()) + "SearchChatTurnsParams" -> rt(SearchChatTurnsParams.serializer()) + "SearchChatTurnsResult" -> rt(SearchChatTurnsResult.serializer()) "ChatSource" -> rt(ChatSource.serializer()) "Snapshot" -> rt(Snapshot.serializer()) "SubscribeParams" -> rt(SubscribeParams.serializer()) diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index dc6fe0f7c..181a1f5bd 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -1830,7 +1830,7 @@ pub struct ChatTruncatedAction { /// Loads older completed turns into this chat's state. /// /// Hosts dispatch this before responding to `fetchTurns`, and before applying -/// any operation that references a turn older than the currently loaded window. +/// any state-changing operation that references a turn older than the currently loaded window. /// `turns` is ordered oldest-first and is prepended to the current `turns` /// window. `turnsNextCursor` replaces the state's cursor; omit it when all /// retained turns are now loaded. diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index 6764fd470..9e81d081a 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -109,6 +109,29 @@ impl<'de> serde::Deserialize<'de> for ChatMoveDestinationKind { } } +/// Which contiguous window of completed turns to read, relative to an anchor. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ChatTurnReadDirection { + /// Include the anchor and nearby turns. + #[serde(rename = "around")] + Around, + /// Immediately preceding turns, excluding the anchor. + #[serde(rename = "before")] + Before, + /// Immediately following turns, excluding the anchor. + #[serde(rename = "after")] + After, +} + +/// The searchable side of a completed turn. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ChatTurnMatchKind { + #[serde(rename = "request")] + Request, + #[serde(rename = "response")] + Response, +} + /// Native filesystem path grammar used by a host environment. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum PathStyle { @@ -1671,7 +1694,7 @@ pub struct CreateResourceWatchResult { /// channel's `turns` state, ahead of the already-loaded window, and update or /// clear `turnsNextCursor`. /// -/// Before applying any operation that references a turn outside the currently +/// Before applying any state-changing operation that references a turn outside the currently /// loaded window, the host MUST eagerly load enough older turns into state for /// that operation to reduce against valid state. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -1697,6 +1720,151 @@ pub struct FetchTurnsParams { #[serde(rename_all = "camelCase")] pub struct FetchTurnsResult {} +/// A prompt in the retained history, identified by its turn rather than its position. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatTurnIndexEntry { + /// Stable identifier of the completed turn in this chat. + pub turn_id: String, + /// First nonempty trimmed prompt line, or empty string. If truncated, the + /// 80 Unicode scalar values include the trailing ellipsis. + pub preview: String, + /// The turn's ISO 8601 start time, if known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub started_at: Option, +} + +/// Lists every visible non-system prompt in retained turns, oldest first, across pages. +/// Requires `ChatState.historyNavigation`. Does not load turns into state. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ListChatTurnsParams { + /// 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, + /// Maximum number of entries to return in this page. The server SHOULD respect + /// this bound but MAY return fewer entries and MAY impose its own upper cap. + /// Omit to let the server choose the page size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + /// Omit to fetch the first page. Cursors are server-defined and MUST be treated + /// as opaque — do not parse, modify, or persist them across connections. An + /// unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cursor: Option, +} + +/// One chronological page of the prompt index. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ListChatTurnsResult { + /// Opaque cursor for the next page. Present when more entries exist beyond the + /// returned page; absent signals the end of the collection. Pass it back as + /// {@link PaginatedParams.cursor} to fetch the following page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// One entry per eligible prompt in transcript order. + pub items: Vec, +} + +/// Reads a byte-bounded window of completed turns directly, without changing +/// any subscription or fetching intervening pages. Requires +/// `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadChatTurnsParams { + /// 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, + /// Identifier of the retained completed turn anchoring the window. + pub turn_id: String, + /// Defaults to `around`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub direction: Option, + /// Maximum number of whole turns, including the anchor for `around`; defaults to 10. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// A contiguous slice of the transcript, not a chat snapshot or a state update. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadChatTurnsResult { + /// Whole turns in chronological order for all three directions. + pub turns: Vec, + /// Whether retained completed turns precede this window. + pub has_before: bool, + /// Whether retained completed turns follow this window. + pub has_after: bool, +} + +/// A match locator, not a snippet, text offset, or response-part identifier. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatTurnMatch { + pub turn_id: String, + pub kind: ChatTurnMatchKind, + /// Zero-based index of this nonempty match in forward text order on this + /// side of the turn, for the same query and flags. + pub occurrence: i64, +} + +/// Searches visible request and response text in retained completed turns. +/// Returns match locators newest first, independently of the subscription. +/// Requires `ChatState.historyNavigation`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchChatTurnsParams { + /// 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, + /// Maximum number of entries to return in this page. The server SHOULD respect + /// this bound but MAY return fewer entries and MAY impose its own upper cap. + /// Omit to let the server choose the page size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + /// Omit to fetch the first page. Cursors are server-defined and MUST be treated + /// as opaque — do not parse, modify, or persist them across connections. An + /// unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cursor: Option, + /// Nonempty literal text, or a pattern when `isRegex` is true. + pub query: String, + /// Case-sensitive matching; defaults to false. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub match_case: Option, + /// Require whole-word matches; defaults to false. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub whole_word: Option, + /// Treat the query as a regular expression; defaults to false. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is_regex: Option, +} + +/// One page of match locators, which may end within a turn or side. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchChatTurnsResult { + /// Opaque cursor for the next page. Present when more entries exist beyond the + /// returned page; absent signals the end of the collection. Pass it back as + /// {@link PaginatedParams.cursor} to fetch the following page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Match locators in reverse transcript order. + pub items: Vec, +} + /// Stop receiving updates for a channel. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 00738265d..38545a20d 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2274,6 +2274,11 @@ pub struct ChatState { pub config: Option, /// Completed turns pub turns: Vec, + /// When true, the host supports `listChatTurns`, `readChatTurns`, and + /// `searchChatTurns` over this chat's retained history, independently of + /// the subscription window. Absent or false means unsupported. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub history_navigation: Option, /// Cursor for loading older completed turns into this chat state. /// /// Presence means `turns` is a tail window and more historical turns are diff --git a/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs b/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs index 330f28625..3622963a5 100644 --- a/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs +++ b/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs @@ -30,8 +30,10 @@ use ahp_types::{ actions::{ActionEnvelope, StateAction}, commands::{ AuthenticateParams, ChangesetOperationTarget, ChatSource, CreateChatParams, - CreateTcpConnectionParams, Implementation, InitializeResult, ReconnectParams, - ReconnectResult, ResourceReadParams, ResourceReadResult, SubscribeParams, SubscribeResult, + CreateTcpConnectionParams, Implementation, InitializeResult, ListChatTurnsParams, + ListChatTurnsResult, ReadChatTurnsParams, ReadChatTurnsResult, ReconnectParams, + ReconnectResult, ResourceReadParams, ResourceReadResult, SearchChatTurnsParams, + SearchChatTurnsResult, SubscribeParams, SubscribeResult, }, common::StringOrMarkdown, messages::JsonRpcMessage, @@ -231,6 +233,12 @@ fn decode_and_reencode(file: &str, type_name: &str, input_json: &str) -> Result< "Implementation" => round_trip!(Implementation), "InitializeResult" => round_trip!(InitializeResult), "CreateChatParams" => round_trip!(CreateChatParams), + "ListChatTurnsParams" => round_trip!(ListChatTurnsParams), + "ListChatTurnsResult" => round_trip!(ListChatTurnsResult), + "ReadChatTurnsParams" => round_trip!(ReadChatTurnsParams), + "ReadChatTurnsResult" => round_trip!(ReadChatTurnsResult), + "SearchChatTurnsParams" => round_trip!(SearchChatTurnsParams), + "SearchChatTurnsResult" => round_trip!(SearchChatTurnsResult), "ChatSource" => round_trip!(ChatSource), "Snapshot" => round_trip!(Snapshot), "SubscribeParams" => round_trip!(SubscribeParams), diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 702224823..a58f28ea8 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -2388,6 +2388,7 @@ mod tests { canvases: None, config: None, turns: Vec::new(), + history_navigation: None, turns_next_cursor: None, active_turn: None, steering_message: None, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 0f4e6dda7..072374acd 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -68,6 +68,22 @@ public enum ChatMoveDestinationKind: Codable, Sendable, Equatable { } } +/// Which contiguous window of completed turns to read, relative to an anchor. +public enum ChatTurnReadDirection: String, Codable, Sendable { + /// Include the anchor and nearby turns. + case around = "around" + /// Immediately preceding turns, excluding the anchor. + case before = "before" + /// Immediately following turns, excluding the anchor. + case after = "after" +} + +/// The searchable side of a completed turn. +public enum ChatTurnMatchKind: String, Codable, Sendable { + case request = "request" + case response = "response" +} + /// Native filesystem path grammar used by a host environment. public enum PathStyle: String, Codable, Sendable { case posix = "posix" @@ -1906,6 +1922,225 @@ public struct FetchTurnsResult: Codable, Sendable, Equatable { } } +public struct ChatTurnIndexEntry: Codable, Sendable, Equatable { + /// Stable identifier of the completed turn in this chat. + public var turnId: String + /// First nonempty trimmed prompt line, or empty string. If truncated, the + /// 80 Unicode scalar values include the trailing ellipsis. + public var preview: String + /// The turn's ISO 8601 start time, if known. + public var startedAt: String? + + public init( + turnId: String, + preview: String, + startedAt: String? = nil + ) { + self.turnId = turnId + self.preview = preview + self.startedAt = startedAt + } +} + +public struct ListChatTurnsParams: 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]? + /// Maximum number of entries to return in this page. The server SHOULD respect + /// this bound but MAY return fewer entries and MAY impose its own upper cap. + /// Omit to let the server choose the page size. + public var limit: Int? + /// Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + /// Omit to fetch the first page. Cursors are server-defined and MUST be treated + /// as opaque — do not parse, modify, or persist them across connections. An + /// unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + public var cursor: String? + + enum CodingKeys: String, CodingKey { + case channel + case meta = "_meta" + case limit + case cursor + } + + public init( + channel: String, + meta: [String: AnyCodable]? = nil, + limit: Int? = nil, + cursor: String? = nil + ) { + self.channel = channel + self.meta = meta + self.limit = limit + self.cursor = cursor + } +} + +public struct ListChatTurnsResult: Codable, Sendable, Equatable { + /// Opaque cursor for the next page. Present when more entries exist beyond the + /// returned page; absent signals the end of the collection. Pass it back as + /// {@link PaginatedParams.cursor} to fetch the following page. + public var nextCursor: String? + /// One entry per eligible prompt in transcript order. + public var items: [ChatTurnIndexEntry] + + public init( + nextCursor: String? = nil, + items: [ChatTurnIndexEntry] + ) { + self.nextCursor = nextCursor + self.items = items + } +} + +public struct ReadChatTurnsParams: 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]? + /// Identifier of the retained completed turn anchoring the window. + public var turnId: String + /// Defaults to `around`. + public var direction: ChatTurnReadDirection? + /// Maximum number of whole turns, including the anchor for `around`; defaults to 10. + public var limit: Int? + + enum CodingKeys: String, CodingKey { + case channel + case meta = "_meta" + case turnId + case direction + case limit + } + + public init( + channel: String, + meta: [String: AnyCodable]? = nil, + turnId: String, + direction: ChatTurnReadDirection? = nil, + limit: Int? = nil + ) { + self.channel = channel + self.meta = meta + self.turnId = turnId + self.direction = direction + self.limit = limit + } +} + +public struct ReadChatTurnsResult: Codable, Sendable, Equatable { + /// Whole turns in chronological order for all three directions. + public var turns: [Turn] + /// Whether retained completed turns precede this window. + public var hasBefore: Bool + /// Whether retained completed turns follow this window. + public var hasAfter: Bool + + public init( + turns: [Turn], + hasBefore: Bool, + hasAfter: Bool + ) { + self.turns = turns + self.hasBefore = hasBefore + self.hasAfter = hasAfter + } +} + +public struct ChatTurnMatch: Codable, Sendable, Equatable { + public var turnId: String + public var kind: ChatTurnMatchKind + /// Zero-based index of this nonempty match in forward text order on this + /// side of the turn, for the same query and flags. + public var occurrence: Int + + public init( + turnId: String, + kind: ChatTurnMatchKind, + occurrence: Int + ) { + self.turnId = turnId + self.kind = kind + self.occurrence = occurrence + } +} + +public struct SearchChatTurnsParams: 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]? + /// Maximum number of entries to return in this page. The server SHOULD respect + /// this bound but MAY return fewer entries and MAY impose its own upper cap. + /// Omit to let the server choose the page size. + public var limit: Int? + /// Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. + /// Omit to fetch the first page. Cursors are server-defined and MUST be treated + /// as opaque — do not parse, modify, or persist them across connections. An + /// unrecognised cursor SHOULD be rejected with an `InvalidParams` error. + public var cursor: String? + /// Nonempty literal text, or a pattern when `isRegex` is true. + public var query: String + /// Case-sensitive matching; defaults to false. + public var matchCase: Bool? + /// Require whole-word matches; defaults to false. + public var wholeWord: Bool? + /// Treat the query as a regular expression; defaults to false. + public var isRegex: Bool? + + enum CodingKeys: String, CodingKey { + case channel + case meta = "_meta" + case limit + case cursor + case query + case matchCase + case wholeWord + case isRegex + } + + public init( + channel: String, + meta: [String: AnyCodable]? = nil, + limit: Int? = nil, + cursor: String? = nil, + query: String, + matchCase: Bool? = nil, + wholeWord: Bool? = nil, + isRegex: Bool? = nil + ) { + self.channel = channel + self.meta = meta + self.limit = limit + self.cursor = cursor + self.query = query + self.matchCase = matchCase + self.wholeWord = wholeWord + self.isRegex = isRegex + } +} + +public struct SearchChatTurnsResult: Codable, Sendable, Equatable { + /// Opaque cursor for the next page. Present when more entries exist beyond the + /// returned page; absent signals the end of the collection. Pass it back as + /// {@link PaginatedParams.cursor} to fetch the following page. + public var nextCursor: String? + /// Match locators in reverse transcript order. + public var items: [ChatTurnMatch] + + public init( + nextCursor: String? = nil, + items: [ChatTurnMatch] + ) { + self.nextCursor = nextCursor + self.items = items + } +} + public struct UnsubscribeParams: Codable, Sendable, Equatable { /// Channel URI to unsubscribe from public var channel: String @@ -2945,6 +3180,21 @@ extension DisposeChatParams: AHPCommand { public static let method = "disposeChat" } +extension ListChatTurnsParams: AHPCommand { + public typealias Result = ListChatTurnsResult + public static let method = "listChatTurns" +} + +extension ReadChatTurnsParams: AHPCommand { + public typealias Result = ReadChatTurnsResult + public static let method = "readChatTurns" +} + +extension SearchChatTurnsParams: AHPCommand { + public typealias Result = SearchChatTurnsResult + public static let method = "searchChatTurns" +} + extension CreateTerminalParams: AHPCommand { public typealias Result = AHPNullResult public static let method = "createTerminal" diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift index 2d88c1b78..28cd20c24 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift @@ -133,6 +133,18 @@ public enum AHPCommands { JsonRpcRequest(id: id, method: "fetchTurns", params: params) } + public static func listChatTurns(id: Int, params: ListChatTurnsParams) -> JsonRpcRequest { + JsonRpcRequest(id: id, method: "listChatTurns", params: params) + } + + public static func readChatTurns(id: Int, params: ReadChatTurnsParams) -> JsonRpcRequest { + JsonRpcRequest(id: id, method: "readChatTurns", params: params) + } + + public static func searchChatTurns(id: Int, params: SearchChatTurnsParams) -> JsonRpcRequest { + JsonRpcRequest(id: id, method: "searchChatTurns", params: params) + } + public static func authenticate(id: Int, params: AuthenticateParams) -> JsonRpcRequest { JsonRpcRequest(id: id, method: "authenticate", params: params) } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index b862d7552..17b8bbf6d 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -2040,6 +2040,10 @@ public struct ChatState: Codable, Sendable, Equatable { public var config: ChatConfigState? /// Completed turns public var turns: [Turn] + /// When true, the host supports `listChatTurns`, `readChatTurns`, and + /// `searchChatTurns` over this chat's retained history, independently of + /// the subscription window. Absent or false means unsupported. + public var historyNavigation: Bool? /// Cursor for loading older completed turns into this chat state. /// /// Presence means `turns` is a tail window and more historical turns are @@ -2090,6 +2094,7 @@ public struct ChatState: Codable, Sendable, Equatable { case canvases case config case turns + case historyNavigation case turnsNextCursor case activeTurn case steeringMessage @@ -2115,6 +2120,7 @@ public struct ChatState: Codable, Sendable, Equatable { canvases: [CanvasReference]? = nil, config: ChatConfigState? = nil, turns: [Turn], + historyNavigation: Bool? = nil, turnsNextCursor: String? = nil, activeTurn: ActiveTurn? = nil, steeringMessage: PendingMessage? = nil, @@ -2138,6 +2144,7 @@ public struct ChatState: Codable, Sendable, Equatable { self.canvases = canvases self.config = config self.turns = turns + self.historyNavigation = historyNavigation self.turnsNextCursor = turnsNextCursor self.activeTurn = activeTurn self.steeringMessage = steeringMessage diff --git a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift index 225d8d0ea..6a3573078 100644 --- a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift +++ b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift @@ -190,6 +190,18 @@ final class TypesRoundTripFixtureTests: XCTestCase { return try reencode(dec.decode(InitializeResult.self, from: inputData)) case "CreateChatParams": return try reencode(dec.decode(CreateChatParams.self, from: inputData)) + case "ListChatTurnsParams": + return try reencode(dec.decode(ListChatTurnsParams.self, from: inputData)) + case "ListChatTurnsResult": + return try reencode(dec.decode(ListChatTurnsResult.self, from: inputData)) + case "ReadChatTurnsParams": + return try reencode(dec.decode(ReadChatTurnsParams.self, from: inputData)) + case "ReadChatTurnsResult": + return try reencode(dec.decode(ReadChatTurnsResult.self, from: inputData)) + case "SearchChatTurnsParams": + return try reencode(dec.decode(SearchChatTurnsParams.self, from: inputData)) + case "SearchChatTurnsResult": + return try reencode(dec.decode(SearchChatTurnsResult.self, from: inputData)) case "ChatSource": return try reencode(dec.decode(ChatSource.self, from: inputData)) case "Snapshot": diff --git a/clients/typescript/test/types-round-trip.test.ts b/clients/typescript/test/types-round-trip.test.ts index 086c8bf6a..8a1bb9cb2 100644 --- a/clients/typescript/test/types-round-trip.test.ts +++ b/clients/typescript/test/types-round-trip.test.ts @@ -66,7 +66,10 @@ import type { import type { ChannelFrameParams, ChannelCreditParams } from '../src/types/common/notifications.js'; import type { TcpDataParams, TcpEofParams, TcpResetParams } from '../src/types/channels-tcp/notifications.js'; import type { CreateTcpConnectionParams } from '../src/types/channels-tcp/commands.js'; -import type { ChatSource, CreateChatParams } from '../src/types/channels-chat/commands.js'; +import type { + ChatSource, CreateChatParams, ListChatTurnsParams, ListChatTurnsResult, ReadChatTurnsParams, + ReadChatTurnsResult, SearchChatTurnsParams, SearchChatTurnsResult, +} from '../src/types/channels-chat/commands.js'; // ─── Fixture directory ─────────────────────────────────────────────────────── @@ -250,6 +253,12 @@ function bindToType(file: string, type: string, parsed: unknown): void { case 'Implementation': void (parsed as Implementation); break; case 'InitializeResult': void (parsed as InitializeResult); break; case 'CreateChatParams': void (parsed as CreateChatParams); break; + case 'ListChatTurnsParams': void (parsed as ListChatTurnsParams); break; + case 'ListChatTurnsResult': void (parsed as ListChatTurnsResult); break; + case 'ReadChatTurnsParams': void (parsed as ReadChatTurnsParams); break; + case 'ReadChatTurnsResult': void (parsed as ReadChatTurnsResult); break; + case 'SearchChatTurnsParams': void (parsed as SearchChatTurnsParams); break; + case 'SearchChatTurnsResult': void (parsed as SearchChatTurnsResult); break; case 'ChatSource': void (parsed as ChatSource); break; case 'Snapshot': void (parsed as Snapshot); break; case 'SubscribeParams': void (parsed as SubscribeParams); break; diff --git a/docs/.changes/20261119-chat-history-navigation.json b/docs/.changes/20261119-chat-history-navigation.json new file mode 100644 index 000000000..551e5bf93 --- /dev/null +++ b/docs/.changes/20261119-chat-history-navigation.json @@ -0,0 +1,4 @@ +{ + "type": "added", + "message": "Optional `ChatState.historyNavigation` advertises `listChatTurns`, `readChatTurns`, and `searchChatTurns` for browsing retained history without loading the intervening transcript into a subscription." +} diff --git a/docs/specification/chat-channel.md b/docs/specification/chat-channel.md index 8bed3089c..be6162a91 100644 --- a/docs/specification/chat-channel.md +++ b/docs/specification/chat-channel.md @@ -46,10 +46,55 @@ dispatch `chat/turnsLoaded`, which prepends older turns into the same reduced chat state and updates or clears `turnsNextCursor`. Hosts MUST also eagerly load older turns into state before applying any -operation that references a turn outside the currently loaded window (for +state-changing operation that references a turn outside the currently loaded window (for example, a fork, side-chat source, chat attachment, or truncation targeting an older turn). +### Read-only history navigation + +When `ChatState.historyNavigation` is `true`, the host supports **all three** commands below on that chat URI. Absent or `false` means unsupported. A client discovers this from the snapshot, including after reconnect; it MUST NOT infer support from the protocol version or `turnsNextCursor`. + +These are reads of the host's retained, completed transcript, including turns outside the subscription window. “Completed” means a `Turn` with any terminal state, not just `complete`. Drafts, pending messages and `activeTurn` are not history. Apply the same access checks and visibility rules as for reading the chat. Each result is private to the caller. The commands MUST NOT create or expand a subscription, fetch the gap, dispatch `chat/turnsLoaded`, change `turnsNextCursor`, or mark the chat read. Queries, selected matches, sidebar position and viewport are client-local, not replayable chat state. + +#### List the prompt index + +`listChatTurns` returns one `{ turnId, preview, startedAt? }` per eligible turn, **oldest first in transcript order**, not timestamp or ID order. A turn is eligible when its initiating message is a prompt shown in the transcript: exclude system notifications and hidden requests. Include a visible attachment-only prompt, even if it has no text. Hosts MUST NOT sample or bucket entries; following all pages yields the complete eligible index, not just prompts in `ChatState.turns`. + +`preview` is the first nonempty trimmed line of visible request text, or `""` if none exists. When the line exceeds 80 Unicode scalar values, use its first 79 followed by `…`. Do not include attachment bodies, metadata, or response text. Copy `Turn.startedAt` when present; do not synthesize a timestamp. + +#### Read a window + +`readChatTurns` takes a stable `turnId`. The default `direction` is `around` and the default `limit` is 10 **total turns**, not 10 on each side. The result is a contiguous slice of whole `Turn` objects in **chronological order**: + +| Direction | Selection | +|---|---| +| `around` | Include the anchor exactly once, with nearby turns on either side as space permits. With `limit: 1`, return just the anchor. | +| `before` | Take immediately preceding turns, excluding the anchor. | +| `after` | Take immediately following turns, excluding the anchor. | + +`hasBefore` and `hasAfter` describe whether retained turns exist outside the **returned window**, not just whether the requested count was met. An empty `before` at the oldest anchor returns `false, true`; an empty `after` at the newest returns `true, false` (the anchor exists on the other side). To extend a nonempty window, use `before` its first ID or `after` its last ID. Each read uses the current retained history; if an anchor is missing, pruned, or active rather than completed, return `NotFound` (`-32008`), not an empty success or a nearby substitute. + +Hosts MUST bound both the turn count and the serialized response size. Target at most 4 MiB of UTF-8 encoded JSON per result; a smaller budget is permitted. If the required turn (the anchor for `around`, the nearest adjacent turn for `before`/`after`) alone exceeds this target, the host may return it alone **only** within a finite, transport-safe hard byte limit. If it cannot fit, return `InternalError` (`-32603`) with an explanatory message. Do not truncate a turn, skip an oversized immediate neighbor, or return an empty page that cannot advance. + +#### Search visible text + +`searchChatTurns` returns `{ turnId, kind, occurrence }` locators, not snippets or offsets. Search only text that can be revealed to the caller: + +- `request`: the full visible initiating `Message.text`, not its index preview. Exclude hidden requests and system notifications. +- `response`: visible text of `markdown` response parts in stream order. Match their displayed text (for example, a link's label, not its destination or Markdown delimiters), separately per part. Matches do not cross parts. Do not search reasoning, tool names, calls, arguments or output, attachments, content references, other response-part kinds, metadata, or raw provider transcripts. + +Omitted `matchCase`, `wholeWord` and `isRegex` each mean `false`: the default query is literal, case-insensitive, and may match inside words. A regex uses ECMAScript Unicode matching, case-insensitive unless `matchCase` is true. Whole-word mode applies ECMAScript word boundaries at word ends. Match left to right without overlap, ignoring zero-width matches. A host SHOULD bound regex execution; reject an invalid or over-budget pattern rather than report a partial scan as exhaustive. + +Number nonempty matches **from zero in forward text order**, restarting for each side of each turn and continuing across the visible Markdown parts of the response. Return turns **newest first**; within a turn return response before request and occurrences in descending order. For example, searching `map` in a request `map` and a response `map then map` yields `response:1`, `response:0`, `request:0`. A page may end between these matches. To reveal a match outside the subscription, read `around` its turn ID and locate the same forward occurrence on that side. The client need not load the intervening transcript. + +#### Continuation and errors + +For list and search, omit `cursor` for the first page; the default `limit` is 100 **entries or matches**. For all three commands `limit` must be a positive integer; hosts may cap it and return fewer. Echo `nextCursor` unchanged for the following page. Its absence means the traversal is complete. A bounded search may return no matches yet with an advancing `nextCursor`; this is not a final “no matches.” + +Cursors are opaque and scoped to the connection, method, chat, and (for search) the query and effective flags. They are not `turnsNextCursor` values. Following a chain MUST enumerate the first page's ordered history without duplicates or omissions, even when a page ends within a turn. New completions do not join a traversal already in progress. A retry of the same cursor resumes from the same boundary or fails explicitly. If a change to retained history or cursor expiry prevents a consistent continuation, return `Conflict` (`-32011`); the client discards that traversal and restarts without a cursor. Discard cursors on reconnect. + +Return `InvalidParams` (`-32602`) for malformed, unrecognized or mis-scoped cursors, invalid direction or limit, empty query, or an invalid or over-budget regex. An unavailable command, including for a chat that does not advertise `historyNavigation`, returns `MethodNotFound` (`-32601`); a host that implements the command returns `NotFound` (`-32008`) for an unknown chat. Unsupported is not an empty index or a successful search. Clients without support can still use their subscribed state and the existing explicit `fetchTurns` backfill operation. + ### Reasoning timing [`ReasoningResponsePart`](/reference/chat#reasoningresponsepart) may include a producer-recorded `startedAt` timestamp and a final `duration` in non-negative integer milliseconds. Timing is optional: an absent duration means unfinished or unknown, not zero. Clients MUST treat a supplied duration as producer-owned data rather than measuring replay, subtracting their local clock from `startedAt`, or substituting a minimum display value into stored state. @@ -389,6 +434,9 @@ This section lists wire methods that are interpreted in the context of a chat UR | Method | Kind | Purpose | |---|---|---| | `fetchTurns` | request | Ask the host to load older historical turns into this chat state. | +| `listChatTurns` | request | Page the retained prompt index without loading turns into state. | +| `readChatTurns` | request | Read a bounded window around, before, or after a retained turn. | +| `searchChatTurns` | request | Find occurrences in visible retained request and response text. | | `completions` | request | Chat-scoped inline completions (e.g. user-message mentions). | `createChat` is dispatched against the owning session URI (`params.channel = "ahp-session:/"`). diff --git a/docs/specification/subscriptions.md b/docs/specification/subscriptions.md index a310b4c24..7c3f5a452 100644 --- a/docs/specification/subscriptions.md +++ b/docs/specification/subscriptions.md @@ -53,7 +53,7 @@ route any message using only its `method` and `params.channel`. | `resourceRead`, `resourceWrite`, `resourceList`, `resourceCopy`, `resourceDelete`, `resourceMove`, `resourceResolve`, `resourceMkdir`, `resourceRequest`, `createResourceWatch` | `ahp-root://`. Either peer can send these requests. | | `runAutomation`, `fetchAutomationRuns` | `ahp-automations://` | | `createSession`, `disposeSession`, `createChat` | The session URI. For `createSession`, this is the URI of the new session. | -| `fetchTurns`, `completions`, `disposeChat` | The chat URI | +| `fetchTurns`, `listChatTurns`, `readChatTurns`, `searchChatTurns`, `completions`, `disposeChat` | The chat URI | | `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 | @@ -197,6 +197,8 @@ absent, the server MUST return all turns that it retains. If older turns are available, `ChatState.turnsNextCursor` is present. The client passes that cursor to `fetchTurns` to load older turns into the chat state. +When advertised, [read-only history navigation](./chat-channel#read-only-history-navigation) can locate and read distant turns without changing this window or using its cursor. + ## Unsubscribing {#unsubscribe-notification} A client stops receiving messages for a channel by sending an `unsubscribe` diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 61ae7f7b3..4bf20c801 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -1580,7 +1580,7 @@ }, "ChatTurnsLoadedAction": { "type": "object", - "description": "Loads older completed turns into this chat's state.\n\nHosts dispatch this before responding to `fetchTurns`, and before applying\nany operation that references a turn older than the currently loaded window.\n`turns` is ordered oldest-first and is prepended to the current `turns`\nwindow. `turnsNextCursor` replaces the state's cursor; omit it when all\nretained turns are now loaded.", + "description": "Loads older completed turns into this chat's state.\n\nHosts dispatch this before responding to `fetchTurns`, and before applying\nany state-changing operation that references a turn older than the currently loaded window.\n`turns` is ordered oldest-first and is prepended to the current `turns`\nwindow. `turnsNextCursor` replaces the state's cursor; omit it when all\nretained turns are now loaded.", "properties": { "type": { "const": "chat/turnsLoaded" @@ -5319,6 +5319,10 @@ }, "description": "Completed turns" }, + "historyNavigation": { + "type": "boolean", + "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + }, "turnsNextCursor": { "type": "string", "description": "Cursor for loading older completed turns into this chat state.\n\nPresence means `turns` is a tail window and more historical turns are\navailable. Pass this opaque cursor to `fetchTurns`; the host MUST insert\nthe loaded turns into state and update or clear this cursor before\nresponding. Absence means the state contains all retained turns." diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 1f16c1696..d63e6f29a 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1347,7 +1347,7 @@ }, "FetchTurnsParams": { "type": "object", - "description": "Requests that the host load older historical turns into a chat state.\n\nThe command result does not carry turns. Instead, before responding, the host\nMUST dispatch `chat/turnsLoaded` to insert any loaded turns into the chat\nchannel's `turns` state, ahead of the already-loaded window, and update or\nclear `turnsNextCursor`.\n\nBefore applying any operation that references a turn outside the currently\nloaded window, the host MUST eagerly load enough older turns into state for\nthat operation to reduce against valid state.", + "description": "Requests that the host load older historical turns into a chat state.\n\nThe command result does not carry turns. Instead, before responding, the host\nMUST dispatch `chat/turnsLoaded` to insert any loaded turns into the chat\nchannel's `turns` state, ahead of the already-loaded window, and update or\nclear `turnsNextCursor`.\n\nBefore applying any state-changing operation that references a turn outside the currently\nloaded window, the host MUST eagerly load enough older turns into state for\nthat operation to reduce against valid state.", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -1632,6 +1632,221 @@ "channel" ] }, + "ChatTurnIndexEntry": { + "type": "object", + "description": "A prompt in the retained history, identified by its turn rather than its position.", + "properties": { + "turnId": { + "type": "string", + "description": "Stable identifier of the completed turn in this chat." + }, + "preview": { + "type": "string", + "description": "First nonempty trimmed prompt line, or empty string. If truncated, the\n80 Unicode scalar values include the trailing ellipsis.", + "maxLength": 80 + }, + "startedAt": { + "type": "string", + "description": "The turn's ISO 8601 start time, if known." + } + }, + "required": [ + "turnId", + "preview" + ] + }, + "ListChatTurnsParams": { + "type": "object", + "description": "Lists every visible non-system prompt in retained turns, oldest first, across pages.\nRequires `ChatState.historyNavigation`. Does not load turns into state.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "limit": { + "type": "integer", + "description": "Maximum entries in the page; defaults to 100. The host may return fewer.", + "minimum": 1 + }, + "cursor": { + "type": "string", + "description": "Opaque index cursor for this chat; omit to start at the oldest eligible prompt." + } + }, + "required": [ + "channel" + ] + }, + "ListChatTurnsResult": { + "type": "object", + "description": "One chronological page of the prompt index.", + "properties": { + "nextCursor": { + "type": "string", + "description": "Continue this index after the last entry; absent at the end of the index." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/$defs/ChatTurnIndexEntry" + }, + "description": "One entry per eligible prompt in transcript order." + } + }, + "required": [ + "items" + ] + }, + "ReadChatTurnsParams": { + "type": "object", + "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008).", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "turnId": { + "type": "string", + "description": "Identifier of the retained completed turn anchoring the window." + }, + "direction": { + "$ref": "#/$defs/ChatTurnReadDirection", + "description": "Defaults to `around`." + }, + "limit": { + "type": "integer", + "description": "Maximum number of whole turns, including the anchor for `around`; defaults to 10.", + "minimum": 1 + } + }, + "required": [ + "channel", + "turnId" + ] + }, + "ReadChatTurnsResult": { + "type": "object", + "description": "A contiguous slice of the transcript, not a chat snapshot or a state update.", + "properties": { + "turns": { + "type": "array", + "items": { + "$ref": "#/$defs/Turn" + }, + "description": "Whole turns in chronological order for all three directions." + }, + "hasBefore": { + "type": "boolean", + "description": "Whether retained completed turns precede this window." + }, + "hasAfter": { + "type": "boolean", + "description": "Whether retained completed turns follow this window." + } + }, + "required": [ + "turns", + "hasBefore", + "hasAfter" + ] + }, + "ChatTurnMatch": { + "type": "object", + "description": "A match locator, not a snippet, text offset, or response-part identifier.", + "properties": { + "turnId": { + "type": "string" + }, + "kind": { + "$ref": "#/$defs/ChatTurnMatchKind" + }, + "occurrence": { + "type": "integer", + "description": "Zero-based index of this nonempty match in forward text order on this\nside of the turn, for the same query and flags.", + "minimum": 0 + } + }, + "required": [ + "turnId", + "kind", + "occurrence" + ] + }, + "SearchChatTurnsParams": { + "type": "object", + "description": "Searches visible request and response text in retained completed turns.\nReturns match locators newest first, independently of the subscription.\nRequires `ChatState.historyNavigation`.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "limit": { + "type": "integer", + "description": "Maximum matches in the page; defaults to 100. The host may return fewer.", + "minimum": 1 + }, + "cursor": { + "type": "string", + "description": "Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn." + }, + "query": { + "type": "string", + "description": "Nonempty literal text, or a pattern when `isRegex` is true.", + "minLength": 1 + }, + "matchCase": { + "type": "boolean", + "description": "Case-sensitive matching; defaults to false." + }, + "wholeWord": { + "type": "boolean", + "description": "Require whole-word matches; defaults to false." + }, + "isRegex": { + "type": "boolean", + "description": "Treat the query as a regular expression; defaults to false." + } + }, + "required": [ + "channel", + "query" + ] + }, + "SearchChatTurnsResult": { + "type": "object", + "description": "One page of match locators, which may end within a turn or side.", + "properties": { + "nextCursor": { + "type": "string", + "description": "Resume after the last result or scanned position. A bounded scan may\nreturn no matches with an advancing cursor; only absence means done." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/$defs/ChatTurnMatch" + }, + "description": "Match locators in reverse transcript order." + } + }, + "required": [ + "items" + ] + }, "CreateTerminalParams": { "type": "object", "description": "Creates a new terminal on the server.\n\nAfter creation, the client should subscribe to the terminal URI to receive\nstate updates. The server dispatches `root/terminalsChanged` to update the\nroot terminal list.", @@ -4675,6 +4890,10 @@ }, "description": "Completed turns" }, + "historyNavigation": { + "type": "boolean", + "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + }, "turnsNextCursor": { "type": "string", "description": "Cursor for loading older completed turns into this chat state.\n\nPresence means `turns` is a tail window and more historical turns are\navailable. Pass this opaque cursor to `fetchTurns`; the host MUST insert\nthe loaded turns into state and update or clear this cursor before\nresponding. Absence means the state contains all retained turns." @@ -9784,7 +10003,7 @@ }, "ChatTurnsLoadedAction": { "type": "object", - "description": "Loads older completed turns into this chat's state.\n\nHosts dispatch this before responding to `fetchTurns`, and before applying\nany operation that references a turn older than the currently loaded window.\n`turns` is ordered oldest-first and is prepended to the current `turns`\nwindow. `turnsNextCursor` replaces the state's cursor; omit it when all\nretained turns are now loaded.", + "description": "Loads older completed turns into this chat's state.\n\nHosts dispatch this before responding to `fetchTurns`, and before applying\nany state-changing operation that references a turn older than the currently loaded window.\n`turns` is ordered oldest-first and is prepended to the current `turns`\nwindow. `turnsNextCursor` replaces the state's cursor; omit it when all\nretained turns are now loaded.", "properties": { "type": { "const": "chat/turnsLoaded" @@ -11191,6 +11410,23 @@ ], "description": "An attachment associated with a {@link Message}." }, + "ChatTurnReadDirection": { + "enum": [ + "around", + "before", + "after" + ], + "type": "string", + "description": "Which contiguous window of completed turns to read, relative to an anchor." + }, + "ChatTurnMatchKind": { + "enum": [ + "request", + "response" + ], + "type": "string", + "description": "The searchable side of a completed turn." + }, "TerminalClaim": { "oneOf": [ { diff --git a/schema/errors.schema.json b/schema/errors.schema.json index b2edbe1f0..df499a9d3 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -2688,6 +2688,10 @@ }, "description": "Completed turns" }, + "historyNavigation": { + "type": "boolean", + "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + }, "turnsNextCursor": { "type": "string", "description": "Cursor for loading older completed turns into this chat state.\n\nPresence means `turns` is a tail window and more historical turns are\navailable. Pass this opaque cursor to `fetchTurns`; the host MUST insert\nthe loaded turns into state and update or clear this cursor before\nresponding. Absence means the state contains all retained turns." @@ -7564,7 +7568,7 @@ }, "FetchTurnsParams": { "type": "object", - "description": "Requests that the host load older historical turns into a chat state.\n\nThe command result does not carry turns. Instead, before responding, the host\nMUST dispatch `chat/turnsLoaded` to insert any loaded turns into the chat\nchannel's `turns` state, ahead of the already-loaded window, and update or\nclear `turnsNextCursor`.\n\nBefore applying any operation that references a turn outside the currently\nloaded window, the host MUST eagerly load enough older turns into state for\nthat operation to reduce against valid state.", + "description": "Requests that the host load older historical turns into a chat state.\n\nThe command result does not carry turns. Instead, before responding, the host\nMUST dispatch `chat/turnsLoaded` to insert any loaded turns into the chat\nchannel's `turns` state, ahead of the already-loaded window, and update or\nclear `turnsNextCursor`.\n\nBefore applying any state-changing operation that references a turn outside the currently\nloaded window, the host MUST eagerly load enough older turns into state for\nthat operation to reduce against valid state.", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -7849,6 +7853,221 @@ "channel" ] }, + "ChatTurnIndexEntry": { + "type": "object", + "description": "A prompt in the retained history, identified by its turn rather than its position.", + "properties": { + "turnId": { + "type": "string", + "description": "Stable identifier of the completed turn in this chat." + }, + "preview": { + "type": "string", + "description": "First nonempty trimmed prompt line, or empty string. If truncated, the\n80 Unicode scalar values include the trailing ellipsis.", + "maxLength": 80 + }, + "startedAt": { + "type": "string", + "description": "The turn's ISO 8601 start time, if known." + } + }, + "required": [ + "turnId", + "preview" + ] + }, + "ListChatTurnsParams": { + "type": "object", + "description": "Lists every visible non-system prompt in retained turns, oldest first, across pages.\nRequires `ChatState.historyNavigation`. Does not load turns into state.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "limit": { + "type": "integer", + "description": "Maximum entries in the page; defaults to 100. The host may return fewer.", + "minimum": 1 + }, + "cursor": { + "type": "string", + "description": "Opaque index cursor for this chat; omit to start at the oldest eligible prompt." + } + }, + "required": [ + "channel" + ] + }, + "ListChatTurnsResult": { + "type": "object", + "description": "One chronological page of the prompt index.", + "properties": { + "nextCursor": { + "type": "string", + "description": "Continue this index after the last entry; absent at the end of the index." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/$defs/ChatTurnIndexEntry" + }, + "description": "One entry per eligible prompt in transcript order." + } + }, + "required": [ + "items" + ] + }, + "ReadChatTurnsParams": { + "type": "object", + "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008).", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "turnId": { + "type": "string", + "description": "Identifier of the retained completed turn anchoring the window." + }, + "direction": { + "$ref": "#/$defs/ChatTurnReadDirection", + "description": "Defaults to `around`." + }, + "limit": { + "type": "integer", + "description": "Maximum number of whole turns, including the anchor for `around`; defaults to 10.", + "minimum": 1 + } + }, + "required": [ + "channel", + "turnId" + ] + }, + "ReadChatTurnsResult": { + "type": "object", + "description": "A contiguous slice of the transcript, not a chat snapshot or a state update.", + "properties": { + "turns": { + "type": "array", + "items": { + "$ref": "#/$defs/Turn" + }, + "description": "Whole turns in chronological order for all three directions." + }, + "hasBefore": { + "type": "boolean", + "description": "Whether retained completed turns precede this window." + }, + "hasAfter": { + "type": "boolean", + "description": "Whether retained completed turns follow this window." + } + }, + "required": [ + "turns", + "hasBefore", + "hasAfter" + ] + }, + "ChatTurnMatch": { + "type": "object", + "description": "A match locator, not a snippet, text offset, or response-part identifier.", + "properties": { + "turnId": { + "type": "string" + }, + "kind": { + "$ref": "#/$defs/ChatTurnMatchKind" + }, + "occurrence": { + "type": "integer", + "description": "Zero-based index of this nonempty match in forward text order on this\nside of the turn, for the same query and flags.", + "minimum": 0 + } + }, + "required": [ + "turnId", + "kind", + "occurrence" + ] + }, + "SearchChatTurnsParams": { + "type": "object", + "description": "Searches visible request and response text in retained completed turns.\nReturns match locators newest first, independently of the subscription.\nRequires `ChatState.historyNavigation`.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "limit": { + "type": "integer", + "description": "Maximum matches in the page; defaults to 100. The host may return fewer.", + "minimum": 1 + }, + "cursor": { + "type": "string", + "description": "Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn." + }, + "query": { + "type": "string", + "description": "Nonempty literal text, or a pattern when `isRegex` is true.", + "minLength": 1 + }, + "matchCase": { + "type": "boolean", + "description": "Case-sensitive matching; defaults to false." + }, + "wholeWord": { + "type": "boolean", + "description": "Require whole-word matches; defaults to false." + }, + "isRegex": { + "type": "boolean", + "description": "Treat the query as a regular expression; defaults to false." + } + }, + "required": [ + "channel", + "query" + ] + }, + "SearchChatTurnsResult": { + "type": "object", + "description": "One page of match locators, which may end within a turn or side.", + "properties": { + "nextCursor": { + "type": "string", + "description": "Resume after the last result or scanned position. A bounded scan may\nreturn no matches with an advancing cursor; only absence means done." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/$defs/ChatTurnMatch" + }, + "description": "Match locators in reverse transcript order." + } + }, + "required": [ + "items" + ] + }, "CreateTerminalParams": { "type": "object", "description": "Creates a new terminal on the server.\n\nAfter creation, the client should subscribe to the terminal URI to receive\nstate updates. The server dispatches `root/terminalsChanged` to update the\nroot terminal list.", @@ -9395,6 +9614,23 @@ ], "description": "Identifies the destination of an atomic chat move." }, + "ChatTurnReadDirection": { + "enum": [ + "around", + "before", + "after" + ], + "type": "string", + "description": "Which contiguous window of completed turns to read, relative to an anchor." + }, + "ChatTurnMatchKind": { + "enum": [ + "request", + "response" + ], + "type": "string", + "description": "The searchable side of a completed turn." + }, "ChangesetOperationTarget": { "oneOf": [ { @@ -11146,7 +11382,7 @@ }, "ChatTurnsLoadedAction": { "type": "object", - "description": "Loads older completed turns into this chat's state.\n\nHosts dispatch this before responding to `fetchTurns`, and before applying\nany operation that references a turn older than the currently loaded window.\n`turns` is ordered oldest-first and is prepended to the current `turns`\nwindow. `turnsNextCursor` replaces the state's cursor; omit it when all\nretained turns are now loaded.", + "description": "Loads older completed turns into this chat's state.\n\nHosts dispatch this before responding to `fetchTurns`, and before applying\nany state-changing operation that references a turn older than the currently loaded window.\n`turns` is ordered oldest-first and is prepended to the current `turns`\nwindow. `turnsNextCursor` replaces the state's cursor; omit it when all\nretained turns are now loaded.", "properties": { "type": { "const": "chat/turnsLoaded" diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 345f11f22..aaa44d29c 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -2990,6 +2990,10 @@ }, "description": "Completed turns" }, + "historyNavigation": { + "type": "boolean", + "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + }, "turnsNextCursor": { "type": "string", "description": "Cursor for loading older completed turns into this chat state.\n\nPresence means `turns` is a tail window and more historical turns are\navailable. Pass this opaque cursor to `fetchTurns`; the host MUST insert\nthe loaded turns into state and update or clear this cursor before\nresponding. Absence means the state contains all retained turns." diff --git a/schema/state.schema.json b/schema/state.schema.json index 6b3ee7740..2f513dd34 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -2599,6 +2599,10 @@ }, "description": "Completed turns" }, + "historyNavigation": { + "type": "boolean", + "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + }, "turnsNextCursor": { "type": "string", "description": "Cursor for loading older completed turns into this chat state.\n\nPresence means `turns` is a tail window and more historical turns are\navailable. Pass this opaque cursor to `fetchTurns`; the host MUST insert\nthe loaded turns into state and update or clear this cursor before\nresponding. Absence means the state contains all retained turns." diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index a66676407..47fa4cee9 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -2328,7 +2328,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, @@ -2380,6 +2380,9 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: str { name: 'ResourceRequestParams' }, { name: 'ResourceRequestResult' }, { name: 'CreateResourceWatchParams' }, { name: 'CreateResourceWatchResult' }, { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, + { name: 'ChatTurnIndexEntry' }, { name: 'ListChatTurnsParams' }, { name: 'ListChatTurnsResult' }, + { name: 'ReadChatTurnsParams' }, { name: 'ReadChatTurnsResult' }, + { name: 'ChatTurnMatch' }, { name: 'SearchChatTurnsParams' }, { name: 'SearchChatTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index c8c124d9d..f8c5dd1ea 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -1840,7 +1840,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, @@ -1879,6 +1879,9 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: str { name: 'ResourceRequestParams' }, { name: 'ResourceRequestResult' }, { name: 'CreateResourceWatchParams' }, { name: 'CreateResourceWatchResult' }, { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, + { name: 'ChatTurnIndexEntry' }, { name: 'ListChatTurnsParams' }, { name: 'ListChatTurnsResult' }, + { name: 'ReadChatTurnsParams' }, { name: 'ReadChatTurnsResult' }, + { name: 'ChatTurnMatch' }, { name: 'SearchChatTurnsParams' }, { name: 'SearchChatTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-json-schema.test.ts b/scripts/generate-json-schema.test.ts index 6cd94baa3..c95293010 100644 --- a/scripts/generate-json-schema.test.ts +++ b/scripts/generate-json-schema.test.ts @@ -153,7 +153,8 @@ function schemaAccepts( switch (schema.type) { case 'string': return typeof value === 'string' && - (typeof schema.minLength !== 'number' || [...value].length >= schema.minLength); + (typeof schema.minLength !== 'number' || [...value].length >= schema.minLength) && + (typeof schema.maxLength !== 'number' || [...value].length <= schema.maxLength); case 'number': case 'integer': return typeof value === 'number' && @@ -610,6 +611,41 @@ describe('generated JSON schemas', () => { ); }); + it('keeps chat history reads optional and their pages bounded and addressable', () => { + if (file !== 'commands.schema.json') { + return; + } + const defs = schema.$defs as Record>; + const channel = 'ahp-chat:/c1'; + const turnId = 'anchor'; + const accepts = (name: string, value: unknown) => { + assert.ok(defs[name], `${name} must be a named wire type`); + return schemaAccepts(schema, defs[name] as JsonNode, value); + }; + for (const [name, params] of [ + ['ListChatTurnsParams', { channel }], + ['ReadChatTurnsParams', { channel, turnId }], + ['SearchChatTurnsParams', { channel, query: 'x' }], + ] as const) { + assert.ok(accepts(name, params), 'all modifiers are optional'); + assert.ok(!accepts(name, { ...params, limit: 0 })); + assert.ok(!accepts(name, { ...params, limit: 1.5 })); + } + assert.ok(!accepts('ReadChatTurnsParams', { channel })); + assert.ok(!accepts('ReadChatTurnsParams', { channel, turnId, direction: 'latest' })); + assert.ok(!accepts('ReadChatTurnsResult', { turns: [], hasBefore: false })); + assert.ok(!accepts('ReadChatTurnsResult', { turns: [{ turnId }], hasBefore: false, hasAfter: true })); + assert.ok(!accepts('SearchChatTurnsParams', { channel, query: '' })); + assert.ok(!accepts('SearchChatTurnsResult', { items: [{ turnId, kind: 'reasoning', occurrence: 0 }] })); + assert.ok(!accepts('SearchChatTurnsResult', { items: [{ turnId, kind: 'response', occurrence: -1 }] })); + const page = (preview: string) => ({ items: [{ turnId, preview }] }); + assert.ok(accepts('ListChatTurnsResult', page('🌱'.repeat(80)))); + assert.ok(!accepts('ListChatTurnsResult', page('🌱'.repeat(81)))); + + assert.equal((defs.ChatState.properties as Record).historyNavigation.type, 'boolean'); + assert.ok(!(defs.ChatState.required as string[]).includes('historyNavigation')); + }); + it('constrains stable chat move destinations and results', () => { if (file !== 'commands.schema.json') { return; diff --git a/scripts/generate-json-schema.ts b/scripts/generate-json-schema.ts index b22fa9d81..577086f8f 100644 --- a/scripts/generate-json-schema.ts +++ b/scripts/generate-json-schema.ts @@ -40,6 +40,7 @@ interface JsonSchema { minimum?: number; maximum?: number; minLength?: number; + maxLength?: number; oneOf?: JsonSchema[]; allOf?: JsonSchema[]; anyOf?: JsonSchema[]; @@ -431,14 +432,16 @@ function interfaceToSchema(iface: InterfaceDeclaration, project: Project): JsonS propSchema[constraint] = value; } } - const minLength = getNumericPropertyTag(prop, 'minLength'); - if (minLength !== undefined) { - if (propSchema.type !== 'string' || !Number.isInteger(minLength) || minLength < 0) { - throw new Error( - `${prop.getSourceFile().getFilePath()}: ${name} uses invalid @minLength on ${typeText}`, - ); + for (const constraint of ['minLength', 'maxLength'] as const) { + const length = getNumericPropertyTag(prop, constraint); + if (length !== undefined) { + if (propSchema.type !== 'string' || !Number.isInteger(length) || length < 0) { + throw new Error( + `${prop.getSourceFile().getFilePath()}: ${name} uses invalid @${constraint} on ${typeText}`, + ); + } + propSchema[constraint] = length; } - propSchema.minLength = minLength; } const uniqueItemsBy = getUniqueItemsByConstraints(prop); if (uniqueItemsBy) { diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index de2f5d6ee..a54010e5e 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1818,7 +1818,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS = [ 'CreateTcpConnectionParams', 'CreateTcpConnectionResult', @@ -1853,6 +1853,9 @@ const COMMAND_STRUCTS = [ 'ResourceRequestParams', 'ResourceRequestResult', 'CreateResourceWatchParams', 'CreateResourceWatchResult', 'FetchTurnsParams', 'FetchTurnsResult', + 'ChatTurnIndexEntry', 'ListChatTurnsParams', 'ListChatTurnsResult', + 'ReadChatTurnsParams', 'ReadChatTurnsResult', + 'ChatTurnMatch', 'SearchChatTurnsParams', 'SearchChatTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', @@ -2387,6 +2390,15 @@ object AhpCommands { fun fetchTurns(id: Long, params: FetchTurnsParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "fetchTurns", params = params) + fun listChatTurns(id: Long, params: ListChatTurnsParams): JsonRpcRequest = + JsonRpcRequest(id = id, method = "listChatTurns", params = params) + + fun readChatTurns(id: Long, params: ReadChatTurnsParams): JsonRpcRequest = + JsonRpcRequest(id = id, method = "readChatTurns", params = params) + + fun searchChatTurns(id: Long, params: SearchChatTurnsParams): JsonRpcRequest = + JsonRpcRequest(id = id, method = "searchChatTurns", params = params) + fun authenticate(id: Long, params: AuthenticateParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "authenticate", params = params) diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 47322a0f0..0aba0e663 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -1912,7 +1912,7 @@ pub struct ActionEnvelope { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, @@ -1953,6 +1953,9 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: s { name: 'ResourceRequestParams' }, { name: 'ResourceRequestResult' }, { name: 'CreateResourceWatchParams' }, { name: 'CreateResourceWatchResult' }, { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, + { name: 'ChatTurnIndexEntry' }, { name: 'ListChatTurnsParams' }, { name: 'ListChatTurnsResult' }, + { name: 'ReadChatTurnsParams' }, { name: 'ReadChatTurnsResult' }, + { name: 'ChatTurnMatch' }, { name: 'SearchChatTurnsParams' }, { name: 'SearchChatTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget', omitDiscriminants: true }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index d5f1f5940..2af1e5a0b 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -1766,7 +1766,7 @@ public func isClientDispatchable(_ action: StateAction) -> Bool { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS = [ 'CreateTcpConnectionParams', 'CreateTcpConnectionResult', @@ -1800,6 +1800,9 @@ const COMMAND_STRUCTS = [ 'ResourceRequestParams', 'ResourceRequestResult', 'CreateResourceWatchParams', 'CreateResourceWatchResult', 'FetchTurnsParams', 'FetchTurnsResult', + 'ChatTurnIndexEntry', 'ListChatTurnsParams', 'ListChatTurnsResult', + 'ReadChatTurnsParams', 'ReadChatTurnsResult', + 'ChatTurnMatch', 'SearchChatTurnsParams', 'SearchChatTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', @@ -2379,6 +2382,18 @@ public enum AHPCommands { JsonRpcRequest(id: id, method: "fetchTurns", params: params) } + public static func listChatTurns(id: Int, params: ListChatTurnsParams) -> JsonRpcRequest { + JsonRpcRequest(id: id, method: "listChatTurns", params: params) + } + + public static func readChatTurns(id: Int, params: ReadChatTurnsParams) -> JsonRpcRequest { + JsonRpcRequest(id: id, method: "readChatTurns", params: params) + } + + public static func searchChatTurns(id: Int, params: SearchChatTurnsParams) -> JsonRpcRequest { + JsonRpcRequest(id: id, method: "searchChatTurns", params: params) + } + public static func authenticate(id: Int, params: AuthenticateParams) -> JsonRpcRequest { JsonRpcRequest(id: id, method: "authenticate", params: params) } diff --git a/types/channels-chat/actions.ts b/types/channels-chat/actions.ts index c8f076508..02b8ffd44 100644 --- a/types/channels-chat/actions.ts +++ b/types/channels-chat/actions.ts @@ -756,7 +756,7 @@ export interface ChatTruncatedAction { * Loads older completed turns into this chat's state. * * Hosts dispatch this before responding to `fetchTurns`, and before applying - * any operation that references a turn older than the currently loaded window. + * any state-changing operation that references a turn older than the currently loaded window. * `turns` is ordered oldest-first and is prepended to the current `turns` * window. `turnsNextCursor` replaces the state's cursor; omit it when all * retained turns are now loaded. diff --git a/types/channels-chat/commands.ts b/types/channels-chat/commands.ts index 846b3db57..1b2387eef 100644 --- a/types/channels-chat/commands.ts +++ b/types/channels-chat/commands.ts @@ -1,12 +1,12 @@ /** - * Chat Channel Commands — `createChat`, `moveChat`, and `disposeChat`. + * Chat lifecycle and read-only history navigation commands. * * @module channels-chat/commands */ import type { URI } from '../common/state.js'; -import type { BaseParams } from '../common/commands.js'; -import type { Message, SideChatSelection } from './state.js'; +import type { BaseParams, PaginatedParams, PaginatedResult } from '../common/commands.js'; +import type { Message, SideChatSelection, Turn } from './state.js'; // ─── createChat ────────────────────────────────────────────────────────────── @@ -257,3 +257,170 @@ export interface MoveChatResult { * @version 1 */ export interface DisposeChatParams extends BaseParams {} + +// ─── Read-only history navigation ──────────────────────────────────────────── + +/** A prompt in the retained history, identified by its turn rather than its position. */ +export interface ChatTurnIndexEntry { + /** Stable identifier of the completed turn in this chat. */ + turnId: string; + /** + * First nonempty trimmed prompt line, or empty string. If truncated, the + * 80 Unicode scalar values include the trailing ellipsis. + * @maxLength 80 + */ + preview: string; + /** The turn's ISO 8601 start time, if known. */ + startedAt?: string; +} + +/** + * Lists every visible non-system prompt in retained turns, oldest first, across pages. + * Requires `ChatState.historyNavigation`. Does not load turns into state. + * + * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} + * @category Commands + * @method listChatTurns + * @direction Client → Server + * @messageType Request + * @version 1 + */ +export interface ListChatTurnsParams extends BaseParams, PaginatedParams { + /** Chat URI. */ + channel: URI; + /** Opaque index cursor for this chat; omit to start at the oldest eligible prompt. */ + cursor?: string; + /** + * Maximum entries in the page; defaults to 100. The host may return fewer. + * @integer + * @minimum 1 + */ + limit?: number; +} + +/** One chronological page of the prompt index. */ +export interface ListChatTurnsResult extends PaginatedResult { + /** One entry per eligible prompt in transcript order. */ + items: ChatTurnIndexEntry[]; + /** Continue this index after the last entry; absent at the end of the index. */ + nextCursor?: string; +} + +/** + * Which contiguous window of completed turns to read, relative to an anchor. + * @exhaustive + */ +export const enum ChatTurnReadDirection { + /** Include the anchor and nearby turns. */ + Around = 'around', + /** Immediately preceding turns, excluding the anchor. */ + Before = 'before', + /** Immediately following turns, excluding the anchor. */ + After = 'after', +} + +/** + * Reads a byte-bounded window of completed turns directly, without changing + * any subscription or fetching intervening pages. Requires + * `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). + * + * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} + * @category Commands + * @method readChatTurns + * @direction Client → Server + * @messageType Request + * @version 1 + */ +export interface ReadChatTurnsParams extends BaseParams { + /** Chat URI. */ + channel: URI; + /** Identifier of the retained completed turn anchoring the window. */ + turnId: string; + /** Defaults to `around`. */ + direction?: ChatTurnReadDirection; + /** + * Maximum number of whole turns, including the anchor for `around`; defaults to 10. + * @integer + * @minimum 1 + */ + limit?: number; +} + +/** A contiguous slice of the transcript, not a chat snapshot or a state update. */ +export interface ReadChatTurnsResult { + /** Whole turns in chronological order for all three directions. */ + turns: Turn[]; + /** Whether retained completed turns precede this window. */ + hasBefore: boolean; + /** Whether retained completed turns follow this window. */ + hasAfter: boolean; +} + +/** + * The searchable side of a completed turn. + * @exhaustive + */ +export const enum ChatTurnMatchKind { + Request = 'request', + Response = 'response', +} + +/** A match locator, not a snippet, text offset, or response-part identifier. */ +export interface ChatTurnMatch { + turnId: string; + kind: ChatTurnMatchKind; + /** + * Zero-based index of this nonempty match in forward text order on this + * side of the turn, for the same query and flags. + * @integer + * @minimum 0 + */ + occurrence: number; +} + +/** + * Searches visible request and response text in retained completed turns. + * Returns match locators newest first, independently of the subscription. + * Requires `ChatState.historyNavigation`. + * + * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} + * @category Commands + * @method searchChatTurns + * @direction Client → Server + * @messageType Request + * @version 1 + */ +export interface SearchChatTurnsParams extends BaseParams, PaginatedParams { + /** Chat URI. */ + channel: URI; + /** + * Nonempty literal text, or a pattern when `isRegex` is true. + * @minLength 1 + */ + query: string; + /** Case-sensitive matching; defaults to false. */ + matchCase?: boolean; + /** Require whole-word matches; defaults to false. */ + wholeWord?: boolean; + /** Treat the query as a regular expression; defaults to false. */ + isRegex?: boolean; + /** Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn. */ + cursor?: string; + /** + * Maximum matches in the page; defaults to 100. The host may return fewer. + * @integer + * @minimum 1 + */ + limit?: number; +} + +/** One page of match locators, which may end within a turn or side. */ +export interface SearchChatTurnsResult extends PaginatedResult { + /** Match locators in reverse transcript order. */ + items: ChatTurnMatch[]; + /** + * Resume after the last result or scanned position. A bounded scan may + * return no matches with an advancing cursor; only absence means done. + */ + nextCursor?: string; +} diff --git a/types/channels-chat/state.ts b/types/channels-chat/state.ts index 28861c4aa..6665d73a6 100644 --- a/types/channels-chat/state.ts +++ b/types/channels-chat/state.ts @@ -145,6 +145,12 @@ export interface ChatState { // ── Conversation contents ────────────────────────────────────────── /** Completed turns */ turns: Turn[]; + /** + * When true, the host supports `listChatTurns`, `readChatTurns`, and + * `searchChatTurns` over this chat's retained history, independently of + * the subscription window. Absent or false means unsupported. + */ + historyNavigation?: boolean; /** * Cursor for loading older completed turns into this chat state. * diff --git a/types/channels-session/commands.ts b/types/channels-session/commands.ts index 5c452067b..4cf7eb6d4 100644 --- a/types/channels-session/commands.ts +++ b/types/channels-session/commands.ts @@ -123,7 +123,7 @@ export interface DisposeSessionParams extends BaseParams {} * channel's `turns` state, ahead of the already-loaded window, and update or * clear `turnsNextCursor`. * - * Before applying any operation that references a turn outside the currently + * Before applying any state-changing operation that references a turn outside the currently * loaded window, the host MUST eagerly load enough older turns into state for * that operation to reduce against valid state. * diff --git a/types/common/messages.ts b/types/common/messages.ts index c2f85ff62..fc25b95b3 100644 --- a/types/common/messages.ts +++ b/types/common/messages.ts @@ -59,6 +59,12 @@ import type { MoveChatParams, MoveChatResult, DisposeChatParams, + ListChatTurnsParams, + ListChatTurnsResult, + ReadChatTurnsParams, + ReadChatTurnsResult, + SearchChatTurnsParams, + SearchChatTurnsResult, } from '../channels-chat/commands.js'; import type { CreateTerminalParams, @@ -174,6 +180,9 @@ export interface CommandMap { 'createTcpConnection': { params: CreateTcpConnectionParams; result: CreateTcpConnectionResult }; 'moveChat': { params: MoveChatParams; result: MoveChatResult }; 'disposeChat': { params: DisposeChatParams; result: null }; + 'listChatTurns': { params: ListChatTurnsParams; result: ListChatTurnsResult }; + 'readChatTurns': { params: ReadChatTurnsParams; result: ReadChatTurnsResult }; + 'searchChatTurns': { params: SearchChatTurnsParams; result: SearchChatTurnsResult }; 'createTerminal': { params: CreateTerminalParams; result: null }; 'disposeTerminal': { params: DisposeTerminalParams; result: null }; 'createResourceWatch': { params: CreateResourceWatchParams; result: CreateResourceWatchResult }; diff --git a/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json b/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json new file mode 100644 index 000000000..25dd14299 --- /dev/null +++ b/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json @@ -0,0 +1,16 @@ +{ + "name": "chat-history-navigation-snapshot", + "group": "A", + "description": "A joining client discovers navigation even when the subscription has loaded no completed turns.", + "type": "Snapshot", + "input": { + "resource": "ahp-chat:/c1", + "fromSeq": 10, + "state": { "resource": "ahp-chat:/c1", "title": "Design", "status": 1, "modifiedAt": "2026-11-18T12:00:00Z", "turns": [], "turnsNextCursor": "older", "historyNavigation": true } + }, + "acceptableOutputs": [{ + "resource": "ahp-chat:/c1", + "fromSeq": 10, + "state": { "resource": "ahp-chat:/c1", "title": "Design", "status": 1, "modifiedAt": "2026-11-18T12:00:00Z", "turns": [], "turnsNextCursor": "older", "historyNavigation": true } + }] +} diff --git a/types/test-cases/round-trips/101-list-chat-turns-params.json b/types/test-cases/round-trips/101-list-chat-turns-params.json new file mode 100644 index 000000000..571ca6d26 --- /dev/null +++ b/types/test-cases/round-trips/101-list-chat-turns-params.json @@ -0,0 +1,8 @@ +{ + "name": "list-chat-turns-params", + "group": "A", + "description": "Continue a prompt index using its own opaque cursor, not the subscription cursor.", + "type": "ListChatTurnsParams", + "input": { "channel": "ahp-chat:/c1", "cursor": "index-page-two", "limit": 2 }, + "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "cursor": "index-page-two", "limit": 2 }] +} diff --git a/types/test-cases/round-trips/102-list-chat-turns-result.json b/types/test-cases/round-trips/102-list-chat-turns-result.json new file mode 100644 index 000000000..93930d10e --- /dev/null +++ b/types/test-cases/round-trips/102-list-chat-turns-result.json @@ -0,0 +1,14 @@ +{ + "name": "list-chat-turns-result", + "group": "A", + "description": "Chronological prompt previews may lack timestamps; more eligible prompts remain.", + "type": "ListChatTurnsResult", + "input": { + "items": [{ "turnId": "t1", "preview": "Sketch the design" }, { "turnId": "t3", "preview": "Check the design", "startedAt": "2026-11-18T12:00:00Z" }], + "nextCursor": "index-page-two" + }, + "acceptableOutputs": [{ + "items": [{ "turnId": "t1", "preview": "Sketch the design" }, { "turnId": "t3", "preview": "Check the design", "startedAt": "2026-11-18T12:00:00Z" }], + "nextCursor": "index-page-two" + }] +} diff --git a/types/test-cases/round-trips/103-read-chat-turns-params.json b/types/test-cases/round-trips/103-read-chat-turns-params.json new file mode 100644 index 000000000..15a0386b4 --- /dev/null +++ b/types/test-cases/round-trips/103-read-chat-turns-params.json @@ -0,0 +1,8 @@ +{ + "name": "read-chat-turns-params", + "group": "A", + "description": "Read immediately before a known historical turn without backfilling the subscription.", + "type": "ReadChatTurnsParams", + "input": { "channel": "ahp-chat:/c1", "turnId": "t2", "direction": "before", "limit": 1 }, + "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "turnId": "t2", "direction": "before", "limit": 1 }] +} diff --git a/types/test-cases/round-trips/104-read-chat-turns-result.json b/types/test-cases/round-trips/104-read-chat-turns-result.json new file mode 100644 index 000000000..1cfd9dbbd --- /dev/null +++ b/types/test-cases/round-trips/104-read-chat-turns-result.json @@ -0,0 +1,16 @@ +{ + "name": "read-chat-turns-result", + "group": "A", + "description": "An exclusive window at the start of the transcript contains the whole preceding turn.", + "type": "ReadChatTurnsResult", + "input": { + "turns": [{ "id": "t1", "message": { "origin": { "kind": "user" }, "text": "Sketch the design" }, "responseParts": [{ "kind": "markdown", "id": "part-1", "content": "Design A or design B?" }], "state": "complete" }], + "hasBefore": false, + "hasAfter": true + }, + "acceptableOutputs": [{ + "turns": [{ "id": "t1", "message": { "origin": { "kind": "user" }, "text": "Sketch the design" }, "responseParts": [{ "kind": "markdown", "id": "part-1", "content": "Design A or design B?" }], "state": "complete" }], + "hasBefore": false, + "hasAfter": true + }] +} diff --git a/types/test-cases/round-trips/105-search-chat-turns-params.json b/types/test-cases/round-trips/105-search-chat-turns-params.json new file mode 100644 index 000000000..0f758991b --- /dev/null +++ b/types/test-cases/round-trips/105-search-chat-turns-params.json @@ -0,0 +1,8 @@ +{ + "name": "search-chat-turns-params", + "group": "A", + "description": "A search page retains its query and all search modifiers.", + "type": "SearchChatTurnsParams", + "input": { "channel": "ahp-chat:/c1", "query": "des[i]gn", "matchCase": false, "wholeWord": true, "isRegex": true, "cursor": "matches", "limit": 3 }, + "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "query": "des[i]gn", "matchCase": false, "wholeWord": true, "isRegex": true, "cursor": "matches", "limit": 3 }] +} diff --git a/types/test-cases/round-trips/106-search-chat-turns-result.json b/types/test-cases/round-trips/106-search-chat-turns-result.json new file mode 100644 index 000000000..e257446da --- /dev/null +++ b/types/test-cases/round-trips/106-search-chat-turns-result.json @@ -0,0 +1,8 @@ +{ + "name": "search-chat-turns-result", + "group": "A", + "description": "Repeated matches are located per side in forward text, but delivered in reverse; a final page omits nextCursor.", + "type": "SearchChatTurnsResult", + "input": { "items": [{ "turnId": "t1", "kind": "response", "occurrence": 1 }, { "turnId": "t1", "kind": "response", "occurrence": 0 }, { "turnId": "t1", "kind": "request", "occurrence": 0 }] }, + "acceptableOutputs": [{ "items": [{ "turnId": "t1", "kind": "response", "occurrence": 1 }, { "turnId": "t1", "kind": "response", "occurrence": 0 }, { "turnId": "t1", "kind": "request", "occurrence": 0 }] }] +} diff --git a/types/version/message-checks.ts b/types/version/message-checks.ts index cc84e3bf9..00ce1d27c 100644 --- a/types/version/message-checks.ts +++ b/types/version/message-checks.ts @@ -60,6 +60,9 @@ type _ExpectedCommands = | 'createTcpConnection' | 'moveChat' | 'disposeChat' + | 'listChatTurns' + | 'readChatTurns' + | 'searchChatTurns' | 'createTerminal' | 'disposeTerminal' | 'createResourceWatch' From 58920e23996448b1e17bcc5ccaa4421feb15f7a9 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Fri, 20 Nov 2026 11:27:42 -0800 Subject: [PATCH 2/3] chat: separate history browsing from transcript search Make the prompt index and direct turn-window reads available on their own. Advertise the pair with a per-chat presence object; keep subscription paging unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Commands.generated.cs | 76 +----------- .../JsonSerializerContext.generated.cs | 5 +- .../Generated/State.generated.cs | 11 +- .../TypesRoundTripFixtures.cs | 4 - clients/go/ahptypes/commands.generated.go | 59 +--------- clients/go/ahptypes/roundtrip_fixture_test.go | 8 -- clients/go/ahptypes/state.generated.go | 10 +- .../generated/Commands.generated.kt | 79 ------------- .../generated/Messages.generated.kt | 3 - .../generated/State.generated.kt | 9 +- .../agenthostprotocol/RoundTripCorpusTest.kt | 4 - clients/rust/crates/ahp-types/src/commands.rs | 73 +----------- clients/rust/crates/ahp-types/src/state.rs | 11 +- .../ahp-types/tests/roundtrip_corpus.rs | 5 +- clients/rust/crates/ahp/src/reducers.rs | 2 +- .../Generated/Commands.generated.swift | 102 ---------------- .../Generated/Messages.generated.swift | 4 - .../Generated/State.generated.swift | 20 ++-- .../TypesRoundTripFixtureTests.swift | 4 - .../typescript/test/types-round-trip.test.ts | 4 +- .../20261119-chat-history-navigation.json | 2 +- docs/specification/chat-channel.md | 22 +--- docs/specification/subscriptions.md | 2 +- schema/actions.schema.json | 11 +- schema/commands.schema.json | 110 ++---------------- schema/errors.schema.json | 110 ++---------------- schema/notifications.schema.json | 11 +- schema/state.schema.json | 11 +- scripts/generate-csharp.ts | 4 +- scripts/generate-go.ts | 4 +- scripts/generate-json-schema.test.ts | 10 +- scripts/generate-kotlin.ts | 7 +- scripts/generate-rust.ts | 4 +- scripts/generate-swift.ts | 8 +- types/channels-chat/commands.ts | 73 +----------- types/channels-chat/state.ts | 11 +- types/common/messages.ts | 3 - .../100-chat-history-navigation-snapshot.json | 4 +- .../105-search-chat-turns-params.json | 8 -- .../106-search-chat-turns-result.json | 8 -- types/version/message-checks.ts | 1 - 41 files changed, 122 insertions(+), 795 deletions(-) delete mode 100644 types/test-cases/round-trips/105-search-chat-turns-params.json delete mode 100644 types/test-cases/round-trips/106-search-chat-turns-result.json diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 0822cd202..6b04221f4 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -140,16 +140,6 @@ public enum ChatTurnReadDirection After, } -/// The searchable side of a completed turn. -[JsonConverter(typeof(WireEnumConverter))] -public enum ChatTurnMatchKind -{ - [WireValue("request")] - Request, - [WireValue("response")] - Response, -} - /// Native filesystem path grammar used by a host environment. [JsonConverter(typeof(WireEnumConverter))] public enum PathStyle @@ -1873,7 +1863,7 @@ public sealed record ChatTurnIndexEntry } /// Lists every visible non-system prompt in retained turns, oldest first, across pages. -/// Requires `ChatState.historyNavigation`. Does not load turns into state. +/// Requires `ChatState.historyBrowsing`. Does not load turns into state. public sealed record ListChatTurnsParams { /// Chat URI. @@ -1907,7 +1897,7 @@ public sealed record ListChatTurnsResult /// Reads a byte-bounded window of completed turns directly, without changing /// any subscription or fetching intervening pages. Requires -/// `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). +/// `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). public sealed record ReadChatTurnsParams { /// Chat URI. @@ -1944,68 +1934,6 @@ public sealed record ReadChatTurnsResult public bool HasAfter { get; init; } } -/// A match locator, not a snippet, text offset, or response-part identifier. -public sealed record ChatTurnMatch -{ - public required string TurnId { get; init; } - - public ChatTurnMatchKind Kind { get; init; } - - /// Zero-based index of this nonempty match in forward text order on this - /// side of the turn, for the same query and flags. - public long Occurrence { get; init; } -} - -/// Searches visible request and response text in retained completed turns. -/// Returns match locators newest first, independently of the subscription. -/// Requires `ChatState.historyNavigation`. -public sealed record SearchChatTurnsParams -{ - /// Chat URI. - 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; } - - /// Maximum matches in the page; defaults to 100. The host may return fewer. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public long? Limit { get; init; } - - /// Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? Cursor { get; init; } - - /// Nonempty literal text, or a pattern when `isRegex` is true. - public required string Query { get; init; } - - /// Case-sensitive matching; defaults to false. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public bool? MatchCase { get; init; } - - /// Require whole-word matches; defaults to false. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public bool? WholeWord { get; init; } - - /// Treat the query as a regular expression; defaults to false. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public bool? IsRegex { get; init; } -} - -/// One page of match locators, which may end within a turn or side. -public sealed record SearchChatTurnsResult -{ - /// Resume after the last result or scanned position. A bounded scan may - /// return no matches with an advancing cursor; only absence means done. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? NextCursor { get; init; } - - /// Match locators in reverse transcript order. - public required List Items { get; init; } -} - /// Stop receiving updates for a channel. public sealed record UnsubscribeParams { diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index ac3caded7..eb3f220ca 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -137,6 +137,7 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ChatDeltaAction))] [JsonSerializable(typeof(ChatDraftChangedAction))] [JsonSerializable(typeof(ChatErrorAction))] +[JsonSerializable(typeof(ChatHistoryBrowsingCapability))] [JsonSerializable(typeof(ChatInputAnswer))] [JsonSerializable(typeof(ChatInputAnswerChangedAction))] [JsonSerializable(typeof(ChatInputAnswered))] @@ -198,8 +199,6 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ChatTurnCancelledAction))] [JsonSerializable(typeof(ChatTurnCompleteAction))] [JsonSerializable(typeof(ChatTurnIndexEntry))] -[JsonSerializable(typeof(ChatTurnMatch))] -[JsonSerializable(typeof(ChatTurnMatchKind))] [JsonSerializable(typeof(ChatTurnReadDirection))] [JsonSerializable(typeof(ChatTurnResumeAction))] [JsonSerializable(typeof(ChatTurnsLoadedAction))] @@ -371,8 +370,6 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RuleCustomization))] [JsonSerializable(typeof(RunAutomationParams))] [JsonSerializable(typeof(RunAutomationResult))] -[JsonSerializable(typeof(SearchChatTurnsParams))] -[JsonSerializable(typeof(SearchChatTurnsResult))] [JsonSerializable(typeof(SessionActiveClient))] [JsonSerializable(typeof(SessionActiveClientRemovedAction))] [JsonSerializable(typeof(SessionActiveClientSetAction))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 51d768ab4..e697d0a0b 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2173,6 +2173,11 @@ public sealed record MultipleChatsCapability public bool? SideChat { get; init; } } +/// Presence advertises `listChatTurns` and `readChatTurns` for this chat. +public sealed record ChatHistoryBrowsingCapability +{ +} + /// Options for the {@link AgentCapabilities.multipleWorkingDirectories} capability. public sealed record MultipleWorkingDirectoriesCapability { @@ -2643,11 +2648,9 @@ public sealed class ChatState /// Completed turns public required List Turns { get; set; } - /// When true, the host supports `listChatTurns`, `readChatTurns`, and - /// `searchChatTurns` over this chat's retained history, independently of - /// the subscription window. Absent or false means unsupported. + /// Browse retained history independently of the subscription window. Absent when unsupported. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public bool? HistoryNavigation { get; set; } + public ChatHistoryBrowsingCapability? HistoryBrowsing { get; set; } /// Cursor for loading older completed turns into this chat state. /// diff --git a/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs b/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs index b4bbb9193..4937291ba 100644 --- a/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs +++ b/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs @@ -174,10 +174,6 @@ private static (object decoded, string reencoded) DecodeAndReencode(string type, return Wrap(Ser.Deserialize(inputJson)); case "ReadChatTurnsResult": return Wrap(Ser.Deserialize(inputJson)); - case "SearchChatTurnsParams": - return Wrap(Ser.Deserialize(inputJson)); - case "SearchChatTurnsResult": - return Wrap(Ser.Deserialize(inputJson)); case "Snapshot": return Wrap(Ser.Deserialize(inputJson)); case "SubscribeParams": diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index d49cff660..a1cffbd9e 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -55,14 +55,6 @@ const ( ChatTurnReadDirectionAfter ChatTurnReadDirection = "after" ) -// The searchable side of a completed turn. -type ChatTurnMatchKind string - -const ( - ChatTurnMatchKindRequest ChatTurnMatchKind = "request" - ChatTurnMatchKindResponse ChatTurnMatchKind = "response" -) - // Native filesystem path grammar used by a host environment. type PathStyle string @@ -1340,7 +1332,7 @@ type ChatTurnIndexEntry struct { } // Lists every visible non-system prompt in retained turns, oldest first, across pages. -// Requires `ChatState.historyNavigation`. Does not load turns into state. +// Requires `ChatState.historyBrowsing`. Does not load turns into state. type ListChatTurnsParams struct { // Channel URI this command targets. Channel URI `json:"channel"` @@ -1370,7 +1362,7 @@ type ListChatTurnsResult struct { // Reads a byte-bounded window of completed turns directly, without changing // any subscription or fetching intervening pages. Requires -// `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). +// `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). type ReadChatTurnsParams struct { // Channel URI this command targets. Channel URI `json:"channel"` @@ -1395,53 +1387,6 @@ type ReadChatTurnsResult struct { HasAfter bool `json:"hasAfter"` } -// A match locator, not a snippet, text offset, or response-part identifier. -type ChatTurnMatch struct { - TurnId string `json:"turnId"` - Kind ChatTurnMatchKind `json:"kind"` - // Zero-based index of this nonempty match in forward text order on this - // side of the turn, for the same query and flags. - Occurrence int64 `json:"occurrence"` -} - -// Searches visible request and response text in retained completed turns. -// Returns match locators newest first, independently of the subscription. -// Requires `ChatState.historyNavigation`. -type SearchChatTurnsParams 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"` - // Maximum number of entries to return in this page. The server SHOULD respect - // this bound but MAY return fewer entries and MAY impose its own upper cap. - // Omit to let the server choose the page size. - Limit *int64 `json:"limit,omitempty"` - // Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. - // Omit to fetch the first page. Cursors are server-defined and MUST be treated - // as opaque — do not parse, modify, or persist them across connections. An - // unrecognised cursor SHOULD be rejected with an `InvalidParams` error. - Cursor *string `json:"cursor,omitempty"` - // Nonempty literal text, or a pattern when `isRegex` is true. - Query string `json:"query"` - // Case-sensitive matching; defaults to false. - MatchCase *bool `json:"matchCase,omitempty"` - // Require whole-word matches; defaults to false. - WholeWord *bool `json:"wholeWord,omitempty"` - // Treat the query as a regular expression; defaults to false. - IsRegex *bool `json:"isRegex,omitempty"` -} - -// One page of match locators, which may end within a turn or side. -type SearchChatTurnsResult struct { - // Opaque cursor for the next page. Present when more entries exist beyond the - // returned page; absent signals the end of the collection. Pass it back as - // {@link PaginatedParams.cursor} to fetch the following page. - NextCursor *string `json:"nextCursor,omitempty"` - // Match locators in reverse transcript order. - Items []ChatTurnMatch `json:"items"` -} - // Stop receiving updates for a channel. type UnsubscribeParams struct { // Channel URI to unsubscribe from diff --git a/clients/go/ahptypes/roundtrip_fixture_test.go b/clients/go/ahptypes/roundtrip_fixture_test.go index c6ec5ea0c..9d470a215 100644 --- a/clients/go/ahptypes/roundtrip_fixture_test.go +++ b/clients/go/ahptypes/roundtrip_fixture_test.go @@ -278,14 +278,6 @@ func decodeAndReencode(t *testing.T, name, typ, inputJSON string) string { var v ReadChatTurnsResult dec(&v) return enc(&v) - case "SearchChatTurnsParams": - var v SearchChatTurnsParams - dec(&v) - return enc(&v) - case "SearchChatTurnsResult": - var v SearchChatTurnsResult - dec(&v) - return enc(&v) case "ChatSource": var v ChatSource dec(&v) diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 237ac6688..e1292043e 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -876,6 +876,10 @@ type MultipleChatsCapability struct { SideChat *bool `json:"sideChat,omitempty"` } +// Presence advertises `listChatTurns` and `readChatTurns` for this chat. +type ChatHistoryBrowsingCapability struct { +} + // Options for the {@link AgentCapabilities.multipleWorkingDirectories} capability. type MultipleWorkingDirectoriesCapability struct { // The agent's **first** working directory (index `0` of @@ -1522,10 +1526,8 @@ type ChatState struct { Config *ChatConfigState `json:"config,omitempty"` // Completed turns Turns []Turn `json:"turns"` - // When true, the host supports `listChatTurns`, `readChatTurns`, and - // `searchChatTurns` over this chat's retained history, independently of - // the subscription window. Absent or false means unsupported. - HistoryNavigation *bool `json:"historyNavigation,omitempty"` + // Browse retained history independently of the subscription window. Absent when unsupported. + HistoryBrowsing *ChatHistoryBrowsingCapability `json:"historyBrowsing,omitempty"` // Cursor for loading older completed turns into this chat state. // // Presence means `turns` is a tail window and more historical turns are 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 abea80936..096f2e94f 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 @@ -111,17 +111,6 @@ enum class ChatTurnReadDirection { AFTER } -/** - * The searchable side of a completed turn. - */ -@Serializable -enum class ChatTurnMatchKind { - @SerialName("request") - REQUEST, - @SerialName("response") - RESPONSE -} - /** * Native filesystem path grammar used by a host environment. */ @@ -1697,74 +1686,6 @@ data class ReadChatTurnsResult( val hasAfter: Boolean ) -@Serializable -data class ChatTurnMatch( - val turnId: String, - val kind: ChatTurnMatchKind, - /** - * Zero-based index of this nonempty match in forward text order on this - * side of the turn, for the same query and flags. - */ - val occurrence: Long -) - -@Serializable -data class SearchChatTurnsParams( - /** - * 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, - /** - * Maximum number of entries to return in this page. The server SHOULD respect - * this bound but MAY return fewer entries and MAY impose its own upper cap. - * Omit to let the server choose the page size. - */ - val limit: Long? = null, - /** - * Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. - * Omit to fetch the first page. Cursors are server-defined and MUST be treated - * as opaque — do not parse, modify, or persist them across connections. An - * unrecognised cursor SHOULD be rejected with an `InvalidParams` error. - */ - val cursor: String? = null, - /** - * Nonempty literal text, or a pattern when `isRegex` is true. - */ - val query: String, - /** - * Case-sensitive matching; defaults to false. - */ - val matchCase: Boolean? = null, - /** - * Require whole-word matches; defaults to false. - */ - val wholeWord: Boolean? = null, - /** - * Treat the query as a regular expression; defaults to false. - */ - val isRegex: Boolean? = null -) - -@Serializable -data class SearchChatTurnsResult( - /** - * Opaque cursor for the next page. Present when more entries exist beyond the - * returned page; absent signals the end of the collection. Pass it back as - * {@link PaginatedParams.cursor} to fetch the following page. - */ - val nextCursor: String? = null, - /** - * Match locators in reverse transcript order. - */ - val items: List -) - @Serializable data class UnsubscribeParams( /** diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt index 9aa4e5c3f..d3cf31552 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Messages.generated.kt @@ -137,9 +137,6 @@ object AhpCommands { fun readChatTurns(id: Long, params: ReadChatTurnsParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "readChatTurns", params = params) - fun searchChatTurns(id: Long, params: SearchChatTurnsParams): JsonRpcRequest = - JsonRpcRequest(id = id, method = "searchChatTurns", params = params) - fun authenticate(id: Long, params: AuthenticateParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "authenticate", params = params) 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 c5f0fcb29..dd0bf54b3 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 @@ -1644,6 +1644,9 @@ data class MultipleChatsCapability( val sideChat: Boolean? = null ) +@Serializable +class ChatHistoryBrowsingCapability + @Serializable data class MultipleWorkingDirectoriesCapability( /** @@ -1984,11 +1987,9 @@ data class ChatState( */ val turns: List, /** - * When true, the host supports `listChatTurns`, `readChatTurns`, and - * `searchChatTurns` over this chat's retained history, independently of - * the subscription window. Absent or false means unsupported. + * Browse retained history independently of the subscription window. Absent when unsupported. */ - val historyNavigation: Boolean? = null, + val historyBrowsing: ChatHistoryBrowsingCapability? = null, /** * Cursor for loading older completed turns into this chat state. * diff --git a/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt b/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt index 047e00640..f36aa4712 100644 --- a/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt +++ b/clients/kotlin/src/test/kotlin/com/microsoft/agenthostprotocol/RoundTripCorpusTest.kt @@ -37,8 +37,6 @@ import com.microsoft.agenthostprotocol.generated.ListChatTurnsParams import com.microsoft.agenthostprotocol.generated.ListChatTurnsResult import com.microsoft.agenthostprotocol.generated.ReadChatTurnsParams import com.microsoft.agenthostprotocol.generated.ReadChatTurnsResult -import com.microsoft.agenthostprotocol.generated.SearchChatTurnsParams -import com.microsoft.agenthostprotocol.generated.SearchChatTurnsResult import com.microsoft.agenthostprotocol.generated.Customization import com.microsoft.agenthostprotocol.generated.Implementation import com.microsoft.agenthostprotocol.generated.InitializeResult @@ -278,8 +276,6 @@ class RoundTripCorpusTest { "ListChatTurnsResult" -> rt(ListChatTurnsResult.serializer()) "ReadChatTurnsParams" -> rt(ReadChatTurnsParams.serializer()) "ReadChatTurnsResult" -> rt(ReadChatTurnsResult.serializer()) - "SearchChatTurnsParams" -> rt(SearchChatTurnsParams.serializer()) - "SearchChatTurnsResult" -> rt(SearchChatTurnsResult.serializer()) "ChatSource" -> rt(ChatSource.serializer()) "Snapshot" -> rt(Snapshot.serializer()) "SubscribeParams" -> rt(SubscribeParams.serializer()) diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index 9e81d081a..f6fa29a8c 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -123,15 +123,6 @@ pub enum ChatTurnReadDirection { After, } -/// The searchable side of a completed turn. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum ChatTurnMatchKind { - #[serde(rename = "request")] - Request, - #[serde(rename = "response")] - Response, -} - /// Native filesystem path grammar used by a host environment. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum PathStyle { @@ -1735,7 +1726,7 @@ pub struct ChatTurnIndexEntry { } /// Lists every visible non-system prompt in retained turns, oldest first, across pages. -/// Requires `ChatState.historyNavigation`. Does not load turns into state. +/// Requires `ChatState.historyBrowsing`. Does not load turns into state. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListChatTurnsParams { @@ -1773,7 +1764,7 @@ pub struct ListChatTurnsResult { /// Reads a byte-bounded window of completed turns directly, without changing /// any subscription or fetching intervening pages. Requires -/// `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). +/// `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReadChatTurnsParams { @@ -1805,66 +1796,6 @@ pub struct ReadChatTurnsResult { pub has_after: bool, } -/// A match locator, not a snippet, text offset, or response-part identifier. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ChatTurnMatch { - pub turn_id: String, - pub kind: ChatTurnMatchKind, - /// Zero-based index of this nonempty match in forward text order on this - /// side of the turn, for the same query and flags. - pub occurrence: i64, -} - -/// Searches visible request and response text in retained completed turns. -/// Returns match locators newest first, independently of the subscription. -/// Requires `ChatState.historyNavigation`. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SearchChatTurnsParams { - /// 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, - /// Maximum number of entries to return in this page. The server SHOULD respect - /// this bound but MAY return fewer entries and MAY impose its own upper cap. - /// Omit to let the server choose the page size. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub limit: Option, - /// Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. - /// Omit to fetch the first page. Cursors are server-defined and MUST be treated - /// as opaque — do not parse, modify, or persist them across connections. An - /// unrecognised cursor SHOULD be rejected with an `InvalidParams` error. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cursor: Option, - /// Nonempty literal text, or a pattern when `isRegex` is true. - pub query: String, - /// Case-sensitive matching; defaults to false. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub match_case: Option, - /// Require whole-word matches; defaults to false. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub whole_word: Option, - /// Treat the query as a regular expression; defaults to false. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub is_regex: Option, -} - -/// One page of match locators, which may end within a turn or side. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SearchChatTurnsResult { - /// Opaque cursor for the next page. Present when more entries exist beyond the - /// returned page; absent signals the end of the collection. Pass it back as - /// {@link PaginatedParams.cursor} to fetch the following page. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub next_cursor: Option, - /// Match locators in reverse transcript order. - pub items: Vec, -} - /// Stop receiving updates for a channel. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 38545a20d..d22918829 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1967,6 +1967,11 @@ pub struct MultipleChatsCapability { pub side_chat: Option, } +/// Presence advertises `listChatTurns` and `readChatTurns` for this chat. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatHistoryBrowsingCapability {} + /// Options for the {@link AgentCapabilities.multipleWorkingDirectories} capability. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] @@ -2274,11 +2279,9 @@ pub struct ChatState { pub config: Option, /// Completed turns pub turns: Vec, - /// When true, the host supports `listChatTurns`, `readChatTurns`, and - /// `searchChatTurns` over this chat's retained history, independently of - /// the subscription window. Absent or false means unsupported. + /// Browse retained history independently of the subscription window. Absent when unsupported. #[serde(default, skip_serializing_if = "Option::is_none")] - pub history_navigation: Option, + pub history_browsing: Option, /// Cursor for loading older completed turns into this chat state. /// /// Presence means `turns` is a tail window and more historical turns are diff --git a/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs b/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs index 3622963a5..432bb94e1 100644 --- a/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs +++ b/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs @@ -32,8 +32,7 @@ use ahp_types::{ AuthenticateParams, ChangesetOperationTarget, ChatSource, CreateChatParams, CreateTcpConnectionParams, Implementation, InitializeResult, ListChatTurnsParams, ListChatTurnsResult, ReadChatTurnsParams, ReadChatTurnsResult, ReconnectParams, - ReconnectResult, ResourceReadParams, ResourceReadResult, SearchChatTurnsParams, - SearchChatTurnsResult, SubscribeParams, SubscribeResult, + ReconnectResult, ResourceReadParams, ResourceReadResult, SubscribeParams, SubscribeResult, }, common::StringOrMarkdown, messages::JsonRpcMessage, @@ -237,8 +236,6 @@ fn decode_and_reencode(file: &str, type_name: &str, input_json: &str) -> Result< "ListChatTurnsResult" => round_trip!(ListChatTurnsResult), "ReadChatTurnsParams" => round_trip!(ReadChatTurnsParams), "ReadChatTurnsResult" => round_trip!(ReadChatTurnsResult), - "SearchChatTurnsParams" => round_trip!(SearchChatTurnsParams), - "SearchChatTurnsResult" => round_trip!(SearchChatTurnsResult), "ChatSource" => round_trip!(ChatSource), "Snapshot" => round_trip!(Snapshot), "SubscribeParams" => round_trip!(SubscribeParams), diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index a58f28ea8..36b37962a 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -2388,7 +2388,7 @@ mod tests { canvases: None, config: None, turns: Vec::new(), - history_navigation: None, + history_browsing: None, turns_next_cursor: None, active_turn: None, steering_message: None, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 072374acd..5363caa10 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -78,12 +78,6 @@ public enum ChatTurnReadDirection: String, Codable, Sendable { case after = "after" } -/// The searchable side of a completed turn. -public enum ChatTurnMatchKind: String, Codable, Sendable { - case request = "request" - case response = "response" -} - /// Native filesystem path grammar used by a host environment. public enum PathStyle: String, Codable, Sendable { case posix = "posix" @@ -2050,97 +2044,6 @@ public struct ReadChatTurnsResult: Codable, Sendable, Equatable { } } -public struct ChatTurnMatch: Codable, Sendable, Equatable { - public var turnId: String - public var kind: ChatTurnMatchKind - /// Zero-based index of this nonempty match in forward text order on this - /// side of the turn, for the same query and flags. - public var occurrence: Int - - public init( - turnId: String, - kind: ChatTurnMatchKind, - occurrence: Int - ) { - self.turnId = turnId - self.kind = kind - self.occurrence = occurrence - } -} - -public struct SearchChatTurnsParams: 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]? - /// Maximum number of entries to return in this page. The server SHOULD respect - /// this bound but MAY return fewer entries and MAY impose its own upper cap. - /// Omit to let the server choose the page size. - public var limit: Int? - /// Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}. - /// Omit to fetch the first page. Cursors are server-defined and MUST be treated - /// as opaque — do not parse, modify, or persist them across connections. An - /// unrecognised cursor SHOULD be rejected with an `InvalidParams` error. - public var cursor: String? - /// Nonempty literal text, or a pattern when `isRegex` is true. - public var query: String - /// Case-sensitive matching; defaults to false. - public var matchCase: Bool? - /// Require whole-word matches; defaults to false. - public var wholeWord: Bool? - /// Treat the query as a regular expression; defaults to false. - public var isRegex: Bool? - - enum CodingKeys: String, CodingKey { - case channel - case meta = "_meta" - case limit - case cursor - case query - case matchCase - case wholeWord - case isRegex - } - - public init( - channel: String, - meta: [String: AnyCodable]? = nil, - limit: Int? = nil, - cursor: String? = nil, - query: String, - matchCase: Bool? = nil, - wholeWord: Bool? = nil, - isRegex: Bool? = nil - ) { - self.channel = channel - self.meta = meta - self.limit = limit - self.cursor = cursor - self.query = query - self.matchCase = matchCase - self.wholeWord = wholeWord - self.isRegex = isRegex - } -} - -public struct SearchChatTurnsResult: Codable, Sendable, Equatable { - /// Opaque cursor for the next page. Present when more entries exist beyond the - /// returned page; absent signals the end of the collection. Pass it back as - /// {@link PaginatedParams.cursor} to fetch the following page. - public var nextCursor: String? - /// Match locators in reverse transcript order. - public var items: [ChatTurnMatch] - - public init( - nextCursor: String? = nil, - items: [ChatTurnMatch] - ) { - self.nextCursor = nextCursor - self.items = items - } -} - public struct UnsubscribeParams: Codable, Sendable, Equatable { /// Channel URI to unsubscribe from public var channel: String @@ -3190,11 +3093,6 @@ extension ReadChatTurnsParams: AHPCommand { public static let method = "readChatTurns" } -extension SearchChatTurnsParams: AHPCommand { - public typealias Result = SearchChatTurnsResult - public static let method = "searchChatTurns" -} - extension CreateTerminalParams: AHPCommand { public typealias Result = AHPNullResult public static let method = "createTerminal" diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift index 28cd20c24..2afb27e9d 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift @@ -141,10 +141,6 @@ public enum AHPCommands { JsonRpcRequest(id: id, method: "readChatTurns", params: params) } - public static func searchChatTurns(id: Int, params: SearchChatTurnsParams) -> JsonRpcRequest { - JsonRpcRequest(id: id, method: "searchChatTurns", params: params) - } - public static func authenticate(id: Int, params: AuthenticateParams) -> JsonRpcRequest { JsonRpcRequest(id: id, method: "authenticate", params: params) } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 17b8bbf6d..dd461c9be 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1641,6 +1641,14 @@ public struct MultipleChatsCapability: Codable, Sendable, Equatable { } } +public struct ChatHistoryBrowsingCapability: Codable, Sendable, Equatable { + + public init( + + ) { + } +} + public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable { /// The agent's **first** working directory (index `0` of /// {@link CreateSessionParams.workingDirectories}) is an immutable primary: @@ -2040,10 +2048,8 @@ public struct ChatState: Codable, Sendable, Equatable { public var config: ChatConfigState? /// Completed turns public var turns: [Turn] - /// When true, the host supports `listChatTurns`, `readChatTurns`, and - /// `searchChatTurns` over this chat's retained history, independently of - /// the subscription window. Absent or false means unsupported. - public var historyNavigation: Bool? + /// Browse retained history independently of the subscription window. Absent when unsupported. + public var historyBrowsing: ChatHistoryBrowsingCapability? /// Cursor for loading older completed turns into this chat state. /// /// Presence means `turns` is a tail window and more historical turns are @@ -2094,7 +2100,7 @@ public struct ChatState: Codable, Sendable, Equatable { case canvases case config case turns - case historyNavigation + case historyBrowsing case turnsNextCursor case activeTurn case steeringMessage @@ -2120,7 +2126,7 @@ public struct ChatState: Codable, Sendable, Equatable { canvases: [CanvasReference]? = nil, config: ChatConfigState? = nil, turns: [Turn], - historyNavigation: Bool? = nil, + historyBrowsing: ChatHistoryBrowsingCapability? = nil, turnsNextCursor: String? = nil, activeTurn: ActiveTurn? = nil, steeringMessage: PendingMessage? = nil, @@ -2144,7 +2150,7 @@ public struct ChatState: Codable, Sendable, Equatable { self.canvases = canvases self.config = config self.turns = turns - self.historyNavigation = historyNavigation + self.historyBrowsing = historyBrowsing self.turnsNextCursor = turnsNextCursor self.activeTurn = activeTurn self.steeringMessage = steeringMessage diff --git a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift index 6a3573078..9713a69b7 100644 --- a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift +++ b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift @@ -198,10 +198,6 @@ final class TypesRoundTripFixtureTests: XCTestCase { return try reencode(dec.decode(ReadChatTurnsParams.self, from: inputData)) case "ReadChatTurnsResult": return try reencode(dec.decode(ReadChatTurnsResult.self, from: inputData)) - case "SearchChatTurnsParams": - return try reencode(dec.decode(SearchChatTurnsParams.self, from: inputData)) - case "SearchChatTurnsResult": - return try reencode(dec.decode(SearchChatTurnsResult.self, from: inputData)) case "ChatSource": return try reencode(dec.decode(ChatSource.self, from: inputData)) case "Snapshot": diff --git a/clients/typescript/test/types-round-trip.test.ts b/clients/typescript/test/types-round-trip.test.ts index 8a1bb9cb2..6ef5ff2c9 100644 --- a/clients/typescript/test/types-round-trip.test.ts +++ b/clients/typescript/test/types-round-trip.test.ts @@ -68,7 +68,7 @@ import type { TcpDataParams, TcpEofParams, TcpResetParams } from '../src/types/c import type { CreateTcpConnectionParams } from '../src/types/channels-tcp/commands.js'; import type { ChatSource, CreateChatParams, ListChatTurnsParams, ListChatTurnsResult, ReadChatTurnsParams, - ReadChatTurnsResult, SearchChatTurnsParams, SearchChatTurnsResult, + ReadChatTurnsResult, } from '../src/types/channels-chat/commands.js'; // ─── Fixture directory ─────────────────────────────────────────────────────── @@ -257,8 +257,6 @@ function bindToType(file: string, type: string, parsed: unknown): void { case 'ListChatTurnsResult': void (parsed as ListChatTurnsResult); break; case 'ReadChatTurnsParams': void (parsed as ReadChatTurnsParams); break; case 'ReadChatTurnsResult': void (parsed as ReadChatTurnsResult); break; - case 'SearchChatTurnsParams': void (parsed as SearchChatTurnsParams); break; - case 'SearchChatTurnsResult': void (parsed as SearchChatTurnsResult); break; case 'ChatSource': void (parsed as ChatSource); break; case 'Snapshot': void (parsed as Snapshot); break; case 'SubscribeParams': void (parsed as SubscribeParams); break; diff --git a/docs/.changes/20261119-chat-history-navigation.json b/docs/.changes/20261119-chat-history-navigation.json index 551e5bf93..c1d8d48ce 100644 --- a/docs/.changes/20261119-chat-history-navigation.json +++ b/docs/.changes/20261119-chat-history-navigation.json @@ -1,4 +1,4 @@ { "type": "added", - "message": "Optional `ChatState.historyNavigation` advertises `listChatTurns`, `readChatTurns`, and `searchChatTurns` for browsing retained history without loading the intervening transcript into a subscription." + "message": "Optional `ChatState.historyBrowsing` advertises `listChatTurns` and `readChatTurns` for browsing retained history without loading intervening turns into a subscription." } diff --git a/docs/specification/chat-channel.md b/docs/specification/chat-channel.md index be6162a91..87279cc83 100644 --- a/docs/specification/chat-channel.md +++ b/docs/specification/chat-channel.md @@ -52,9 +52,9 @@ older turn). ### Read-only history navigation -When `ChatState.historyNavigation` is `true`, the host supports **all three** commands below on that chat URI. Absent or `false` means unsupported. A client discovers this from the snapshot, including after reconnect; it MUST NOT infer support from the protocol version or `turnsNextCursor`. +When `ChatState.historyBrowsing` is present (for example, `"historyBrowsing": {}`), the host supports both `listChatTurns` and `readChatTurns` on that chat URI. Absence means unsupported. A client discovers support from the snapshot, including after reconnect; it MUST NOT infer support from the protocol version or `turnsNextCursor`. -These are reads of the host's retained, completed transcript, including turns outside the subscription window. “Completed” means a `Turn` with any terminal state, not just `complete`. Drafts, pending messages and `activeTurn` are not history. Apply the same access checks and visibility rules as for reading the chat. Each result is private to the caller. The commands MUST NOT create or expand a subscription, fetch the gap, dispatch `chat/turnsLoaded`, change `turnsNextCursor`, or mark the chat read. Queries, selected matches, sidebar position and viewport are client-local, not replayable chat state. +These are reads of the host's retained, completed transcript, including turns outside the subscription window. “Completed” means a `Turn` with any terminal state, not just `complete`. Drafts, pending messages and `activeTurn` are not history. Apply the same access checks and visibility rules as for reading the chat. Each result is private to the caller. The commands MUST NOT create or expand a subscription, fetch the gap, dispatch `chat/turnsLoaded`, change `turnsNextCursor`, or mark the chat read. The reader's position is client-local, not replayable chat state. #### List the prompt index @@ -76,24 +76,13 @@ These are reads of the host's retained, completed transcript, including turns ou Hosts MUST bound both the turn count and the serialized response size. Target at most 4 MiB of UTF-8 encoded JSON per result; a smaller budget is permitted. If the required turn (the anchor for `around`, the nearest adjacent turn for `before`/`after`) alone exceeds this target, the host may return it alone **only** within a finite, transport-safe hard byte limit. If it cannot fit, return `InternalError` (`-32603`) with an explanatory message. Do not truncate a turn, skip an oversized immediate neighbor, or return an empty page that cannot advance. -#### Search visible text - -`searchChatTurns` returns `{ turnId, kind, occurrence }` locators, not snippets or offsets. Search only text that can be revealed to the caller: - -- `request`: the full visible initiating `Message.text`, not its index preview. Exclude hidden requests and system notifications. -- `response`: visible text of `markdown` response parts in stream order. Match their displayed text (for example, a link's label, not its destination or Markdown delimiters), separately per part. Matches do not cross parts. Do not search reasoning, tool names, calls, arguments or output, attachments, content references, other response-part kinds, metadata, or raw provider transcripts. - -Omitted `matchCase`, `wholeWord` and `isRegex` each mean `false`: the default query is literal, case-insensitive, and may match inside words. A regex uses ECMAScript Unicode matching, case-insensitive unless `matchCase` is true. Whole-word mode applies ECMAScript word boundaries at word ends. Match left to right without overlap, ignoring zero-width matches. A host SHOULD bound regex execution; reject an invalid or over-budget pattern rather than report a partial scan as exhaustive. - -Number nonempty matches **from zero in forward text order**, restarting for each side of each turn and continuing across the visible Markdown parts of the response. Return turns **newest first**; within a turn return response before request and occurrences in descending order. For example, searching `map` in a request `map` and a response `map then map` yields `response:1`, `response:0`, `request:0`. A page may end between these matches. To reveal a match outside the subscription, read `around` its turn ID and locate the same forward occurrence on that side. The client need not load the intervening transcript. - #### Continuation and errors -For list and search, omit `cursor` for the first page; the default `limit` is 100 **entries or matches**. For all three commands `limit` must be a positive integer; hosts may cap it and return fewer. Echo `nextCursor` unchanged for the following page. Its absence means the traversal is complete. A bounded search may return no matches yet with an advancing `nextCursor`; this is not a final “no matches.” +For `listChatTurns`, omit `cursor` for the first page; the default `limit` is 100 entries. Echo `nextCursor` unchanged for the following page. Its absence means the traversal is complete. For both commands `limit` must be a positive integer; hosts may cap it and return fewer. -Cursors are opaque and scoped to the connection, method, chat, and (for search) the query and effective flags. They are not `turnsNextCursor` values. Following a chain MUST enumerate the first page's ordered history without duplicates or omissions, even when a page ends within a turn. New completions do not join a traversal already in progress. A retry of the same cursor resumes from the same boundary or fails explicitly. If a change to retained history or cursor expiry prevents a consistent continuation, return `Conflict` (`-32011`); the client discards that traversal and restarts without a cursor. Discard cursors on reconnect. +Cursors are opaque and scoped to the connection, method, and chat. They are not `turnsNextCursor` values. Following a chain MUST enumerate the first page's ordered index without duplicates or omissions. New completions do not join a traversal already in progress. A retry of the same cursor resumes from the same boundary or fails explicitly. If a change to retained history or cursor expiry prevents a consistent continuation, return `Conflict` (`-32011`); the client discards that traversal and restarts without a cursor. Discard cursors on reconnect. -Return `InvalidParams` (`-32602`) for malformed, unrecognized or mis-scoped cursors, invalid direction or limit, empty query, or an invalid or over-budget regex. An unavailable command, including for a chat that does not advertise `historyNavigation`, returns `MethodNotFound` (`-32601`); a host that implements the command returns `NotFound` (`-32008`) for an unknown chat. Unsupported is not an empty index or a successful search. Clients without support can still use their subscribed state and the existing explicit `fetchTurns` backfill operation. +Return `InvalidParams` (`-32602`) for malformed, unrecognized or mis-scoped cursors, or an invalid direction or limit. An unavailable command, including for a chat that does not advertise `historyBrowsing`, returns `MethodNotFound` (`-32601`); a host that implements the command returns `NotFound` (`-32008`) for an unknown chat. Unsupported is not an empty index. Clients without support can still use their subscribed state and the existing explicit `fetchTurns` backfill operation. ### Reasoning timing @@ -436,7 +425,6 @@ This section lists wire methods that are interpreted in the context of a chat UR | `fetchTurns` | request | Ask the host to load older historical turns into this chat state. | | `listChatTurns` | request | Page the retained prompt index without loading turns into state. | | `readChatTurns` | request | Read a bounded window around, before, or after a retained turn. | -| `searchChatTurns` | request | Find occurrences in visible retained request and response text. | | `completions` | request | Chat-scoped inline completions (e.g. user-message mentions). | `createChat` is dispatched against the owning session URI (`params.channel = "ahp-session:/"`). diff --git a/docs/specification/subscriptions.md b/docs/specification/subscriptions.md index 7c3f5a452..58405cfce 100644 --- a/docs/specification/subscriptions.md +++ b/docs/specification/subscriptions.md @@ -53,7 +53,7 @@ route any message using only its `method` and `params.channel`. | `resourceRead`, `resourceWrite`, `resourceList`, `resourceCopy`, `resourceDelete`, `resourceMove`, `resourceResolve`, `resourceMkdir`, `resourceRequest`, `createResourceWatch` | `ahp-root://`. Either peer can send these requests. | | `runAutomation`, `fetchAutomationRuns` | `ahp-automations://` | | `createSession`, `disposeSession`, `createChat` | The session URI. For `createSession`, this is the URI of the new session. | -| `fetchTurns`, `listChatTurns`, `readChatTurns`, `searchChatTurns`, `completions`, `disposeChat` | The chat URI | +| `fetchTurns`, `listChatTurns`, `readChatTurns`, `completions`, `disposeChat` | The chat URI | | `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 | diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 4bf20c801..bbcad23b5 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -5236,6 +5236,11 @@ "kind" ] }, + "ChatHistoryBrowsingCapability": { + "type": "object", + "description": "Presence advertises `listChatTurns` and `readChatTurns` for this chat.", + "properties": {} + }, "ChatState": { "type": "object", "description": "Full state for a single chat, loaded when a client subscribes to the chat's\nURI.\n\nThe lightweight catalog representation of a chat is {@link ChatSummary},\ncarried in {@link SessionState.chats | `SessionState.chats`}. `ChatState`\n**denormalizes** every {@link ChatSummary} field directly onto itself so\nsubscribers receive one flat object instead of having to merge a nested\n`summary` sub-object. Producers MUST keep the two representations\nconsistent: any change to the inlined fields below SHOULD also be\nannounced on the parent session via the matching\n{@link SessionChatUpdatedAction | `session/chatUpdated`} action.", @@ -5319,9 +5324,9 @@ }, "description": "Completed turns" }, - "historyNavigation": { - "type": "boolean", - "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when unsupported." }, "turnsNextCursor": { "type": "string", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index d63e6f29a..a81423d1b 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1657,7 +1657,7 @@ }, "ListChatTurnsParams": { "type": "object", - "description": "Lists every visible non-system prompt in retained turns, oldest first, across pages.\nRequires `ChatState.historyNavigation`. Does not load turns into state.", + "description": "Lists every visible non-system prompt in retained turns, oldest first, across pages.\nRequires `ChatState.historyBrowsing`. Does not load turns into state.", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -1704,7 +1704,7 @@ }, "ReadChatTurnsParams": { "type": "object", - "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008).", + "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008).", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -1760,93 +1760,6 @@ "hasAfter" ] }, - "ChatTurnMatch": { - "type": "object", - "description": "A match locator, not a snippet, text offset, or response-part identifier.", - "properties": { - "turnId": { - "type": "string" - }, - "kind": { - "$ref": "#/$defs/ChatTurnMatchKind" - }, - "occurrence": { - "type": "integer", - "description": "Zero-based index of this nonempty match in forward text order on this\nside of the turn, for the same query and flags.", - "minimum": 0 - } - }, - "required": [ - "turnId", - "kind", - "occurrence" - ] - }, - "SearchChatTurnsParams": { - "type": "object", - "description": "Searches visible request and response text in retained completed turns.\nReturns match locators newest first, independently of the subscription.\nRequires `ChatState.historyNavigation`.", - "properties": { - "channel": { - "$ref": "#/$defs/URI", - "description": "Chat URI." - }, - "_meta": { - "type": "object", - "additionalProperties": {}, - "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." - }, - "limit": { - "type": "integer", - "description": "Maximum matches in the page; defaults to 100. The host may return fewer.", - "minimum": 1 - }, - "cursor": { - "type": "string", - "description": "Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn." - }, - "query": { - "type": "string", - "description": "Nonempty literal text, or a pattern when `isRegex` is true.", - "minLength": 1 - }, - "matchCase": { - "type": "boolean", - "description": "Case-sensitive matching; defaults to false." - }, - "wholeWord": { - "type": "boolean", - "description": "Require whole-word matches; defaults to false." - }, - "isRegex": { - "type": "boolean", - "description": "Treat the query as a regular expression; defaults to false." - } - }, - "required": [ - "channel", - "query" - ] - }, - "SearchChatTurnsResult": { - "type": "object", - "description": "One page of match locators, which may end within a turn or side.", - "properties": { - "nextCursor": { - "type": "string", - "description": "Resume after the last result or scanned position. A bounded scan may\nreturn no matches with an advancing cursor; only absence means done." - }, - "items": { - "type": "array", - "items": { - "$ref": "#/$defs/ChatTurnMatch" - }, - "description": "Match locators in reverse transcript order." - } - }, - "required": [ - "items" - ] - }, "CreateTerminalParams": { "type": "object", "description": "Creates a new terminal on the server.\n\nAfter creation, the client should subscribe to the terminal URI to receive\nstate updates. The server dispatches `root/terminalsChanged` to update the\nroot terminal list.", @@ -4807,6 +4720,11 @@ "kind" ] }, + "ChatHistoryBrowsingCapability": { + "type": "object", + "description": "Presence advertises `listChatTurns` and `readChatTurns` for this chat.", + "properties": {} + }, "ChatState": { "type": "object", "description": "Full state for a single chat, loaded when a client subscribes to the chat's\nURI.\n\nThe lightweight catalog representation of a chat is {@link ChatSummary},\ncarried in {@link SessionState.chats | `SessionState.chats`}. `ChatState`\n**denormalizes** every {@link ChatSummary} field directly onto itself so\nsubscribers receive one flat object instead of having to merge a nested\n`summary` sub-object. Producers MUST keep the two representations\nconsistent: any change to the inlined fields below SHOULD also be\nannounced on the parent session via the matching\n{@link SessionChatUpdatedAction | `session/chatUpdated`} action.", @@ -4890,9 +4808,9 @@ }, "description": "Completed turns" }, - "historyNavigation": { - "type": "boolean", - "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when unsupported." }, "turnsNextCursor": { "type": "string", @@ -11419,14 +11337,6 @@ "type": "string", "description": "Which contiguous window of completed turns to read, relative to an anchor." }, - "ChatTurnMatchKind": { - "enum": [ - "request", - "response" - ], - "type": "string", - "description": "The searchable side of a completed turn." - }, "TerminalClaim": { "oneOf": [ { diff --git a/schema/errors.schema.json b/schema/errors.schema.json index df499a9d3..6d192ce4a 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -2605,6 +2605,11 @@ "kind" ] }, + "ChatHistoryBrowsingCapability": { + "type": "object", + "description": "Presence advertises `listChatTurns` and `readChatTurns` for this chat.", + "properties": {} + }, "ChatState": { "type": "object", "description": "Full state for a single chat, loaded when a client subscribes to the chat's\nURI.\n\nThe lightweight catalog representation of a chat is {@link ChatSummary},\ncarried in {@link SessionState.chats | `SessionState.chats`}. `ChatState`\n**denormalizes** every {@link ChatSummary} field directly onto itself so\nsubscribers receive one flat object instead of having to merge a nested\n`summary` sub-object. Producers MUST keep the two representations\nconsistent: any change to the inlined fields below SHOULD also be\nannounced on the parent session via the matching\n{@link SessionChatUpdatedAction | `session/chatUpdated`} action.", @@ -2688,9 +2693,9 @@ }, "description": "Completed turns" }, - "historyNavigation": { - "type": "boolean", - "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when unsupported." }, "turnsNextCursor": { "type": "string", @@ -7878,7 +7883,7 @@ }, "ListChatTurnsParams": { "type": "object", - "description": "Lists every visible non-system prompt in retained turns, oldest first, across pages.\nRequires `ChatState.historyNavigation`. Does not load turns into state.", + "description": "Lists every visible non-system prompt in retained turns, oldest first, across pages.\nRequires `ChatState.historyBrowsing`. Does not load turns into state.", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -7925,7 +7930,7 @@ }, "ReadChatTurnsParams": { "type": "object", - "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008).", + "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008).", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -7981,93 +7986,6 @@ "hasAfter" ] }, - "ChatTurnMatch": { - "type": "object", - "description": "A match locator, not a snippet, text offset, or response-part identifier.", - "properties": { - "turnId": { - "type": "string" - }, - "kind": { - "$ref": "#/$defs/ChatTurnMatchKind" - }, - "occurrence": { - "type": "integer", - "description": "Zero-based index of this nonempty match in forward text order on this\nside of the turn, for the same query and flags.", - "minimum": 0 - } - }, - "required": [ - "turnId", - "kind", - "occurrence" - ] - }, - "SearchChatTurnsParams": { - "type": "object", - "description": "Searches visible request and response text in retained completed turns.\nReturns match locators newest first, independently of the subscription.\nRequires `ChatState.historyNavigation`.", - "properties": { - "channel": { - "$ref": "#/$defs/URI", - "description": "Chat URI." - }, - "_meta": { - "type": "object", - "additionalProperties": {}, - "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." - }, - "limit": { - "type": "integer", - "description": "Maximum matches in the page; defaults to 100. The host may return fewer.", - "minimum": 1 - }, - "cursor": { - "type": "string", - "description": "Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn." - }, - "query": { - "type": "string", - "description": "Nonempty literal text, or a pattern when `isRegex` is true.", - "minLength": 1 - }, - "matchCase": { - "type": "boolean", - "description": "Case-sensitive matching; defaults to false." - }, - "wholeWord": { - "type": "boolean", - "description": "Require whole-word matches; defaults to false." - }, - "isRegex": { - "type": "boolean", - "description": "Treat the query as a regular expression; defaults to false." - } - }, - "required": [ - "channel", - "query" - ] - }, - "SearchChatTurnsResult": { - "type": "object", - "description": "One page of match locators, which may end within a turn or side.", - "properties": { - "nextCursor": { - "type": "string", - "description": "Resume after the last result or scanned position. A bounded scan may\nreturn no matches with an advancing cursor; only absence means done." - }, - "items": { - "type": "array", - "items": { - "$ref": "#/$defs/ChatTurnMatch" - }, - "description": "Match locators in reverse transcript order." - } - }, - "required": [ - "items" - ] - }, "CreateTerminalParams": { "type": "object", "description": "Creates a new terminal on the server.\n\nAfter creation, the client should subscribe to the terminal URI to receive\nstate updates. The server dispatches `root/terminalsChanged` to update the\nroot terminal list.", @@ -9623,14 +9541,6 @@ "type": "string", "description": "Which contiguous window of completed turns to read, relative to an anchor." }, - "ChatTurnMatchKind": { - "enum": [ - "request", - "response" - ], - "type": "string", - "description": "The searchable side of a completed turn." - }, "ChangesetOperationTarget": { "oneOf": [ { diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index aaa44d29c..ab56ff2f5 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -2907,6 +2907,11 @@ "kind" ] }, + "ChatHistoryBrowsingCapability": { + "type": "object", + "description": "Presence advertises `listChatTurns` and `readChatTurns` for this chat.", + "properties": {} + }, "ChatState": { "type": "object", "description": "Full state for a single chat, loaded when a client subscribes to the chat's\nURI.\n\nThe lightweight catalog representation of a chat is {@link ChatSummary},\ncarried in {@link SessionState.chats | `SessionState.chats`}. `ChatState`\n**denormalizes** every {@link ChatSummary} field directly onto itself so\nsubscribers receive one flat object instead of having to merge a nested\n`summary` sub-object. Producers MUST keep the two representations\nconsistent: any change to the inlined fields below SHOULD also be\nannounced on the parent session via the matching\n{@link SessionChatUpdatedAction | `session/chatUpdated`} action.", @@ -2990,9 +2995,9 @@ }, "description": "Completed turns" }, - "historyNavigation": { - "type": "boolean", - "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when unsupported." }, "turnsNextCursor": { "type": "string", diff --git a/schema/state.schema.json b/schema/state.schema.json index 2f513dd34..d8ba5d9ab 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -2516,6 +2516,11 @@ "kind" ] }, + "ChatHistoryBrowsingCapability": { + "type": "object", + "description": "Presence advertises `listChatTurns` and `readChatTurns` for this chat.", + "properties": {} + }, "ChatState": { "type": "object", "description": "Full state for a single chat, loaded when a client subscribes to the chat's\nURI.\n\nThe lightweight catalog representation of a chat is {@link ChatSummary},\ncarried in {@link SessionState.chats | `SessionState.chats`}. `ChatState`\n**denormalizes** every {@link ChatSummary} field directly onto itself so\nsubscribers receive one flat object instead of having to merge a nested\n`summary` sub-object. Producers MUST keep the two representations\nconsistent: any change to the inlined fields below SHOULD also be\nannounced on the parent session via the matching\n{@link SessionChatUpdatedAction | `session/chatUpdated`} action.", @@ -2599,9 +2604,9 @@ }, "description": "Completed turns" }, - "historyNavigation": { - "type": "boolean", - "description": "When true, the host supports `listChatTurns`, `readChatTurns`, and\n`searchChatTurns` over this chat's retained history, independently of\nthe subscription window. Absent or false means unsupported." + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when unsupported." }, "turnsNextCursor": { "type": "string", diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index 47fa4cee9..c86653665 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -793,6 +793,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'AgentInfo' }, { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, + { name: 'ChatHistoryBrowsingCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, @@ -2328,7 +2329,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, @@ -2382,7 +2383,6 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: str { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'ChatTurnIndexEntry' }, { name: 'ListChatTurnsParams' }, { name: 'ListChatTurnsResult' }, { name: 'ReadChatTurnsParams' }, { name: 'ReadChatTurnsResult' }, - { name: 'ChatTurnMatch' }, { name: 'SearchChatTurnsParams' }, { name: 'SearchChatTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index f8c5dd1ea..271e4df25 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -776,6 +776,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'AgentInfo' }, { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, + { name: 'ChatHistoryBrowsingCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, @@ -1840,7 +1841,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, @@ -1881,7 +1882,6 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: str { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'ChatTurnIndexEntry' }, { name: 'ListChatTurnsParams' }, { name: 'ListChatTurnsResult' }, { name: 'ReadChatTurnsParams' }, { name: 'ReadChatTurnsResult' }, - { name: 'ChatTurnMatch' }, { name: 'SearchChatTurnsParams' }, { name: 'SearchChatTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-json-schema.test.ts b/scripts/generate-json-schema.test.ts index c95293010..f1d210c6a 100644 --- a/scripts/generate-json-schema.test.ts +++ b/scripts/generate-json-schema.test.ts @@ -625,7 +625,6 @@ describe('generated JSON schemas', () => { for (const [name, params] of [ ['ListChatTurnsParams', { channel }], ['ReadChatTurnsParams', { channel, turnId }], - ['SearchChatTurnsParams', { channel, query: 'x' }], ] as const) { assert.ok(accepts(name, params), 'all modifiers are optional'); assert.ok(!accepts(name, { ...params, limit: 0 })); @@ -635,15 +634,14 @@ describe('generated JSON schemas', () => { assert.ok(!accepts('ReadChatTurnsParams', { channel, turnId, direction: 'latest' })); assert.ok(!accepts('ReadChatTurnsResult', { turns: [], hasBefore: false })); assert.ok(!accepts('ReadChatTurnsResult', { turns: [{ turnId }], hasBefore: false, hasAfter: true })); - assert.ok(!accepts('SearchChatTurnsParams', { channel, query: '' })); - assert.ok(!accepts('SearchChatTurnsResult', { items: [{ turnId, kind: 'reasoning', occurrence: 0 }] })); - assert.ok(!accepts('SearchChatTurnsResult', { items: [{ turnId, kind: 'response', occurrence: -1 }] })); const page = (preview: string) => ({ items: [{ turnId, preview }] }); assert.ok(accepts('ListChatTurnsResult', page('🌱'.repeat(80)))); assert.ok(!accepts('ListChatTurnsResult', page('🌱'.repeat(81)))); - assert.equal((defs.ChatState.properties as Record).historyNavigation.type, 'boolean'); - assert.ok(!(defs.ChatState.required as string[]).includes('historyNavigation')); + const browsing = (defs.ChatState.properties as Record).historyBrowsing; + assert.ok(schemaAccepts(schema, browsing, {})); + assert.ok(!schemaAccepts(schema, browsing, true)); + assert.ok(!(defs.ChatState.required as string[]).includes('historyBrowsing')); }); it('constrains stable chat move destinations and results', () => { diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index a54010e5e..2680cbf2f 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1027,6 +1027,7 @@ const STATE_STRUCTS = [ 'Icon', 'ProtectedResourceMetadata', 'RootState', 'RootConfigState', 'AgentInfo', 'AgentCapabilities', 'MultipleChatsCapability', + 'ChatHistoryBrowsingCapability', 'MultipleWorkingDirectoriesCapability', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', @@ -1818,7 +1819,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS = [ 'CreateTcpConnectionParams', 'CreateTcpConnectionResult', @@ -1855,7 +1856,6 @@ const COMMAND_STRUCTS = [ 'FetchTurnsParams', 'FetchTurnsResult', 'ChatTurnIndexEntry', 'ListChatTurnsParams', 'ListChatTurnsResult', 'ReadChatTurnsParams', 'ReadChatTurnsResult', - 'ChatTurnMatch', 'SearchChatTurnsParams', 'SearchChatTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', @@ -2396,9 +2396,6 @@ object AhpCommands { fun readChatTurns(id: Long, params: ReadChatTurnsParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "readChatTurns", params = params) - fun searchChatTurns(id: Long, params: SearchChatTurnsParams): JsonRpcRequest = - JsonRpcRequest(id = id, method = "searchChatTurns", params = params) - fun authenticate(id: Long, params: AuthenticateParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "authenticate", params = params) diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 0aba0e663..6bffd79e2 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -878,6 +878,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'AgentInfo' }, { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, + { name: 'ChatHistoryBrowsingCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, @@ -1912,7 +1913,7 @@ pub struct ActionEnvelope { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, @@ -1955,7 +1956,6 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: s { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'ChatTurnIndexEntry' }, { name: 'ListChatTurnsParams' }, { name: 'ListChatTurnsResult' }, { name: 'ReadChatTurnsParams' }, { name: 'ReadChatTurnsResult' }, - { name: 'ChatTurnMatch' }, { name: 'SearchChatTurnsParams' }, { name: 'SearchChatTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget', omitDiscriminants: true }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 2af1e5a0b..21af58a16 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -750,6 +750,7 @@ const STATE_STRUCTS = [ 'Icon', 'ProtectedResourceMetadata', 'RootState', 'RootConfigState', 'AgentInfo', 'AgentCapabilities', 'MultipleChatsCapability', + 'ChatHistoryBrowsingCapability', 'MultipleWorkingDirectoriesCapability', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', @@ -1766,7 +1767,7 @@ public func isClientDispatchable(_ action: StateAction) -> Bool { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'ChatTurnMatchKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS = [ 'CreateTcpConnectionParams', 'CreateTcpConnectionResult', @@ -1802,7 +1803,6 @@ const COMMAND_STRUCTS = [ 'FetchTurnsParams', 'FetchTurnsResult', 'ChatTurnIndexEntry', 'ListChatTurnsParams', 'ListChatTurnsResult', 'ReadChatTurnsParams', 'ReadChatTurnsResult', - 'ChatTurnMatch', 'SearchChatTurnsParams', 'SearchChatTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', @@ -2390,10 +2390,6 @@ public enum AHPCommands { JsonRpcRequest(id: id, method: "readChatTurns", params: params) } - public static func searchChatTurns(id: Int, params: SearchChatTurnsParams) -> JsonRpcRequest { - JsonRpcRequest(id: id, method: "searchChatTurns", params: params) - } - public static func authenticate(id: Int, params: AuthenticateParams) -> JsonRpcRequest { JsonRpcRequest(id: id, method: "authenticate", params: params) } diff --git a/types/channels-chat/commands.ts b/types/channels-chat/commands.ts index 1b2387eef..ef4c204b8 100644 --- a/types/channels-chat/commands.ts +++ b/types/channels-chat/commands.ts @@ -276,7 +276,7 @@ export interface ChatTurnIndexEntry { /** * Lists every visible non-system prompt in retained turns, oldest first, across pages. - * Requires `ChatState.historyNavigation`. Does not load turns into state. + * Requires `ChatState.historyBrowsing`. Does not load turns into state. * * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} * @category Commands @@ -322,7 +322,7 @@ export const enum ChatTurnReadDirection { /** * Reads a byte-bounded window of completed turns directly, without changing * any subscription or fetching intervening pages. Requires - * `ChatState.historyNavigation`. A missing anchor is `NotFound` (-32008). + * `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). * * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} * @category Commands @@ -355,72 +355,3 @@ export interface ReadChatTurnsResult { /** Whether retained completed turns follow this window. */ hasAfter: boolean; } - -/** - * The searchable side of a completed turn. - * @exhaustive - */ -export const enum ChatTurnMatchKind { - Request = 'request', - Response = 'response', -} - -/** A match locator, not a snippet, text offset, or response-part identifier. */ -export interface ChatTurnMatch { - turnId: string; - kind: ChatTurnMatchKind; - /** - * Zero-based index of this nonempty match in forward text order on this - * side of the turn, for the same query and flags. - * @integer - * @minimum 0 - */ - occurrence: number; -} - -/** - * Searches visible request and response text in retained completed turns. - * Returns match locators newest first, independently of the subscription. - * Requires `ChatState.historyNavigation`. - * - * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} - * @category Commands - * @method searchChatTurns - * @direction Client → Server - * @messageType Request - * @version 1 - */ -export interface SearchChatTurnsParams extends BaseParams, PaginatedParams { - /** Chat URI. */ - channel: URI; - /** - * Nonempty literal text, or a pattern when `isRegex` is true. - * @minLength 1 - */ - query: string; - /** Case-sensitive matching; defaults to false. */ - matchCase?: boolean; - /** Require whole-word matches; defaults to false. */ - wholeWord?: boolean; - /** Treat the query as a regular expression; defaults to false. */ - isRegex?: boolean; - /** Opaque cursor for the same chat, query and effective flags; omit to start at the newest turn. */ - cursor?: string; - /** - * Maximum matches in the page; defaults to 100. The host may return fewer. - * @integer - * @minimum 1 - */ - limit?: number; -} - -/** One page of match locators, which may end within a turn or side. */ -export interface SearchChatTurnsResult extends PaginatedResult { - /** Match locators in reverse transcript order. */ - items: ChatTurnMatch[]; - /** - * Resume after the last result or scanned position. A bounded scan may - * return no matches with an advancing cursor; only absence means done. - */ - nextCursor?: string; -} diff --git a/types/channels-chat/state.ts b/types/channels-chat/state.ts index 6665d73a6..f6483bd08 100644 --- a/types/channels-chat/state.ts +++ b/types/channels-chat/state.ts @@ -31,6 +31,9 @@ import type { // ─── Chat State ────────────────────────────────────────────────────────────── +/** Presence advertises `listChatTurns` and `readChatTurns` for this chat. */ +export interface ChatHistoryBrowsingCapability {} + /** * Full state for a single chat, loaded when a client subscribes to the chat's * URI. @@ -145,12 +148,8 @@ export interface ChatState { // ── Conversation contents ────────────────────────────────────────── /** Completed turns */ turns: Turn[]; - /** - * When true, the host supports `listChatTurns`, `readChatTurns`, and - * `searchChatTurns` over this chat's retained history, independently of - * the subscription window. Absent or false means unsupported. - */ - historyNavigation?: boolean; + /** Browse retained history independently of the subscription window. Absent when unsupported. */ + historyBrowsing?: ChatHistoryBrowsingCapability; /** * Cursor for loading older completed turns into this chat state. * diff --git a/types/common/messages.ts b/types/common/messages.ts index fc25b95b3..1329a7c03 100644 --- a/types/common/messages.ts +++ b/types/common/messages.ts @@ -63,8 +63,6 @@ import type { ListChatTurnsResult, ReadChatTurnsParams, ReadChatTurnsResult, - SearchChatTurnsParams, - SearchChatTurnsResult, } from '../channels-chat/commands.js'; import type { CreateTerminalParams, @@ -182,7 +180,6 @@ export interface CommandMap { 'disposeChat': { params: DisposeChatParams; result: null }; 'listChatTurns': { params: ListChatTurnsParams; result: ListChatTurnsResult }; 'readChatTurns': { params: ReadChatTurnsParams; result: ReadChatTurnsResult }; - 'searchChatTurns': { params: SearchChatTurnsParams; result: SearchChatTurnsResult }; 'createTerminal': { params: CreateTerminalParams; result: null }; 'disposeTerminal': { params: DisposeTerminalParams; result: null }; 'createResourceWatch': { params: CreateResourceWatchParams; result: CreateResourceWatchResult }; diff --git a/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json b/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json index 25dd14299..34c7d7f7d 100644 --- a/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json +++ b/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json @@ -6,11 +6,11 @@ "input": { "resource": "ahp-chat:/c1", "fromSeq": 10, - "state": { "resource": "ahp-chat:/c1", "title": "Design", "status": 1, "modifiedAt": "2026-11-18T12:00:00Z", "turns": [], "turnsNextCursor": "older", "historyNavigation": true } + "state": { "resource": "ahp-chat:/c1", "title": "Design", "status": 1, "modifiedAt": "2026-11-18T12:00:00Z", "turns": [], "turnsNextCursor": "older", "historyBrowsing": {} } }, "acceptableOutputs": [{ "resource": "ahp-chat:/c1", "fromSeq": 10, - "state": { "resource": "ahp-chat:/c1", "title": "Design", "status": 1, "modifiedAt": "2026-11-18T12:00:00Z", "turns": [], "turnsNextCursor": "older", "historyNavigation": true } + "state": { "resource": "ahp-chat:/c1", "title": "Design", "status": 1, "modifiedAt": "2026-11-18T12:00:00Z", "turns": [], "turnsNextCursor": "older", "historyBrowsing": {} } }] } diff --git a/types/test-cases/round-trips/105-search-chat-turns-params.json b/types/test-cases/round-trips/105-search-chat-turns-params.json deleted file mode 100644 index 0f758991b..000000000 --- a/types/test-cases/round-trips/105-search-chat-turns-params.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "search-chat-turns-params", - "group": "A", - "description": "A search page retains its query and all search modifiers.", - "type": "SearchChatTurnsParams", - "input": { "channel": "ahp-chat:/c1", "query": "des[i]gn", "matchCase": false, "wholeWord": true, "isRegex": true, "cursor": "matches", "limit": 3 }, - "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "query": "des[i]gn", "matchCase": false, "wholeWord": true, "isRegex": true, "cursor": "matches", "limit": 3 }] -} diff --git a/types/test-cases/round-trips/106-search-chat-turns-result.json b/types/test-cases/round-trips/106-search-chat-turns-result.json deleted file mode 100644 index e257446da..000000000 --- a/types/test-cases/round-trips/106-search-chat-turns-result.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "search-chat-turns-result", - "group": "A", - "description": "Repeated matches are located per side in forward text, but delivered in reverse; a final page omits nextCursor.", - "type": "SearchChatTurnsResult", - "input": { "items": [{ "turnId": "t1", "kind": "response", "occurrence": 1 }, { "turnId": "t1", "kind": "response", "occurrence": 0 }, { "turnId": "t1", "kind": "request", "occurrence": 0 }] }, - "acceptableOutputs": [{ "items": [{ "turnId": "t1", "kind": "response", "occurrence": 1 }, { "turnId": "t1", "kind": "response", "occurrence": 0 }, { "turnId": "t1", "kind": "request", "occurrence": 0 }] }] -} diff --git a/types/version/message-checks.ts b/types/version/message-checks.ts index 00ce1d27c..f2c678455 100644 --- a/types/version/message-checks.ts +++ b/types/version/message-checks.ts @@ -62,7 +62,6 @@ type _ExpectedCommands = | 'disposeChat' | 'listChatTurns' | 'readChatTurns' - | 'searchChatTurns' | 'createTerminal' | 'disposeTerminal' | 'createResourceWatch' From 2bd68ad904820f92d8f16ecf380415fea95d7253 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Fri, 20 Nov 2026 12:05:28 -0800 Subject: [PATCH 3/3] chat: open history at a turn and page by cursor Start at the selected turn rather than centering a window. Return opaque continuations on each available side, leaving the live chat subscription unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Commands.generated.cs | 48 +++---- .../JsonSerializerContext.generated.cs | 1 - clients/go/ahptypes/commands.generated.go | 42 +++--- .../generated/Commands.generated.kt | 46 ++----- clients/rust/crates/ahp-types/src/commands.rs | 47 +++---- .../Generated/Commands.generated.swift | 52 ++++---- .../20261119-chat-history-navigation.json | 2 +- docs/specification/chat-channel.md | 20 ++- schema/commands.schema.json | 120 +++++++++++++----- schema/errors.schema.json | 109 +++++++++++----- scripts/find-protocol-sources.ts | 10 ++ scripts/generate-csharp.ts | 6 +- scripts/generate-go.ts | 6 +- scripts/generate-json-schema.test.ts | 13 +- scripts/generate-json-schema.ts | 11 +- scripts/generate-kotlin.ts | 6 +- scripts/generate-markdown.ts | 10 +- scripts/generate-rust.ts | 6 +- scripts/generate-swift.ts | 6 +- types/channels-chat/commands.ts | 66 +++++----- types/messages.test.ts | 2 +- .../103-read-chat-turns-params.json | 6 +- .../104-read-chat-turns-by-cursor.json | 8 ++ .../104-read-chat-turns-result.json | 10 +- 24 files changed, 372 insertions(+), 281 deletions(-) create mode 100644 types/test-cases/round-trips/104-read-chat-turns-by-cursor.json diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 6b04221f4..bea4e110d 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -125,21 +125,6 @@ public override void Write(Utf8JsonWriter writer, ChatMoveDestinationKind value, => writer.WriteStringValue(value.Value); } -/// Which contiguous window of completed turns to read, relative to an anchor. -[JsonConverter(typeof(WireEnumConverter))] -public enum ChatTurnReadDirection -{ - /// Include the anchor and nearby turns. - [WireValue("around")] - Around, - /// Immediately preceding turns, excluding the anchor. - [WireValue("before")] - Before, - /// Immediately following turns, excluding the anchor. - [WireValue("after")] - After, -} - /// Native filesystem path grammar used by a host environment. [JsonConverter(typeof(WireEnumConverter))] public enum PathStyle @@ -1895,9 +1880,9 @@ public sealed record ListChatTurnsResult public required List Items { get; init; } } -/// Reads a byte-bounded window of completed turns directly, without changing -/// any subscription or fetching intervening pages. Requires -/// `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). +/// Reads a byte-bounded page of completed turns without changing a subscription. +/// Supply exactly one of `fromTurnId` (open at that turn) or `cursor` (scroll). +/// Requires `ChatState.historyBrowsing`. public sealed record ReadChatTurnsParams { /// Chat URI. @@ -1909,29 +1894,32 @@ public sealed record ReadChatTurnsParams [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary? Meta { get; init; } - /// Identifier of the retained completed turn anchoring the window. - public required string TurnId { get; init; } + /// Stable ID of the first turn to return. Omit when continuing by cursor. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? FromTurnId { get; init; } - /// Defaults to `around`. + /// Echo either cursor from a previous read page. Omit when opening by ID. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public ChatTurnReadDirection? Direction { get; init; } + public string? Cursor { get; init; } - /// Maximum number of whole turns, including the anchor for `around`; defaults to 10. + /// Maximum number of whole turns on this page; defaults to 10. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public long? Limit { get; init; } } -/// A contiguous slice of the transcript, not a chat snapshot or a state update. +/// A contiguous page of the transcript, not a chat snapshot or a state update. public sealed record ReadChatTurnsResult { - /// Whole turns in chronological order for all three directions. - public required List Turns { get; init; } + /// Read immediately after the last returned turn; absent at the end. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? NextCursor { get; init; } - /// Whether retained completed turns precede this window. - public bool HasBefore { get; init; } + /// Consecutive whole turns, oldest first, including on a previous-page read. + public required List Turns { get; init; } - /// Whether retained completed turns follow this window. - public bool HasAfter { get; init; } + /// Read immediately before the first returned turn; absent at the start. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PreviousCursor { get; init; } } /// Stop receiving updates for a channel. diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index eb3f220ca..9be3d79ee 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -199,7 +199,6 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ChatTurnCancelledAction))] [JsonSerializable(typeof(ChatTurnCompleteAction))] [JsonSerializable(typeof(ChatTurnIndexEntry))] -[JsonSerializable(typeof(ChatTurnReadDirection))] [JsonSerializable(typeof(ChatTurnResumeAction))] [JsonSerializable(typeof(ChatTurnsLoadedAction))] [JsonSerializable(typeof(ChatTurnStartedAction))] diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index a1cffbd9e..5c8d1e1f0 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -43,18 +43,6 @@ const ( ChatMoveDestinationKindNewSession ChatMoveDestinationKind = "newSession" ) -// Which contiguous window of completed turns to read, relative to an anchor. -type ChatTurnReadDirection string - -const ( - // Include the anchor and nearby turns. - ChatTurnReadDirectionAround ChatTurnReadDirection = "around" - // Immediately preceding turns, excluding the anchor. - ChatTurnReadDirectionBefore ChatTurnReadDirection = "before" - // Immediately following turns, excluding the anchor. - ChatTurnReadDirectionAfter ChatTurnReadDirection = "after" -) - // Native filesystem path grammar used by a host environment. type PathStyle string @@ -1360,31 +1348,33 @@ type ListChatTurnsResult struct { Items []ChatTurnIndexEntry `json:"items"` } -// Reads a byte-bounded window of completed turns directly, without changing -// any subscription or fetching intervening pages. Requires -// `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). +// Reads a byte-bounded page of completed turns without changing a subscription. +// Supply exactly one of `fromTurnId` (open at that turn) or `cursor` (scroll). +// Requires `ChatState.historyBrowsing`. type ReadChatTurnsParams 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"` - // Identifier of the retained completed turn anchoring the window. - TurnId string `json:"turnId"` - // Defaults to `around`. - Direction *ChatTurnReadDirection `json:"direction,omitempty"` - // Maximum number of whole turns, including the anchor for `around`; defaults to 10. + // Stable ID of the first turn to return. Omit when continuing by cursor. + FromTurnId *string `json:"fromTurnId,omitempty"` + // Echo either cursor from a previous read page. Omit when opening by ID. + Cursor *string `json:"cursor,omitempty"` + // Maximum number of whole turns on this page; defaults to 10. Limit *int64 `json:"limit,omitempty"` } -// A contiguous slice of the transcript, not a chat snapshot or a state update. +// A contiguous page of the transcript, not a chat snapshot or a state update. type ReadChatTurnsResult struct { - // Whole turns in chronological order for all three directions. + // Opaque cursor for the next page. Present when more entries exist beyond the + // returned page; absent signals the end of the collection. Pass it back as + // {@link PaginatedParams.cursor} to fetch the following page. + NextCursor *string `json:"nextCursor,omitempty"` + // Consecutive whole turns, oldest first, including on a previous-page read. Turns []Turn `json:"turns"` - // Whether retained completed turns precede this window. - HasBefore bool `json:"hasBefore"` - // Whether retained completed turns follow this window. - HasAfter bool `json:"hasAfter"` + // Read immediately before the first returned turn; absent at the start. + PreviousCursor *string `json:"previousCursor,omitempty"` } // Stop receiving updates for a channel. 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 096f2e94f..5967dc876 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 @@ -89,28 +89,6 @@ internal object ChatMoveDestinationKindSerializer : KSerializer? = null, /** - * Identifier of the retained completed turn anchoring the window. + * Stable ID of the first turn to return. Omit when continuing by cursor. */ - val turnId: String, + val fromTurnId: String? = null, /** - * Defaults to `around`. + * Echo either cursor from a previous read page. Omit when opening by ID. */ - val direction: ChatTurnReadDirection? = null, + val cursor: String? = null, /** - * Maximum number of whole turns, including the anchor for `around`; defaults to 10. + * Maximum number of whole turns on this page; defaults to 10. */ val limit: Long? = null ) @@ -1673,17 +1651,19 @@ data class ReadChatTurnsParams( @Serializable data class ReadChatTurnsResult( /** - * Whole turns in chronological order for all three directions. + * Opaque cursor for the next page. Present when more entries exist beyond the + * returned page; absent signals the end of the collection. Pass it back as + * {@link PaginatedParams.cursor} to fetch the following page. */ - val turns: List, + val nextCursor: String? = null, /** - * Whether retained completed turns precede this window. + * Consecutive whole turns, oldest first, including on a previous-page read. */ - val hasBefore: Boolean, + val turns: List, /** - * Whether retained completed turns follow this window. + * Read immediately before the first returned turn; absent at the start. */ - val hasAfter: Boolean + val previousCursor: String? = null ) @Serializable diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index f6fa29a8c..507661782 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -109,20 +109,6 @@ impl<'de> serde::Deserialize<'de> for ChatMoveDestinationKind { } } -/// Which contiguous window of completed turns to read, relative to an anchor. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum ChatTurnReadDirection { - /// Include the anchor and nearby turns. - #[serde(rename = "around")] - Around, - /// Immediately preceding turns, excluding the anchor. - #[serde(rename = "before")] - Before, - /// Immediately following turns, excluding the anchor. - #[serde(rename = "after")] - After, -} - /// Native filesystem path grammar used by a host environment. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum PathStyle { @@ -1762,9 +1748,9 @@ pub struct ListChatTurnsResult { pub items: Vec, } -/// Reads a byte-bounded window of completed turns directly, without changing -/// any subscription or fetching intervening pages. Requires -/// `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). +/// Reads a byte-bounded page of completed turns without changing a subscription. +/// Supply exactly one of `fromTurnId` (open at that turn) or `cursor` (scroll). +/// Requires `ChatState.historyBrowsing`. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReadChatTurnsParams { @@ -1774,26 +1760,31 @@ pub struct ReadChatTurnsParams { /// Receivers MUST ignore keys they do not understand. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] pub meta: Option, - /// Identifier of the retained completed turn anchoring the window. - pub turn_id: String, - /// Defaults to `around`. + /// Stable ID of the first turn to return. Omit when continuing by cursor. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_turn_id: Option, + /// Echo either cursor from a previous read page. Omit when opening by ID. #[serde(default, skip_serializing_if = "Option::is_none")] - pub direction: Option, - /// Maximum number of whole turns, including the anchor for `around`; defaults to 10. + pub cursor: Option, + /// Maximum number of whole turns on this page; defaults to 10. #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option, } -/// A contiguous slice of the transcript, not a chat snapshot or a state update. +/// A contiguous page of the transcript, not a chat snapshot or a state update. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReadChatTurnsResult { - /// Whole turns in chronological order for all three directions. + /// Opaque cursor for the next page. Present when more entries exist beyond the + /// returned page; absent signals the end of the collection. Pass it back as + /// {@link PaginatedParams.cursor} to fetch the following page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Consecutive whole turns, oldest first, including on a previous-page read. pub turns: Vec, - /// Whether retained completed turns precede this window. - pub has_before: bool, - /// Whether retained completed turns follow this window. - pub has_after: bool, + /// Read immediately before the first returned turn; absent at the start. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_cursor: Option, } /// Stop receiving updates for a channel. diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 5363caa10..d3da24afc 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -68,16 +68,6 @@ public enum ChatMoveDestinationKind: Codable, Sendable, Equatable { } } -/// Which contiguous window of completed turns to read, relative to an anchor. -public enum ChatTurnReadDirection: String, Codable, Sendable { - /// Include the anchor and nearby turns. - case around = "around" - /// Immediately preceding turns, excluding the anchor. - case before = "before" - /// Immediately following turns, excluding the anchor. - case after = "after" -} - /// Native filesystem path grammar used by a host environment. public enum PathStyle: String, Codable, Sendable { case posix = "posix" @@ -1995,52 +1985,54 @@ public struct ReadChatTurnsParams: Codable, Sendable, Equatable { /// Optional JSON-serializable metadata associated with this request. /// Receivers MUST ignore keys they do not understand. public var meta: [String: AnyCodable]? - /// Identifier of the retained completed turn anchoring the window. - public var turnId: String - /// Defaults to `around`. - public var direction: ChatTurnReadDirection? - /// Maximum number of whole turns, including the anchor for `around`; defaults to 10. + /// Stable ID of the first turn to return. Omit when continuing by cursor. + public var fromTurnId: String? + /// Echo either cursor from a previous read page. Omit when opening by ID. + public var cursor: String? + /// Maximum number of whole turns on this page; defaults to 10. public var limit: Int? enum CodingKeys: String, CodingKey { case channel case meta = "_meta" - case turnId - case direction + case fromTurnId + case cursor case limit } public init( channel: String, meta: [String: AnyCodable]? = nil, - turnId: String, - direction: ChatTurnReadDirection? = nil, + fromTurnId: String? = nil, + cursor: String? = nil, limit: Int? = nil ) { self.channel = channel self.meta = meta - self.turnId = turnId - self.direction = direction + self.fromTurnId = fromTurnId + self.cursor = cursor self.limit = limit } } public struct ReadChatTurnsResult: Codable, Sendable, Equatable { - /// Whole turns in chronological order for all three directions. + /// Opaque cursor for the next page. Present when more entries exist beyond the + /// returned page; absent signals the end of the collection. Pass it back as + /// {@link PaginatedParams.cursor} to fetch the following page. + public var nextCursor: String? + /// Consecutive whole turns, oldest first, including on a previous-page read. public var turns: [Turn] - /// Whether retained completed turns precede this window. - public var hasBefore: Bool - /// Whether retained completed turns follow this window. - public var hasAfter: Bool + /// Read immediately before the first returned turn; absent at the start. + public var previousCursor: String? public init( + nextCursor: String? = nil, turns: [Turn], - hasBefore: Bool, - hasAfter: Bool + previousCursor: String? = nil ) { + self.nextCursor = nextCursor self.turns = turns - self.hasBefore = hasBefore - self.hasAfter = hasAfter + self.previousCursor = previousCursor } } diff --git a/docs/.changes/20261119-chat-history-navigation.json b/docs/.changes/20261119-chat-history-navigation.json index c1d8d48ce..e2036d203 100644 --- a/docs/.changes/20261119-chat-history-navigation.json +++ b/docs/.changes/20261119-chat-history-navigation.json @@ -1,4 +1,4 @@ { "type": "added", - "message": "Optional `ChatState.historyBrowsing` advertises `listChatTurns` and `readChatTurns` for browsing retained history without loading intervening turns into a subscription." + "message": "Optional `ChatState.historyBrowsing` advertises `listChatTurns` for the prompt index and `readChatTurns` to open a retained turn by ID and page in either direction by cursor, without loading intervening turns into a subscription." } diff --git a/docs/specification/chat-channel.md b/docs/specification/chat-channel.md index 87279cc83..f4b41135d 100644 --- a/docs/specification/chat-channel.md +++ b/docs/specification/chat-channel.md @@ -62,27 +62,23 @@ These are reads of the host's retained, completed transcript, including turns ou `preview` is the first nonempty trimmed line of visible request text, or `""` if none exists. When the line exceeds 80 Unicode scalar values, use its first 79 followed by `…`. Do not include attachment bodies, metadata, or response text. Copy `Turn.startedAt` when present; do not synthesize a timestamp. -#### Read a window +#### Open a turn and page by cursor -`readChatTurns` takes a stable `turnId`. The default `direction` is `around` and the default `limit` is 10 **total turns**, not 10 on each side. The result is a contiguous slice of whole `Turn` objects in **chronological order**: +To open a turn, send `readChatTurns` with the chat `channel` and `fromTurnId`. The first returned turn MUST be that retained completed turn, followed by its immediate successors. Do not fill the page with earlier turns near the end of history. If the ID is unknown, pruned, or still active, return `NotFound` (`-32008`), not a nearby substitute. -| Direction | Selection | -|---|---| -| `around` | Include the anchor exactly once, with nearby turns on either side as space permits. With `limit: 1`, return just the anchor. | -| `before` | Take immediately preceding turns, excluding the anchor. | -| `after` | Take immediately following turns, excluding the anchor. | +Every successful page contains one or more consecutive whole turns, oldest first. Return a `previousCursor` if and only if earlier turns exist, and a `nextCursor` if and only if later turns exist, relative to this page in the same traversal. To scroll, echo either token as `cursor` instead of `fromTurnId`. A previous page ends immediately before the current page; a next page starts immediately after it. Neither repeats the boundary turn, even when the page size changes. -`hasBefore` and `hasAfter` describe whether retained turns exist outside the **returned window**, not just whether the requested count was met. An empty `before` at the oldest anchor returns `false, true`; an empty `after` at the newest returns `true, false` (the anchor exists on the other side). To extend a nonempty window, use `before` its first ID or `after` its last ID. Each read uses the current retained history; if an anchor is missing, pruned, or active rather than completed, return `NotFound` (`-32008`), not an empty success or a nearby substitute. +For example, `{ "channel": "ahp-chat:/c1", "fromTurnId": "t45", "limit": 5 }` can return turns 45–49. With the same limit and enough space, sending the page's `previousCursor` returns 40–44 in that order; sending its `nextCursor` returns 50–54. The live subscription at turn 100 is unchanged. -Hosts MUST bound both the turn count and the serialized response size. Target at most 4 MiB of UTF-8 encoded JSON per result; a smaller budget is permitted. If the required turn (the anchor for `around`, the nearest adjacent turn for `before`/`after`) alone exceeds this target, the host may return it alone **only** within a finite, transport-safe hard byte limit. If it cannot fit, return `InternalError` (`-32603`) with an explanatory message. Do not truncate a turn, skip an oversized immediate neighbor, or return an empty page that cannot advance. +The default `limit` is 10 turns per request. Hosts MUST also bound the serialized response size. Target at most 4 MiB of UTF-8 encoded JSON per result; a smaller budget is permitted. If the required turn (the requested ID on opening, or the immediate neighbor on continuation) alone exceeds this target, the host may return it alone **only** within a finite, transport-safe hard byte limit. If it cannot fit, return `InternalError` (`-32603`) with an explanatory message. Never truncate or skip it to make a smaller page. #### Continuation and errors For `listChatTurns`, omit `cursor` for the first page; the default `limit` is 100 entries. Echo `nextCursor` unchanged for the following page. Its absence means the traversal is complete. For both commands `limit` must be a positive integer; hosts may cap it and return fewer. -Cursors are opaque and scoped to the connection, method, and chat. They are not `turnsNextCursor` values. Following a chain MUST enumerate the first page's ordered index without duplicates or omissions. New completions do not join a traversal already in progress. A retry of the same cursor resumes from the same boundary or fails explicitly. If a change to retained history or cursor expiry prevents a consistent continuation, return `Conflict` (`-32011`); the client discards that traversal and restarts without a cursor. Discard cursors on reconnect. +Cursors are opaque and scoped to the connection, method, and chat. They are not `turnsNextCursor` values. Following cursors in one direction MUST enumerate that side of the first page's ordered history without duplicates or omissions. New completions do not join a traversal already in progress. A retry of the same cursor resumes from the same boundary or fails explicitly. If a change to retained history or cursor expiry prevents a consistent continuation, return `Conflict` (`-32011`); the client discards that traversal. Restart a list without a cursor; restart a read with a retained `fromTurnId`. Discard cursors on reconnect. -Return `InvalidParams` (`-32602`) for malformed, unrecognized or mis-scoped cursors, or an invalid direction or limit. An unavailable command, including for a chat that does not advertise `historyBrowsing`, returns `MethodNotFound` (`-32601`); a host that implements the command returns `NotFound` (`-32008`) for an unknown chat. Unsupported is not an empty index. Clients without support can still use their subscribed state and the existing explicit `fetchTurns` backfill operation. +Return `InvalidParams` (`-32602`) for malformed, unrecognized or mis-scoped cursors, an invalid limit, or a read with both or neither of `fromTurnId` and `cursor`. An unavailable command, including for a chat that does not advertise `historyBrowsing`, returns `MethodNotFound` (`-32601`); a host that implements the command returns `NotFound` (`-32008`) for an unknown chat. Unsupported is not an empty index. Clients without support can still use their subscribed state and the existing explicit `fetchTurns` backfill operation. ### Reasoning timing @@ -424,7 +420,7 @@ This section lists wire methods that are interpreted in the context of a chat UR |---|---|---| | `fetchTurns` | request | Ask the host to load older historical turns into this chat state. | | `listChatTurns` | request | Page the retained prompt index without loading turns into state. | -| `readChatTurns` | request | Read a bounded window around, before, or after a retained turn. | +| `readChatTurns` | request | Open a retained turn by ID or read the adjacent page by cursor. | | `completions` | request | Chat-scoped inline completions (e.g. user-message mentions). | `createChat` is dispatched against the owning session URI (`params.channel = "ahp-session:/"`). diff --git a/schema/commands.schema.json b/schema/commands.schema.json index a81423d1b..c9f2a0890 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1702,9 +1702,9 @@ "items" ] }, - "ReadChatTurnsParams": { + "ReadChatTurnsPageParams": { "type": "object", - "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008).", + "description": "Reads a byte-bounded page of completed turns without changing a subscription.\nSupply exactly one of `fromTurnId` (open at that turn) or `cursor` (scroll).\nRequires `ChatState.historyBrowsing`.", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -1715,49 +1715,107 @@ "additionalProperties": {}, "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." }, - "turnId": { + "fromTurnId": { "type": "string", - "description": "Identifier of the retained completed turn anchoring the window." + "description": "Stable ID of the first turn to return. Omit when continuing by cursor." }, - "direction": { - "$ref": "#/$defs/ChatTurnReadDirection", - "description": "Defaults to `around`." + "cursor": { + "type": "string", + "description": "Echo either cursor from a previous read page. Omit when opening by ID." }, "limit": { "type": "integer", - "description": "Maximum number of whole turns, including the anchor for `around`; defaults to 10.", + "description": "Maximum number of whole turns on this page; defaults to 10.", + "minimum": 1 + } + }, + "required": [ + "channel" + ] + }, + "ReadChatTurnsFromTurnParams": { + "type": "object", + "description": "Open a page starting at a retained completed turn, inclusive.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "fromTurnId": { + "type": "string" + }, + "cursor": { + "not": {} + }, + "limit": { + "type": "integer", + "description": "Maximum number of whole turns on this page; defaults to 10.", "minimum": 1 } }, "required": [ "channel", - "turnId" + "fromTurnId" + ] + }, + "ReadChatTurnsFromCursorParams": { + "type": "object", + "description": "Continue immediately before or after a returned page. The cursor carries the direction.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "fromTurnId": { + "not": {} + }, + "cursor": { + "type": "string" + }, + "limit": { + "type": "integer", + "description": "Maximum number of whole turns on this page; defaults to 10.", + "minimum": 1 + } + }, + "required": [ + "channel", + "cursor" ] }, "ReadChatTurnsResult": { "type": "object", - "description": "A contiguous slice of the transcript, not a chat snapshot or a state update.", + "description": "A contiguous page of the transcript, not a chat snapshot or a state update.", "properties": { + "nextCursor": { + "type": "string", + "description": "Read immediately after the last returned turn; absent at the end." + }, "turns": { "type": "array", "items": { "$ref": "#/$defs/Turn" }, - "description": "Whole turns in chronological order for all three directions." - }, - "hasBefore": { - "type": "boolean", - "description": "Whether retained completed turns precede this window." + "description": "Consecutive whole turns, oldest first, including on a previous-page read.", + "minItems": 1 }, - "hasAfter": { - "type": "boolean", - "description": "Whether retained completed turns follow this window." + "previousCursor": { + "type": "string", + "description": "Read immediately before the first returned turn; absent at the start." } }, "required": [ - "turns", - "hasBefore", - "hasAfter" + "turns" ] }, "CreateTerminalParams": { @@ -2150,6 +2208,17 @@ ], "description": "Identifies the destination of an atomic chat move." }, + "ReadChatTurnsParams": { + "oneOf": [ + { + "$ref": "#/$defs/ReadChatTurnsFromTurnParams" + }, + { + "$ref": "#/$defs/ReadChatTurnsFromCursorParams" + } + ], + "description": "Select exactly one starting position: a turn ID or a continuation cursor." + }, "ChangesetOperationTarget": { "oneOf": [ { @@ -11328,15 +11397,6 @@ ], "description": "An attachment associated with a {@link Message}." }, - "ChatTurnReadDirection": { - "enum": [ - "around", - "before", - "after" - ], - "type": "string", - "description": "Which contiguous window of completed turns to read, relative to an anchor." - }, "TerminalClaim": { "oneOf": [ { diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 6d192ce4a..46d995153 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -7928,9 +7928,9 @@ "items" ] }, - "ReadChatTurnsParams": { + "ReadChatTurnsPageParams": { "type": "object", - "description": "Reads a byte-bounded window of completed turns directly, without changing\nany subscription or fetching intervening pages. Requires\n`ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008).", + "description": "Reads a byte-bounded page of completed turns without changing a subscription.\nSupply exactly one of `fromTurnId` (open at that turn) or `cursor` (scroll).\nRequires `ChatState.historyBrowsing`.", "properties": { "channel": { "$ref": "#/$defs/URI", @@ -7941,49 +7941,107 @@ "additionalProperties": {}, "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." }, - "turnId": { + "fromTurnId": { + "type": "string", + "description": "Stable ID of the first turn to return. Omit when continuing by cursor." + }, + "cursor": { "type": "string", - "description": "Identifier of the retained completed turn anchoring the window." + "description": "Echo either cursor from a previous read page. Omit when opening by ID." + }, + "limit": { + "type": "integer", + "description": "Maximum number of whole turns on this page; defaults to 10.", + "minimum": 1 + } + }, + "required": [ + "channel" + ] + }, + "ReadChatTurnsFromTurnParams": { + "type": "object", + "description": "Open a page starting at a retained completed turn, inclusive.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." }, - "direction": { - "$ref": "#/$defs/ChatTurnReadDirection", - "description": "Defaults to `around`." + "fromTurnId": { + "type": "string" + }, + "cursor": { + "not": {} }, "limit": { "type": "integer", - "description": "Maximum number of whole turns, including the anchor for `around`; defaults to 10.", + "description": "Maximum number of whole turns on this page; defaults to 10.", "minimum": 1 } }, "required": [ "channel", - "turnId" + "fromTurnId" + ] + }, + "ReadChatTurnsFromCursorParams": { + "type": "object", + "description": "Continue immediately before or after a returned page. The cursor carries the direction.", + "properties": { + "channel": { + "$ref": "#/$defs/URI", + "description": "Chat URI." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Optional JSON-serializable metadata associated with this request.\nReceivers MUST ignore keys they do not understand." + }, + "fromTurnId": { + "not": {} + }, + "cursor": { + "type": "string" + }, + "limit": { + "type": "integer", + "description": "Maximum number of whole turns on this page; defaults to 10.", + "minimum": 1 + } + }, + "required": [ + "channel", + "cursor" ] }, "ReadChatTurnsResult": { "type": "object", - "description": "A contiguous slice of the transcript, not a chat snapshot or a state update.", + "description": "A contiguous page of the transcript, not a chat snapshot or a state update.", "properties": { + "nextCursor": { + "type": "string", + "description": "Read immediately after the last returned turn; absent at the end." + }, "turns": { "type": "array", "items": { "$ref": "#/$defs/Turn" }, - "description": "Whole turns in chronological order for all three directions." - }, - "hasBefore": { - "type": "boolean", - "description": "Whether retained completed turns precede this window." + "description": "Consecutive whole turns, oldest first, including on a previous-page read.", + "minItems": 1 }, - "hasAfter": { - "type": "boolean", - "description": "Whether retained completed turns follow this window." + "previousCursor": { + "type": "string", + "description": "Read immediately before the first returned turn; absent at the start." } }, "required": [ - "turns", - "hasBefore", - "hasAfter" + "turns" ] }, "CreateTerminalParams": { @@ -9532,15 +9590,6 @@ ], "description": "Identifies the destination of an atomic chat move." }, - "ChatTurnReadDirection": { - "enum": [ - "around", - "before", - "after" - ], - "type": "string", - "description": "Which contiguous window of completed turns to read, relative to an anchor." - }, "ChangesetOperationTarget": { "oneOf": [ { diff --git a/scripts/find-protocol-sources.ts b/scripts/find-protocol-sources.ts index 7ab1e3899..0ac4a51f7 100644 --- a/scripts/find-protocol-sources.ts +++ b/scripts/find-protocol-sources.ts @@ -8,6 +8,16 @@ import { Project, SourceFile } from 'ts-morph'; import path from 'path'; +/** Flat fields for native records and reference tables; schema generation keeps the TS union. */ +export function findWireFields(sf: SourceFile, name: string) { + const iface = sf.getInterface(name); + if (iface) return iface; + const tag = sf.getTypeAlias(name)?.getJsDocs().flatMap(doc => doc.getTags()) + .find(tag => tag.getTagName() === 'wireFields'); + if (tag) return sf.getInterfaceOrThrow(tag.getCommentText()?.trim() ?? ''); + return undefined; +} + /** * Folders containing canonical declarations. Iteration order is * `common, channels-root, channels-session, channels-terminal, diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index c86653665..e623a5cd9 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -45,7 +45,7 @@ import { } from 'ts-morph'; import fs from 'fs'; import path from 'path'; -import { findProtocolSourceFiles } from './find-protocol-sources.js'; +import { findProtocolSourceFiles, findWireFields } from './find-protocol-sources.js'; import { getDocumentation } from './read-stability.js'; import { isNonexhaustiveEnum, discriminatedUnionAllowsUnknown, isBitsetEnum } from './enum-compatibility.js'; import { readProtocolVersions } from './read-protocol-versions.js'; @@ -286,7 +286,7 @@ function getAllProperties(iface: InterfaceDeclaration, project: Project): Proper function findInterface(project: Project, name: string): InterfaceDeclaration | undefined { for (const sf of project.getSourceFiles()) { - const iface = sf.getInterface(name); + const iface = findWireFields(sf, name); if (iface) return iface; } return undefined; @@ -2329,7 +2329,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index 271e4df25..2e16cace4 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -39,7 +39,7 @@ import { import { execFileSync } from 'child_process'; import fs from 'fs'; import path from 'path'; -import { findProtocolSourceFiles } from './find-protocol-sources.js'; +import { findProtocolSourceFiles, findWireFields } from './find-protocol-sources.js'; import { getDocumentation } from './read-stability.js'; import { readProtocolVersions } from './read-protocol-versions.js'; import { readWindowExemptMethods } from './read-window-exempt.js'; @@ -293,7 +293,7 @@ function getAllProperties(iface: InterfaceDeclaration, project: Project): Proper function findInterface(project: Project, name: string): InterfaceDeclaration | undefined { for (const sf of project.getSourceFiles()) { - const iface = sf.getInterface(name); + const iface = findWireFields(sf, name); if (iface) return iface; } return undefined; @@ -1841,7 +1841,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, diff --git a/scripts/generate-json-schema.test.ts b/scripts/generate-json-schema.test.ts index f1d210c6a..44b2ea263 100644 --- a/scripts/generate-json-schema.test.ts +++ b/scripts/generate-json-schema.test.ts @@ -167,6 +167,7 @@ function schemaAccepts( return value === null; case 'array': return Array.isArray(value) && + (typeof schema.minItems !== 'number' || value.length >= schema.minItems) && (!schema.items || value.every(item => schemaAccepts(root, schema.items as JsonNode, item))); } @@ -624,16 +625,20 @@ describe('generated JSON schemas', () => { }; for (const [name, params] of [ ['ListChatTurnsParams', { channel }], - ['ReadChatTurnsParams', { channel, turnId }], + ['ReadChatTurnsParams', { channel, fromTurnId: turnId }], + ['ReadChatTurnsParams', { channel, cursor: 'older' }], ] as const) { assert.ok(accepts(name, params), 'all modifiers are optional'); assert.ok(!accepts(name, { ...params, limit: 0 })); assert.ok(!accepts(name, { ...params, limit: 1.5 })); } assert.ok(!accepts('ReadChatTurnsParams', { channel })); - assert.ok(!accepts('ReadChatTurnsParams', { channel, turnId, direction: 'latest' })); - assert.ok(!accepts('ReadChatTurnsResult', { turns: [], hasBefore: false })); - assert.ok(!accepts('ReadChatTurnsResult', { turns: [{ turnId }], hasBefore: false, hasAfter: true })); + assert.ok(!accepts('ReadChatTurnsParams', { channel, fromTurnId: turnId, cursor: 'older' })); + assert.ok(!accepts('ReadChatTurnsParams', { channel, turnId, direction: 'around' })); + assert.ok(!accepts('ReadChatTurnsResult', { turns: [], nextCursor: 'later' })); + assert.ok(!accepts('ReadChatTurnsResult', { turns: [{ turnId }] })); + const onlyTurn = { id: turnId, message: { text: 'only', origin: { kind: 'user' } }, responseParts: [], state: 'complete' }; + assert.ok(accepts('ReadChatTurnsResult', { turns: [onlyTurn] }), 'neither cursor at both ends'); const page = (preview: string) => ({ items: [{ turnId, preview }] }); assert.ok(accepts('ListChatTurnsResult', page('🌱'.repeat(80)))); assert.ok(!accepts('ListChatTurnsResult', page('🌱'.repeat(81)))); diff --git a/scripts/generate-json-schema.ts b/scripts/generate-json-schema.ts index 577086f8f..4011c8b3d 100644 --- a/scripts/generate-json-schema.ts +++ b/scripts/generate-json-schema.ts @@ -32,6 +32,7 @@ interface JsonSchema { required?: string[]; additionalProperties?: boolean | JsonSchema; items?: JsonSchema; + minItems?: number; contains?: JsonSchema; minContains?: number; maxContains?: number; @@ -411,7 +412,8 @@ function interfaceToSchema(iface: InterfaceDeclaration, project: Project): JsonS const name = prop.getName(); const typeText = getPropertyType(prop); const desc = getPropertyDescription(prop); - const propSchema = typeTextToSchema(typeText, project); + // An optional never field forbids the key on this branch of an exclusive union. + const propSchema: JsonSchema = typeText === 'never' ? { not: {} } : typeTextToSchema(typeText, project); if (desc) propSchema.description = desc; if (hasPropertyTag(prop, 'integer')) { if (propSchema.type !== 'number') { @@ -443,6 +445,13 @@ function interfaceToSchema(iface: InterfaceDeclaration, project: Project): JsonS propSchema[constraint] = length; } } + const minItems = getNumericPropertyTag(prop, 'minItems'); + if (minItems !== undefined) { + if (propSchema.type !== 'array' || !Number.isInteger(minItems) || minItems < 0) { + throw new Error(`${iface.getName()}.${name} uses invalid @minItems on ${typeText}`); + } + propSchema.minItems = minItems; + } const uniqueItemsBy = getUniqueItemsByConstraints(prop); if (uniqueItemsBy) { propSchema.allOf = uniqueItemsBy; diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index 2680cbf2f..368f099d3 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -33,7 +33,7 @@ import { } from 'ts-morph'; import fs from 'fs'; import path from 'path'; -import { findProtocolSourceFiles } from './find-protocol-sources.js'; +import { findProtocolSourceFiles, findWireFields } from './find-protocol-sources.js'; import { getDocumentation, readStability } from './read-stability.js'; import { readProtocolVersions } from './read-protocol-versions.js'; import { @@ -273,7 +273,7 @@ function getAllProperties(iface: InterfaceDeclaration, project: Project): Proper function findInterface(project: Project, name: string): InterfaceDeclaration | undefined { for (const sf of project.getSourceFiles()) { - const iface = sf.getInterface(name); + const iface = findWireFields(sf, name); if (iface) return iface; } return undefined; @@ -1819,7 +1819,7 @@ function generateActionsFile(project: Project): string { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS = [ 'CreateTcpConnectionParams', 'CreateTcpConnectionResult', diff --git a/scripts/generate-markdown.ts b/scripts/generate-markdown.ts index f513924cc..d0e456fdd 100644 --- a/scripts/generate-markdown.ts +++ b/scripts/generate-markdown.ts @@ -28,7 +28,7 @@ import { } from 'ts-morph'; import fs from 'fs'; import path from 'path'; -import { findProtocolSourceFiles } from './find-protocol-sources.js'; +import { findProtocolSourceFiles, findWireFields } from './find-protocol-sources.js'; import { getDescription, getDocumentation, readStability } from './read-stability.js'; const GENERATED_HEADER = '\n\n'; @@ -491,7 +491,7 @@ function findChannelSourceFile(project: Project, dirName: string, baseName: stri function getInterfaceMaybe(project: Project, name: string): InterfaceDeclaration | undefined { for (const sf of project.getSourceFiles()) { if (!isCanonicalSourceFile(sf)) continue; - const iface = sf.getInterface(name); + const iface = findWireFields(sf, name); if (iface) return iface; } return undefined; @@ -661,6 +661,12 @@ function emitCommandsSection(project: Project, sourceFiles: SourceFile[]): strin const lines: string[] = []; for (const sf of sourceFiles) { for (const stmt of sf.getStatements()) { + if (Node.isTypeAliasDeclaration(stmt) && stmt.isExported()) { + const entry = methodByParams.get(stmt.getName()); + const fields = entry && findWireFields(sf, entry.paramsType); + if (entry && fields) lines.push(emitCommandBlock(project, entry, fields)); + continue; + } if (!Node.isInterfaceDeclaration(stmt) || !stmt.isExported()) continue; const name = stmt.getName(); const entry = methodByParams.get(name); diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 6bffd79e2..abeef726a 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -20,7 +20,7 @@ import { import { execFileSync } from 'child_process'; import fs from 'fs'; import path from 'path'; -import { findProtocolSourceFiles } from './find-protocol-sources.js'; +import { findProtocolSourceFiles, findWireFields } from './find-protocol-sources.js'; import { getDocumentation } from './read-stability.js'; import { readProtocolVersions } from './read-protocol-versions.js'; import { readWindowExemptMethods } from './read-window-exempt.js'; @@ -271,7 +271,7 @@ function getAllProperties(iface: InterfaceDeclaration, project: Project): Proper function findInterface(project: Project, name: string): InterfaceDeclaration | undefined { for (const sf of project.getSourceFiles()) { - const iface = sf.getInterface(name); + const iface = findWireFields(sf, name); if (iface) return iface; } return undefined; @@ -1913,7 +1913,7 @@ pub struct ActionEnvelope { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: string }[] = [ { name: 'CreateTcpConnectionParams' }, { name: 'CreateTcpConnectionResult' }, diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 21af58a16..ac1a308e2 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -21,7 +21,7 @@ import { } from 'ts-morph'; import fs from 'fs'; import path from 'path'; -import { findProtocolSourceFiles } from './find-protocol-sources.js'; +import { findProtocolSourceFiles, findWireFields } from './find-protocol-sources.js'; import { getDocumentation, readStability } from './read-stability.js'; import { readProtocolVersions } from './read-protocol-versions.js'; import { @@ -243,7 +243,7 @@ function getAllProperties(iface: InterfaceDeclaration, project: Project): Proper function findInterface(project: Project, name: string): InterfaceDeclaration | undefined { for (const sf of project.getSourceFiles()) { - const iface = sf.getInterface(name); + const iface = findWireFields(sf, name); if (iface) return iface; } return undefined; @@ -1767,7 +1767,7 @@ public func isClientDispatchable(_ action: StateAction) -> Bool { // ─── Commands File Generator ───────────────────────────────────────────────── -const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'ChatTurnReadDirection', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; +const COMMAND_ENUMS = ['ReconnectResultType', 'ChatSourceKind', 'ChatMoveDestinationKind', 'PathStyle', 'ContentEncoding', 'CompletionItemKind', 'ResourceType', 'ResourceWriteMode', 'AuthenticateTargetKind']; const COMMAND_STRUCTS = [ 'CreateTcpConnectionParams', 'CreateTcpConnectionResult', diff --git a/types/channels-chat/commands.ts b/types/channels-chat/commands.ts index ef4c204b8..aca2357f9 100644 --- a/types/channels-chat/commands.ts +++ b/types/channels-chat/commands.ts @@ -307,22 +307,9 @@ export interface ListChatTurnsResult extends PaginatedResult { } /** - * Which contiguous window of completed turns to read, relative to an anchor. - * @exhaustive - */ -export const enum ChatTurnReadDirection { - /** Include the anchor and nearby turns. */ - Around = 'around', - /** Immediately preceding turns, excluding the anchor. */ - Before = 'before', - /** Immediately following turns, excluding the anchor. */ - After = 'after', -} - -/** - * Reads a byte-bounded window of completed turns directly, without changing - * any subscription or fetching intervening pages. Requires - * `ChatState.historyBrowsing`. A missing anchor is `NotFound` (-32008). + * Reads a byte-bounded page of completed turns without changing a subscription. + * Supply exactly one of `fromTurnId` (open at that turn) or `cursor` (scroll). + * Requires `ChatState.historyBrowsing`. * * @see {@link /specification/chat-channel#read-only-history-navigation | Read-only history navigation} * @category Commands @@ -331,27 +318,48 @@ export const enum ChatTurnReadDirection { * @messageType Request * @version 1 */ -export interface ReadChatTurnsParams extends BaseParams { +interface ReadChatTurnsPageParams extends BaseParams { /** Chat URI. */ channel: URI; - /** Identifier of the retained completed turn anchoring the window. */ - turnId: string; - /** Defaults to `around`. */ - direction?: ChatTurnReadDirection; + /** Stable ID of the first turn to return. Omit when continuing by cursor. */ + fromTurnId?: string; + /** Echo either cursor from a previous read page. Omit when opening by ID. */ + cursor?: string; /** - * Maximum number of whole turns, including the anchor for `around`; defaults to 10. + * Maximum number of whole turns on this page; defaults to 10. * @integer * @minimum 1 */ limit?: number; } -/** A contiguous slice of the transcript, not a chat snapshot or a state update. */ -export interface ReadChatTurnsResult { - /** Whole turns in chronological order for all three directions. */ +/** Open a page starting at a retained completed turn, inclusive. */ +interface ReadChatTurnsFromTurnParams extends ReadChatTurnsPageParams { + fromTurnId: string; + cursor?: never; +} + +/** Continue immediately before or after a returned page. The cursor carries the direction. */ +interface ReadChatTurnsFromCursorParams extends ReadChatTurnsPageParams { + fromTurnId?: never; + cursor: string; +} + +/** + * Select exactly one starting position: a turn ID or a continuation cursor. + * @wireFields ReadChatTurnsPageParams + */ +export type ReadChatTurnsParams = ReadChatTurnsFromTurnParams | ReadChatTurnsFromCursorParams; + +/** A contiguous page of the transcript, not a chat snapshot or a state update. */ +export interface ReadChatTurnsResult extends PaginatedResult { + /** + * Consecutive whole turns, oldest first, including on a previous-page read. + * @minItems 1 + */ turns: Turn[]; - /** Whether retained completed turns precede this window. */ - hasBefore: boolean; - /** Whether retained completed turns follow this window. */ - hasAfter: boolean; + /** Read immediately before the first returned turn; absent at the start. */ + previousCursor?: string; + /** Read immediately after the last returned turn; absent at the end. */ + nextCursor?: string; } diff --git a/types/messages.test.ts b/types/messages.test.ts index 4d2f22b3c..7b782cfdb 100644 --- a/types/messages.test.ts +++ b/types/messages.test.ts @@ -216,7 +216,7 @@ describe('command params/result naming conventions', () => { it(`${method}: ${paramsName} is exported from commands.ts`, () => { assert.ok( - new RegExp(`export\\s+interface\\s+${paramsName}\\b`).test(commandsSrc), + new RegExp(`export\\s+(?:interface|type)\\s+${paramsName}\\b`).test(commandsSrc), `Expected ${paramsName} to be exported from commands.ts`, ); }); diff --git a/types/test-cases/round-trips/103-read-chat-turns-params.json b/types/test-cases/round-trips/103-read-chat-turns-params.json index 15a0386b4..854f557b3 100644 --- a/types/test-cases/round-trips/103-read-chat-turns-params.json +++ b/types/test-cases/round-trips/103-read-chat-turns-params.json @@ -1,8 +1,8 @@ { "name": "read-chat-turns-params", "group": "A", - "description": "Read immediately before a known historical turn without backfilling the subscription.", + "description": "Open a page starting at the selected turn without backfilling the subscription.", "type": "ReadChatTurnsParams", - "input": { "channel": "ahp-chat:/c1", "turnId": "t2", "direction": "before", "limit": 1 }, - "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "turnId": "t2", "direction": "before", "limit": 1 }] + "input": { "channel": "ahp-chat:/c1", "fromTurnId": "t1", "limit": 1 }, + "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "fromTurnId": "t1", "limit": 1 }] } diff --git a/types/test-cases/round-trips/104-read-chat-turns-by-cursor.json b/types/test-cases/round-trips/104-read-chat-turns-by-cursor.json new file mode 100644 index 000000000..8dbdd9326 --- /dev/null +++ b/types/test-cases/round-trips/104-read-chat-turns-by-cursor.json @@ -0,0 +1,8 @@ +{ + "name": "read-chat-turns-by-cursor", + "group": "A", + "description": "Scroll by passing the previous page's token without a turn ID or direction.", + "type": "ReadChatTurnsParams", + "input": { "channel": "ahp-chat:/c1", "cursor": "older", "limit": 5 }, + "acceptableOutputs": [{ "channel": "ahp-chat:/c1", "cursor": "older", "limit": 5 }] +} diff --git a/types/test-cases/round-trips/104-read-chat-turns-result.json b/types/test-cases/round-trips/104-read-chat-turns-result.json index 1cfd9dbbd..4cb8023f6 100644 --- a/types/test-cases/round-trips/104-read-chat-turns-result.json +++ b/types/test-cases/round-trips/104-read-chat-turns-result.json @@ -1,16 +1,16 @@ { "name": "read-chat-turns-result", "group": "A", - "description": "An exclusive window at the start of the transcript contains the whole preceding turn.", + "description": "A page in the middle includes the selected whole turn and one continuation for each side.", "type": "ReadChatTurnsResult", "input": { "turns": [{ "id": "t1", "message": { "origin": { "kind": "user" }, "text": "Sketch the design" }, "responseParts": [{ "kind": "markdown", "id": "part-1", "content": "Design A or design B?" }], "state": "complete" }], - "hasBefore": false, - "hasAfter": true + "previousCursor": "older", + "nextCursor": "newer" }, "acceptableOutputs": [{ "turns": [{ "id": "t1", "message": { "origin": { "kind": "user" }, "text": "Sketch the design" }, "responseParts": [{ "kind": "markdown", "id": "part-1", "content": "Design A or design B?" }], "state": "complete" }], - "hasBefore": false, - "hasAfter": true + "previousCursor": "older", + "nextCursor": "newer" }] }