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..bea4e110d 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1804,7 +1804,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 +1832,96 @@ 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.historyBrowsing`. 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 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. + 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; } + + /// Stable ID of the first turn to return. Omit when continuing by cursor. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? FromTurnId { get; init; } + + /// Echo either cursor from a previous read page. Omit when opening by ID. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Cursor { get; init; } + + /// Maximum number of whole turns on this page; defaults to 10. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? Limit { get; init; } +} + +/// A contiguous page of the transcript, not a chat snapshot or a state update. +public sealed record ReadChatTurnsResult +{ + /// Read immediately after the last returned turn; absent at the end. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? NextCursor { get; init; } + + /// Consecutive whole turns, oldest first, including on a previous-page read. + public required List Turns { 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. 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..9be3d79ee 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))] @@ -197,6 +198,7 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ChatTruncatedAction))] [JsonSerializable(typeof(ChatTurnCancelledAction))] [JsonSerializable(typeof(ChatTurnCompleteAction))] +[JsonSerializable(typeof(ChatTurnIndexEntry))] [JsonSerializable(typeof(ChatTurnResumeAction))] [JsonSerializable(typeof(ChatTurnsLoadedAction))] [JsonSerializable(typeof(ChatTurnStartedAction))] @@ -272,6 +274,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 +322,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))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 3be11f1f2..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,6 +2648,10 @@ public sealed class ChatState /// Completed turns public required List Turns { get; set; } + /// Browse retained history independently of the subscription window. Absent when unsupported. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ChatHistoryBrowsingCapability? HistoryBrowsing { 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..4937291ba 100644 --- a/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs +++ b/clients/dotnet/tests/AgentHostProtocol.Tests/TypesRoundTripFixtures.cs @@ -166,6 +166,14 @@ 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 "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..5c8d1e1f0 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1287,7 +1287,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 +1308,75 @@ 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.historyBrowsing`. 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 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"` + // 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 page of the transcript, not a chat snapshot or a state update. +type ReadChatTurnsResult 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"` + // Consecutive whole turns, oldest first, including on a previous-page read. + Turns []Turn `json:"turns"` + // Read immediately before the first returned turn; absent at the start. + PreviousCursor *string `json:"previousCursor,omitempty"` +} + // 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..9d470a215 100644 --- a/clients/go/ahptypes/roundtrip_fixture_test.go +++ b/clients/go/ahptypes/roundtrip_fixture_test.go @@ -262,6 +262,22 @@ 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 "ChatSource": var v ChatSource dec(&v) diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 127394dd7..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,6 +1526,8 @@ type ChatState struct { Config *ChatConfigState `json:"config,omitempty"` // Completed turns Turns []Turn `json:"turns"` + // 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 80e23fac8..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 @@ -1564,6 +1564,108 @@ data class FetchTurnsParams( @Serializable class FetchTurnsResult +@Serializable +data class ChatTurnIndexEntry( + /** + * Stable identifier of the completed turn in this chat. + */ + val turnId: String, + /** + * First nonempty trimmed prompt line, or empty string. If truncated, the + * 80 Unicode scalar values include the trailing ellipsis. + */ + val preview: String, + /** + * The turn's ISO 8601 start time, if known. + */ + val startedAt: String? = null +) + +@Serializable +data class ListChatTurnsParams( + /** + * 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 +) + +@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, + /** + * Stable ID of the first turn to return. Omit when continuing by cursor. + */ + val fromTurnId: String? = null, + /** + * Echo either cursor from a previous read page. Omit when opening by ID. + */ + val cursor: String? = null, + /** + * Maximum number of whole turns on this page; defaults to 10. + */ + val limit: Long? = null +) + +@Serializable +data class ReadChatTurnsResult( + /** + * 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, + /** + * Consecutive whole turns, oldest first, including on a previous-page read. + */ + val turns: List, + /** + * Read immediately before the first returned turn; absent at the start. + */ + val previousCursor: String? = null +) + @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..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 @@ -131,6 +131,12 @@ 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 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..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( /** @@ -1983,6 +1986,10 @@ data class ChatState( * Completed turns */ val turns: List, + /** + * Browse retained history independently of the subscription window. Absent when unsupported. + */ + 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 38b1b7f3c..f36aa4712 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,10 @@ 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.Customization import com.microsoft.agenthostprotocol.generated.Implementation import com.microsoft.agenthostprotocol.generated.InitializeResult @@ -268,6 +272,10 @@ 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()) "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..507661782 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1671,7 +1671,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 +1697,96 @@ 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.historyBrowsing`. 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 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 { + /// 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, + /// 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 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 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 { + /// 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, + /// 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. #[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..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,6 +2279,9 @@ pub struct ChatState { pub config: Option, /// Completed turns pub turns: Vec, + /// Browse retained history independently of the subscription window. Absent when unsupported. + #[serde(default, skip_serializing_if = "Option::is_none")] + 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 330f28625..432bb94e1 100644 --- a/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs +++ b/clients/rust/crates/ahp-types/tests/roundtrip_corpus.rs @@ -30,7 +30,8 @@ use ahp_types::{ actions::{ActionEnvelope, StateAction}, commands::{ AuthenticateParams, ChangesetOperationTarget, ChatSource, CreateChatParams, - CreateTcpConnectionParams, Implementation, InitializeResult, ReconnectParams, + CreateTcpConnectionParams, Implementation, InitializeResult, ListChatTurnsParams, + ListChatTurnsResult, ReadChatTurnsParams, ReadChatTurnsResult, ReconnectParams, ReconnectResult, ResourceReadParams, ResourceReadResult, SubscribeParams, SubscribeResult, }, common::StringOrMarkdown, @@ -231,6 +232,10 @@ 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), "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..36b37962a 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_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 0f4e6dda7..d3da24afc 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -1906,6 +1906,136 @@ 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]? + /// 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 fromTurnId + case cursor + case limit + } + + public init( + channel: String, + meta: [String: AnyCodable]? = nil, + fromTurnId: String? = nil, + cursor: String? = nil, + limit: Int? = nil + ) { + self.channel = channel + self.meta = meta + self.fromTurnId = fromTurnId + self.cursor = cursor + self.limit = limit + } +} + +public struct ReadChatTurnsResult: 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? + /// Consecutive whole turns, oldest first, including on a previous-page read. + public var turns: [Turn] + /// Read immediately before the first returned turn; absent at the start. + public var previousCursor: String? + + public init( + nextCursor: String? = nil, + turns: [Turn], + previousCursor: String? = nil + ) { + self.nextCursor = nextCursor + self.turns = turns + self.previousCursor = previousCursor + } +} + public struct UnsubscribeParams: Codable, Sendable, Equatable { /// Channel URI to unsubscribe from public var channel: String @@ -2945,6 +3075,16 @@ 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 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..2afb27e9d 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Messages.generated.swift @@ -133,6 +133,14 @@ 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 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..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,6 +2048,8 @@ public struct ChatState: Codable, Sendable, Equatable { public var config: ChatConfigState? /// Completed turns public var turns: [Turn] + /// 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 @@ -2090,6 +2100,7 @@ public struct ChatState: Codable, Sendable, Equatable { case canvases case config case turns + case historyBrowsing case turnsNextCursor case activeTurn case steeringMessage @@ -2115,6 +2126,7 @@ public struct ChatState: Codable, Sendable, Equatable { canvases: [CanvasReference]? = nil, config: ChatConfigState? = nil, turns: [Turn], + historyBrowsing: ChatHistoryBrowsingCapability? = nil, turnsNextCursor: String? = nil, activeTurn: ActiveTurn? = nil, steeringMessage: PendingMessage? = nil, @@ -2138,6 +2150,7 @@ public struct ChatState: Codable, Sendable, Equatable { self.canvases = canvases self.config = config self.turns = turns + 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 225d8d0ea..9713a69b7 100644 --- a/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift +++ b/clients/swift/AgentHostProtocol/Tests/AgentHostProtocolClientTests/TypesRoundTripFixtureTests.swift @@ -190,6 +190,14 @@ 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 "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..6ef5ff2c9 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, +} from '../src/types/channels-chat/commands.js'; // ─── Fixture directory ─────────────────────────────────────────────────────── @@ -250,6 +253,10 @@ 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 '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..e2036d203 --- /dev/null +++ b/docs/.changes/20261119-chat-history-navigation.json @@ -0,0 +1,4 @@ +{ + "type": "added", + "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 8bed3089c..f4b41135d 100644 --- a/docs/specification/chat-channel.md +++ b/docs/specification/chat-channel.md @@ -46,10 +46,40 @@ 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.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. The reader's position is 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. + +#### Open a turn and page by cursor + +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. + +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. + +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. + +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 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, 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 [`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 +419,8 @@ 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 | 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/docs/specification/subscriptions.md b/docs/specification/subscriptions.md index a310b4c24..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`, `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 | @@ -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..bbcad23b5 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" @@ -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,6 +5324,10 @@ }, "description": "Completed turns" }, + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when 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..c9f2a0890 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,192 @@ "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.historyBrowsing`. 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" + ] + }, + "ReadChatTurnsPageParams": { + "type": "object", + "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", + "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", + "description": "Stable ID of the first turn to return. Omit when continuing by cursor." + }, + "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 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", + "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 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": "Consecutive whole turns, oldest first, including on a previous-page read.", + "minItems": 1 + }, + "previousCursor": { + "type": "string", + "description": "Read immediately before the first returned turn; absent at the start." + } + }, + "required": [ + "turns" + ] + }, "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.", @@ -2022,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": [ { @@ -4592,6 +4789,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.", @@ -4675,6 +4877,10 @@ }, "description": "Completed turns" }, + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when 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 +9990,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/errors.schema.json b/schema/errors.schema.json index b2edbe1f0..46d995153 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,6 +2693,10 @@ }, "description": "Completed turns" }, + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when 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 +7573,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 +7858,192 @@ "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.historyBrowsing`. 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" + ] + }, + "ReadChatTurnsPageParams": { + "type": "object", + "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", + "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", + "description": "Stable ID of the first turn to return. Omit when continuing by cursor." + }, + "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 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", + "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 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": "Consecutive whole turns, oldest first, including on a previous-page read.", + "minItems": 1 + }, + "previousCursor": { + "type": "string", + "description": "Read immediately before the first returned turn; absent at the start." + } + }, + "required": [ + "turns" + ] + }, "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.", @@ -11146,7 +11341,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..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,6 +2995,10 @@ }, "description": "Completed turns" }, + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when 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..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,6 +2604,10 @@ }, "description": "Completed turns" }, + "historyBrowsing": { + "$ref": "#/$defs/ChatHistoryBrowsingCapability", + "description": "Browse retained history independently of the subscription window. Absent when 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/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 a66676407..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; @@ -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' }, @@ -2380,6 +2381,8 @@ 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: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index c8c124d9d..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; @@ -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' }, @@ -1879,6 +1880,8 @@ 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: '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..44b2ea263 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' && @@ -166,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))); } @@ -610,6 +612,43 @@ 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, 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, 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)))); + + 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', () => { if (file !== 'commands.schema.json') { return; diff --git a/scripts/generate-json-schema.ts b/scripts/generate-json-schema.ts index b22fa9d81..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; @@ -40,6 +41,7 @@ interface JsonSchema { minimum?: number; maximum?: number; minLength?: number; + maxLength?: number; oneOf?: JsonSchema[]; allOf?: JsonSchema[]; anyOf?: JsonSchema[]; @@ -410,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') { @@ -431,14 +434,23 @@ 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; + } + } + 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.minLength = minLength; + propSchema.minItems = minItems; } const uniqueItemsBy = getUniqueItemsByConstraints(prop); if (uniqueItemsBy) { diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index de2f5d6ee..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; @@ -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', @@ -1853,6 +1854,8 @@ const COMMAND_STRUCTS = [ 'ResourceRequestParams', 'ResourceRequestResult', 'CreateResourceWatchParams', 'CreateResourceWatchResult', 'FetchTurnsParams', 'FetchTurnsResult', + 'ChatTurnIndexEntry', 'ListChatTurnsParams', 'ListChatTurnsResult', + 'ReadChatTurnsParams', 'ReadChatTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', @@ -2387,6 +2390,12 @@ 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 authenticate(id: Long, params: AuthenticateParams): JsonRpcRequest = JsonRpcRequest(id = id, method = "authenticate", params = params) 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 47322a0f0..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; @@ -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' }, @@ -1953,6 +1954,8 @@ 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: '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..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; @@ -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', @@ -1800,6 +1801,8 @@ const COMMAND_STRUCTS = [ 'ResourceRequestParams', 'ResourceRequestResult', 'CreateResourceWatchParams', 'CreateResourceWatchResult', 'FetchTurnsParams', 'FetchTurnsResult', + 'ChatTurnIndexEntry', 'ListChatTurnsParams', 'ListChatTurnsResult', + 'ReadChatTurnsParams', 'ReadChatTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', 'McpServerAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', @@ -2379,6 +2382,14 @@ 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 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..aca2357f9 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,109 @@ 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.historyBrowsing`. 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; +} + +/** + * 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 + * @method readChatTurns + * @direction Client → Server + * @messageType Request + * @version 1 + */ +interface ReadChatTurnsPageParams extends BaseParams { + /** Chat URI. */ + channel: URI; + /** 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 on this page; defaults to 10. + * @integer + * @minimum 1 + */ + limit?: number; +} + +/** 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[]; + /** 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/channels-chat/state.ts b/types/channels-chat/state.ts index 28861c4aa..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,6 +148,8 @@ export interface ChatState { // ── Conversation contents ────────────────────────────────────────── /** Completed turns */ turns: Turn[]; + /** 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/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..1329a7c03 100644 --- a/types/common/messages.ts +++ b/types/common/messages.ts @@ -59,6 +59,10 @@ import type { MoveChatParams, MoveChatResult, DisposeChatParams, + ListChatTurnsParams, + ListChatTurnsResult, + ReadChatTurnsParams, + ReadChatTurnsResult, } from '../channels-chat/commands.js'; import type { CreateTerminalParams, @@ -174,6 +178,8 @@ 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 }; 'createTerminal': { params: CreateTerminalParams; result: null }; 'disposeTerminal': { params: DisposeTerminalParams; result: null }; 'createResourceWatch': { params: CreateResourceWatchParams; result: CreateResourceWatchResult }; 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/100-chat-history-navigation-snapshot.json b/types/test-cases/round-trips/100-chat-history-navigation-snapshot.json new file mode 100644 index 000000000..34c7d7f7d --- /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", "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", "historyBrowsing": {} } + }] +} 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..854f557b3 --- /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": "Open a page starting at the selected turn without backfilling the subscription.", + "type": "ReadChatTurnsParams", + "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 new file mode 100644 index 000000000..4cb8023f6 --- /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": "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" }], + "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" }], + "previousCursor": "older", + "nextCursor": "newer" + }] +} diff --git a/types/version/message-checks.ts b/types/version/message-checks.ts index cc84e3bf9..f2c678455 100644 --- a/types/version/message-checks.ts +++ b/types/version/message-checks.ts @@ -60,6 +60,8 @@ type _ExpectedCommands = | 'createTcpConnection' | 'moveChat' | 'disposeChat' + | 'listChatTurns' + | 'readChatTurns' | 'createTerminal' | 'disposeTerminal' | 'createResourceWatch'