From 0ae73ce59ea844501152e87a9881f12a7dcb7450 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Mon, 23 Nov 2026 18:04:50 -0500 Subject: [PATCH 01/17] models: add model source registry Implements the host-wide model source registry from the model source registry proposal (#622): - `RootState.modelSourceRegistrations` with `ModelSourceRegistration`, its sharing and retention policies, and the `starting`, `ready`, `authRequired`, and `error` states. - Client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions (introduced in 1.2.0) with root reducers in TypeScript and every client. - `AgentCapabilities.modelSourceRegistration` listing the definition formats an agent reads. - A `modelSource` `authenticate` target for delivering a registered source's credential. - Generator registration, reducer and round-trip fixtures, spec and naming docs, and changelog fragments. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../protocol-naming.instructions.md | 5 +- .../Generated/Actions.generated.cs | 33 ++ .../Generated/Commands.generated.cs | 62 +- .../JsonSerializerContext.generated.cs | 14 + .../Generated/State.generated.cs | 392 ++++++++++++- .../Generated/ActionMetadata.generated.cs | 6 + .../dotnet/src/AgentHostProtocol/Reducers.cs | 28 + clients/go/ahp/reducers.go | 17 + clients/go/ahptypes/actions.generated.go | 39 ++ clients/go/ahptypes/commands.generated.go | 69 ++- clients/go/ahptypes/state.generated.go | 326 ++++++++++- .../microsoft/agenthostprotocol/Reducers.kt | 19 + .../generated/Actions.generated.kt | 41 ++ .../generated/Commands.generated.kt | 54 +- .../generated/State.generated.kt | 412 ++++++++++++- clients/rust/crates/ahp-types/src/actions.rs | 48 +- clients/rust/crates/ahp-types/src/commands.rs | 63 +- clients/rust/crates/ahp-types/src/state.rs | 325 ++++++++++- .../rust/crates/ahp/examples/reducers_demo.rs | 1 + clients/rust/crates/ahp/src/hosts/runtime.rs | 1 + clients/rust/crates/ahp/src/lib.rs | 1 + .../crates/ahp/src/multi_host_state_mirror.rs | 1 + clients/rust/crates/ahp/src/reducers.rs | 23 + .../ahp/tests/multi_host_state_mirror.rs | 1 + .../Generated/ActionOrigin.generated.swift | 4 + .../Generated/Actions.generated.swift | 53 ++ .../Generated/Commands.generated.swift | 58 +- .../Generated/State.generated.swift | 542 +++++++++++++++++- .../AgentHostProtocol/NativeReducer.swift | 26 + .../Sources/AgentHostProtocol/Reducers.swift | 10 + ...61123-model-source-registry-migration.json | 6 + .../20261123-model-source-registry.json | 5 + docs/guide/actions.md | 4 +- docs/guide/state-model.md | 1 + docs/proposals/model-source-registry.md | 2 +- docs/specification/authentication.md | 49 +- docs/specification/root-channel.md | 65 ++- schema/actions.schema.json | 263 ++++++++- schema/commands.schema.json | 301 +++++++++- schema/errors.schema.json | 301 +++++++++- schema/notifications.schema.json | 215 ++++++- schema/state.schema.json | 223 ++++++- scripts/generate-csharp.ts | 30 +- scripts/generate-go.ts | 28 + scripts/generate-kotlin.ts | 24 +- scripts/generate-rust.ts | 32 +- scripts/generate-swift.ts | 23 +- scripts/read-stability.test.ts | 2 +- types/action-origin.generated.ts | 8 + types/channels-root/actions.ts | 35 +- types/channels-root/reducer.ts | 26 + types/channels-root/state.ts | 231 +++++++- types/common/actions.ts | 6 + types/common/commands.ts | 72 ++- ...gistrationset-adds-to-absent-registry.json | 43 ++ ...lsourceregistrationset-appends-new-id.json | 71 +++ ...lsourceregistrationset-replaces-by-id.json | 90 +++ ...urceregistrationremoved-removes-by-id.json | 59 ++ ...istrationremoved-no-op-for-unknown-id.json | 46 ++ ...ionremoved-no-op-when-registry-absent.json | 16 + .../102-model-source-registry-snapshot.json | 354 ++++++++++++ ...03-root-model-source-registration-set.json | 52 ++ ...oot-model-source-registration-removed.json | 16 + .../105-authenticate-model-source-target.json | 26 + types/version/registry.ts | 2 + 65 files changed, 5248 insertions(+), 153 deletions(-) create mode 100644 docs/.changes/20261123-model-source-registry-migration.json create mode 100644 docs/.changes/20261123-model-source-registry.json create mode 100644 types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json create mode 100644 types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json create mode 100644 types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json create mode 100644 types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json create mode 100644 types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json create mode 100644 types/test-cases/reducers/335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json create mode 100644 types/test-cases/round-trips/102-model-source-registry-snapshot.json create mode 100644 types/test-cases/round-trips/103-root-model-source-registration-set.json create mode 100644 types/test-cases/round-trips/104-root-model-source-registration-removed.json create mode 100644 types/test-cases/round-trips/105-authenticate-model-source-target.json diff --git a/.github/instructions/protocol-naming.instructions.md b/.github/instructions/protocol-naming.instructions.md index 9564a57b6..57c7f7b5d 100644 --- a/.github/instructions/protocol-naming.instructions.md +++ b/.github/instructions/protocol-naming.instructions.md @@ -36,8 +36,11 @@ but don't use them as precedent. | **response part** | One typed piece of a turn's response: markdown, reasoning, tool call, content reference, and so on. | | | **tool call** | A response part with its own lifecycle (`ToolCallStatus`) and confirmation flow. | | | **agent** | An agent implementation that the host exposes, described by `AgentInfo`. | | -| **agent provider** (`provider`) | The ID of the agent backing a session or chat (`AgentInfo.provider`, `SessionState.provider`, `ChatState.provider`). Always write "agent provider" in prose. | The **custom agent** (`Message.agent`, `AgentSelection`): a configured persona within an agent provider. The **model vendor** (`SessionModelInfo.vendor`): the company that serves a model. | +| **agent provider** (`provider`) | The ID of the agent backing a session or chat (`AgentInfo.provider`, `SessionState.provider`, `ChatState.provider`). Always write "agent provider" in prose. | The **custom agent** (`Message.agent`, `AgentSelection`): a configured persona within an agent provider. The **model vendor** (`SessionModelInfo.vendor`): the company that serves a model. The **model source** (`modelSourceId`): where a model comes from. | | **model** | A model offered by an agent provider (`SessionModelInfo`). It is selected per message (`Message.model`). | | +| **model source** (`modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `AgentInfo.modelSources` (`ModelSourceInfo`). Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | +| **registration** (`ModelSourceRegistration`) | A model source a client or the host added to the host's registry in `RootState.modelSourceRegistrations`, with its definition and status. A ready registration joins its agent's catalog as a model source. | The **model source** it becomes in the catalog. | +| **contributing client** | The client that added a client-contributed entry, named by its `clientId`, such as the client that registered a model source. It supplies the source's credential and chooses its sharing and retention. | The **action origin**'s `clientId`, which names the client that dispatched one action. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | | **pending message** | Input waiting to be consumed. Its `kind` is **steering** (injected into the active turn) or **queued** (starts a later turn). Both kinds live in `ChatState.queuedMessages`. | | | **working directories** | The session's set of directories. A chat may use a subset. | Don't use "workspace" for a protocol field. | diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 394577de9..cf2e65f7d 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -199,6 +199,10 @@ public ActionType(string value) public static readonly ActionType RootConfigChanged = new ActionType("root/configChanged"); + public static readonly ActionType RootModelSourceRegistrationSet = new ActionType("root/modelSourceRegistrationSet"); + + public static readonly ActionType RootModelSourceRegistrationRemoved = new ActionType("root/modelSourceRegistrationRemoved"); + public static readonly ActionType TerminalData = new ActionType("terminal/data"); public static readonly ActionType TerminalInput = new ActionType("terminal/input"); @@ -340,6 +344,33 @@ public sealed record RootConfigChangedAction public bool? Replace { get; init; } } +/// Adds a model source registration, or replaces the one with the same `id`. +/// +/// A client registers a source by dispatching this with its own `clientId` and +/// no `state`. The host reports status by dispatching it again with the same +/// registration and a `state`. +/// +/// Stability: 1.0 - Early development. +public sealed record RootModelSourceRegistrationSetAction +{ + public ActionType Type { get; init; } = ActionType.RootModelSourceRegistrationSet; + + /// The registration to add or replace, matched by `id`. + public required ModelSourceRegistration Registration { get; init; } +} + +/// Removes the model source registration with the given `id`. A no-op when +/// none matches. +/// +/// Stability: 1.0 - Early development. +public sealed record RootModelSourceRegistrationRemovedAction +{ + public ActionType Type { get; init; } = ActionType.RootModelSourceRegistrationRemoved; + + /// The registration's `id`. + public required string Id { get; init; } +} + /// Session backend initialized successfully. public sealed record SessionReadyAction { @@ -2858,6 +2889,8 @@ public StateActionConverter() ["root/agentsChanged"] = typeof(RootAgentsChangedAction), ["root/activeSessionsChanged"] = typeof(RootActiveSessionsChangedAction), ["root/configChanged"] = typeof(RootConfigChangedAction), + ["root/modelSourceRegistrationSet"] = typeof(RootModelSourceRegistrationSetAction), + ["root/modelSourceRegistrationRemoved"] = typeof(RootModelSourceRegistrationRemovedAction), ["session/ready"] = typeof(SessionReadyAction), ["session/creationFailed"] = typeof(SessionCreationFailedAction), ["session/turnStarted"] = typeof(SessionTurnStartedAction), diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 1b015b8cc..49d97f096 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -298,6 +298,9 @@ public AuthenticateTargetKind(string value) public static readonly AuthenticateTargetKind McpServer = new AuthenticateTargetKind("mcpServer"); + /// A {@link ModelSourceAuthenticateTarget}. + public static readonly AuthenticateTargetKind ModelSource = new AuthenticateTargetKind("modelSource"); + /// public bool Equals(AuthenticateTargetKind other) => string.Equals(Value, other.Value, StringComparison.Ordinal); @@ -1872,19 +1875,32 @@ public sealed record McpServerAuthenticateTarget public required string CustomizationId { get; init; } } -/// Pushes a Bearer token for a protected resource. The `resource` field MUST +/// A registered model source. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceAuthenticateTarget +{ + public AuthenticateTargetKind Kind { get; init; } = AuthenticateTargetKind.ModelSource; + + /// The registration's `ModelSourceRegistration.id`. + public required string ModelSourceId { get; init; } +} + +/// Pushes a credential for a protected resource. The `resource` field MUST /// match a protected-resource identifier the client has discovered from the /// server — whether declared statically in `AgentInfo.protectedResources`, -/// or discovered dynamically from a live `McpServerAuthRequiredState.resource` -/// or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the -/// corresponding MCP server or tool call actually challenges for auth). -/// Servers MUST accept any `resource` value they have themselves advertised -/// through one of these three mechanisms. +/// or discovered dynamically from a live `McpServerAuthRequiredState.resource`, +/// `ToolCallAuthRequiredState.auth.resource`, or +/// `ModelSourceAuthRequiredState.resource` (each surfaced only once the +/// corresponding MCP server, tool call, or model source actually challenges +/// for auth). Servers MUST accept any `resource` value they have themselves +/// advertised through one of these mechanisms. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the /// authorization server(s) listed in the resource's metadata and pushes it -/// to the server via this command. +/// to the server via this command. A model source's token is instead an +/// opaque secret, such as an API key. public sealed record AuthenticateParams { public required string Channel { get; init; } @@ -1898,10 +1914,12 @@ public sealed record AuthenticateParams /// The protected resource identifier. MUST match a `resource` value the /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live - /// `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`. + /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, + /// or `ModelSourceAuthRequiredState.resource`. public required string Resource { get; init; } - /// Bearer token obtained from the resource's authorization server + /// Bearer token obtained from the resource's authorization server, or an + /// opaque secret for a model source. An empty string revokes the credential. public required string Token { get; init; } /// The access token's remaining lifetime, in seconds, when this @@ -1913,6 +1931,8 @@ public sealed record AuthenticateParams /// authorization server did not supply an expiry or the expiry is otherwise /// unknown. When supplied, the value MUST be a positive integer. /// + /// An API key omits this field. + /// /// This field is irrelevant when `token` is empty to revoke authentication /// and SHOULD be omitted in that case. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -1923,21 +1943,28 @@ public sealed record AuthenticateParams /// `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is /// satisfied without decoding the (opaque, server-specific) token itself. /// Omit when the client doesn't track granted scopes separately from the - /// token. + /// token. Scopes apply to OAuth-issued tokens only. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? Scopes { get; init; } /// Optional consumer of the token. Clients SHOULD include this when answering /// a specific MCP server's `McpServerAuthRequiredState` or - /// `ToolCallAuthRequiredState` challenge, and omit it for provider-level + /// `ToolCallAuthRequiredState` challenge, MUST include it when delivering a + /// registered model source's credential, and omit it for provider-level /// resources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data). /// - /// When present, the host MUST apply the token only to that MCP server in - /// that session, never to sibling servers, other sessions, or agent-level - /// resources, even if they share the resource and scopes. `resource` MUST - /// still equal that server's advertised `McpAuthRequirement.resource.resource`. - /// The host MUST reject an unknown session or customization, or a - /// customization that is not an MCP server, with `InvalidParams` (-32602). + /// For an `mcpServer` target, the host MUST apply the token only to that MCP + /// server in that session, never to sibling servers, other sessions, or + /// agent-level resources, even if they share the resource and scopes. + /// `resource` MUST still equal that server's advertised + /// `McpAuthRequirement.resource.resource`. The host MUST reject an unknown + /// session or customization, or a customization that is not an MCP server, + /// with `InvalidParams` (-32602). + /// + /// A registered model source takes its credential only through a + /// `modelSource` target. See + /// [Model source credentials](/specification/authentication#model-source-credentials) + /// for its rules. /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2370,6 +2397,7 @@ public AuthenticateTargetConverter() variants: new Dictionary { ["mcpServer"] = typeof(McpServerAuthenticateTarget), + ["modelSource"] = typeof(ModelSourceAuthenticateTarget), }, allowUnknown: true) { diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index b16e335a1..00cec27a8 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -298,7 +298,19 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(MessageOrigin))] [JsonSerializable(typeof(MessageResourceAttachment))] [JsonSerializable(typeof(ModelSelection))] +[JsonSerializable(typeof(ModelSourceAuthenticateTarget))] +[JsonSerializable(typeof(ModelSourceAuthRequiredState))] +[JsonSerializable(typeof(ModelSourceAuthRequirement))] +[JsonSerializable(typeof(ModelSourceErrorState))] [JsonSerializable(typeof(ModelSourceInfo))] +[JsonSerializable(typeof(ModelSourceReadyState))] +[JsonSerializable(typeof(ModelSourceRegistration))] +[JsonSerializable(typeof(ModelSourceRegistrationCapability))] +[JsonSerializable(typeof(ModelSourceRetentionPolicy))] +[JsonSerializable(typeof(ModelSourceSharingPolicy))] +[JsonSerializable(typeof(ModelSourceStartingState))] +[JsonSerializable(typeof(ModelSourceState))] +[JsonSerializable(typeof(ModelSourceStatus))] [JsonSerializable(typeof(MoveChatParams))] [JsonSerializable(typeof(MoveChatResult))] [JsonSerializable(typeof(MultipleChatProvidersCapability))] @@ -359,6 +371,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RootAgentsChangedAction))] [JsonSerializable(typeof(RootConfigChangedAction))] [JsonSerializable(typeof(RootConfigState))] +[JsonSerializable(typeof(RootModelSourceRegistrationRemovedAction))] +[JsonSerializable(typeof(RootModelSourceRegistrationSetAction))] [JsonSerializable(typeof(RootState))] [JsonSerializable(typeof(RootTerminalsChangedAction))] [JsonSerializable(typeof(RuleCustomization))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 8052b466e..98898a104 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1408,6 +1408,177 @@ public override void Write(Utf8JsonWriter writer, McpAuthRequiredReason value, J => writer.WriteStringValue(value.Value); } +/// Discriminant for the {@link ModelSourceState} union. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(ModelSourceStatusConverter))] +public readonly struct ModelSourceStatus : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public ModelSourceStatus(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// The agent is reading and validating the definition. + public static readonly ModelSourceStatus Starting = new ModelSourceStatus("starting"); + + /// The source is usable, and its models are in the agent's catalog. + public static readonly ModelSourceStatus Ready = new ModelSourceStatus("ready"); + + /// The source needs a credential before it can be used. + public static readonly ModelSourceStatus AuthRequired = new ModelSourceStatus("authRequired"); + + /// The source failed, or the host declined it. + public static readonly ModelSourceStatus Error = new ModelSourceStatus("error"); + + /// + public bool Equals(ModelSourceStatus other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is ModelSourceStatus other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(ModelSourceStatus left, ModelSourceStatus right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(ModelSourceStatus left, ModelSourceStatus right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class ModelSourceStatusConverter : JsonConverter +{ + /// + public override ModelSourceStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new ModelSourceStatus(reader.GetString() ?? throw new JsonException("ModelSourceStatus expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, ModelSourceStatus value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + +/// Who may select a registered model source's models. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(ModelSourceSharingPolicyConverter))] +public readonly struct ModelSourceSharingPolicy : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public ModelSourceSharingPolicy(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// Only turns and pending messages the contributing client dispatches. + public static readonly ModelSourceSharingPolicy ContributingClient = new ModelSourceSharingPolicy("contributingClient"); + + /// Any client, and work the host starts itself, such as automations. + public static readonly ModelSourceSharingPolicy Host = new ModelSourceSharingPolicy("host"); + + /// + public bool Equals(ModelSourceSharingPolicy other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is ModelSourceSharingPolicy other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(ModelSourceSharingPolicy left, ModelSourceSharingPolicy right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(ModelSourceSharingPolicy left, ModelSourceSharingPolicy right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class ModelSourceSharingPolicyConverter : JsonConverter +{ + /// + public override ModelSourceSharingPolicy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new ModelSourceSharingPolicy(reader.GetString() ?? throw new JsonException("ModelSourceSharingPolicy expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, ModelSourceSharingPolicy value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + +/// How long a registered model source lasts once its contributing client leaves. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(ModelSourceRetentionPolicyConverter))] +public readonly struct ModelSourceRetentionPolicy : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public ModelSourceRetentionPolicy(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// Removed when the contributing client leaves, once running turns finish. + public static readonly ModelSourceRetentionPolicy ContributingClient = new ModelSourceRetentionPolicy("contributingClient"); + + /// Kept until a client removes it or host policy expires it. + public static readonly ModelSourceRetentionPolicy Host = new ModelSourceRetentionPolicy("host"); + + /// + public bool Equals(ModelSourceRetentionPolicy other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is ModelSourceRetentionPolicy other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(ModelSourceRetentionPolicy left, ModelSourceRetentionPolicy right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(ModelSourceRetentionPolicy left, ModelSourceRetentionPolicy right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class ModelSourceRetentionPolicyConverter : JsonConverter +{ + /// + public override ModelSourceRetentionPolicy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new ModelSourceRetentionPolicy(reader.GetString() ?? throw new JsonException("ModelSourceRetentionPolicy expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, ModelSourceRetentionPolicy value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + /// Computation lifecycle of a {@link ChangesetState}. [JsonConverter(typeof(ChangesetStatusConverter))] public readonly struct ChangesetStatus : IEquatable @@ -2055,6 +2226,12 @@ public sealed class RootState [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public RootConfigState? Config { get; set; } + /// Model sources registered on this host, keyed by `id`. + /// + /// Stability: 1.0 - Early development. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? ModelSourceRegistrations { get; set; } + /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -2152,6 +2329,13 @@ public sealed record AgentCapabilities /// {@link CreateSessionParams.workingDirectories}. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public MultipleWorkingDirectoriesCapability? MultipleWorkingDirectories { get; init; } + + /// The agent serves models from registered model sources, in the listed + /// definition formats. + /// + /// Stability: 1.0 - Early development. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ModelSourceRegistrationCapability? ModelSourceRegistration { get; init; } } /// Options for the {@link AgentCapabilities.multipleChats} capability. @@ -2213,11 +2397,185 @@ public sealed record MultipleWorkingDirectoriesCapability public bool? PrimaryReplacement { get; init; } } +/// Options for the {@link AgentCapabilities.modelSourceRegistration} capability. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceRegistrationCapability +{ + /// Definition formats the agent reads, most preferred first. Format names + /// are defined by agent implementations and SHOULD be namespaced, for + /// example `example.com/model-source@1`. + public required List Formats { get; init; } + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// A model source registered on this host by a client, or by the host itself. +/// Its definition is in a format the agent named by `provider` reads. It never +/// contains a credential. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceRegistration +{ + /// Host-unique ID, chosen by whoever registers the source. Also the + /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the + /// {@link SessionModelInfo.modelSourceId} of its models. + public required string Id { get; init; } + + /// Agent provider whose agent reads the definition and serves the models. + public required string Provider { get; init; } + + /// Display name, published as {@link ModelSourceInfo.displayName}. + public required string Name { get; init; } + + /// Icons for UI display. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Icons { get; init; } + + /// Definition format, one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. + public required string Format { get; init; } + + /// How to reach the source: endpoint, wire format, models, and so on, in + /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain + /// a credential. + public required Dictionary Definition { get; init; } + + /// The contributing client. Absent for a source the host registered itself. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? ClientId { get; init; } + + /// Who may select the source's models. Absent means `contributingClient`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ModelSourceSharingPolicy? Sharing { get; init; } + + /// What happens when the contributing client leaves. Absent means `contributingClient`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ModelSourceRetentionPolicy? Retention { get; init; } + + /// Host-reported status. Absent means the host hasn't reported one yet. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ModelSourceState? State { get; init; } + + /// Additional implementation-defined metadata for this registration. + /// MUST NOT contain a credential. + [JsonPropertyName("_meta")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public Dictionary? Meta { get; init; } + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// The agent is reading and validating the definition, or listing the +/// source's models again after a credential change. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceStartingState +{ + public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Starting; + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// The source is usable, and its models are in the catalog of the agent named +/// by the registration's `provider`. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceReadyState +{ + public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Ready; + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// What a model source needs in order to become ready. Deliberately carries no +/// credential. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceAuthRequirement +{ + /// Why a credential is needed. + public AuthRequiredReason Reason { get; init; } + + /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the + /// endpoint URL as the definition names it, in any scheme the agent + /// supports (for example `http://localhost:11434/v1`). It's the value a + /// client passes back as `authenticate({ resource })`, and nothing fetches + /// it. `resource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + public required ProtectedResourceMetadata Resource { get; init; } + + /// Human-readable hint, for example the endpoint's error description. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Description { get; init; } + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// The source needs a credential before it can be used. A client answers with +/// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceAuthRequiredState +{ + /// Why a credential is needed. + public AuthRequiredReason Reason { get; init; } + + /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the + /// endpoint URL as the definition names it, in any scheme the agent + /// supports (for example `http://localhost:11434/v1`). It's the value a + /// client passes back as `authenticate({ resource })`, and nothing fetches + /// it. `resource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + public required ProtectedResourceMetadata Resource { get; init; } + + /// Human-readable hint, for example the endpoint's error description. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Description { get; init; } + + public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.AuthRequired; + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// The source failed, or the host declined it, for example by policy. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceErrorState +{ + public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Error; + + /// Error details. MUST NOT contain the credential. + public required ErrorInfo Error { get; init; } + + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + /// A source that an agent provider offers models from, such as a service or /// subscription. public sealed record ModelSourceInfo { - /// Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + /// Model source identifier, unique within the agent's + /// {@link AgentInfo.modelSources}. For a registered model source, this is + /// the {@link ModelSourceRegistration.id}. public required string Id { get; init; } /// Human-readable name @@ -2228,7 +2586,8 @@ public sealed record SessionModelInfo { /// Model identifier, unique within the agent's {@link AgentInfo.models}. /// When several model sources serve the same upstream model, the host gives - /// each entry its own ID. + /// each entry its own ID. An ID the host publishes for a registered model + /// source stays bound to that registration and upstream model. public required string Id { get; init; } /// Agent provider that owns this model. Matches {@link AgentInfo.provider}. @@ -8092,6 +8451,35 @@ public McpServerStateConverter() } } +/// ModelSourceState is the lifecycle state of a registered model source. +[JsonConverter(typeof(ModelSourceStateConverter))] +public sealed class ModelSourceState : AhpUnion +{ + /// Creates an empty ModelSourceState (no active variant). + public ModelSourceState() { } + + /// Creates a ModelSourceState wrapping the given variant value. + public ModelSourceState(object? value) : base(value) { } +} + +/// System.Text.Json converter for the ModelSourceState discriminated union. +internal sealed class ModelSourceStateConverter : UnionConverter +{ + public ModelSourceStateConverter() + : base( + discriminator: "kind", + variants: new Dictionary + { + ["starting"] = typeof(ModelSourceStartingState), + ["ready"] = typeof(ModelSourceReadyState), + ["authRequired"] = typeof(ModelSourceAuthRequiredState), + ["error"] = typeof(ModelSourceErrorState), + }, + allowUnknown: true) + { + } +} + /// ToolCallContributor identifies who provides a tool call (client or MCP server). [JsonConverter(typeof(ToolCallContributorConverter))] public sealed class ToolCallContributor : AhpUnion diff --git a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs index 1cc062b11..e7f995d71 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -211,6 +211,12 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootConfigChangedAction value: actionType = value.Type; return true; + case RootModelSourceRegistrationRemovedAction value: + actionType = value.Type; + return true; + case RootModelSourceRegistrationSetAction value: + actionType = value.Type; + return true; case RootTerminalsChangedAction value: actionType = value.Type; return true; diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index dadc1c50f..6f0d8a74d 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -680,6 +680,32 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) state.Config.Values = MergeConfig(state.Config.Values, a.Config, a.Replace); return ReduceOutcome.Applied; + case RootModelSourceRegistrationSetAction a: + { + List list = state.ModelSourceRegistrations ??= new List(); + int index = list.FindIndex(r => r.Id == a.Registration.Id); + if (index < 0) + { + list.Add(a.Registration); + } + else + { + list[index] = a.Registration; + } + + return ReduceOutcome.Applied; + } + case RootModelSourceRegistrationRemovedAction a: + { + int index = state.ModelSourceRegistrations?.FindIndex(r => r.Id == a.Id) ?? -1; + if (index < 0) + { + return ReduceOutcome.NoOp; + } + + state.ModelSourceRegistrations!.RemoveAt(index); + return ReduceOutcome.Applied; + } } return ReduceOutcome.OutOfScope; @@ -2625,6 +2651,8 @@ public static ReduceOutcome ApplyToAutomationRun( private static readonly string[] s_clientDispatchableActionNames = { "root/configChanged", + "root/modelSourceRegistrationSet", + "root/modelSourceRegistrationRemoved", // Chat-channel actions (post-#213) "chat/turnStarted", "chat/toolCallConfirmed", diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 22fe67c01..5afe4f9bb 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -537,6 +537,23 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R state.Config.Values[k] = v } return ReduceOutcomeApplied + case *ahptypes.RootModelSourceRegistrationSetAction: + for i := range state.ModelSourceRegistrations { + if state.ModelSourceRegistrations[i].Id == a.Registration.Id { + state.ModelSourceRegistrations[i] = a.Registration + return ReduceOutcomeApplied + } + } + state.ModelSourceRegistrations = append(state.ModelSourceRegistrations, a.Registration) + return ReduceOutcomeApplied + case *ahptypes.RootModelSourceRegistrationRemovedAction: + for i := range state.ModelSourceRegistrations { + if state.ModelSourceRegistrations[i].Id == a.Id { + state.ModelSourceRegistrations = append(state.ModelSourceRegistrations[:i], state.ModelSourceRegistrations[i+1:]...) + return ReduceOutcomeApplied + } + } + return ReduceOutcomeNoOp } return ReduceOutcomeOutOfScope } diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index cfb71a816..92b2475a1 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -106,6 +106,8 @@ const ( ActionTypeAnnotationsEntryRemoved ActionType = "annotations/entryRemoved" ActionTypeRootTerminalsChanged ActionType = "root/terminalsChanged" ActionTypeRootConfigChanged ActionType = "root/configChanged" + ActionTypeRootModelSourceRegistrationSet ActionType = "root/modelSourceRegistrationSet" + ActionTypeRootModelSourceRegistrationRemoved ActionType = "root/modelSourceRegistrationRemoved" ActionTypeTerminalData ActionType = "terminal/data" ActionTypeTerminalInput ActionType = "terminal/input" ActionTypeTerminalResized ActionType = "terminal/resized" @@ -176,6 +178,29 @@ type RootConfigChangedAction struct { Replace *bool `json:"replace,omitempty"` } +// Adds a model source registration, or replaces the one with the same `id`. +// +// A client registers a source by dispatching this with its own `clientId` and +// no `state`. The host reports status by dispatching it again with the same +// registration and a `state`. +// +// Stability: 1.0 - Early development. +type RootModelSourceRegistrationSetAction struct { + Type ActionType `json:"type"` + // The registration to add or replace, matched by `id`. + Registration ModelSourceRegistration `json:"registration"` +} + +// Removes the model source registration with the given `id`. A no-op when +// none matches. +// +// Stability: 1.0 - Early development. +type RootModelSourceRegistrationRemovedAction struct { + Type ActionType `json:"type"` + // The registration's `id`. + Id string `json:"id"` +} + // Session backend initialized successfully. type SessionReadyAction struct { Type ActionType `json:"type"` @@ -1861,6 +1886,8 @@ type isStateAction interface{ isStateAction() } func (*RootAgentsChangedAction) isStateAction() {} func (*RootActiveSessionsChangedAction) isStateAction() {} func (*RootConfigChangedAction) isStateAction() {} +func (*RootModelSourceRegistrationSetAction) isStateAction() {} +func (*RootModelSourceRegistrationRemovedAction) isStateAction() {} func (*SessionReadyAction) isStateAction() {} func (*SessionCreationFailedAction) isStateAction() {} func (*SessionChatAddedAction) isStateAction() {} @@ -1999,6 +2026,18 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value + case "root/modelSourceRegistrationSet": + var value RootModelSourceRegistrationSetAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "root/modelSourceRegistrationRemoved": + var value RootModelSourceRegistrationRemovedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value case "session/ready": var value SessionReadyAction if err := json.Unmarshal(data, &value); err != nil { diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index 88c458bf5..ea0f5daf7 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -110,6 +110,8 @@ type AuthenticateTargetKind string const ( AuthenticateTargetKindMcpServer AuthenticateTargetKind = "mcpServer" + // A {@link ModelSourceAuthenticateTarget}. + AuthenticateTargetKindModelSource AuthenticateTargetKind = "modelSource" ) // ─── Command Payloads ───────────────────────────────────────────────── @@ -1341,19 +1343,30 @@ type McpServerAuthenticateTarget struct { CustomizationId string `json:"customizationId"` } -// Pushes a Bearer token for a protected resource. The `resource` field MUST +// A registered model source. +// +// Stability: 1.0 - Early development. +type ModelSourceAuthenticateTarget struct { + Kind AuthenticateTargetKind `json:"kind"` + // The registration's `ModelSourceRegistration.id`. + ModelSourceId string `json:"modelSourceId"` +} + +// Pushes a credential for a protected resource. The `resource` field MUST // match a protected-resource identifier the client has discovered from the // server — whether declared statically in `AgentInfo.protectedResources`, -// or discovered dynamically from a live `McpServerAuthRequiredState.resource` -// or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the -// corresponding MCP server or tool call actually challenges for auth). -// Servers MUST accept any `resource` value they have themselves advertised -// through one of these three mechanisms. +// or discovered dynamically from a live `McpServerAuthRequiredState.resource`, +// `ToolCallAuthRequiredState.auth.resource`, or +// `ModelSourceAuthRequiredState.resource` (each surfaced only once the +// corresponding MCP server, tool call, or model source actually challenges +// for auth). Servers MUST accept any `resource` value they have themselves +// advertised through one of these mechanisms. // // Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) // (Bearer Token Usage) semantics. The client obtains the token from the // authorization server(s) listed in the resource's metadata and pushes it -// to the server via this command. +// to the server via this command. A model source's token is instead an +// opaque secret, such as an API key. type AuthenticateParams struct { // Channel URI this command targets. Channel URI `json:"channel"` @@ -1363,9 +1376,11 @@ type AuthenticateParams struct { // The protected resource identifier. MUST match a `resource` value the // server has advertised — via `ProtectedResourceMetadata` in // `AgentInfo.protectedResources`, or via a live - // `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`. + // `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, + // or `ModelSourceAuthRequiredState.resource`. Resource string `json:"resource"` - // Bearer token obtained from the resource's authorization server + // Bearer token obtained from the resource's authorization server, or an + // opaque secret for a model source. An empty string revokes the credential. Token string `json:"token"` // The access token's remaining lifetime, in seconds, when this // `authenticate` request is sent. This corresponds to `expires_in` in an @@ -1376,6 +1391,8 @@ type AuthenticateParams struct { // authorization server did not supply an expiry or the expiry is otherwise // unknown. When supplied, the value MUST be a positive integer. // + // An API key omits this field. + // // This field is irrelevant when `token` is empty to revoke authentication // and SHOULD be omitted in that case. ExpiresIn *int64 `json:"expiresIn,omitempty"` @@ -1384,19 +1401,26 @@ type AuthenticateParams struct { // `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is // satisfied without decoding the (opaque, server-specific) token itself. // Omit when the client doesn't track granted scopes separately from the - // token. + // token. Scopes apply to OAuth-issued tokens only. Scopes []string `json:"scopes,omitempty"` // Optional consumer of the token. Clients SHOULD include this when answering // a specific MCP server's `McpServerAuthRequiredState` or - // `ToolCallAuthRequiredState` challenge, and omit it for provider-level + // `ToolCallAuthRequiredState` challenge, MUST include it when delivering a + // registered model source's credential, and omit it for provider-level // resources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data). // - // When present, the host MUST apply the token only to that MCP server in - // that session, never to sibling servers, other sessions, or agent-level - // resources, even if they share the resource and scopes. `resource` MUST - // still equal that server's advertised `McpAuthRequirement.resource.resource`. - // The host MUST reject an unknown session or customization, or a - // customization that is not an MCP server, with `InvalidParams` (-32602). + // For an `mcpServer` target, the host MUST apply the token only to that MCP + // server in that session, never to sibling servers, other sessions, or + // agent-level resources, even if they share the resource and scopes. + // `resource` MUST still equal that server's advertised + // `McpAuthRequirement.resource.resource`. The host MUST reject an unknown + // session or customization, or a customization that is not an MCP server, + // with `InvalidParams` (-32602). + // + // A registered model source takes its credential only through a + // `modelSource` target. See + // [Model source credentials](/specification/authentication#model-source-credentials) + // for its rules. // // Without a target, resource/scope matching is unchanged; the token may // satisfy every matching pending challenge. Older hosts ignore this field. @@ -1951,7 +1975,8 @@ type AuthenticateTarget struct { // concrete variant of AuthenticateTarget. type isAuthenticateTarget interface{ isAuthenticateTarget() } -func (*McpServerAuthenticateTarget) isAuthenticateTarget() {} +func (*McpServerAuthenticateTarget) isAuthenticateTarget() {} +func (*ModelSourceAuthenticateTarget) isAuthenticateTarget() {} // AuthenticateTargetUnknown carries an unrecognized AuthenticateTarget variant — typically a discriminator value introduced by a newer protocol version. The original JSON object is preserved verbatim so that re-encoding round-trips faithfully. type AuthenticateTargetUnknown struct { @@ -1973,6 +1998,12 @@ func (u *AuthenticateTarget) UnmarshalJSON(data []byte) error { return err } u.Value = &value + case "modelSource": + var value ModelSourceAuthenticateTarget + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value default: raw := make(json.RawMessage, len(data)) copy(raw, data) @@ -2006,6 +2037,8 @@ func (u AuthenticateTarget) MarshalJSON() ([]byte, error) { switch u.Value.(type) { case *McpServerAuthenticateTarget: object["kind"] = json.RawMessage("\"mcpServer\"") + case *ModelSourceAuthenticateTarget: + object["kind"] = json.RawMessage("\"modelSource\"") } return json.Marshal(object) } diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index f3f579d2f..e80a9d5e8 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -436,6 +436,46 @@ const ( McpAuthRequiredReasonInsufficientScope McpAuthRequiredReason = "insufficientScope" ) +// Discriminant for the {@link ModelSourceState} union. +// +// Stability: 1.0 - Early development. +type ModelSourceStatus string + +const ( + // The agent is reading and validating the definition. + ModelSourceStatusStarting ModelSourceStatus = "starting" + // The source is usable, and its models are in the agent's catalog. + ModelSourceStatusReady ModelSourceStatus = "ready" + // The source needs a credential before it can be used. + ModelSourceStatusAuthRequired ModelSourceStatus = "authRequired" + // The source failed, or the host declined it. + ModelSourceStatusError ModelSourceStatus = "error" +) + +// Who may select a registered model source's models. +// +// Stability: 1.0 - Early development. +type ModelSourceSharingPolicy string + +const ( + // Only turns and pending messages the contributing client dispatches. + ModelSourceSharingPolicyContributingClient ModelSourceSharingPolicy = "contributingClient" + // Any client, and work the host starts itself, such as automations. + ModelSourceSharingPolicyHost ModelSourceSharingPolicy = "host" +) + +// How long a registered model source lasts once its contributing client leaves. +// +// Stability: 1.0 - Early development. +type ModelSourceRetentionPolicy string + +const ( + // Removed when the contributing client leaves, once running turns finish. + ModelSourceRetentionPolicyContributingClient ModelSourceRetentionPolicy = "contributingClient" + // Kept until a client removes it or host policy expires it. + ModelSourceRetentionPolicyHost ModelSourceRetentionPolicy = "host" +) + // Computation lifecycle of a {@link ChangesetState}. type ChangesetStatus string @@ -780,6 +820,10 @@ type RootState struct { Terminals []TerminalInfo `json:"terminals,omitempty"` // Agent host configuration schema and current values Config *RootConfigState `json:"config,omitempty"` + // Model sources registered on this host, keyed by `id`. + // + // Stability: 1.0 - Early development. + ModelSourceRegistrations []ModelSourceRegistration `json:"modelSourceRegistrations,omitempty"` // Additional implementation-defined metadata about the agent host itself. // // Clients MAY look for well-known keys here to provide enhanced UI. @@ -857,6 +901,11 @@ type AgentCapabilities struct { // set and MUST NOT set more than one entry in // {@link CreateSessionParams.workingDirectories}. MultipleWorkingDirectories *MultipleWorkingDirectoriesCapability `json:"multipleWorkingDirectories,omitempty"` + // The agent serves models from registered model sources, in the listed + // definition formats. + // + // Stability: 1.0 - Early development. + ModelSourceRegistration *ModelSourceRegistrationCapability `json:"modelSourceRegistration,omitempty"` } // Options for the {@link AgentCapabilities.multipleChats} capability. @@ -910,10 +959,208 @@ type MultipleWorkingDirectoriesCapability struct { PrimaryReplacement *bool `json:"primaryReplacement,omitempty"` } +// Options for the {@link AgentCapabilities.modelSourceRegistration} capability. +// +// Stability: 1.0 - Early development. +type ModelSourceRegistrationCapability struct { + // Definition formats the agent reads, most preferred first. Format names + // are defined by agent implementations and SHOULD be namespaced, for + // example `example.com/model-source@1`. + Formats []string `json:"formats"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceRegistrationCapability) UnmarshalJSON(data []byte) error { + type wire ModelSourceRegistrationCapability + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "formats") +} + +func (v ModelSourceRegistrationCapability) MarshalJSON() ([]byte, error) { + type wire ModelSourceRegistrationCapability + return marshalWithExtra(wire(v), v.Extra, "formats") +} + +// A model source registered on this host by a client, or by the host itself. +// Its definition is in a format the agent named by `provider` reads. It never +// contains a credential. +// +// Stability: 1.0 - Early development. +type ModelSourceRegistration struct { + // Host-unique ID, chosen by whoever registers the source. Also the + // source's {@link ModelSourceInfo.id} in the agent's catalog, and the + // {@link SessionModelInfo.modelSourceId} of its models. + Id string `json:"id"` + // Agent provider whose agent reads the definition and serves the models. + Provider string `json:"provider"` + // Display name, published as {@link ModelSourceInfo.displayName}. + Name string `json:"name"` + // Icons for UI display. + Icons []Icon `json:"icons,omitempty"` + // Definition format, one of the agent's + // {@link ModelSourceRegistrationCapability.formats}. + Format string `json:"format"` + // How to reach the source: endpoint, wire format, models, and so on, in + // `format`. Its shape belongs to the agent that reads it. MUST NOT contain + // a credential. + Definition map[string]json.RawMessage `json:"definition"` + // The contributing client. Absent for a source the host registered itself. + ClientId *string `json:"clientId,omitempty"` + // Who may select the source's models. Absent means `contributingClient`. + Sharing *ModelSourceSharingPolicy `json:"sharing,omitempty"` + // What happens when the contributing client leaves. Absent means `contributingClient`. + Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` + // Host-reported status. Absent means the host hasn't reported one yet. + State *ModelSourceState `json:"state,omitempty"` + // Additional implementation-defined metadata for this registration. + // MUST NOT contain a credential. + Meta map[string]json.RawMessage `json:"_meta,omitempty"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { + type wire ModelSourceRegistration + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "_meta") +} + +func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { + type wire ModelSourceRegistration + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "_meta") +} + +// The agent is reading and validating the definition, or listing the +// source's models again after a credential change. +// +// Stability: 1.0 - Early development. +type ModelSourceStartingState struct { + Kind ModelSourceStatus `json:"kind"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceStartingState) UnmarshalJSON(data []byte) error { + type wire ModelSourceStartingState + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind") +} + +func (v ModelSourceStartingState) MarshalJSON() ([]byte, error) { + type wire ModelSourceStartingState + return marshalWithExtra(wire(v), v.Extra, "kind") +} + +// The source is usable, and its models are in the catalog of the agent named +// by the registration's `provider`. +// +// Stability: 1.0 - Early development. +type ModelSourceReadyState struct { + Kind ModelSourceStatus `json:"kind"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceReadyState) UnmarshalJSON(data []byte) error { + type wire ModelSourceReadyState + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind") +} + +func (v ModelSourceReadyState) MarshalJSON() ([]byte, error) { + type wire ModelSourceReadyState + return marshalWithExtra(wire(v), v.Extra, "kind") +} + +// What a model source needs in order to become ready. Deliberately carries no +// credential. +// +// Stability: 1.0 - Early development. +type ModelSourceAuthRequirement struct { + // Why a credential is needed. + Reason AuthRequiredReason `json:"reason"` + // RFC 9728 metadata for the source's endpoint. `resource.resource` is the + // endpoint URL as the definition names it, in any scheme the agent + // supports (for example `http://localhost:11434/v1`). It's the value a + // client passes back as `authenticate({ resource })`, and nothing fetches + // it. `resource.resource_name` labels the prompt (for example + // "OpenRouter API key"). A source that accepts OAuth access tokens + // advertises `authorization_servers` and `scopes_supported`. A source that + // takes a user-supplied secret omits them. + Resource ProtectedResourceMetadata `json:"resource"` + // Human-readable hint, for example the endpoint's error description. + Description *string `json:"description,omitempty"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceAuthRequirement) UnmarshalJSON(data []byte) error { + type wire ModelSourceAuthRequirement + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "resource", "description") +} + +func (v ModelSourceAuthRequirement) MarshalJSON() ([]byte, error) { + type wire ModelSourceAuthRequirement + return marshalWithExtra(wire(v), v.Extra, "reason", "resource", "description") +} + +// The source needs a credential before it can be used. A client answers with +// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +// +// Stability: 1.0 - Early development. +type ModelSourceAuthRequiredState struct { + // Why a credential is needed. + Reason AuthRequiredReason `json:"reason"` + // RFC 9728 metadata for the source's endpoint. `resource.resource` is the + // endpoint URL as the definition names it, in any scheme the agent + // supports (for example `http://localhost:11434/v1`). It's the value a + // client passes back as `authenticate({ resource })`, and nothing fetches + // it. `resource.resource_name` labels the prompt (for example + // "OpenRouter API key"). A source that accepts OAuth access tokens + // advertises `authorization_servers` and `scopes_supported`. A source that + // takes a user-supplied secret omits them. + Resource ProtectedResourceMetadata `json:"resource"` + // Human-readable hint, for example the endpoint's error description. + Description *string `json:"description,omitempty"` + Kind ModelSourceStatus `json:"kind"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceAuthRequiredState) UnmarshalJSON(data []byte) error { + type wire ModelSourceAuthRequiredState + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "resource", "description", "kind") +} + +func (v ModelSourceAuthRequiredState) MarshalJSON() ([]byte, error) { + type wire ModelSourceAuthRequiredState + return marshalWithExtra(wire(v), v.Extra, "reason", "resource", "description", "kind") +} + +// The source failed, or the host declined it, for example by policy. +// +// Stability: 1.0 - Early development. +type ModelSourceErrorState struct { + Kind ModelSourceStatus `json:"kind"` + // Error details. MUST NOT contain the credential. + Error ErrorInfo `json:"error"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceErrorState) UnmarshalJSON(data []byte) error { + type wire ModelSourceErrorState + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind", "error") +} + +func (v ModelSourceErrorState) MarshalJSON() ([]byte, error) { + type wire ModelSourceErrorState + return marshalWithExtra(wire(v), v.Extra, "kind", "error") +} + // A source that an agent provider offers models from, such as a service or // subscription. type ModelSourceInfo struct { - // Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + // Model source identifier, unique within the agent's + // {@link AgentInfo.modelSources}. For a registered model source, this is + // the {@link ModelSourceRegistration.id}. Id string `json:"id"` // Human-readable name DisplayName string `json:"displayName"` @@ -922,7 +1169,8 @@ type ModelSourceInfo struct { type SessionModelInfo struct { // Model identifier, unique within the agent's {@link AgentInfo.models}. // When several model sources serve the same upstream model, the host gives - // each entry its own ID. + // each entry its own ID. An ID the host publishes for a registered model + // source stays bound to that registration and upstream model. Id string `json:"id"` // Agent provider that owns this model. Matches {@link AgentInfo.provider}. Provider string `json:"provider"` @@ -6547,6 +6795,80 @@ func (u McpServerState) MarshalJSON() ([]byte, error) { return json.Marshal(u.Value) } +// ModelSourceState is the discriminated lifecycle status of a registered model source. +type ModelSourceState struct { + Value isModelSourceState +} + +// isModelSourceState is the marker interface implemented by every +// concrete variant of ModelSourceState. +type isModelSourceState interface{ isModelSourceState() } + +func (*ModelSourceStartingState) isModelSourceState() {} +func (*ModelSourceReadyState) isModelSourceState() {} +func (*ModelSourceAuthRequiredState) isModelSourceState() {} +func (*ModelSourceErrorState) isModelSourceState() {} + +// ModelSourceStateUnknown carries an unrecognized ModelSourceState variant — typically a discriminator value introduced by a newer protocol version. The original JSON object is preserved verbatim so that re-encoding round-trips faithfully. +type ModelSourceStateUnknown struct { + Raw json.RawMessage +} + +func (*ModelSourceStateUnknown) isModelSourceState() {} + +// UnmarshalJSON decodes the variant indicated by the "kind" discriminator. +func (u *ModelSourceState) UnmarshalJSON(data []byte) error { + disc, _, err := readDiscriminator(data, "kind") + if err != nil { + return err + } + switch disc { + case "starting": + var value ModelSourceStartingState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "ready": + var value ModelSourceReadyState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "authRequired": + var value ModelSourceAuthRequiredState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "error": + var value ModelSourceErrorState + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + default: + raw := make(json.RawMessage, len(data)) + copy(raw, data) + u.Value = &ModelSourceStateUnknown{Raw: raw} + } + return nil +} + +// MarshalJSON encodes the active variant back to JSON. +func (u ModelSourceState) MarshalJSON() ([]byte, error) { + if unk, ok := u.Value.(*ModelSourceStateUnknown); ok { + if len(unk.Raw) == 0 { + return []byte("null"), nil + } + return unk.Raw, nil + } + if u.Value == nil { + return []byte("null"), nil + } + return json.Marshal(u.Value) +} + // ToolCallContributor identifies the contributor (client or MCP server) of a tool call. type ToolCallContributor struct { Value isToolCallContributor diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index dd291e656..3b69faff5 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -575,6 +575,25 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when } } + is StateActionRootModelSourceRegistrationSet -> { + val registration = action.value.registration + val list = state.modelSourceRegistrations.orEmpty() + val idx = list.indexOfFirst { it.id == registration.id } + val updated = list.toMutableList() + if (idx < 0) updated.add(registration) else updated[idx] = registration + state.copy(modelSourceRegistrations = updated) + } + + is StateActionRootModelSourceRegistrationRemoved -> { + val list = state.modelSourceRegistrations + val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 + if (list == null || idx < 0) { + state + } else { + state.copy(modelSourceRegistrations = list.toMutableList().apply { removeAt(idx) }) + } + } + else -> state } diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 70d6a8322..334fc82aa 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -116,6 +116,8 @@ value class ActionType(val rawValue: String) { val ANNOTATIONS_ENTRY_REMOVED: ActionType = ActionType("annotations/entryRemoved") val ROOT_TERMINALS_CHANGED: ActionType = ActionType("root/terminalsChanged") val ROOT_CONFIG_CHANGED: ActionType = ActionType("root/configChanged") + val ROOT_MODEL_SOURCE_REGISTRATION_SET: ActionType = ActionType("root/modelSourceRegistrationSet") + val ROOT_MODEL_SOURCE_REGISTRATION_REMOVED: ActionType = ActionType("root/modelSourceRegistrationRemoved") val TERMINAL_DATA: ActionType = ActionType("terminal/data") val TERMINAL_INPUT: ActionType = ActionType("terminal/input") val TERMINAL_RESIZED: ActionType = ActionType("terminal/resized") @@ -1482,6 +1484,39 @@ data class RootConfigChangedAction( val replace: Boolean? = null ) +/** + * Adds a model source registration, or replaces the one with the same `id`. + * + * A client registers a source by dispatching this with its own `clientId` and + * no `state`. The host reports status by dispatching it again with the same + * registration and a `state`. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class RootModelSourceRegistrationSetAction( + val type: ActionType, + /** + * The registration to add or replace, matched by `id`. + */ + val registration: ModelSourceRegistration +) + +/** + * Removes the model source registration with the given `id`. A no-op when + * none matches. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class RootModelSourceRegistrationRemovedAction( + val type: ActionType, + /** + * The registration's `id`. + */ + val id: String +) + @Serializable data class TerminalDataAction( val type: ActionType, @@ -1853,6 +1888,8 @@ sealed interface StateAction @JvmInline value class StateActionAnnotationsEntryRemoved(val value: AnnotationsEntryRemovedAction) : StateAction @JvmInline value class StateActionRootTerminalsChanged(val value: RootTerminalsChangedAction) : StateAction @JvmInline value class StateActionRootConfigChanged(val value: RootConfigChangedAction) : StateAction +@JvmInline value class StateActionRootModelSourceRegistrationSet(val value: RootModelSourceRegistrationSetAction) : StateAction +@JvmInline value class StateActionRootModelSourceRegistrationRemoved(val value: RootModelSourceRegistrationRemovedAction) : StateAction @JvmInline value class StateActionTerminalData(val value: TerminalDataAction) : StateAction @JvmInline value class StateActionTerminalInput(val value: TerminalInputAction) : StateAction @JvmInline value class StateActionTerminalResized(val value: TerminalResizedAction) : StateAction @@ -1976,6 +2013,8 @@ internal object StateActionSerializer : KSerializer { "annotations/entryRemoved" -> StateActionAnnotationsEntryRemoved(input.json.decodeFromJsonElement(AnnotationsEntryRemovedAction.serializer(), element)) "root/terminalsChanged" -> StateActionRootTerminalsChanged(input.json.decodeFromJsonElement(RootTerminalsChangedAction.serializer(), element)) "root/configChanged" -> StateActionRootConfigChanged(input.json.decodeFromJsonElement(RootConfigChangedAction.serializer(), element)) + "root/modelSourceRegistrationSet" -> StateActionRootModelSourceRegistrationSet(input.json.decodeFromJsonElement(RootModelSourceRegistrationSetAction.serializer(), element)) + "root/modelSourceRegistrationRemoved" -> StateActionRootModelSourceRegistrationRemoved(input.json.decodeFromJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), element)) "terminal/data" -> StateActionTerminalData(input.json.decodeFromJsonElement(TerminalDataAction.serializer(), element)) "terminal/input" -> StateActionTerminalInput(input.json.decodeFromJsonElement(TerminalInputAction.serializer(), element)) "terminal/resized" -> StateActionTerminalResized(input.json.decodeFromJsonElement(TerminalResizedAction.serializer(), element)) @@ -2092,6 +2131,8 @@ internal object StateActionSerializer : KSerializer { is StateActionAnnotationsEntryRemoved -> output.json.encodeToJsonElement(AnnotationsEntryRemovedAction.serializer(), value.value) is StateActionRootTerminalsChanged -> output.json.encodeToJsonElement(RootTerminalsChangedAction.serializer(), value.value) is StateActionRootConfigChanged -> output.json.encodeToJsonElement(RootConfigChangedAction.serializer(), value.value) + is StateActionRootModelSourceRegistrationSet -> output.json.encodeToJsonElement(RootModelSourceRegistrationSetAction.serializer(), value.value) + is StateActionRootModelSourceRegistrationRemoved -> output.json.encodeToJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), value.value) is StateActionTerminalData -> output.json.encodeToJsonElement(TerminalDataAction.serializer(), value.value) is StateActionTerminalInput -> output.json.encodeToJsonElement(TerminalInputAction.serializer(), value.value) is StateActionTerminalResized -> output.json.encodeToJsonElement(TerminalResizedAction.serializer(), value.value) diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt index 80e23fac8..6d080ab4b 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 @@ -199,6 +199,10 @@ enum class ResourceWriteMode { value class AuthenticateTargetKind(val rawValue: String) { companion object { val MCP_SERVER: AuthenticateTargetKind = AuthenticateTargetKind("mcpServer") + /** + * A {@link ModelSourceAuthenticateTarget}. + */ + val MODEL_SOURCE: AuthenticateTargetKind = AuthenticateTargetKind("modelSource") } } @@ -1603,6 +1607,20 @@ data class McpServerAuthenticateTarget( val customizationId: String ) +/** + * A registered model source. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceAuthenticateTarget( + val kind: AuthenticateTargetKind, + /** + * The registration's `ModelSourceRegistration.id`. + */ + val modelSourceId: String +) + @Serializable data class AuthenticateParams( /** @@ -1619,11 +1637,13 @@ data class AuthenticateParams( * The protected resource identifier. MUST match a `resource` value the * server has advertised — via `ProtectedResourceMetadata` in * `AgentInfo.protectedResources`, or via a live - * `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`. + * `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, + * or `ModelSourceAuthRequiredState.resource`. */ val resource: String, /** - * Bearer token obtained from the resource's authorization server + * Bearer token obtained from the resource's authorization server, or an + * opaque secret for a model source. An empty string revokes the credential. */ val token: String, /** @@ -1636,6 +1656,8 @@ data class AuthenticateParams( * authorization server did not supply an expiry or the expiry is otherwise * unknown. When supplied, the value MUST be a positive integer. * + * An API key omits this field. + * * This field is irrelevant when `token` is empty to revoke authentication * and SHOULD be omitted in that case. */ @@ -1646,21 +1668,28 @@ data class AuthenticateParams( * `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is * satisfied without decoding the (opaque, server-specific) token itself. * Omit when the client doesn't track granted scopes separately from the - * token. + * token. Scopes apply to OAuth-issued tokens only. */ val scopes: List? = null, /** * Optional consumer of the token. Clients SHOULD include this when answering * a specific MCP server's `McpServerAuthRequiredState` or - * `ToolCallAuthRequiredState` challenge, and omit it for provider-level + * `ToolCallAuthRequiredState` challenge, MUST include it when delivering a + * registered model source's credential, and omit it for provider-level * resources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data). * - * When present, the host MUST apply the token only to that MCP server in - * that session, never to sibling servers, other sessions, or agent-level - * resources, even if they share the resource and scopes. `resource` MUST - * still equal that server's advertised `McpAuthRequirement.resource.resource`. - * The host MUST reject an unknown session or customization, or a - * customization that is not an MCP server, with `InvalidParams` (-32602). + * For an `mcpServer` target, the host MUST apply the token only to that MCP + * server in that session, never to sibling servers, other sessions, or + * agent-level resources, even if they share the resource and scopes. + * `resource` MUST still equal that server's advertised + * `McpAuthRequirement.resource.resource`. The host MUST reject an unknown + * session or customization, or a customization that is not an MCP server, + * with `InvalidParams` (-32602). + * + * A registered model source takes its credential only through a + * `modelSource` target. See + * [Model source credentials](/specification/authentication#model-source-credentials) + * for its rules. * * Without a target, resource/scope matching is unchanged; the token may * satisfy every matching pending challenge. Older hosts ignore this field. @@ -2226,6 +2255,8 @@ sealed interface AuthenticateTarget @JvmInline value class AuthenticateTargetMcpServer(val value: McpServerAuthenticateTarget) : AuthenticateTarget +@JvmInline +value class AuthenticateTargetModelSource(val value: ModelSourceAuthenticateTarget) : AuthenticateTarget /** * Forward-compat catch-all for unknown AuthenticateTarget discriminators. * @@ -2251,6 +2282,7 @@ internal object AuthenticateTargetSerializer : KSerializer { ?: return AuthenticateTargetUnknown(obj) return when (discriminant) { "mcpServer" -> AuthenticateTargetMcpServer(input.json.decodeFromJsonElement(McpServerAuthenticateTarget.serializer(), element)) + "modelSource" -> AuthenticateTargetModelSource(input.json.decodeFromJsonElement(ModelSourceAuthenticateTarget.serializer(), element)) else -> AuthenticateTargetUnknown(obj) } } @@ -2260,11 +2292,13 @@ internal object AuthenticateTargetSerializer : KSerializer { ?: error("AuthenticateTarget can only be serialized to JSON") val element: JsonElement = when (value) { is AuthenticateTargetMcpServer -> output.json.encodeToJsonElement(McpServerAuthenticateTarget.serializer(), value.value) + is AuthenticateTargetModelSource -> output.json.encodeToJsonElement(ModelSourceAuthenticateTarget.serializer(), value.value) is AuthenticateTargetUnknown -> value.raw } val encodedObject = element.jsonObject.toMutableMap() val discriminant = when (value) { is AuthenticateTargetMcpServer -> "mcpServer" + is AuthenticateTargetModelSource -> "modelSource" is AuthenticateTargetUnknown -> null } if (discriminant != null) encodedObject["kind"] = JsonPrimitive(discriminant) 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 0dedba2c7..950bda29a 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 @@ -921,6 +921,104 @@ internal object McpAuthRequiredReasonSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("ModelSourceStatus", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: ModelSourceStatus) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): ModelSourceStatus = + ModelSourceStatus(decoder.decodeString()) +} + +/** + * Who may select a registered model source's models. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = ModelSourceSharingPolicySerializer::class) +@JvmInline +value class ModelSourceSharingPolicy(val rawValue: String) { + companion object { + /** + * Only turns and pending messages the contributing client dispatches. + */ + val CONTRIBUTING_CLIENT: ModelSourceSharingPolicy = ModelSourceSharingPolicy("contributingClient") + /** + * Any client, and work the host starts itself, such as automations. + */ + val HOST: ModelSourceSharingPolicy = ModelSourceSharingPolicy("host") + } +} + +internal object ModelSourceSharingPolicySerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("ModelSourceSharingPolicy", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: ModelSourceSharingPolicy) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): ModelSourceSharingPolicy = + ModelSourceSharingPolicy(decoder.decodeString()) +} + +/** + * How long a registered model source lasts once its contributing client leaves. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = ModelSourceRetentionPolicySerializer::class) +@JvmInline +value class ModelSourceRetentionPolicy(val rawValue: String) { + companion object { + /** + * Removed when the contributing client leaves, once running turns finish. + */ + val CONTRIBUTING_CLIENT: ModelSourceRetentionPolicy = ModelSourceRetentionPolicy("contributingClient") + /** + * Kept until a client removes it or host policy expires it. + */ + val HOST: ModelSourceRetentionPolicy = ModelSourceRetentionPolicy("host") + } +} + +internal object ModelSourceRetentionPolicySerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("ModelSourceRetentionPolicy", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: ModelSourceRetentionPolicy) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): ModelSourceRetentionPolicy = + ModelSourceRetentionPolicy(decoder.decodeString()) +} + /** * Computation lifecycle of a {@link ChangesetState}. */ @@ -1525,6 +1623,12 @@ data class RootState( * Agent host configuration schema and current values */ val config: RootConfigState? = null, + /** + * Model sources registered on this host, keyed by `id`. + * + * Stability: 1.0 - Early development. + */ + val modelSourceRegistrations: List? = null, /** * Additional implementation-defined metadata about the agent host itself. * @@ -1622,7 +1726,14 @@ data class AgentCapabilities( * set and MUST NOT set more than one entry in * {@link CreateSessionParams.workingDirectories}. */ - val multipleWorkingDirectories: MultipleWorkingDirectoriesCapability? = null + val multipleWorkingDirectories: MultipleWorkingDirectoriesCapability? = null, + /** + * The agent serves models from registered model sources, in the listed + * definition formats. + * + * Stability: 1.0 - Early development. + */ + val modelSourceRegistration: ModelSourceRegistrationCapability? = null ) @Serializable @@ -1684,10 +1795,247 @@ data class MultipleWorkingDirectoriesCapability( val primaryReplacement: Boolean? = null ) +/** + * Options for the {@link AgentCapabilities.modelSourceRegistration} capability. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceRegistrationCapabilitySerializer::class) +data class ModelSourceRegistrationCapability( + /** + * Definition formats the agent reads, most preferred first. Format names + * are defined by agent implementations and SHOULD be namespaced, for + * example `example.com/model-source@1`. + */ + val formats: List, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceRegistrationCapabilitySerializer : UnknownMembersSerializer( + ModelSourceRegistrationCapability.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * A model source registered on this host by a client, or by the host itself. + * Its definition is in a format the agent named by `provider` reads. It never + * contains a credential. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceRegistrationSerializer::class) +data class ModelSourceRegistration( + /** + * Host-unique ID, chosen by whoever registers the source. Also the + * source's {@link ModelSourceInfo.id} in the agent's catalog, and the + * {@link SessionModelInfo.modelSourceId} of its models. + */ + val id: String, + /** + * Agent provider whose agent reads the definition and serves the models. + */ + val provider: String, + /** + * Display name, published as {@link ModelSourceInfo.displayName}. + */ + val name: String, + /** + * Icons for UI display. + */ + val icons: List? = null, + /** + * Definition format, one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. + */ + val format: String, + /** + * How to reach the source: endpoint, wire format, models, and so on, in + * `format`. Its shape belongs to the agent that reads it. MUST NOT contain + * a credential. + */ + val definition: Map, + /** + * The contributing client. Absent for a source the host registered itself. + */ + val clientId: String? = null, + /** + * Who may select the source's models. Absent means `contributingClient`. + */ + val sharing: ModelSourceSharingPolicy? = null, + /** + * What happens when the contributing client leaves. Absent means `contributingClient`. + */ + val retention: ModelSourceRetentionPolicy? = null, + /** + * Host-reported status. Absent means the host hasn't reported one yet. + */ + val state: ModelSourceState? = null, + /** + * Additional implementation-defined metadata for this registration. + * MUST NOT contain a credential. + */ + @SerialName("_meta") + val meta: Map? = null, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceRegistrationSerializer : UnknownMembersSerializer( + ModelSourceRegistration.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * The agent is reading and validating the definition, or listing the + * source's models again after a credential change. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceStartingStateSerializer::class) +data class ModelSourceStartingState( + val kind: ModelSourceStatus, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceStartingStateSerializer : UnknownMembersSerializer( + ModelSourceStartingState.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * The source is usable, and its models are in the catalog of the agent named + * by the registration's `provider`. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceReadyStateSerializer::class) +data class ModelSourceReadyState( + val kind: ModelSourceStatus, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceReadyStateSerializer : UnknownMembersSerializer( + ModelSourceReadyState.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * What a model source needs in order to become ready. Deliberately carries no + * credential. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceAuthRequirementSerializer::class) +data class ModelSourceAuthRequirement( + /** + * Why a credential is needed. + */ + val reason: AuthRequiredReason, + /** + * RFC 9728 metadata for the source's endpoint. `resource.resource` is the + * endpoint URL as the definition names it, in any scheme the agent + * supports (for example `http://localhost:11434/v1`). It's the value a + * client passes back as `authenticate({ resource })`, and nothing fetches + * it. `resource.resource_name` labels the prompt (for example + * "OpenRouter API key"). A source that accepts OAuth access tokens + * advertises `authorization_servers` and `scopes_supported`. A source that + * takes a user-supplied secret omits them. + */ + val resource: ProtectedResourceMetadata, + /** + * Human-readable hint, for example the endpoint's error description. + */ + val description: String? = null, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceAuthRequirementSerializer : UnknownMembersSerializer( + ModelSourceAuthRequirement.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * The source needs a credential before it can be used. A client answers with + * `authenticate` and a {@link ModelSourceAuthenticateTarget}. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceAuthRequiredStateSerializer::class) +data class ModelSourceAuthRequiredState( + /** + * Why a credential is needed. + */ + val reason: AuthRequiredReason, + /** + * RFC 9728 metadata for the source's endpoint. `resource.resource` is the + * endpoint URL as the definition names it, in any scheme the agent + * supports (for example `http://localhost:11434/v1`). It's the value a + * client passes back as `authenticate({ resource })`, and nothing fetches + * it. `resource.resource_name` labels the prompt (for example + * "OpenRouter API key"). A source that accepts OAuth access tokens + * advertises `authorization_servers` and `scopes_supported`. A source that + * takes a user-supplied secret omits them. + */ + val resource: ProtectedResourceMetadata, + /** + * Human-readable hint, for example the endpoint's error description. + */ + val description: String? = null, + val kind: ModelSourceStatus, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceAuthRequiredStateSerializer : UnknownMembersSerializer( + ModelSourceAuthRequiredState.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + +/** + * The source failed, or the host declined it, for example by policy. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceErrorStateSerializer::class) +data class ModelSourceErrorState( + val kind: ModelSourceStatus, + /** + * Error details. MUST NOT contain the credential. + */ + val error: ErrorInfo, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceErrorStateSerializer : UnknownMembersSerializer( + ModelSourceErrorState.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + @Serializable data class ModelSourceInfo( /** - * Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + * Model source identifier, unique within the agent's + * {@link AgentInfo.modelSources}. For a registered model source, this is + * the {@link ModelSourceRegistration.id}. */ val id: String, /** @@ -1701,7 +2049,8 @@ data class SessionModelInfo( /** * Model identifier, unique within the agent's {@link AgentInfo.models}. * When several model sources serve the same upstream model, the host gives - * each entry its own ID. + * each entry its own ID. An ID the host publishes for a registered model + * source stays bound to that registration and upstream model. */ val id: String, /** @@ -7809,6 +8158,63 @@ internal object McpServerStateSerializer : KSerializer { } } +@Serializable(with = ModelSourceStateSerializer::class) +sealed interface ModelSourceState + +@JvmInline +value class ModelSourceStateStarting(val value: ModelSourceStartingState) : ModelSourceState +@JvmInline +value class ModelSourceStateReady(val value: ModelSourceReadyState) : ModelSourceState +@JvmInline +value class ModelSourceStateAuthRequired(val value: ModelSourceAuthRequiredState) : ModelSourceState +@JvmInline +value class ModelSourceStateError(val value: ModelSourceErrorState) : ModelSourceState +/** + * Forward-compat catch-all for unknown ModelSourceState discriminators. + * + * Older clients may receive newer wire variants they don't recognise; capturing + * the raw `JsonObject` lets such payloads round-trip through the client unchanged. + * Reducers handle this variant conservatively on a per-union basis (typically + * as a no-op, but see `Reducers.kt` for the exact treatment). + */ +@JvmInline +value class ModelSourceStateUnknown(val raw: JsonObject) : ModelSourceState + +internal object ModelSourceStateSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("ModelSourceState") + + override fun deserialize(decoder: Decoder): ModelSourceState { + val input = decoder as? JsonDecoder + ?: error("ModelSourceState can only be deserialized from JSON") + val element = input.decodeJsonElement() + val obj = element as? JsonObject + ?: error("Expected JsonObject for ModelSourceState") + val discriminant = (obj["kind"] as? JsonPrimitive)?.content + ?: return ModelSourceStateUnknown(obj) + return when (discriminant) { + "starting" -> ModelSourceStateStarting(input.json.decodeFromJsonElement(ModelSourceStartingState.serializer(), element)) + "ready" -> ModelSourceStateReady(input.json.decodeFromJsonElement(ModelSourceReadyState.serializer(), element)) + "authRequired" -> ModelSourceStateAuthRequired(input.json.decodeFromJsonElement(ModelSourceAuthRequiredState.serializer(), element)) + "error" -> ModelSourceStateError(input.json.decodeFromJsonElement(ModelSourceErrorState.serializer(), element)) + else -> ModelSourceStateUnknown(obj) + } + } + + override fun serialize(encoder: Encoder, value: ModelSourceState) { + val output = encoder as? JsonEncoder + ?: error("ModelSourceState can only be serialized to JSON") + val element: JsonElement = when (value) { + is ModelSourceStateStarting -> output.json.encodeToJsonElement(ModelSourceStartingState.serializer(), value.value) + is ModelSourceStateReady -> output.json.encodeToJsonElement(ModelSourceReadyState.serializer(), value.value) + is ModelSourceStateAuthRequired -> output.json.encodeToJsonElement(ModelSourceAuthRequiredState.serializer(), value.value) + is ModelSourceStateError -> output.json.encodeToJsonElement(ModelSourceErrorState.serializer(), value.value) + is ModelSourceStateUnknown -> value.raw + } + output.encodeJsonElement(element) + } +} + @Serializable(with = ToolCallContributorSerializer::class) sealed interface ToolCallContributor diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index dc6fe0f7c..22069a6f3 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -20,10 +20,11 @@ use crate::state::{ ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ChatSummary, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, Message, - ModelSelection, PendingMessageKind, ResponsePart, SessionActiveClient, SessionConfigSchema, - SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, - ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributor, ToolCallResult, - ToolCallRiskAssessment, ToolDefinition, ToolInput, ToolResultContent, Turn, UsageInfo, + ModelSelection, ModelSourceRegistration, PendingMessageKind, ResponsePart, SessionActiveClient, + SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, + TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributor, + ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, ToolResultContent, Turn, + UsageInfo, }; // ─── ActionType ────────────────────────────────────────────────────── @@ -118,6 +119,8 @@ pub enum ActionType { AnnotationsEntryRemoved, RootTerminalsChanged, RootConfigChanged, + RootModelSourceRegistrationSet, + RootModelSourceRegistrationRemoved, TerminalData, TerminalInput, TerminalResized, @@ -286,6 +289,12 @@ impl serde::Serialize for ActionType { Self::AnnotationsEntryRemoved => serializer.serialize_str("annotations/entryRemoved"), Self::RootTerminalsChanged => serializer.serialize_str("root/terminalsChanged"), Self::RootConfigChanged => serializer.serialize_str("root/configChanged"), + Self::RootModelSourceRegistrationSet => { + serializer.serialize_str("root/modelSourceRegistrationSet") + } + Self::RootModelSourceRegistrationRemoved => { + serializer.serialize_str("root/modelSourceRegistrationRemoved") + } Self::TerminalData => serializer.serialize_str("terminal/data"), Self::TerminalInput => serializer.serialize_str("terminal/input"), Self::TerminalResized => serializer.serialize_str("terminal/resized"), @@ -420,6 +429,8 @@ impl<'de> serde::Deserialize<'de> for ActionType { "annotations/entryRemoved" => Self::AnnotationsEntryRemoved, "root/terminalsChanged" => Self::RootTerminalsChanged, "root/configChanged" => Self::RootConfigChanged, + "root/modelSourceRegistrationSet" => Self::RootModelSourceRegistrationSet, + "root/modelSourceRegistrationRemoved" => Self::RootModelSourceRegistrationRemoved, "terminal/data" => Self::TerminalData, "terminal/input" => Self::TerminalInput, "terminal/resized" => Self::TerminalResized, @@ -508,6 +519,31 @@ pub struct RootConfigChangedAction { pub replace: Option, } +/// Adds a model source registration, or replaces the one with the same `id`. +/// +/// A client registers a source by dispatching this with its own `clientId` and +/// no `state`. The host reports status by dispatching it again with the same +/// registration and a `state`. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RootModelSourceRegistrationSetAction { + /// The registration to add or replace, matched by `id`. + pub registration: ModelSourceRegistration, +} + +/// Removes the model source registration with the given `id`. A no-op when +/// none matches. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RootModelSourceRegistrationRemovedAction { + /// The registration's `id`. + pub id: String, +} + /// Session backend initialized successfully. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2455,6 +2491,10 @@ pub enum StateAction { RootActiveSessionsChanged(RootActiveSessionsChangedAction), #[serde(rename = "root/configChanged")] RootConfigChanged(RootConfigChangedAction), + #[serde(rename = "root/modelSourceRegistrationSet")] + RootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction), + #[serde(rename = "root/modelSourceRegistrationRemoved")] + RootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction), #[serde(rename = "session/ready")] SessionReady(SessionReadyAction), #[serde(rename = "session/creationFailed")] diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index 6764fd470..b8fd1acbd 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -235,6 +235,8 @@ pub enum ResourceWriteMode { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum AuthenticateTargetKind { McpServer, + /// A {@link ModelSourceAuthenticateTarget}. + ModelSource, /// Unknown raw value from a newer protocol version, preserved verbatim. Unknown(String), } @@ -246,6 +248,7 @@ impl serde::Serialize for AuthenticateTargetKind { { match self { Self::McpServer => serializer.serialize_str("mcpServer"), + Self::ModelSource => serializer.serialize_str("modelSource"), Self::Unknown(value) => serializer.serialize_str(value), } } @@ -259,6 +262,7 @@ impl<'de> serde::Deserialize<'de> for AuthenticateTargetKind { let raw = ::deserialize(deserializer)?; Ok(match raw.as_str() { "mcpServer" => Self::McpServer, + "modelSource" => Self::ModelSource, _ => Self::Unknown(raw), }) } @@ -1735,19 +1739,31 @@ pub struct McpServerAuthenticateTarget { pub customization_id: String, } -/// Pushes a Bearer token for a protected resource. The `resource` field MUST +/// A registered model source. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceAuthenticateTarget { + /// The registration's `ModelSourceRegistration.id`. + pub model_source_id: String, +} + +/// Pushes a credential for a protected resource. The `resource` field MUST /// match a protected-resource identifier the client has discovered from the /// server — whether declared statically in `AgentInfo.protectedResources`, -/// or discovered dynamically from a live `McpServerAuthRequiredState.resource` -/// or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the -/// corresponding MCP server or tool call actually challenges for auth). -/// Servers MUST accept any `resource` value they have themselves advertised -/// through one of these three mechanisms. +/// or discovered dynamically from a live `McpServerAuthRequiredState.resource`, +/// `ToolCallAuthRequiredState.auth.resource`, or +/// `ModelSourceAuthRequiredState.resource` (each surfaced only once the +/// corresponding MCP server, tool call, or model source actually challenges +/// for auth). Servers MUST accept any `resource` value they have themselves +/// advertised through one of these mechanisms. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the /// authorization server(s) listed in the resource's metadata and pushes it -/// to the server via this command. +/// to the server via this command. A model source's token is instead an +/// opaque secret, such as an API key. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticateParams { @@ -1760,9 +1776,11 @@ pub struct AuthenticateParams { /// The protected resource identifier. MUST match a `resource` value the /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live - /// `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`. + /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, + /// or `ModelSourceAuthRequiredState.resource`. pub resource: String, - /// Bearer token obtained from the resource's authorization server + /// Bearer token obtained from the resource's authorization server, or an + /// opaque secret for a model source. An empty string revokes the credential. pub token: String, /// The access token's remaining lifetime, in seconds, when this /// `authenticate` request is sent. This corresponds to `expires_in` in an @@ -1773,6 +1791,8 @@ pub struct AuthenticateParams { /// authorization server did not supply an expiry or the expiry is otherwise /// unknown. When supplied, the value MUST be a positive integer. /// + /// An API key omits this field. + /// /// This field is irrelevant when `token` is empty to revoke authentication /// and SHOULD be omitted in that case. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1782,20 +1802,27 @@ pub struct AuthenticateParams { /// `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is /// satisfied without decoding the (opaque, server-specific) token itself. /// Omit when the client doesn't track granted scopes separately from the - /// token. + /// token. Scopes apply to OAuth-issued tokens only. #[serde(default, skip_serializing_if = "Option::is_none")] pub scopes: Option>, /// Optional consumer of the token. Clients SHOULD include this when answering /// a specific MCP server's `McpServerAuthRequiredState` or - /// `ToolCallAuthRequiredState` challenge, and omit it for provider-level + /// `ToolCallAuthRequiredState` challenge, MUST include it when delivering a + /// registered model source's credential, and omit it for provider-level /// resources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data). /// - /// When present, the host MUST apply the token only to that MCP server in - /// that session, never to sibling servers, other sessions, or agent-level - /// resources, even if they share the resource and scopes. `resource` MUST - /// still equal that server's advertised `McpAuthRequirement.resource.resource`. - /// The host MUST reject an unknown session or customization, or a - /// customization that is not an MCP server, with `InvalidParams` (-32602). + /// For an `mcpServer` target, the host MUST apply the token only to that MCP + /// server in that session, never to sibling servers, other sessions, or + /// agent-level resources, even if they share the resource and scopes. + /// `resource` MUST still equal that server's advertised + /// `McpAuthRequirement.resource.resource`. The host MUST reject an unknown + /// session or customization, or a customization that is not an MCP server, + /// with `InvalidParams` (-32602). + /// + /// A registered model source takes its credential only through a + /// `modelSource` target. See + /// [Model source credentials](/specification/authentication#model-source-credentials) + /// for its rules. /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2214,6 +2241,8 @@ pub enum ChatMoveDestination { pub enum AuthenticateTarget { #[serde(rename = "mcpServer")] McpServer(McpServerAuthenticateTarget), + #[serde(rename = "modelSource")] + ModelSource(ModelSourceAuthenticateTarget), /// Unknown or future variant — preserved as raw JSON for round-trip fidelity. /// Reducers treat this as a no-op. #[serde(untagged)] diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 84256b4a4..067156268 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -11,6 +11,8 @@ use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use serde_repr::{Deserialize_repr, Serialize_repr}; +use crate::notifications::AuthRequiredReason; + // ─── Enums ──────────────────────────────────────────────────────────── /// How the server resumes sending data on a windowed subscription after @@ -1165,6 +1167,134 @@ impl<'de> serde::Deserialize<'de> for McpAuthRequiredReason { } } +/// Discriminant for the {@link ModelSourceState} union. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelSourceStatus { + /// The agent is reading and validating the definition. + Starting, + /// The source is usable, and its models are in the agent's catalog. + Ready, + /// The source needs a credential before it can be used. + AuthRequired, + /// The source failed, or the host declined it. + Error, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for ModelSourceStatus { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::Starting => serializer.serialize_str("starting"), + Self::Ready => serializer.serialize_str("ready"), + Self::AuthRequired => serializer.serialize_str("authRequired"), + Self::Error => serializer.serialize_str("error"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for ModelSourceStatus { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "starting" => Self::Starting, + "ready" => Self::Ready, + "authRequired" => Self::AuthRequired, + "error" => Self::Error, + _ => Self::Unknown(raw), + }) + } +} + +/// Who may select a registered model source's models. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelSourceSharingPolicy { + /// Only turns and pending messages the contributing client dispatches. + ContributingClient, + /// Any client, and work the host starts itself, such as automations. + Host, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for ModelSourceSharingPolicy { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::ContributingClient => serializer.serialize_str("contributingClient"), + Self::Host => serializer.serialize_str("host"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for ModelSourceSharingPolicy { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "contributingClient" => Self::ContributingClient, + "host" => Self::Host, + _ => Self::Unknown(raw), + }) + } +} + +/// How long a registered model source lasts once its contributing client leaves. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelSourceRetentionPolicy { + /// Removed when the contributing client leaves, once running turns finish. + ContributingClient, + /// Kept until a client removes it or host policy expires it. + Host, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for ModelSourceRetentionPolicy { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::ContributingClient => serializer.serialize_str("contributingClient"), + Self::Host => serializer.serialize_str("host"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for ModelSourceRetentionPolicy { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "contributingClient" => Self::ContributingClient, + "host" => Self::Host, + _ => Self::Unknown(raw), + }) + } +} + /// Computation lifecycle of a {@link ChangesetState}. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ChangesetStatus { @@ -1620,25 +1750,25 @@ pub enum AutomationRunOriginKind { Trigger, } -fn deserialize_extra_without_type<'de, D>( +fn deserialize_extra_without_kind<'de, D>( deserializer: D, ) -> Result, D::Error> where D: serde::Deserializer<'de>, { let mut extra = serde_json::Map::::deserialize(deserializer)?; - extra.remove("type"); + extra.remove("kind"); Ok(extra) } -fn deserialize_extra_without_kind<'de, D>( +fn deserialize_extra_without_type<'de, D>( deserializer: D, ) -> Result, D::Error> where D: serde::Deserializer<'de>, { let mut extra = serde_json::Map::::deserialize(deserializer)?; - extra.remove("kind"); + extra.remove("type"); Ok(extra) } @@ -1855,6 +1985,11 @@ pub struct RootState { /// Agent host configuration schema and current values #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option, + /// Model sources registered on this host, keyed by `id`. + /// + /// Stability: 1.0 - Early development. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_source_registrations: Option>, /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -1945,6 +2080,12 @@ pub struct AgentCapabilities { /// {@link CreateSessionParams.workingDirectories}. #[serde(default, skip_serializing_if = "Option::is_none")] pub multiple_working_directories: Option, + /// The agent serves models from registered model sources, in the listed + /// definition formats. + /// + /// Stability: 1.0 - Early development. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_source_registration: Option, } /// Options for the {@link AgentCapabilities.multipleChats} capability. @@ -2006,12 +2147,165 @@ pub struct MultipleWorkingDirectoriesCapability { pub primary_replacement: Option, } +/// Options for the {@link AgentCapabilities.modelSourceRegistration} capability. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceRegistrationCapability { + /// Definition formats the agent reads, most preferred first. Format names + /// are defined by agent implementations and SHOULD be namespaced, for + /// example `example.com/model-source@1`. + pub formats: Vec, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten)] + pub extra: serde_json::Map, +} + +/// A model source registered on this host by a client, or by the host itself. +/// Its definition is in a format the agent named by `provider` reads. It never +/// contains a credential. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceRegistration { + /// Host-unique ID, chosen by whoever registers the source. Also the + /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the + /// {@link SessionModelInfo.modelSourceId} of its models. + pub id: String, + /// Agent provider whose agent reads the definition and serves the models. + pub provider: String, + /// Display name, published as {@link ModelSourceInfo.displayName}. + pub name: String, + /// Icons for UI display. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icons: Option>, + /// Definition format, one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. + pub format: String, + /// How to reach the source: endpoint, wire format, models, and so on, in + /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain + /// a credential. + pub definition: JsonObject, + /// The contributing client. Absent for a source the host registered itself. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Who may select the source's models. Absent means `contributingClient`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sharing: Option, + /// What happens when the contributing client leaves. Absent means `contributingClient`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retention: Option, + /// Host-reported status. Absent means the host hasn't reported one yet. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub state: Option, + /// Additional implementation-defined metadata for this registration. + /// MUST NOT contain a credential. + #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] + pub meta: Option, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten)] + pub extra: serde_json::Map, +} + +/// The agent is reading and validating the definition, or listing the +/// source's models again after a credential change. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceStartingState { + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// The source is usable, and its models are in the catalog of the agent named +/// by the registration's `provider`. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceReadyState { + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// What a model source needs in order to become ready. Deliberately carries no +/// credential. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceAuthRequirement { + /// Why a credential is needed. + pub reason: AuthRequiredReason, + /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the + /// endpoint URL as the definition names it, in any scheme the agent + /// supports (for example `http://localhost:11434/v1`). It's the value a + /// client passes back as `authenticate({ resource })`, and nothing fetches + /// it. `resource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + pub resource: ProtectedResourceMetadata, + /// Human-readable hint, for example the endpoint's error description. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten)] + pub extra: serde_json::Map, +} + +/// The source needs a credential before it can be used. A client answers with +/// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceAuthRequiredState { + /// Why a credential is needed. + pub reason: AuthRequiredReason, + /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the + /// endpoint URL as the definition names it, in any scheme the agent + /// supports (for example `http://localhost:11434/v1`). It's the value a + /// client passes back as `authenticate({ resource })`, and nothing fetches + /// it. `resource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + pub resource: ProtectedResourceMetadata, + /// Human-readable hint, for example the endpoint's error description. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + +/// The source failed, or the host declined it, for example by policy. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceErrorState { + /// Error details. MUST NOT contain the credential. + pub error: ErrorInfo, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] + pub extra: serde_json::Map, +} + /// A source that an agent provider offers models from, such as a service or /// subscription. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceInfo { - /// Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + /// Model source identifier, unique within the agent's + /// {@link AgentInfo.modelSources}. For a registered model source, this is + /// the {@link ModelSourceRegistration.id}. pub id: String, /// Human-readable name pub display_name: String, @@ -2022,7 +2316,8 @@ pub struct ModelSourceInfo { pub struct SessionModelInfo { /// Model identifier, unique within the agent's {@link AgentInfo.models}. /// When several model sources serve the same upstream model, the host gives - /// each entry its own ID. + /// each entry its own ID. An ID the host publishes for a registered model + /// source stays bound to that registration and upstream model. pub id: String, /// Agent provider that owns this model. Matches {@link AgentInfo.provider}. pub provider: String, @@ -7166,6 +7461,24 @@ pub enum McpServerState { Unknown(serde_json::Value), } +/// Discriminated lifecycle status of a registered model source. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind")] +pub enum ModelSourceState { + #[serde(rename = "starting")] + Starting(ModelSourceStartingState), + #[serde(rename = "ready")] + Ready(ModelSourceReadyState), + #[serde(rename = "authRequired")] + AuthRequired(Box), + #[serde(rename = "error")] + Error(ModelSourceErrorState), + /// Unknown or future variant — preserved as raw JSON for round-trip fidelity. + /// Reducers treat this as a no-op. + #[serde(untagged)] + Unknown(serde_json::Value), +} + /// Reference to the contributor of the tool being called. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind")] diff --git a/clients/rust/crates/ahp/examples/reducers_demo.rs b/clients/rust/crates/ahp/examples/reducers_demo.rs index 665dab4ac..cb18fc547 100644 --- a/clients/rust/crates/ahp/examples/reducers_demo.rs +++ b/clients/rust/crates/ahp/examples/reducers_demo.rs @@ -23,6 +23,7 @@ fn main() { active_sessions: None, terminals: None, config: None, + model_source_registrations: None, meta: None, }; diff --git a/clients/rust/crates/ahp/src/hosts/runtime.rs b/clients/rust/crates/ahp/src/hosts/runtime.rs index 681c0b4b0..be0cab7bb 100644 --- a/clients/rust/crates/ahp/src/hosts/runtime.rs +++ b/clients/rust/crates/ahp/src/hosts/runtime.rs @@ -99,6 +99,7 @@ pub(super) fn spawn( active_sessions: None, terminals: None, config: None, + model_source_registrations: None, meta: None, }, subscriptions: config.initial_subscriptions.clone(), diff --git a/clients/rust/crates/ahp/src/lib.rs b/clients/rust/crates/ahp/src/lib.rs index 013229405..1396e713a 100644 --- a/clients/rust/crates/ahp/src/lib.rs +++ b/clients/rust/crates/ahp/src/lib.rs @@ -116,6 +116,7 @@ //! active_sessions: None, //! terminals: None, //! config: None, +//! model_source_registrations: None, //! meta: None, //! }; //! diff --git a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs index 3f895555c..e0e980627 100644 --- a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs @@ -193,6 +193,7 @@ impl MultiHostStateMirror { active_sessions: None, terminals: None, config: None, + model_source_registrations: None, meta: None, }); apply_action_to_root(root, &envelope.action); diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 702224823..5c88cc0b9 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -28,6 +28,7 @@ //! active_sessions: None, //! terminals: None, //! config: None, +//! model_source_registrations: None, //! meta: None, //! }; //! @@ -718,6 +719,27 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu } ReduceOutcome::Applied } + StateAction::RootModelSourceRegistrationSet(a) => { + let list = state + .model_source_registrations + .get_or_insert_with(Vec::new); + if let Some(idx) = list.iter().position(|r| r.id == a.registration.id) { + list[idx] = a.registration.clone(); + } else { + list.push(a.registration.clone()); + } + ReduceOutcome::Applied + } + StateAction::RootModelSourceRegistrationRemoved(a) => { + let Some(list) = state.model_source_registrations.as_mut() else { + return ReduceOutcome::NoOp; + }; + let Some(idx) = list.iter().position(|r| r.id == a.id) else { + return ReduceOutcome::NoOp; + }; + list.remove(idx); + ReduceOutcome::Applied + } _ => ReduceOutcome::OutOfScope, } } @@ -2603,6 +2625,7 @@ mod tests { active_sessions: None, terminals: None, config: None, + model_source_registrations: None, meta: None, }; let a = StateAction::RootActiveSessionsChanged( diff --git a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs index 5c33c6795..c235adca0 100644 --- a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs @@ -41,6 +41,7 @@ fn root_snapshot(agents: Vec) -> Snapshot { active_sessions: None, terminals: None, config: None, + model_source_registrations: None, meta: None, })), from_seq: 0, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift index 09cbbcf54..7a03d5848 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift @@ -5,6 +5,8 @@ import Foundation /// Set of action types that clients are allowed to dispatch. public let clientDispatchableActions: Set = [ "root/configChanged", + "root/modelSourceRegistrationSet", + "root/modelSourceRegistrationRemoved", "session/titleChanged", "session/activeClientSet", "session/activeClientRemoved", @@ -58,6 +60,8 @@ public let clientDispatchableActions: Set = [ public func isClientDispatchable(_ action: StateAction) -> Bool { switch action { case .rootConfigChanged, + .rootModelSourceRegistrationSet, + .rootModelSourceRegistrationRemoved, .sessionTitleChanged, .sessionActiveClientSet, .sessionActiveClientRemoved, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index e97981c39..d6c7858a5 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -93,6 +93,8 @@ public enum ActionType: Codable, Sendable, Equatable { case annotationsEntryRemoved case rootTerminalsChanged case rootConfigChanged + case rootModelSourceRegistrationSet + case rootModelSourceRegistrationRemoved case terminalData case terminalInput case terminalResized @@ -208,6 +210,8 @@ public enum ActionType: Codable, Sendable, Equatable { case "annotations/entryRemoved": self = .annotationsEntryRemoved case "root/terminalsChanged": self = .rootTerminalsChanged case "root/configChanged": self = .rootConfigChanged + case "root/modelSourceRegistrationSet": self = .rootModelSourceRegistrationSet + case "root/modelSourceRegistrationRemoved": self = .rootModelSourceRegistrationRemoved case "terminal/data": self = .terminalData case "terminal/input": self = .terminalInput case "terminal/resized": self = .terminalResized @@ -323,6 +327,8 @@ public enum ActionType: Codable, Sendable, Equatable { case .annotationsEntryRemoved: try container.encode("annotations/entryRemoved") case .rootTerminalsChanged: try container.encode("root/terminalsChanged") case .rootConfigChanged: try container.encode("root/configChanged") + case .rootModelSourceRegistrationSet: try container.encode("root/modelSourceRegistrationSet") + case .rootModelSourceRegistrationRemoved: try container.encode("root/modelSourceRegistrationRemoved") case .terminalData: try container.encode("terminal/data") case .terminalInput: try container.encode("terminal/input") case .terminalResized: try container.encode("terminal/resized") @@ -2281,6 +2287,45 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { } } +/// Adds a model source registration, or replaces the one with the same `id`. +/// +/// A client registers a source by dispatching this with its own `clientId` and +/// no `state`. The host reports status by dispatching it again with the same +/// registration and a `state`. +/// +/// Stability: 1.0 - Early development. +public struct RootModelSourceRegistrationSetAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The registration to add or replace, matched by `id`. + public var registration: ModelSourceRegistration + + public init( + type: ActionType, + registration: ModelSourceRegistration + ) { + self.type = type + self.registration = registration + } +} + +/// Removes the model source registration with the given `id`. A no-op when +/// none matches. +/// +/// Stability: 1.0 - Early development. +public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The registration's `id`. + public var id: String + + public init( + type: ActionType, + id: String + ) { + self.type = type + self.id = id + } +} + public struct TerminalDataAction: Codable, Sendable, Equatable { public var type: ActionType /// Output data (may contain ANSI escape sequences) @@ -2750,6 +2795,8 @@ public enum StateAction: Codable, Sendable, Equatable { case annotationsEntryRemoved(AnnotationsEntryRemovedAction) case rootTerminalsChanged(RootTerminalsChangedAction) case rootConfigChanged(RootConfigChangedAction) + case rootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction) + case rootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction) case terminalData(TerminalDataAction) case terminalInput(TerminalInputAction) case terminalResized(TerminalResizedAction) @@ -2957,6 +3004,10 @@ public enum StateAction: Codable, Sendable, Equatable { self = .rootTerminalsChanged(try RootTerminalsChangedAction(from: decoder)) case "root/configChanged": self = .rootConfigChanged(try RootConfigChangedAction(from: decoder)) + case "root/modelSourceRegistrationSet": + self = .rootModelSourceRegistrationSet(try RootModelSourceRegistrationSetAction(from: decoder)) + case "root/modelSourceRegistrationRemoved": + self = .rootModelSourceRegistrationRemoved(try RootModelSourceRegistrationRemovedAction(from: decoder)) case "terminal/data": self = .terminalData(try TerminalDataAction(from: decoder)) case "terminal/input": @@ -3093,6 +3144,8 @@ public enum StateAction: Codable, Sendable, Equatable { case .annotationsEntryRemoved(let v): try v.encode(to: encoder) case .rootTerminalsChanged(let v): try v.encode(to: encoder) case .rootConfigChanged(let v): try v.encode(to: encoder) + case .rootModelSourceRegistrationSet(let v): try v.encode(to: encoder) + case .rootModelSourceRegistrationRemoved(let v): try v.encode(to: encoder) case .terminalData(let v): try v.encode(to: encoder) case .terminalInput(let v): try v.encode(to: encoder) case .terminalResized(let v): try v.encode(to: encoder) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 0f4e6dda7..aaa2b1571 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -165,6 +165,8 @@ public enum ResourceWriteMode: String, Codable, Sendable { /// Identifies the consumer of an authentication token. public enum AuthenticateTargetKind: Codable, Sendable, Equatable { case mcpServer + /// A {@link ModelSourceAuthenticateTarget}. + case modelSource /// Unknown raw value from a newer protocol version, preserved verbatim. case unknown(String) @@ -173,6 +175,7 @@ public enum AuthenticateTargetKind: Codable, Sendable, Equatable { let raw = try container.decode(String.self) switch raw { case "mcpServer": self = .mcpServer + case "modelSource": self = .modelSource default: self = .unknown(raw) } } @@ -181,6 +184,7 @@ public enum AuthenticateTargetKind: Codable, Sendable, Equatable { var container = encoder.singleValueContainer() switch self { case .mcpServer: try container.encode("mcpServer") + case .modelSource: try container.encode("modelSource") case .unknown(let raw): try container.encode(raw) } } @@ -1956,6 +1960,23 @@ public struct McpServerAuthenticateTarget: Codable, Sendable, Equatable { } } +/// A registered model source. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceAuthenticateTarget: Codable, Sendable, Equatable { + public var kind: AuthenticateTargetKind + /// The registration's `ModelSourceRegistration.id`. + public var modelSourceId: String + + public init( + kind: AuthenticateTargetKind, + modelSourceId: String + ) { + self.kind = kind + self.modelSourceId = modelSourceId + } +} + public struct AuthenticateParams: Codable, Sendable, Equatable { /// Channel URI this command targets. public var channel: String @@ -1965,9 +1986,11 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// The protected resource identifier. MUST match a `resource` value the /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live - /// `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`. + /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, + /// or `ModelSourceAuthRequiredState.resource`. public var resource: String - /// Bearer token obtained from the resource's authorization server + /// Bearer token obtained from the resource's authorization server, or an + /// opaque secret for a model source. An empty string revokes the credential. public var token: String /// The access token's remaining lifetime, in seconds, when this /// `authenticate` request is sent. This corresponds to `expires_in` in an @@ -1978,6 +2001,8 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// authorization server did not supply an expiry or the expiry is otherwise /// unknown. When supplied, the value MUST be a positive integer. /// + /// An API key omits this field. + /// /// This field is irrelevant when `token` is empty to revoke authentication /// and SHOULD be omitted in that case. public var expiresIn: Int? @@ -1986,19 +2011,26 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is /// satisfied without decoding the (opaque, server-specific) token itself. /// Omit when the client doesn't track granted scopes separately from the - /// token. + /// token. Scopes apply to OAuth-issued tokens only. public var scopes: [String]? /// Optional consumer of the token. Clients SHOULD include this when answering /// a specific MCP server's `McpServerAuthRequiredState` or - /// `ToolCallAuthRequiredState` challenge, and omit it for provider-level + /// `ToolCallAuthRequiredState` challenge, MUST include it when delivering a + /// registered model source's credential, and omit it for provider-level /// resources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data). /// - /// When present, the host MUST apply the token only to that MCP server in - /// that session, never to sibling servers, other sessions, or agent-level - /// resources, even if they share the resource and scopes. `resource` MUST - /// still equal that server's advertised `McpAuthRequirement.resource.resource`. - /// The host MUST reject an unknown session or customization, or a - /// customization that is not an MCP server, with `InvalidParams` (-32602). + /// For an `mcpServer` target, the host MUST apply the token only to that MCP + /// server in that session, never to sibling servers, other sessions, or + /// agent-level resources, even if they share the resource and scopes. + /// `resource` MUST still equal that server's advertised + /// `McpAuthRequirement.resource.resource`. The host MUST reject an unknown + /// session or customization, or a customization that is not an MCP server, + /// with `InvalidParams` (-32602). + /// + /// A registered model source takes its credential only through a + /// `modelSource` target. See + /// [Model source credentials](/specification/authentication#model-source-credentials) + /// for its rules. /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2714,6 +2746,7 @@ public enum ChatMoveDestination: Codable, Sendable, Equatable { public enum AuthenticateTarget: Codable, Sendable, Equatable { case mcpServer(McpServerAuthenticateTarget) + case modelSource(ModelSourceAuthenticateTarget) /// Unknown or future discriminant; the raw payload is preserved /// and re-encoded verbatim for forward-compatibility. case unknown(AnyCodable) @@ -2731,6 +2764,8 @@ public enum AuthenticateTarget: Codable, Sendable, Equatable { switch discriminant { case "mcpServer": self = .mcpServer(try McpServerAuthenticateTarget(from: decoder)) + case "modelSource": + self = .modelSource(try ModelSourceAuthenticateTarget(from: decoder)) default: self = .unknown(try AnyCodable(from: decoder)) } @@ -2741,6 +2776,9 @@ public enum AuthenticateTarget: Codable, Sendable, Equatable { case .mcpServer(var value): value.kind = .mcpServer try value.encode(to: encoder) + case .modelSource(var value): + value.kind = .modelSource + try value.encode(to: encoder) case .unknown(let value): try value.encode(to: encoder) } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 7a00f8bd5..6b8df0a9e 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -900,6 +900,107 @@ public enum McpAuthRequiredReason: Codable, Sendable, Equatable { } } +/// Discriminant for the {@link ModelSourceState} union. +/// +/// Stability: 1.0 - Early development. +public enum ModelSourceStatus: Codable, Sendable, Equatable { + /// The agent is reading and validating the definition. + case starting + /// The source is usable, and its models are in the agent's catalog. + case ready + /// The source needs a credential before it can be used. + case authRequired + /// The source failed, or the host declined it. + case error + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "starting": self = .starting + case "ready": self = .ready + case "authRequired": self = .authRequired + case "error": self = .error + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .starting: try container.encode("starting") + case .ready: try container.encode("ready") + case .authRequired: try container.encode("authRequired") + case .error: try container.encode("error") + case .unknown(let raw): try container.encode(raw) + } + } +} + +/// Who may select a registered model source's models. +/// +/// Stability: 1.0 - Early development. +public enum ModelSourceSharingPolicy: Codable, Sendable, Equatable { + /// Only turns and pending messages the contributing client dispatches. + case contributingClient + /// Any client, and work the host starts itself, such as automations. + case host + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "contributingClient": self = .contributingClient + case "host": self = .host + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .contributingClient: try container.encode("contributingClient") + case .host: try container.encode("host") + case .unknown(let raw): try container.encode(raw) + } + } +} + +/// How long a registered model source lasts once its contributing client leaves. +/// +/// Stability: 1.0 - Early development. +public enum ModelSourceRetentionPolicy: Codable, Sendable, Equatable { + /// Removed when the contributing client leaves, once running turns finish. + case contributingClient + /// Kept until a client removes it or host policy expires it. + case host + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "contributingClient": self = .contributingClient + case "host": self = .host + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .contributingClient: try container.encode("contributingClient") + case .host: try container.encode("host") + case .unknown(let raw): try container.encode(raw) + } + } +} + /// Computation lifecycle of a {@link ChangesetState}. public enum ChangesetStatus: Codable, Sendable, Equatable { /// The server is computing this changeset for the first time. @@ -1491,6 +1592,10 @@ public struct RootState: Codable, Sendable, Equatable { public var terminals: [TerminalInfo]? /// Agent host configuration schema and current values public var config: RootConfigState? + /// Model sources registered on this host, keyed by `id`. + /// + /// Stability: 1.0 - Early development. + public var modelSourceRegistrations: [ModelSourceRegistration]? /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -1501,6 +1606,7 @@ public struct RootState: Codable, Sendable, Equatable { case activeSessions case terminals case config + case modelSourceRegistrations case meta = "_meta" } @@ -1509,12 +1615,14 @@ public struct RootState: Codable, Sendable, Equatable { activeSessions: Int? = nil, terminals: [TerminalInfo]? = nil, config: RootConfigState? = nil, + modelSourceRegistrations: [ModelSourceRegistration]? = nil, meta: [String: AnyCodable]? = nil ) { self.agents = agents self.activeSessions = activeSessions self.terminals = terminals self.config = config + self.modelSourceRegistrations = modelSourceRegistrations self.meta = meta } } @@ -1609,13 +1717,20 @@ public struct AgentCapabilities: Codable, Sendable, Equatable { /// set and MUST NOT set more than one entry in /// {@link CreateSessionParams.workingDirectories}. public var multipleWorkingDirectories: MultipleWorkingDirectoriesCapability? + /// The agent serves models from registered model sources, in the listed + /// definition formats. + /// + /// Stability: 1.0 - Early development. + public var modelSourceRegistration: ModelSourceRegistrationCapability? public init( multipleChats: MultipleChatsCapability? = nil, - multipleWorkingDirectories: MultipleWorkingDirectoriesCapability? = nil + multipleWorkingDirectories: MultipleWorkingDirectoriesCapability? = nil, + modelSourceRegistration: ModelSourceRegistrationCapability? = nil ) { self.multipleChats = multipleChats self.multipleWorkingDirectories = multipleWorkingDirectories + self.modelSourceRegistration = modelSourceRegistration } } @@ -1684,8 +1799,384 @@ public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable } } +/// Options for the {@link AgentCapabilities.modelSourceRegistration} capability. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { + /// Definition formats the agent reads, most preferred first. Format names + /// are defined by agent implementations and SHOULD be namespaced, for + /// example `example.com/model-source@1`. + public var formats: [String] + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case formats + } + + public init( + formats: [String], + extra: [String: AnyCodable] = [:] + ) { + self.formats = formats + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.formats = try container.decode([String].self, forKey: .formats) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.formats, forKey: .formats) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// A model source registered on this host by a client, or by the host itself. +/// Its definition is in a format the agent named by `provider` reads. It never +/// contains a credential. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceRegistration: Codable, Sendable, Equatable { + /// Host-unique ID, chosen by whoever registers the source. Also the + /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the + /// {@link SessionModelInfo.modelSourceId} of its models. + public var id: String + /// Agent provider whose agent reads the definition and serves the models. + public var provider: String + /// Display name, published as {@link ModelSourceInfo.displayName}. + public var name: String + /// Icons for UI display. + public var icons: [Icon]? + /// Definition format, one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. + public var format: String + /// How to reach the source: endpoint, wire format, models, and so on, in + /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain + /// a credential. + public var definition: [String: AnyCodable] + /// The contributing client. Absent for a source the host registered itself. + public var clientId: String? + /// Who may select the source's models. Absent means `contributingClient`. + public var sharing: ModelSourceSharingPolicy? + /// What happens when the contributing client leaves. Absent means `contributingClient`. + public var retention: ModelSourceRetentionPolicy? + /// Host-reported status. Absent means the host hasn't reported one yet. + public var state: ModelSourceState? + /// Additional implementation-defined metadata for this registration. + /// MUST NOT contain a credential. + public var meta: [String: AnyCodable]? + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case id + case provider + case name + case icons + case format + case definition + case clientId + case sharing + case retention + case state + case meta = "_meta" + } + + public init( + id: String, + provider: String, + name: String, + icons: [Icon]? = nil, + format: String, + definition: [String: AnyCodable], + clientId: String? = nil, + sharing: ModelSourceSharingPolicy? = nil, + retention: ModelSourceRetentionPolicy? = nil, + state: ModelSourceState? = nil, + meta: [String: AnyCodable]? = nil, + extra: [String: AnyCodable] = [:] + ) { + self.id = id + self.provider = provider + self.name = name + self.icons = icons + self.format = format + self.definition = definition + self.clientId = clientId + self.sharing = sharing + self.retention = retention + self.state = state + self.meta = meta + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.id = try container.decode(String.self, forKey: .id) + self.provider = try container.decode(String.self, forKey: .provider) + self.name = try container.decode(String.self, forKey: .name) + self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) + self.format = try container.decode(String.self, forKey: .format) + self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) + self.clientId = try container.decodeIfPresent(String.self, forKey: .clientId) + self.sharing = try container.decodeIfPresent(ModelSourceSharingPolicy.self, forKey: .sharing) + self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) + self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) + self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.id, forKey: .id) + try container.encode(self.provider, forKey: .provider) + try container.encode(self.name, forKey: .name) + try container.encodeIfPresent(self.icons, forKey: .icons) + try container.encode(self.format, forKey: .format) + try container.encode(self.definition, forKey: .definition) + try container.encodeIfPresent(self.clientId, forKey: .clientId) + try container.encodeIfPresent(self.sharing, forKey: .sharing) + try container.encodeIfPresent(self.retention, forKey: .retention) + try container.encodeIfPresent(self.state, forKey: .state) + try container.encodeIfPresent(self.meta, forKey: .meta) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// The agent is reading and validating the definition, or listing the +/// source's models again after a credential change. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceStartingState: Codable, Sendable, Equatable { + public var kind: ModelSourceStatus + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + public init( + kind: ModelSourceStatus, + extra: [String: AnyCodable] = [:] + ) { + self.kind = kind + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.kind, forKey: .kind) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// The source is usable, and its models are in the catalog of the agent named +/// by the registration's `provider`. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceReadyState: Codable, Sendable, Equatable { + public var kind: ModelSourceStatus + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + public init( + kind: ModelSourceStatus, + extra: [String: AnyCodable] = [:] + ) { + self.kind = kind + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.kind, forKey: .kind) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// What a model source needs in order to become ready. Deliberately carries no +/// credential. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { + /// Why a credential is needed. + public var reason: AuthRequiredReason + /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the + /// endpoint URL as the definition names it, in any scheme the agent + /// supports (for example `http://localhost:11434/v1`). It's the value a + /// client passes back as `authenticate({ resource })`, and nothing fetches + /// it. `resource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + public var resource: ProtectedResourceMetadata + /// Human-readable hint, for example the endpoint's error description. + public var description: String? + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case reason + case resource + case description + } + + public init( + reason: AuthRequiredReason, + resource: ProtectedResourceMetadata, + description: String? = nil, + extra: [String: AnyCodable] = [:] + ) { + self.reason = reason + self.resource = resource + self.description = description + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.reason = try container.decode(AuthRequiredReason.self, forKey: .reason) + self.resource = try container.decode(ProtectedResourceMetadata.self, forKey: .resource) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.reason, forKey: .reason) + try container.encode(self.resource, forKey: .resource) + try container.encodeIfPresent(self.description, forKey: .description) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// The source needs a credential before it can be used. A client answers with +/// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { + /// Why a credential is needed. + public var reason: AuthRequiredReason + /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the + /// endpoint URL as the definition names it, in any scheme the agent + /// supports (for example `http://localhost:11434/v1`). It's the value a + /// client passes back as `authenticate({ resource })`, and nothing fetches + /// it. `resource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + public var resource: ProtectedResourceMetadata + /// Human-readable hint, for example the endpoint's error description. + public var description: String? + public var kind: ModelSourceStatus + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case reason + case resource + case description + case kind + } + + public init( + reason: AuthRequiredReason, + resource: ProtectedResourceMetadata, + description: String? = nil, + kind: ModelSourceStatus, + extra: [String: AnyCodable] = [:] + ) { + self.reason = reason + self.resource = resource + self.description = description + self.kind = kind + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.reason = try container.decode(AuthRequiredReason.self, forKey: .reason) + self.resource = try container.decode(ProtectedResourceMetadata.self, forKey: .resource) + self.description = try container.decodeIfPresent(String.self, forKey: .description) + self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.reason, forKey: .reason) + try container.encode(self.resource, forKey: .resource) + try container.encodeIfPresent(self.description, forKey: .description) + try container.encode(self.kind, forKey: .kind) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// The source failed, or the host declined it, for example by policy. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceErrorState: Codable, Sendable, Equatable { + public var kind: ModelSourceStatus + /// Error details. MUST NOT contain the credential. + public var error: ErrorInfo + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case kind + case error + } + + public init( + kind: ModelSourceStatus, + error: ErrorInfo, + extra: [String: AnyCodable] = [:] + ) { + self.kind = kind + self.error = error + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) + self.error = try container.decode(ErrorInfo.self, forKey: .error) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.kind, forKey: .kind) + try container.encode(self.error, forKey: .error) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + public struct ModelSourceInfo: Codable, Sendable, Equatable { - /// Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + /// Model source identifier, unique within the agent's + /// {@link AgentInfo.modelSources}. For a registered model source, this is + /// the {@link ModelSourceRegistration.id}. public var id: String /// Human-readable name public var displayName: String @@ -1702,7 +2193,8 @@ public struct ModelSourceInfo: Codable, Sendable, Equatable { public struct SessionModelInfo: Codable, Sendable, Equatable { /// Model identifier, unique within the agent's {@link AgentInfo.models}. /// When several model sources serve the same upstream model, the host gives - /// each entry its own ID. + /// each entry its own ID. An ID the host publishes for a registered model + /// source stays bound to that registration and upstream model. public var id: String /// Agent provider that owns this model. Matches {@link AgentInfo.provider}. public var provider: String @@ -9706,6 +10198,50 @@ public enum McpServerState: Codable, Sendable, Equatable { } } +public enum ModelSourceState: Codable, Sendable, Equatable { + case starting(ModelSourceStartingState) + case ready(ModelSourceReadyState) + case authRequired(ModelSourceAuthRequiredState) + case error(ModelSourceErrorState) + /// Unknown or future discriminant; the raw payload is preserved + /// and re-encoded verbatim for forward-compatibility. + case unknown(AnyCodable) + + private enum DiscriminantKey: String, CodingKey { + case discriminant = "kind" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: DiscriminantKey.self) + guard let discriminant = try container.decodeIfPresent(String.self, forKey: .discriminant) else { + self = .unknown(try AnyCodable(from: decoder)) + return + } + switch discriminant { + case "starting": + self = .starting(try ModelSourceStartingState(from: decoder)) + case "ready": + self = .ready(try ModelSourceReadyState(from: decoder)) + case "authRequired": + self = .authRequired(try ModelSourceAuthRequiredState(from: decoder)) + case "error": + self = .error(try ModelSourceErrorState(from: decoder)) + default: + self = .unknown(try AnyCodable(from: decoder)) + } + } + + public func encode(to encoder: Encoder) throws { + switch self { + case .starting(let value): try value.encode(to: encoder) + case .ready(let value): try value.encode(to: encoder) + case .authRequired(let value): try value.encode(to: encoder) + case .error(let value): try value.encode(to: encoder) + case .unknown(let value): try value.encode(to: encoder) + } + } +} + public enum ToolCallContributor: Codable, Sendable, Equatable { case client(ToolCallClientContributor) case mcp(ToolCallMcpContributor) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index 1667f8c34..c02b46ccb 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -103,12 +103,38 @@ public struct AHPRootReducer: Reducer { config.values = a.replace == true ? a.config : config.values.merging(a.config) { _, new in new } state.config = config + case .rootModelSourceRegistrationSet(let a): + applyModelSourceRegistrationSet(&state, a.registration) + + case .rootModelSourceRegistrationRemoved(let a): + _ = applyModelSourceRegistrationRemoved(&state, id: a.id) + default: break } } } +/// Adds `registration` to the registry, or replaces the entry with the same `id`. +func applyModelSourceRegistrationSet(_ state: inout RootState, _ registration: ModelSourceRegistration) { + var list = state.modelSourceRegistrations ?? [] + if let idx = list.firstIndex(where: { $0.id == registration.id }) { + list[idx] = registration + } else { + list.append(registration) + } + state.modelSourceRegistrations = list +} + +/// Removes the registration with `id`. Returns `false` when none matches. +func applyModelSourceRegistrationRemoved(_ state: inout RootState, id: String) -> Bool { + guard var list = state.modelSourceRegistrations, + let idx = list.firstIndex(where: { $0.id == id }) else { return false } + list.remove(at: idx) + state.modelSourceRegistrations = list + return true +} + // MARK: - Chat Reducer (Protocol-based) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index dca8a0725..1093bf056 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -122,6 +122,16 @@ public func rootReducer(state: RootState, action: StateAction) -> RootState { next.config = config return next + case .rootModelSourceRegistrationSet(let a): + var next = state + applyModelSourceRegistrationSet(&next, a.registration) + return next + + case .rootModelSourceRegistrationRemoved(let a): + var next = state + guard applyModelSourceRegistrationRemoved(&next, id: a.id) else { return state } + return next + default: return state } diff --git a/docs/.changes/20261123-model-source-registry-migration.json b/docs/.changes/20261123-model-source-registry-migration.json new file mode 100644 index 000000000..168bc5820 --- /dev/null +++ b/docs/.changes/20261123-model-source-registry-migration.json @@ -0,0 +1,6 @@ +{ + "type": "changed", + "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. Direct Rust struct literals for `RootState` must now include `model_source_registrations: None`, and those for `AgentCapabilities` must include `model_source_registration: None`.", + "targets": ["rust", "swift", "kotlin", "typescript"], + "issues": [619] +} diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json new file mode 100644 index 000000000..6285f7daa --- /dev/null +++ b/docs/.changes/20261123-model-source-registry.json @@ -0,0 +1,5 @@ +{ + "type": "added", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions, and deliver each source's credential with a `modelSource` `authenticate` target. Agents advertise the definition formats they read with `AgentCapabilities.modelSourceRegistration`.", + "issues": [619] +} diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 17b31192a..d9b03501c 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -23,7 +23,7 @@ Individual action payloads do **not** carry their own `session: URI` or `termina ## Root Actions -These mutate root state and travel on the [Root Channel](/specification/root-channel). One root action — `root/configChanged` — is client-dispatchable; the rest are server-originated. +These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged` and the model source registry actions are client-dispatchable; the rest are server-originated. | Type | Client-dispatchable? | When | |---|---|---| @@ -31,6 +31,8 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/activeSessionsChanged` | No | Count of active sessions changed | | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | +| `root/modelSourceRegistrationSet` | **Yes** | A [model source registration](/specification/root-channel#model-source-registry) was added, or replaced by `id` | +| `root/modelSourceRegistrationRemoved` | **Yes** | A model source registration was removed by `id` | ## Automation Catalogue Actions diff --git a/docs/guide/state-model.md b/docs/guide/state-model.md index 8a4013c6e..bc0105dfa 100644 --- a/docs/guide/state-model.md +++ b/docs/guide/state-model.md @@ -12,6 +12,7 @@ RootState { activeSessions?: number // count of non-disposed sessions terminals?: TerminalInfo[] // lightweight terminal catalogue config?: RootConfigState // host-level configuration + modelSourceRegistrations?: ModelSourceRegistration[] // registered model sources } ``` diff --git a/docs/proposals/model-source-registry.md b/docs/proposals/model-source-registry.md index 1af54a4be..dfd5ea85e 100644 --- a/docs/proposals/model-source-registry.md +++ b/docs/proposals/model-source-registry.md @@ -4,7 +4,7 @@ ## Status -Proposal. The type sketches below show the intended shape. They are not part of the protocol until a follow-up change adds them to `types/`, regenerates the clients, and updates the guides and specification. +Implemented by [#627](https://github.com/microsoft/agent-host-protocol/pull/627). The type sketches below show the intended shape; the canonical definitions are in `types/`. An earlier revision proposed model sources as session-scoped plugin customizations. Review pointed out that BYOK configuration belongs to the user rather than to one session, and that automations and long-running headless sessions need model sources that outlive a client's session. This revision moves them to a host-wide registry. [§11](#_11-alternatives-considered) explains the trade-off. diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index 4cb1cc928..ec45cffa9 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -1,6 +1,6 @@ # Authentication -AHP uses [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) (OAuth 2.0 Protected Resource Metadata) semantics for authentication discovery, and [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) (Bearer Token Usage) semantics for token delivery. Communication is JSON-RPC, not HTTP, but the vocabulary and flow mirror the HTTP standards. +AHP uses [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) (OAuth 2.0 Protected Resource Metadata) semantics for authentication discovery, and [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) (Bearer Token Usage) semantics for token delivery. Communication is JSON-RPC, not HTTP, but the vocabulary and flow mirror the HTTP standards. A [registered model source](#model-source-credentials) takes an opaque secret, such as an API key, instead of a Bearer token. ## Overview @@ -87,7 +87,7 @@ Different agents MAY require authentication with different providers. For exampl ## Token Delivery -Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)): +Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `ModelSourceAuthRequiredState.resource` (see [Model source credentials](#model-source-credentials)): ```jsonc // Client → Server @@ -118,7 +118,7 @@ If the client retained the original token response, it MUST subtract elapsed tim `scopes` is optional and lets the client tell the server which OAuth scopes the pushed token actually grants — useful when resolving a `requiredScopes` challenge (from a live `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth`) without the server needing to decode an opaque token. -`target` is an optional, extensible discriminated union identifying the token's consumer. Clients SHOULD include it when answering a challenge from a specific MCP server (`McpServerAuthRequiredState` or `ToolCallAuthRequiredState`), and omit it for provider-level resources (`AgentInfo.protectedResources` or `AuthRequired` `-32007` error data). The currently defined variant is: +`target` is an optional, extensible discriminated union identifying the token's consumer. Clients SHOULD include it when answering a challenge from a specific MCP server (`McpServerAuthRequiredState` or `ToolCallAuthRequiredState`), MUST include it when delivering a registered model source's credential, and omit it for provider-level resources (`AgentInfo.protectedResources` or `AuthRequired` `-32007` error data). The currently defined variants are `mcpServer` and [`modelSource`](#model-source-credentials): ```jsonc // MCP token delivery (the command still uses the root channel) @@ -142,17 +142,54 @@ If the client retained the original token response, it MUST subtract elapsed tim `session` is the URI of the session whose `SessionState.customizations` contains the MCP server, either as a top-level entry or a child customization. `customizationId` is that server's session-unique `McpServerCustomization.id`. Clients only echo these host-published identifiers: `McpServerAuthRequiredState` lives on the customization, and `ToolCallAuthRequiredState.contributor.customizationId` identifies the same customization. -When `target` is present, the host MUST apply the token only to that MCP server in that session — never to sibling servers, other sessions, or agent-level resources — even when they share `resource` and scopes. `resource` MUST still equal the targeted server's advertised `McpAuthRequirement.resource.resource`. If the session or customization is unknown, or the customization is not an MCP server, the host MUST reject the request with `InvalidParams` (`-32602`). +When `target.kind` is `mcpServer`, the host MUST apply the token only to that MCP server in that session — never to sibling servers, other sessions, or agent-level resources — even when they share `resource` and scopes. `resource` MUST still equal the targeted server's advertised `McpAuthRequirement.resource.resource`. If the session or customization is unknown, or the customization is not an MCP server, the host MUST reject the request with `InvalidParams` (`-32602`). -Without `target`, hosts retain resource/scope matching for backwards compatibility; a token may satisfy every matching pending challenge. Older hosts ignore the unknown field and retain this untargeted behavior, so isolation is not guaranteed with older hosts. No capability or protocol version bump is required. +Without `target`, hosts retain resource/scope matching for backwards compatibility; a token may satisfy every matching pending challenge, except a model source's. Older hosts ignore the unknown field and retain this untargeted behavior, so isolation is not guaranteed with older hosts. No capability or protocol version bump is required. If the token is invalid or the resource is unrecognized, the server MUST return a JSON-RPC error (e.g. `AuthRequired` `-32007` or `InvalidParams` `-32602`). +### Model source credentials + +A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. When the source needs a credential, the host sets the registration's state to `ModelSourceAuthRequiredState`, which carries a `reason` and RFC 9728 `resource` metadata for the source's endpoint. A client answers with a `modelSource` target that names the registration: + +```jsonc +// Model source credential delivery +{ + "jsonrpc": "2.0", + "id": 5, + "method": "authenticate", + "params": { + "channel": "ahp-root://", + "resource": "https://api.example.com/v1", + "token": "", + "target": { "kind": "modelSource", "modelSourceId": "2f6c0e1a-model-source" } + } +} +``` + +The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the registration's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `expiresIn` and `scopes`. `resource.resource_name` labels the prompt, for example "OpenRouter API key". + +`resource.resource` is the endpoint URL as the definition names it, in any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Whether the agent sends a credential over plain `http` is the host's network policy. + +When `target.kind` is `modelSource`, the host: + +- MUST apply the credential only to that registration, never to other registrations, MCP servers, or agent-level resources, even when they share `resource`; +- MUST require `resource` to equal the `resource.resource` it most recently advertised for that registration; +- MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); +- MUST reject a credential, including an empty `token` that would revoke one, from a client that may not supply one, with `PermissionDenied` (`-32009`). The contributing client may always supply one. For a registration with `host` sharing, or one the host registered, any client the host allows may supply one; +- MUST treat an empty `token` as revocation: it drops the credential, and the source returns to `authRequired` with `reason: required`. + +The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition` or `_meta`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host drops the credential when the registration is removed, when its definition or contributing client changes, and when the host restarts. + +The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, and SHOULD check that `resource.resource` matches the endpoint in its own copy of the definition before sending a secret. + +If the credential fails during a turn that uses the source, the host SHOULD end the turn with a resumable error (`chat/error` with `part.resumable: true`) rather than wait. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first, including the sharing policy. The host never switches the turn to a different model. + ### Why keyed by `resource` and optional `target`? The RFC 9728 `resource` field identifies the protected resource, but not necessarily its consumer: different MCP servers can share a resource and scopes while using distinct OAuth clients or accounts. `target` adds the session URI and customization ID needed to distinguish these consumers, even when server names repeat across sessions or manifests. Provider-level authentication continues to omit `target` and remains keyed by `resource` and scopes. -The `target.kind` discriminant is extensible so future consumers, such as [host-owned authentication proposed in PR #404](https://github.com/microsoft/agent-host-protocol/pull/404), can add variants rather than new fields to `authenticate`. +The `target.kind` discriminant is extensible so new consumers, such as registered model sources or [host-owned authentication proposed in PR #404](https://github.com/microsoft/agent-host-protocol/pull/404), can add variants rather than new fields to `authenticate`. ### Account selection hints diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index ad44dba06..5d4ac5e48 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -22,6 +22,7 @@ RootState { activeSessions?: number terminals?: TerminalInfo[] config?: RootConfigState + modelSourceRegistrations?: ModelSourceRegistration[] } ``` @@ -29,6 +30,7 @@ RootState { - `activeSessions` — count of non-disposed sessions. Lightweight badge counter. - `terminals` — lightweight per-terminal metadata for rendering a terminal manager UI without subscribing to every terminal. See [Terminal Channel](/specification/terminal-channel) for the full state. - `config` — host-level configuration schema and current values. +- `modelSourceRegistrations` — model sources clients or the host registered. See [Model source registry](#model-source-registry). The session list is **not** part of root state. Clients fetch it imperatively via [`listSessions`](/reference/root#listsessions) and patch it from `root/*` notifications described below. @@ -59,6 +61,65 @@ A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, } ``` +### Model source registry + +Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSourceRegistrations`](/reference/root#modelsourceregistration), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads. + +```json +{ + "id": "2f6c0e1a-model-source", + "provider": "example", + "name": "OpenRouter", + "format": "example.com/model-source@1", + "definition": { "baseUrl": "https://openrouter.ai/api/v1" }, + "clientId": "laptop", + "sharing": "host", + "retention": "host", + "state": { "kind": "ready" } +} +``` + +`definition` says how to reach the source, in `format`. Its shape belongs to the agent that reads it, and it MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). + +#### Registering + +A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId` and no `state`, and removes one with `root/modelSourceRegistrationRemoved`. The host reports status by dispatching `Set` again with a `state`: `starting`, `ready`, `authRequired`, or `error`. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed, because doing so clears the reported state. + +The host rejects a client's `Set` or `Removed`, through `rejectionReason`, when: + +- the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; +- `clientId` isn't the dispatching client's ID, or `state` is present; +- `id` is already a declared `ModelSourceInfo.id` in that agent's catalog; +- the registration belongs to another client and has `contributingClient` sharing, or the host registered it, unless host policy allows the change; +- the host won't honor the requested `sharing` or `retention`. The client can register again with a narrower policy. + +When a `Set` changes a registration's `provider`, `format`, `definition`, or `clientId`, the host drops its credential, and the source goes back through `starting`. A host may also register sources itself. Those registrations have no `clientId`, and both policies behave as `host`. + +#### Catalog + +When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `name`, and its models in `models` with `modelSourceId` set to that `id`. The host lists the models only while the registration is `ready`. It MAY list the `ModelSourceInfo` in other states. + +The host checks every selection of a registered source's model: the model is listed, the chat is backed by the registration's agent provider, and the sharing policy allows it. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. + +#### Sharing and retention + +The contributing client chooses two policies. Absent means `contributingClient`, the narrowest choice. + +- **Sharing.** With `contributingClient`, only turns and pending messages that client dispatches may select the source's models. With `host`, any client may, and so may work the host starts itself, such as automations. +- **Retention.** With `contributingClient`, the source is removed when its client leaves: new work that names its models fails, turns already running on it finish, and then the host removes the registration and drops its credential. With `host`, the registration and its in-memory credential stay until a client removes it, host policy expires it, or the host restarts. + +The host never widens a policy, and it MAY expire `host`-retained registrations. Every client sees every registration, so clients SHOULD offer only the models they may select, using `sharing` and `clientId`. + +A client that reconnects with the same `clientId` within the host's grace period keeps its registrations. A client that comes back with a new `clientId` registers again under the same `id`. For a `host`-shared registration, that takes it over: `clientId` changes, the credential is dropped, and the new contributing client supplies it. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back in `authRequired`. + +#### Reserved model IDs + +Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A host can meet this by minting IDs it never reuses, for example with a random component. + +#### Automations + +An automation may name a registered source's model when the registration has `host` sharing and `host` retention, or was registered by the host. The host SHOULD reject an automation create or update that names any other registration's model. If the source isn't `ready` when a run starts, the run fails through the automation run lifecycle. + ### Paginating the catalogue A large catalogue can be fetched incrementally. [`listSessions`](/reference/root#listsessions) accepts an optional `limit` (the maximum number of entries the client wants in the page — the server SHOULD respect it, but MAY return fewer and MAY impose its own upper cap) and an optional opaque `cursor`. The result carries the page in `items` plus an optional `nextCursor`: @@ -110,7 +171,7 @@ target channel instead. | `root/sessionSummaryChanged` | server → client notification | Session catalogue entry mutated. | | `root/progress` | server → client notification | Generic progress for a long-running operation a client opted into (e.g. an SDK download). | | `unsubscribe` | client → server notification | Stop receiving root-channel messages. | -| `dispatchAction` | client → server notification | Dispatch a root-scoped client action (currently `root/configChanged`). | +| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceRegistrationSet`, or `root/modelSourceRegistrationRemoved`. | `auth/required` may also be emitted on `ahp-root://` when the auth requirement is root-scoped; see [Authentication](/specification/authentication). @@ -125,6 +186,8 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/activeSessionsChanged` | Server | Replaces `activeSessions` | | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | +| `root/modelSourceRegistrationSet` | Server / Client | Adds or replaces a registration in `modelSourceRegistrations` by `id` | +| `root/modelSourceRegistrationRemoved` | Server / Client | Removes a registration by `id` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index f5eabe742..69283d4f0 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -127,6 +127,40 @@ "config" ] }, + "RootModelSourceRegistrationSetAction": { + "type": "object", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId` and\nno `state`. The host reports status by dispatching it again with the same\nregistration and a `state`.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceRegistrationSet" + }, + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "The registration to add or replace, matched by `id`." + } + }, + "required": [ + "type", + "registration" + ] + }, + "RootModelSourceRegistrationRemovedAction": { + "type": "object", + "description": "Removes the model source registration with the given `id`. A no-op when\nnone matches.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceRegistrationRemoved" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + } + }, + "required": [ + "type", + "id" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -3281,6 +3315,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSourceRegistrations": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceRegistration" + }, + "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -3357,6 +3398,10 @@ "multipleWorkingDirectories": { "$ref": "#/$defs/MultipleWorkingDirectoriesCapability", "description": "The session's agent can be granted tool access to more than one working\ndirectory. The directories are treated as equal peers except where the\nagent advertises a protected primary-slot option (some backends pin or\nreplace their first directory as a process root).\n\nWhen absent, clients MUST NOT mutate a session's or chat's working-directory\nset and MUST NOT set more than one entry in\n{@link CreateSessionParams.workingDirectories}." + }, + "modelSourceRegistration": { + "$ref": "#/$defs/ModelSourceRegistrationCapability", + "description": "The agent serves models from registered model sources, in the listed\ndefinition formats.\n\nStability: 1.0 - Early development." } } }, @@ -3394,7 +3439,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's {@link AgentInfo.modelSources}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." }, "displayName": { "type": "string", @@ -3411,7 +3456,7 @@ "properties": { "id": { "type": "string", - "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID." + "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID. An ID the host publishes for a registered model\nsource stays bound to that registration and upstream model." }, "provider": { "type": "string", @@ -3485,6 +3530,173 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + } + }, + "required": [ + "formats" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent reads the definition and serves the models." + }, + "name": { + "type": "string", + "description": "Display name, published as {@link ModelSourceInfo.displayName}." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "format": { + "type": "string", + "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent for a source the host registered itself." + }, + "sharing": { + "$ref": "#/$defs/ModelSourceSharingPolicy", + "description": "Who may select the source's models. Absent means `contributingClient`." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "Host-reported status. Absent means the host hasn't reported one yet." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "name", + "format", + "definition" + ] + }, + "ModelSourceStartingState": { + "type": "object", + "description": "The agent is reading and validating the definition, or listing the\nsource's models again after a credential change.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "starting" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceReadyState": { + "type": "object", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceAuthRequirement": { + "type": "object", + "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + } + }, + "required": [ + "reason", + "resource" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "resource", + "kind" + ] + }, + "ModelSourceErrorState": { + "type": "object", + "description": "The source failed, or the host declined it, for example by policy.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Error details. MUST NOT contain the credential." + } + }, + "required": [ + "kind", + "error" + ] + }, "RootConfigState": { "type": "object", "description": "Live agent-host configuration metadata.\n\nThe schema describes the available configuration properties and the values\ncontain the current value for each resolved property.", @@ -8918,6 +9130,23 @@ ], "description": "A primitive JSON value: a string, number, boolean, or `null`." }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, "SessionOrigin": { "$ref": "#/$defs/AutomationSessionOrigin", "description": "Durable provenance for sessions created by a higher-level AHP workflow." @@ -9481,6 +9710,12 @@ { "$ref": "#/$defs/RootConfigChangedAction" }, + { + "$ref": "#/$defs/RootModelSourceRegistrationSetAction" + }, + { + "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -9878,6 +10113,30 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceSharingPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "Who may select a registered model source's models." + }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its contributing client leaves." + }, + "AuthRequiredReason": { + "enum": [ + "required", + "expired" + ], + "type": "string", + "description": "Reason why authentication is required." + }, "SessionLifecycle": { "enum": [ "creating", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index e8abb6849..4ee1f0e0b 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1049,9 +1049,26 @@ "customizationId" ] }, + "ModelSourceAuthenticateTarget": { + "type": "object", + "description": "A registered model source.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "modelSource" + }, + "modelSourceId": { + "type": "string", + "description": "The registration's `ModelSourceRegistration.id`." + } + }, + "required": [ + "kind", + "modelSourceId" + ] + }, "AuthenticateParams": { "type": "object", - "description": "Pushes a Bearer token for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth).\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these three mechanisms.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -1066,15 +1083,15 @@ }, "resource": { "type": "string", - "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`." + "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceAuthRequiredState.resource`." }, "token": { "type": "string", - "description": "Bearer token obtained from the resource's authorization server" + "description": "Bearer token obtained from the resource's authorization server, or an\nopaque secret for a model source. An empty string revokes the credential." }, "expiresIn": { "type": "integer", - "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", + "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nAn API key omits this field.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", "minimum": 1 }, "scopes": { @@ -1082,11 +1099,11 @@ "items": { "type": "string" }, - "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken." + "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken. Scopes apply to OAuth-issued tokens only." }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nWhen present, the host MUST apply the token only to that MCP server in\nthat session, never to sibling servers, other sessions, or agent-level\nresources, even if they share the resource and scopes. `resource` MUST\nstill equal that server's advertised `McpAuthRequirement.resource.resource`.\nThe host MUST reject an unknown session or customization, or a\ncustomization that is not an MCP server, with `InvalidParams` (-32602).\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", @@ -1997,7 +2014,14 @@ "description": "Result of the `reconnect` command." }, "AuthenticateTarget": { - "$ref": "#/$defs/McpServerAuthenticateTarget", + "oneOf": [ + { + "$ref": "#/$defs/McpServerAuthenticateTarget" + }, + { + "$ref": "#/$defs/ModelSourceAuthenticateTarget" + } + ], "description": "Consumer of an authentication token, discriminated by `kind`.\nExtensible to support additional consumers, such as host-owned authentication." }, "ChatSource": { @@ -2637,6 +2661,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSourceRegistrations": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceRegistration" + }, + "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -2713,6 +2744,10 @@ "multipleWorkingDirectories": { "$ref": "#/$defs/MultipleWorkingDirectoriesCapability", "description": "The session's agent can be granted tool access to more than one working\ndirectory. The directories are treated as equal peers except where the\nagent advertises a protected primary-slot option (some backends pin or\nreplace their first directory as a process root).\n\nWhen absent, clients MUST NOT mutate a session's or chat's working-directory\nset and MUST NOT set more than one entry in\n{@link CreateSessionParams.workingDirectories}." + }, + "modelSourceRegistration": { + "$ref": "#/$defs/ModelSourceRegistrationCapability", + "description": "The agent serves models from registered model sources, in the listed\ndefinition formats.\n\nStability: 1.0 - Early development." } } }, @@ -2750,7 +2785,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's {@link AgentInfo.modelSources}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." }, "displayName": { "type": "string", @@ -2767,7 +2802,7 @@ "properties": { "id": { "type": "string", - "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID." + "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID. An ID the host publishes for a registered model\nsource stays bound to that registration and upstream model." }, "provider": { "type": "string", @@ -2841,6 +2876,173 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + } + }, + "required": [ + "formats" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent reads the definition and serves the models." + }, + "name": { + "type": "string", + "description": "Display name, published as {@link ModelSourceInfo.displayName}." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "format": { + "type": "string", + "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent for a source the host registered itself." + }, + "sharing": { + "$ref": "#/$defs/ModelSourceSharingPolicy", + "description": "Who may select the source's models. Absent means `contributingClient`." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "Host-reported status. Absent means the host hasn't reported one yet." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "name", + "format", + "definition" + ] + }, + "ModelSourceStartingState": { + "type": "object", + "description": "The agent is reading and validating the definition, or listing the\nsource's models again after a credential change.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "starting" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceReadyState": { + "type": "object", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceAuthRequirement": { + "type": "object", + "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + } + }, + "required": [ + "reason", + "resource" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "resource", + "kind" + ] + }, + "ModelSourceErrorState": { + "type": "object", + "description": "The source failed, or the host declined it, for example by policy.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Error details. MUST NOT contain the credential." + } + }, + "required": [ + "kind", + "error" + ] + }, "RootConfigState": { "type": "object", "description": "Live agent-host configuration metadata.\n\nThe schema describes the available configuration properties and the values\ncontain the current value for each resolved property.", @@ -8360,6 +8562,40 @@ "config" ] }, + "RootModelSourceRegistrationSetAction": { + "type": "object", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId` and\nno `state`. The host reports status by dispatching it again with the same\nregistration and a `state`.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceRegistrationSet" + }, + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "The registration to add or replace, matched by `id`." + } + }, + "required": [ + "type", + "registration" + ] + }, + "RootModelSourceRegistrationRemovedAction": { + "type": "object", + "description": "Removes the model source registration with the given `id`. A no-op when\nnone matches.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceRegistrationRemoved" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + } + }, + "required": [ + "type", + "id" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -10852,6 +11088,12 @@ { "$ref": "#/$defs/RootConfigChangedAction" }, + { + "$ref": "#/$defs/RootModelSourceRegistrationSetAction" + }, + { + "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -11299,6 +11541,47 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceSharingPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "Who may select a registered model source's models." + }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its contributing client leaves." + }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, + "AuthRequiredReason": { + "enum": [ + "required", + "expired" + ], + "type": "string", + "description": "Reason why authentication is required." + }, "SessionStatus": { "type": "integer", "minimum": 0, diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 3e12d649a..d2cd333bd 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -650,6 +650,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSourceRegistrations": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceRegistration" + }, + "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -726,6 +733,10 @@ "multipleWorkingDirectories": { "$ref": "#/$defs/MultipleWorkingDirectoriesCapability", "description": "The session's agent can be granted tool access to more than one working\ndirectory. The directories are treated as equal peers except where the\nagent advertises a protected primary-slot option (some backends pin or\nreplace their first directory as a process root).\n\nWhen absent, clients MUST NOT mutate a session's or chat's working-directory\nset and MUST NOT set more than one entry in\n{@link CreateSessionParams.workingDirectories}." + }, + "modelSourceRegistration": { + "$ref": "#/$defs/ModelSourceRegistrationCapability", + "description": "The agent serves models from registered model sources, in the listed\ndefinition formats.\n\nStability: 1.0 - Early development." } } }, @@ -763,7 +774,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's {@link AgentInfo.modelSources}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." }, "displayName": { "type": "string", @@ -780,7 +791,7 @@ "properties": { "id": { "type": "string", - "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID." + "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID. An ID the host publishes for a registered model\nsource stays bound to that registration and upstream model." }, "provider": { "type": "string", @@ -854,6 +865,173 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + } + }, + "required": [ + "formats" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent reads the definition and serves the models." + }, + "name": { + "type": "string", + "description": "Display name, published as {@link ModelSourceInfo.displayName}." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "format": { + "type": "string", + "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent for a source the host registered itself." + }, + "sharing": { + "$ref": "#/$defs/ModelSourceSharingPolicy", + "description": "Who may select the source's models. Absent means `contributingClient`." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "Host-reported status. Absent means the host hasn't reported one yet." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "name", + "format", + "definition" + ] + }, + "ModelSourceStartingState": { + "type": "object", + "description": "The agent is reading and validating the definition, or listing the\nsource's models again after a credential change.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "starting" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceReadyState": { + "type": "object", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceAuthRequirement": { + "type": "object", + "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + } + }, + "required": [ + "reason", + "resource" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "resource", + "kind" + ] + }, + "ModelSourceErrorState": { + "type": "object", + "description": "The source failed, or the host declined it, for example by policy.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Error details. MUST NOT contain the credential." + } + }, + "required": [ + "kind", + "error" + ] + }, "RootConfigState": { "type": "object", "description": "Live agent-host configuration metadata.\n\nThe schema describes the available configuration properties and the values\ncontain the current value for each resolved property.", @@ -7295,9 +7473,26 @@ "customizationId" ] }, + "ModelSourceAuthenticateTarget": { + "type": "object", + "description": "A registered model source.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "modelSource" + }, + "modelSourceId": { + "type": "string", + "description": "The registration's `ModelSourceRegistration.id`." + } + }, + "required": [ + "kind", + "modelSourceId" + ] + }, "AuthenticateParams": { "type": "object", - "description": "Pushes a Bearer token for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth).\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these three mechanisms.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -7312,15 +7507,15 @@ }, "resource": { "type": "string", - "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`." + "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceAuthRequiredState.resource`." }, "token": { "type": "string", - "description": "Bearer token obtained from the resource's authorization server" + "description": "Bearer token obtained from the resource's authorization server, or an\nopaque secret for a model source. An empty string revokes the credential." }, "expiresIn": { "type": "integer", - "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", + "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nAn API key omits this field.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", "minimum": 1 }, "scopes": { @@ -7328,11 +7523,11 @@ "items": { "type": "string" }, - "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken." + "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken. Scopes apply to OAuth-issued tokens only." }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nWhen present, the host MUST apply the token only to that MCP server in\nthat session, never to sibling servers, other sessions, or agent-level\nresources, even if they share the resource and scopes. `resource` MUST\nstill equal that server's advertised `McpAuthRequirement.resource.resource`.\nThe host MUST reject an unknown session or customization, or a\ncustomization that is not an MCP server, with `InvalidParams` (-32602).\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", @@ -8284,6 +8479,47 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceSharingPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "Who may select a registered model source's models." + }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its contributing client leaves." + }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, + "AuthRequiredReason": { + "enum": [ + "required", + "expired" + ], + "type": "string", + "description": "Reason why authentication is required." + }, "SessionStatus": { "type": "integer", "minimum": 0, @@ -9050,6 +9286,12 @@ { "$ref": "#/$defs/RootConfigChangedAction" }, + { + "$ref": "#/$defs/RootModelSourceRegistrationSetAction" + }, + { + "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -9392,7 +9634,14 @@ "description": "Discriminant for {@link ResourceResolveResult.type}." }, "AuthenticateTarget": { - "$ref": "#/$defs/McpServerAuthenticateTarget", + "oneOf": [ + { + "$ref": "#/$defs/McpServerAuthenticateTarget" + }, + { + "$ref": "#/$defs/ModelSourceAuthenticateTarget" + } + ], "description": "Consumer of an authentication token, discriminated by `kind`.\nExtensible to support additional consumers, such as host-owned authentication." }, "CompletionItemKind": { @@ -9578,6 +9827,40 @@ "config" ] }, + "RootModelSourceRegistrationSetAction": { + "type": "object", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId` and\nno `state`. The host reports status by dispatching it again with the same\nregistration and a `state`.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceRegistrationSet" + }, + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "The registration to add or replace, matched by `id`." + } + }, + "required": [ + "type", + "registration" + ] + }, + "RootModelSourceRegistrationRemovedAction": { + "type": "object", + "description": "Removes the model source registration with the given `id`. A no-op when\nnone matches.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceRegistrationRemoved" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + } + }, + "required": [ + "type", + "id" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 53fee5cfd..cadd14c02 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -952,6 +952,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSourceRegistrations": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceRegistration" + }, + "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -1028,6 +1035,10 @@ "multipleWorkingDirectories": { "$ref": "#/$defs/MultipleWorkingDirectoriesCapability", "description": "The session's agent can be granted tool access to more than one working\ndirectory. The directories are treated as equal peers except where the\nagent advertises a protected primary-slot option (some backends pin or\nreplace their first directory as a process root).\n\nWhen absent, clients MUST NOT mutate a session's or chat's working-directory\nset and MUST NOT set more than one entry in\n{@link CreateSessionParams.workingDirectories}." + }, + "modelSourceRegistration": { + "$ref": "#/$defs/ModelSourceRegistrationCapability", + "description": "The agent serves models from registered model sources, in the listed\ndefinition formats.\n\nStability: 1.0 - Early development." } } }, @@ -1065,7 +1076,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's {@link AgentInfo.modelSources}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." }, "displayName": { "type": "string", @@ -1082,7 +1093,7 @@ "properties": { "id": { "type": "string", - "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID." + "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID. An ID the host publishes for a registered model\nsource stays bound to that registration and upstream model." }, "provider": { "type": "string", @@ -1156,6 +1167,173 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + } + }, + "required": [ + "formats" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent reads the definition and serves the models." + }, + "name": { + "type": "string", + "description": "Display name, published as {@link ModelSourceInfo.displayName}." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "format": { + "type": "string", + "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent for a source the host registered itself." + }, + "sharing": { + "$ref": "#/$defs/ModelSourceSharingPolicy", + "description": "Who may select the source's models. Absent means `contributingClient`." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "Host-reported status. Absent means the host hasn't reported one yet." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "name", + "format", + "definition" + ] + }, + "ModelSourceStartingState": { + "type": "object", + "description": "The agent is reading and validating the definition, or listing the\nsource's models again after a credential change.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "starting" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceReadyState": { + "type": "object", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceAuthRequirement": { + "type": "object", + "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + } + }, + "required": [ + "reason", + "resource" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "resource", + "kind" + ] + }, + "ModelSourceErrorState": { + "type": "object", + "description": "The source failed, or the host declined it, for example by policy.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Error details. MUST NOT contain the credential." + } + }, + "required": [ + "kind", + "error" + ] + }, "RootConfigState": { "type": "object", "description": "Live agent-host configuration metadata.\n\nThe schema describes the available configuration properties and the values\ncontain the current value for each resolved property.", @@ -6624,6 +6802,39 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceSharingPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "Who may select a registered model source's models." + }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its contributing client leaves." + }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, "SessionLifecycle": { "enum": [ "creating", diff --git a/schema/state.schema.json b/schema/state.schema.json index 5691639a2..79a92dc7d 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -561,6 +561,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSourceRegistrations": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceRegistration" + }, + "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -637,6 +644,10 @@ "multipleWorkingDirectories": { "$ref": "#/$defs/MultipleWorkingDirectoriesCapability", "description": "The session's agent can be granted tool access to more than one working\ndirectory. The directories are treated as equal peers except where the\nagent advertises a protected primary-slot option (some backends pin or\nreplace their first directory as a process root).\n\nWhen absent, clients MUST NOT mutate a session's or chat's working-directory\nset and MUST NOT set more than one entry in\n{@link CreateSessionParams.workingDirectories}." + }, + "modelSourceRegistration": { + "$ref": "#/$defs/ModelSourceRegistrationCapability", + "description": "The agent serves models from registered model sources, in the listed\ndefinition formats.\n\nStability: 1.0 - Early development." } } }, @@ -674,7 +685,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's {@link AgentInfo.modelSources}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." }, "displayName": { "type": "string", @@ -691,7 +702,7 @@ "properties": { "id": { "type": "string", - "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID." + "description": "Model identifier, unique within the agent's {@link AgentInfo.models}.\nWhen several model sources serve the same upstream model, the host gives\neach entry its own ID. An ID the host publishes for a registered model\nsource stays bound to that registration and upstream model." }, "provider": { "type": "string", @@ -765,6 +776,173 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + } + }, + "required": [ + "formats" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent reads the definition and serves the models." + }, + "name": { + "type": "string", + "description": "Display name, published as {@link ModelSourceInfo.displayName}." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "format": { + "type": "string", + "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent for a source the host registered itself." + }, + "sharing": { + "$ref": "#/$defs/ModelSourceSharingPolicy", + "description": "Who may select the source's models. Absent means `contributingClient`." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "Host-reported status. Absent means the host hasn't reported one yet." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "name", + "format", + "definition" + ] + }, + "ModelSourceStartingState": { + "type": "object", + "description": "The agent is reading and validating the definition, or listing the\nsource's models again after a credential change.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "starting" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceReadyState": { + "type": "object", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "ModelSourceAuthRequirement": { + "type": "object", + "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + } + }, + "required": [ + "reason", + "resource" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/AuthRequiredReason", + "description": "Why a credential is needed." + }, + "resource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + }, + "description": { + "type": "string", + "description": "Human-readable hint, for example the endpoint's error description." + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "resource", + "kind" + ] + }, + "ModelSourceErrorState": { + "type": "object", + "description": "The source failed, or the host declined it, for example by policy.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/ErrorInfo", + "description": "Error details. MUST NOT contain the credential." + } + }, + "required": [ + "kind", + "error" + ] + }, "RootConfigState": { "type": "object", "description": "Live agent-host configuration metadata.\n\nThe schema describes the available configuration properties and the values\ncontain the current value for each resolved property.", @@ -6198,6 +6376,23 @@ ], "description": "A primitive JSON value: a string, number, boolean, or `null`." }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, "SessionOrigin": { "$ref": "#/$defs/AutomationSessionOrigin", "description": "Durable provenance for sessions created by a higher-level AHP workflow." @@ -6768,6 +6963,30 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceSharingPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "Who may select a registered model source's models." + }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its contributing client leaves." + }, + "AuthRequiredReason": { + "enum": [ + "required", + "expired" + ], + "type": "string", + "description": "Reason why authentication is required." + }, "SessionStatus": { "type": "integer", "minimum": 0, diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index 54e9c1635..96f137134 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -773,6 +773,7 @@ const STATE_ENUMS = [ 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', 'AutomationDisableConditionKind', @@ -794,6 +795,13 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, + { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceRegistration' }, + { name: 'ModelSourceStartingState' }, + { name: 'ModelSourceReadyState' }, + { name: 'ModelSourceAuthRequirement' }, + { name: 'ModelSourceAuthRequiredState' }, + { name: 'ModelSourceErrorState' }, { name: 'ModelSourceInfo' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, @@ -1289,6 +1297,19 @@ const MCP_SERVER_STATUS_UNION: UnionConfig = { unknown: true, }; +const MODEL_SOURCE_STATUS_UNION: UnionConfig = { + name: 'ModelSourceState', + discriminantField: 'kind', + doc: 'ModelSourceState is the lifecycle state of a registered model source.', + variants: [ + { variantName: 'Starting', innerType: 'ModelSourceStartingState', wireValue: 'starting' }, + { variantName: 'Ready', innerType: 'ModelSourceReadyState', wireValue: 'ready' }, + { variantName: 'AuthRequired', innerType: 'ModelSourceAuthRequiredState', wireValue: 'authRequired' }, + { variantName: 'Error', innerType: 'ModelSourceErrorState', wireValue: 'error' }, + ], + unknown: true, +}; + const TOOL_CALL_CONTRIBUTOR_UNION: UnionConfig = { name: 'ToolCallContributor', discriminantField: 'kind', @@ -1632,7 +1653,8 @@ function generateStateFile(project: Project): string { CHAT_INPUT_QUESTION_UNION, CHAT_INPUT_ANSWER_VALUE_UNION, CHAT_INPUT_ANSWER_UNION, TOOL_RESULT_CONTENT_UNION, MESSAGE_ATTACHMENT_UNION, CUSTOMIZATION_UNION, CHILD_CUSTOMIZATION_UNION, CUSTOMIZATION_LOAD_STATE_UNION, - MCP_SERVER_STATUS_UNION, TOOL_CALL_CONTRIBUTOR_UNION, SESSION_INPUT_REQUEST_UNION, BACKGROUND_WORK_UNION, + MCP_SERVER_STATUS_UNION, MODEL_SOURCE_STATUS_UNION, TOOL_CALL_CONTRIBUTOR_UNION, SESSION_INPUT_REQUEST_UNION, + BACKGROUND_WORK_UNION, TERMINAL_LIFECYCLE_STATE_UNION, SESSION_ORIGIN_UNION, AUTOMATION_TRIGGER_UNION, AUTOMATION_DISABLE_CONDITION_UNION, AUTOMATION_TARGET_UNION, AUTOMATION_RUN_ORIGIN_UNION, AUTOMATION_RUN_LIFECYCLE_UNION, @@ -1656,6 +1678,8 @@ const ACTION_VARIANTS: { type: string; variantName: string; tsInterface: string { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, + { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, // Session turn/tool-call/error/usage/reasoning actions have no TypeScript interfaces in @@ -2383,6 +2407,7 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: str { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, + { name: 'ModelSourceAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, { name: 'CreateTerminalParams' }, { name: 'DisposeTerminalParams' }, { name: 'ResolveSessionConfigParams' }, { name: 'ResolveSessionConfigResult' }, @@ -2422,6 +2447,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { doc: 'AuthenticateTarget identifies the consumer of an authentication token.', variants: [ { variantName: 'McpServer', innerType: 'McpServerAuthenticateTarget', wireValue: 'mcpServer' }, + { variantName: 'ModelSource', innerType: 'ModelSourceAuthenticateTarget', wireValue: 'modelSource' }, ], }; @@ -2946,7 +2972,7 @@ function checkExhaustiveness(project: Project): void { 'SessionToolCallConfirmedAction', 'PingParams', 'TerminalClaim', 'TerminalContentPart', 'MessageAttachment', 'MessageAttachmentBase', 'Customization', 'ChildCustomization', 'ChildCustomizationType', - 'CustomizationLoadState', 'McpServerState', 'ToolCallContributor', + 'CustomizationLoadState', 'McpServerState', 'ModelSourceState', 'ToolCallContributor', 'SessionOrigin', 'TerminalLifecycleState', 'AutomationTrigger', 'AutomationDisableCondition', 'AutomationTarget', diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index 030fc40af..dbd125b4a 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -758,6 +758,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -778,6 +779,13 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, + { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceRegistration' }, + { name: 'ModelSourceStartingState' }, + { name: 'ModelSourceReadyState' }, + { name: 'ModelSourceAuthRequirement' }, + { name: 'ModelSourceAuthRequiredState' }, + { name: 'ModelSourceErrorState' }, { name: 'ModelSourceInfo' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, @@ -1130,6 +1138,19 @@ const MCP_SERVER_STATUS_UNION: UnionConfig = { unknown: true, }; +const MODEL_SOURCE_STATUS_UNION: UnionConfig = { + name: 'ModelSourceState', + discriminantField: 'kind', + doc: 'ModelSourceState is the discriminated lifecycle status of a registered model source.', + variants: [ + { variantName: 'Starting', innerType: 'ModelSourceStartingState', wireValue: 'starting' }, + { variantName: 'Ready', innerType: 'ModelSourceReadyState', wireValue: 'ready' }, + { variantName: 'AuthRequired', innerType: 'ModelSourceAuthRequiredState', wireValue: 'authRequired' }, + { variantName: 'Error', innerType: 'ModelSourceErrorState', wireValue: 'error' }, + ], + unknown: true, +}; + const TOOL_CALL_CONTRIBUTOR_UNION: UnionConfig = { name: 'ToolCallContributor', discriminantField: 'kind', @@ -1597,6 +1618,8 @@ function generateStateFile(project: Project): string { lines.push(''); lines.push(generateDiscriminatedUnion(project, MCP_SERVER_STATUS_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, MODEL_SOURCE_STATUS_UNION)); + lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_CONTRIBUTOR_UNION)); lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_RISK_ASSESSMENT_UNION)); @@ -1636,6 +1659,8 @@ const ACTION_VARIANTS: { { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, + { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, { type: 'session/chatAdded', variantName: 'SessionChatAdded', tsInterface: 'SessionChatAddedAction' }, @@ -1883,6 +1908,7 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: str { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget' }, + { name: 'ModelSourceAuthenticateTarget' }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, { name: 'CreateTerminalParams' }, { name: 'DisposeTerminalParams' }, { name: 'ResolveSessionConfigParams' }, { name: 'ResolveSessionConfigResult' }, @@ -1902,6 +1928,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { doc: 'AuthenticateTarget identifies the consumer of an authentication token.', variants: [ { variantName: 'McpServer', innerType: 'McpServerAuthenticateTarget', wireValue: 'mcpServer' }, + { variantName: 'ModelSource', innerType: 'ModelSourceAuthenticateTarget', wireValue: 'modelSource' }, ], injectDiscriminantOnMarshal: true, }; @@ -2573,6 +2600,7 @@ function checkExhaustiveness(project: Project): void { 'ChildCustomizationType', 'CustomizationLoadState', 'McpServerState', + 'ModelSourceState', 'ToolCallContributor', 'ToolCallRiskAssessment', 'TerminalLifecycleState', diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index 5aa2507ce..2f5020712 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1012,6 +1012,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1028,6 +1029,9 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', + 'ModelSourceRegistrationCapability', 'ModelSourceRegistration', 'ModelSourceStartingState', + 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', + 'ModelSourceErrorState', 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', 'BackgroundShellWork', 'BackgroundSubagentWork', @@ -1327,6 +1331,18 @@ const MCP_SERVER_STATUS_UNION: UnionConfig = { unknown: true, }; +const MODEL_SOURCE_STATUS_UNION: UnionConfig = { + name: 'ModelSourceState', + discriminantField: 'kind', + variants: [ + { caseName: 'Starting', structName: 'ModelSourceStartingState', discriminantValue: 'starting' }, + { caseName: 'Ready', structName: 'ModelSourceReadyState', discriminantValue: 'ready' }, + { caseName: 'AuthRequired', structName: 'ModelSourceAuthRequiredState', discriminantValue: 'authRequired' }, + { caseName: 'Error', structName: 'ModelSourceErrorState', discriminantValue: 'error' }, + ], + unknown: true, +}; + const TOOL_CALL_CONTRIBUTOR_UNION: UnionConfig = { name: 'ToolCallContributor', discriminantField: 'kind', @@ -1522,6 +1538,8 @@ function generateStateFile(project: Project): string { lines.push(''); lines.push(generateDiscriminatedUnion(project, MCP_SERVER_STATUS_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, MODEL_SOURCE_STATUS_UNION)); + lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_CONTRIBUTOR_UNION)); lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_RISK_ASSESSMENT_UNION)); @@ -1641,6 +1659,8 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'annotations/entryRemoved', caseName: 'AnnotationsEntryRemoved', tsInterface: 'AnnotationsEntryRemovedAction' }, { type: 'root/terminalsChanged', caseName: 'RootTerminalsChanged', tsInterface: 'RootTerminalsChangedAction' }, { type: 'root/configChanged', caseName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, + { type: 'root/modelSourceRegistrationSet', caseName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceRegistrationRemoved', caseName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'terminal/data', caseName: 'TerminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'TerminalInput', tsInterface: 'TerminalInputAction' }, { type: 'terminal/resized', caseName: 'TerminalResized', tsInterface: 'TerminalResizedAction' }, @@ -1854,7 +1874,7 @@ const COMMAND_STRUCTS = [ 'CreateResourceWatchParams', 'CreateResourceWatchResult', 'FetchTurnsParams', 'FetchTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', - 'McpServerAuthenticateTarget', + 'McpServerAuthenticateTarget', 'ModelSourceAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', 'CreateTerminalParams', 'DisposeTerminalParams', 'ResolveSessionConfigParams', 'ResolveSessionConfigResult', @@ -1874,6 +1894,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { discriminantField: 'kind', variants: [ { caseName: 'McpServer', structName: 'McpServerAuthenticateTarget', discriminantValue: 'mcpServer' }, + { caseName: 'ModelSource', structName: 'ModelSourceAuthenticateTarget', discriminantValue: 'modelSource' }, ], injectDiscriminantOnSerialize: true, }; @@ -2512,6 +2533,7 @@ function checkExhaustiveness(project: Project): void { 'Customization', // CUSTOMIZATION_UNION discriminated union 'ChildCustomization', // CHILD_CUSTOMIZATION_UNION discriminated union 'McpServerState', // MCP_SERVER_STATUS_UNION discriminated union + 'ModelSourceState', // MODEL_SOURCE_STATUS_UNION discriminated union 'ToolCallContributor', // TOOL_CALL_CONTRIBUTOR_UNION discriminated union 'ToolCallRiskAssessment', // TOOL_CALL_RISK_ASSESSMENT_UNION discriminated union 'TerminalLifecycleState', // TERMINAL_LIFECYCLE_STATE_UNION discriminated union diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 470852ae0..f2ad9a405 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -854,6 +854,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -879,6 +880,13 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, + { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceRegistration' }, + { name: 'ModelSourceStartingState', omitDiscriminants: true }, + { name: 'ModelSourceReadyState', omitDiscriminants: true }, + { name: 'ModelSourceAuthRequirement' }, + { name: 'ModelSourceAuthRequiredState', omitDiscriminants: true }, + { name: 'ModelSourceErrorState', omitDiscriminants: true }, { name: 'ModelSourceInfo' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, @@ -1236,6 +1244,19 @@ const MCP_SERVER_STATUS_UNION: UnionConfig = { unknown: true, }; +const MODEL_SOURCE_STATUS_UNION: UnionConfig = { + name: 'ModelSourceState', + discriminantField: 'kind', + doc: 'Discriminated lifecycle status of a registered model source.', + variants: [ + { variantName: 'Starting', innerType: 'ModelSourceStartingState', wireValue: 'starting' }, + { variantName: 'Ready', innerType: 'ModelSourceReadyState', wireValue: 'ready' }, + { variantName: 'AuthRequired', innerType: 'ModelSourceAuthRequiredState', wireValue: 'authRequired', boxed: true }, + { variantName: 'Error', innerType: 'ModelSourceErrorState', wireValue: 'error' }, + ], + unknown: true, +}; + const TOOL_CALL_CONTRIBUTOR_UNION: UnionConfig = { name: 'ToolCallContributor', discriminantField: 'kind', @@ -1490,6 +1511,8 @@ pub enum ToolInput { function generateStateFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; + lines.push('use crate::notifications::AuthRequiredReason;'); + lines.push(''); lines.push('// ─── Enums ────────────────────────────────────────────────────────────\n'); for (const enumName of STATE_ENUMS) { @@ -1588,6 +1611,8 @@ where D: serde::Deserializer<'de>, lines.push(''); lines.push(generateDiscriminatedUnion(project, MCP_SERVER_STATUS_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, MODEL_SOURCE_STATUS_UNION)); + lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_CONTRIBUTOR_UNION)); lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_RISK_ASSESSMENT_UNION)); @@ -1628,6 +1653,8 @@ const ACTION_VARIANTS: { { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, + { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, { type: 'session/chatAdded', variantName: 'SessionChatAdded', tsInterface: 'SessionChatAddedAction' }, @@ -1810,7 +1837,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSourceRegistration, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); @@ -1956,6 +1983,7 @@ const COMMAND_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: s { name: 'FetchTurnsParams' }, { name: 'FetchTurnsResult' }, { name: 'UnsubscribeParams' }, { name: 'DispatchActionParams' }, { name: 'McpServerAuthenticateTarget', omitDiscriminants: true }, + { name: 'ModelSourceAuthenticateTarget', omitDiscriminants: true }, { name: 'AuthenticateParams' }, { name: 'AuthenticateResult' }, { name: 'CreateTerminalParams' }, { name: 'DisposeTerminalParams' }, { name: 'ResolveSessionConfigParams' }, { name: 'ResolveSessionConfigResult' }, @@ -1975,6 +2003,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { doc: 'AuthenticateTarget identifies the consumer of an authentication token.', variants: [ { variantName: 'McpServer', innerType: 'McpServerAuthenticateTarget', wireValue: 'mcpServer' }, + { variantName: 'ModelSource', innerType: 'ModelSourceAuthenticateTarget', wireValue: 'modelSource' }, ], }; @@ -2548,6 +2577,7 @@ function checkExhaustiveness(project: Project): void { 'ChildCustomizationType', // TS subset alias of CustomizationType; Rust consumers reuse CustomizationType 'CustomizationLoadState', // CUSTOMIZATION_LOAD_STATE_UNION discriminated union 'McpServerState', // MCP_SERVER_STATUS_UNION discriminated union + 'ModelSourceState', // MODEL_SOURCE_STATUS_UNION discriminated union 'ToolCallContributor', // TOOL_CALL_CONTRIBUTOR_UNION discriminated union 'ToolCallRiskAssessment', // TOOL_CALL_RISK_ASSESSMENT_UNION discriminated union 'TerminalLifecycleState', // TERMINAL_LIFECYCLE_STATE_UNION discriminated union diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 5f20d701d..77eaa9809 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -735,6 +735,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -751,6 +752,9 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', + 'ModelSourceRegistrationCapability', 'ModelSourceRegistration', 'ModelSourceStartingState', + 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', + 'ModelSourceErrorState', 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', 'BackgroundShellWork', 'BackgroundSubagentWork', @@ -1000,6 +1004,17 @@ const MCP_SERVER_STATUS_UNION: UnionConfig = { ], }; +const MODEL_SOURCE_STATUS_UNION: UnionConfig = { + name: 'ModelSourceState', + discriminantField: 'kind', + variants: [ + { caseName: 'starting', structName: 'ModelSourceStartingState', discriminantValue: 'starting' }, + { caseName: 'ready', structName: 'ModelSourceReadyState', discriminantValue: 'ready' }, + { caseName: 'authRequired', structName: 'ModelSourceAuthRequiredState', discriminantValue: 'authRequired' }, + { caseName: 'error', structName: 'ModelSourceErrorState', discriminantValue: 'error' }, + ], +}; + const TOOL_CALL_CONTRIBUTOR_UNION: UnionConfig = { name: 'ToolCallContributor', discriminantField: 'kind', @@ -1432,6 +1447,8 @@ function generateStateFile(project: Project): string { lines.push(''); lines.push(generateDiscriminatedUnion(project, MCP_SERVER_STATUS_UNION)); lines.push(''); + lines.push(generateDiscriminatedUnion(project, MODEL_SOURCE_STATUS_UNION)); + lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_CONTRIBUTOR_UNION)); lines.push(''); lines.push(generateDiscriminatedUnion(project, TOOL_CALL_RISK_ASSESSMENT_UNION)); @@ -1552,6 +1569,8 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'annotations/entryRemoved', caseName: 'annotationsEntryRemoved', tsInterface: 'AnnotationsEntryRemovedAction' }, { type: 'root/terminalsChanged', caseName: 'rootTerminalsChanged', tsInterface: 'RootTerminalsChangedAction' }, { type: 'root/configChanged', caseName: 'rootConfigChanged', tsInterface: 'RootConfigChangedAction' }, + { type: 'root/modelSourceRegistrationSet', caseName: 'rootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceRegistrationRemoved', caseName: 'rootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'terminal/data', caseName: 'terminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'terminalInput', tsInterface: 'TerminalInputAction' }, { type: 'terminal/resized', caseName: 'terminalResized', tsInterface: 'TerminalResizedAction' }, @@ -1801,7 +1820,7 @@ const COMMAND_STRUCTS = [ 'CreateResourceWatchParams', 'CreateResourceWatchResult', 'FetchTurnsParams', 'FetchTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', - 'McpServerAuthenticateTarget', + 'McpServerAuthenticateTarget', 'ModelSourceAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', 'CreateTerminalParams', 'DisposeTerminalParams', 'ResolveSessionConfigParams', 'ResolveSessionConfigResult', @@ -1821,6 +1840,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { discriminantField: 'kind', variants: [ { caseName: 'mcpServer', structName: 'McpServerAuthenticateTarget', discriminantValue: 'mcpServer' }, + { caseName: 'modelSource', structName: 'ModelSourceAuthenticateTarget', discriminantValue: 'modelSource' }, ], injectDiscriminantOnEncode: true, }; @@ -2627,6 +2647,7 @@ function checkExhaustiveness(project: Project): void { 'ChildCustomizationType', // TS subset alias of CustomizationType; consumers reuse the CustomizationType Swift enum 'CustomizationLoadState', // CUSTOMIZATION_LOAD_STATE_UNION discriminated union 'McpServerState', // MCP_SERVER_STATUS_UNION discriminated union + 'ModelSourceState', // MODEL_SOURCE_STATUS_UNION discriminated union 'ToolCallContributor', // TOOL_CALL_CONTRIBUTOR_UNION discriminated union 'ToolCallRiskAssessment', // TOOL_CALL_RISK_ASSESSMENT_UNION discriminated union 'TerminalLifecycleState', // TERMINAL_LIFECYCLE_STATE_UNION discriminated union diff --git a/scripts/read-stability.test.ts b/scripts/read-stability.test.ts index 24958e417..72eb0554a 100644 --- a/scripts/read-stability.test.ts +++ b/scripts/read-stability.test.ts @@ -113,7 +113,7 @@ test('native client docs preserve declaration and entrypoint stability', () => { ['clients/dotnet/src/AgentHostProtocol.Abstractions/Generated', 'Commands.generated.cs', 'Notifications.generated.cs'], ]; for (const [directory, commands, notifications] of clients) { - for (const [file, expected] of [[commands, 15], [notifications, 6]] as const) { + for (const [file, expected] of [[commands, 16], [notifications, 6]] as const) { const content = readFileSync(resolve(root, directory, file), 'utf8'); assert.equal(content.split(marker).length - 1, expected, `${directory}/${file}`); } diff --git a/types/action-origin.generated.ts b/types/action-origin.generated.ts index f3f6281d7..91c83192c 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -7,6 +7,8 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, + RootModelSourceRegistrationSetAction, + RootModelSourceRegistrationRemovedAction, SessionReadyAction, SessionCreationFailedAction, SessionChatAddedAction, @@ -123,11 +125,15 @@ export type RootAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction + | RootModelSourceRegistrationSetAction + | RootModelSourceRegistrationRemovedAction ; /** Union of root actions that clients may dispatch. */ export type ClientRootAction = | RootConfigChangedAction + | RootModelSourceRegistrationSetAction + | RootModelSourceRegistrationRemovedAction ; /** Union of root actions that only the server may produce. */ @@ -467,6 +473,8 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.RootActiveSessionsChanged]: false, [ActionType.RootTerminalsChanged]: false, [ActionType.RootConfigChanged]: true, + [ActionType.RootModelSourceRegistrationSet]: true, + [ActionType.RootModelSourceRegistrationRemoved]: true, [ActionType.SessionReady]: false, [ActionType.SessionCreationFailed]: false, [ActionType.SessionChatAdded]: false, diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 8fa3505e3..619b47f69 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -4,7 +4,7 @@ * @module channels-root/actions */ -import type { AgentInfo } from './state.js'; +import type { AgentInfo, ModelSourceRegistration } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import { ActionType } from '../common/actions.js'; @@ -66,3 +66,36 @@ export interface RootConfigChangedAction { /** When `true`, replaces all config values instead of merging */ replace?: boolean; } + +/** + * Adds a model source registration, or replaces the one with the same `id`. + * + * A client registers a source by dispatching this with its own `clientId` and + * no `state`. The host reports status by dispatching it again with the same + * registration and a `state`. + * + * @category Root Actions + * @stability 1.0 + * @clientDispatchable + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ +export interface RootModelSourceRegistrationSetAction { + type: ActionType.RootModelSourceRegistrationSet; + /** The registration to add or replace, matched by `id`. */ + registration: ModelSourceRegistration; +} + +/** + * Removes the model source registration with the given `id`. A no-op when + * none matches. + * + * @category Root Actions + * @stability 1.0 + * @clientDispatchable + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ +export interface RootModelSourceRegistrationRemovedAction { + type: ActionType.RootModelSourceRegistrationRemoved; + /** The registration's `id`. */ + id: string; +} diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index e1e7b6665..5ac2d62ca 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -35,6 +35,32 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st }, }; + case ActionType.RootModelSourceRegistrationSet: { + const list = state.modelSourceRegistrations ?? []; + const idx = list.findIndex(r => r.id === action.registration.id); + const next = list.slice(); + if (idx < 0) { + next.push(action.registration); + } else { + next[idx] = action.registration; + } + return { ...state, modelSourceRegistrations: next }; + } + + case ActionType.RootModelSourceRegistrationRemoved: { + const list = state.modelSourceRegistrations; + if (!list) { + return state; + } + const idx = list.findIndex(r => r.id === action.id); + if (idx < 0) { + return state; + } + const next = list.slice(); + next.splice(idx, 1); + return { ...state, modelSourceRegistrations: next }; + } + default: softAssertNever(action, log); return state; diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 316b7ca24..215cdd740 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -8,9 +8,12 @@ import type { ConfigSchema, + ErrorInfo, + Icon, JsonPrimitive, ProtectedResourceMetadata, } from '../common/state.js'; +import type { AuthRequiredReason } from '../common/notifications.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import type { Customization } from '../channels-session/state.js'; @@ -42,6 +45,13 @@ export interface RootState { terminals?: TerminalInfo[]; /** Agent host configuration schema and current values */ config?: RootConfigState; + /** + * Model sources registered on this host, keyed by `id`. + * + * @stability 1.0 + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ + modelSourceRegistrations?: ModelSourceRegistration[]; /** * Additional implementation-defined metadata about the agent host itself. * @@ -133,6 +143,14 @@ export interface AgentCapabilities { * {@link CreateSessionParams.workingDirectories}. */ multipleWorkingDirectories?: MultipleWorkingDirectoriesCapability; + /** + * The agent serves models from registered model sources, in the listed + * definition formats. + * + * @stability 1.0 + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ + modelSourceRegistration?: ModelSourceRegistrationCapability; } /** @@ -209,7 +227,11 @@ export interface MultipleWorkingDirectoriesCapability { * @category Root State */ export interface ModelSourceInfo { - /** Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. */ + /** + * Model source identifier, unique within the agent's + * {@link AgentInfo.modelSources}. For a registered model source, this is + * the {@link ModelSourceRegistration.id}. + */ id: string; /** Human-readable name */ displayName: string; @@ -222,7 +244,10 @@ export interface SessionModelInfo { /** * Model identifier, unique within the agent's {@link AgentInfo.models}. * When several model sources serve the same upstream model, the host gives - * each entry its own ID. + * each entry its own ID. An ID the host publishes for a registered model + * source stays bound to that registration and upstream model. + * + * @see {@link /specification/root-channel#reserved-model-ids | Reserved model IDs} */ id: string; /** Agent provider that owns this model. Matches {@link AgentInfo.provider}. */ @@ -288,6 +313,208 @@ export interface ModelSelection { config?: Record; } +// ─── Model Source Registry ─────────────────────────────────────────────────── + +/** + * Options for the {@link AgentCapabilities.modelSourceRegistration} capability. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface ModelSourceRegistrationCapability { + /** + * Definition formats the agent reads, most preferred first. Format names + * are defined by agent implementations and SHOULD be namespaced, for + * example `example.com/model-source@1`. + */ + formats: string[]; +} + +/** + * A model source registered on this host by a client, or by the host itself. + * Its definition is in a format the agent named by `provider` reads. It never + * contains a credential. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ +export interface ModelSourceRegistration { + /** + * Host-unique ID, chosen by whoever registers the source. Also the + * source's {@link ModelSourceInfo.id} in the agent's catalog, and the + * {@link SessionModelInfo.modelSourceId} of its models. + */ + id: string; + /** Agent provider whose agent reads the definition and serves the models. */ + provider: string; + /** Display name, published as {@link ModelSourceInfo.displayName}. */ + name: string; + /** Icons for UI display. */ + icons?: Icon[]; + /** + * Definition format, one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. + */ + format: string; + /** + * How to reach the source: endpoint, wire format, models, and so on, in + * `format`. Its shape belongs to the agent that reads it. MUST NOT contain + * a credential. + */ + definition: Record; + /** The contributing client. Absent for a source the host registered itself. */ + clientId?: string; + /** Who may select the source's models. Absent means `contributingClient`. */ + sharing?: ModelSourceSharingPolicy; + /** What happens when the contributing client leaves. Absent means `contributingClient`. */ + retention?: ModelSourceRetentionPolicy; + /** Host-reported status. Absent means the host hasn't reported one yet. */ + state?: ModelSourceState; + /** + * Additional implementation-defined metadata for this registration. + * MUST NOT contain a credential. + */ + _meta?: Record; +} + +/** + * Who may select a registered model source's models. + * + * @category Root State + * @stability 1.0 + * @nonexhaustive + */ +export const enum ModelSourceSharingPolicy { + /** Only turns and pending messages the contributing client dispatches. */ + ContributingClient = 'contributingClient', + /** Any client, and work the host starts itself, such as automations. */ + Host = 'host', +} + +/** + * How long a registered model source lasts once its contributing client leaves. + * + * @category Root State + * @stability 1.0 + * @nonexhaustive + */ +export const enum ModelSourceRetentionPolicy { + /** Removed when the contributing client leaves, once running turns finish. */ + ContributingClient = 'contributingClient', + /** Kept until a client removes it or host policy expires it. */ + Host = 'host', +} + +/** + * Discriminant for the {@link ModelSourceState} union. + * + * @category Root State + * @stability 1.0 + * @nonexhaustive + */ +export const enum ModelSourceStatus { + /** The agent is reading and validating the definition. */ + Starting = 'starting', + /** The source is usable, and its models are in the agent's catalog. */ + Ready = 'ready', + /** The source needs a credential before it can be used. */ + AuthRequired = 'authRequired', + /** The source failed, or the host declined it. */ + Error = 'error', +} + +/** + * The agent is reading and validating the definition, or listing the + * source's models again after a credential change. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface ModelSourceStartingState { + kind: ModelSourceStatus.Starting; +} + +/** + * The source is usable, and its models are in the catalog of the agent named + * by the registration's `provider`. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface ModelSourceReadyState { + kind: ModelSourceStatus.Ready; +} + +/** + * What a model source needs in order to become ready. Deliberately carries no + * credential. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface ModelSourceAuthRequirement { + /** Why a credential is needed. */ + reason: AuthRequiredReason; + /** + * RFC 9728 metadata for the source's endpoint. `resource.resource` is the + * endpoint URL as the definition names it, in any scheme the agent + * supports (for example `http://localhost:11434/v1`). It's the value a + * client passes back as `authenticate({ resource })`, and nothing fetches + * it. `resource.resource_name` labels the prompt (for example + * "OpenRouter API key"). A source that accepts OAuth access tokens + * advertises `authorization_servers` and `scopes_supported`. A source that + * takes a user-supplied secret omits them. + */ + resource: ProtectedResourceMetadata; + /** Human-readable hint, for example the endpoint's error description. */ + description?: string; +} + +/** + * The source needs a credential before it can be used. A client answers with + * `authenticate` and a {@link ModelSourceAuthenticateTarget}. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ +export interface ModelSourceAuthRequiredState extends ModelSourceAuthRequirement { + kind: ModelSourceStatus.AuthRequired; +} + +/** + * The source failed, or the host declined it, for example by policy. + * + * @category Root State + * @stability 1.0 + * @preserveUnknownMembers + */ +export interface ModelSourceErrorState { + kind: ModelSourceStatus.Error; + /** Error details. MUST NOT contain the credential. */ + error: ErrorInfo; +} + +/** + * Lifecycle state of a {@link ModelSourceRegistration}, discriminated by + * `kind` (a {@link ModelSourceStatus} value). + * + * @category Root State + * @stability 1.0 + */ +export type ModelSourceState = + | ModelSourceStartingState + | ModelSourceReadyState + | ModelSourceAuthRequiredState + | ModelSourceErrorState; + // ─── Root Config Types ─────────────────────────────────────────────────────── /** diff --git a/types/common/actions.ts b/types/common/actions.ts index 55125bf9e..3cd9b0fa5 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -13,6 +13,8 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, + RootModelSourceRegistrationSetAction, + RootModelSourceRegistrationRemovedAction, } from '../channels-root/actions.js'; import type { @@ -240,6 +242,8 @@ export const enum ActionType { AnnotationsEntryRemoved = 'annotations/entryRemoved', RootTerminalsChanged = 'root/terminalsChanged', RootConfigChanged = 'root/configChanged', + RootModelSourceRegistrationSet = 'root/modelSourceRegistrationSet', + RootModelSourceRegistrationRemoved = 'root/modelSourceRegistrationRemoved', TerminalData = 'terminal/data', TerminalInput = 'terminal/input', TerminalResized = 'terminal/resized', @@ -301,6 +305,8 @@ export type StateAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction + | RootModelSourceRegistrationSetAction + | RootModelSourceRegistrationRemovedAction | SessionReadyAction | SessionCreationFailedAction | SessionChatAddedAction diff --git a/types/common/commands.ts b/types/common/commands.ts index 90ffe9d6d..86ea5e2fe 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1446,6 +1446,12 @@ export interface ResourceMkdirResult { */ export const enum AuthenticateTargetKind { McpServer = 'mcpServer', + /** + * A {@link ModelSourceAuthenticateTarget}. + * + * @stability 1.0 + */ + ModelSource = 'modelSource', } /** @@ -1465,28 +1471,45 @@ export interface McpServerAuthenticateTarget { customizationId: string; } +/** + * A registered model source. + * + * @category Commands + * @stability 1.0 + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ +export interface ModelSourceAuthenticateTarget { + kind: AuthenticateTargetKind.ModelSource; + /** The registration's `ModelSourceRegistration.id`. */ + modelSourceId: string; +} + /** * Consumer of an authentication token, discriminated by `kind`. * Extensible to support additional consumers, such as host-owned authentication. * * @category Commands */ -export type AuthenticateTarget = McpServerAuthenticateTarget; +export type AuthenticateTarget = + | McpServerAuthenticateTarget + | ModelSourceAuthenticateTarget; /** - * Pushes a Bearer token for a protected resource. The `resource` field MUST + * Pushes a credential for a protected resource. The `resource` field MUST * match a protected-resource identifier the client has discovered from the * server — whether declared statically in `AgentInfo.protectedResources`, - * or discovered dynamically from a live `McpServerAuthRequiredState.resource` - * or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the - * corresponding MCP server or tool call actually challenges for auth). - * Servers MUST accept any `resource` value they have themselves advertised - * through one of these three mechanisms. + * or discovered dynamically from a live `McpServerAuthRequiredState.resource`, + * `ToolCallAuthRequiredState.auth.resource`, or + * `ModelSourceAuthRequiredState.resource` (each surfaced only once the + * corresponding MCP server, tool call, or model source actually challenges + * for auth). Servers MUST accept any `resource` value they have themselves + * advertised through one of these mechanisms. * * Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) * (Bearer Token Usage) semantics. The client obtains the token from the * authorization server(s) listed in the resource's metadata and pushes it - * to the server via this command. + * to the server via this command. A model source's token is instead an + * opaque secret, such as an API key. * * @category Commands * @method authenticate @@ -1514,10 +1537,14 @@ export interface AuthenticateParams extends BaseParams { * The protected resource identifier. MUST match a `resource` value the * server has advertised — via `ProtectedResourceMetadata` in * `AgentInfo.protectedResources`, or via a live - * `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`. + * `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, + * or `ModelSourceAuthRequiredState.resource`. */ resource: string; - /** Bearer token obtained from the resource's authorization server */ + /** + * Bearer token obtained from the resource's authorization server, or an + * opaque secret for a model source. An empty string revokes the credential. + */ token: string; /** * The access token's remaining lifetime, in seconds, when this @@ -1529,6 +1556,8 @@ export interface AuthenticateParams extends BaseParams { * authorization server did not supply an expiry or the expiry is otherwise * unknown. When supplied, the value MUST be a positive integer. * + * An API key omits this field. + * * This field is irrelevant when `token` is empty to revoke authentication * and SHOULD be omitted in that case. * @@ -1542,21 +1571,28 @@ export interface AuthenticateParams extends BaseParams { * `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is * satisfied without decoding the (opaque, server-specific) token itself. * Omit when the client doesn't track granted scopes separately from the - * token. + * token. Scopes apply to OAuth-issued tokens only. */ scopes?: string[]; /** * Optional consumer of the token. Clients SHOULD include this when answering * a specific MCP server's `McpServerAuthRequiredState` or - * `ToolCallAuthRequiredState` challenge, and omit it for provider-level + * `ToolCallAuthRequiredState` challenge, MUST include it when delivering a + * registered model source's credential, and omit it for provider-level * resources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data). * - * When present, the host MUST apply the token only to that MCP server in - * that session, never to sibling servers, other sessions, or agent-level - * resources, even if they share the resource and scopes. `resource` MUST - * still equal that server's advertised `McpAuthRequirement.resource.resource`. - * The host MUST reject an unknown session or customization, or a - * customization that is not an MCP server, with `InvalidParams` (-32602). + * For an `mcpServer` target, the host MUST apply the token only to that MCP + * server in that session, never to sibling servers, other sessions, or + * agent-level resources, even if they share the resource and scopes. + * `resource` MUST still equal that server's advertised + * `McpAuthRequirement.resource.resource`. The host MUST reject an unknown + * session or customization, or a customization that is not an MCP server, + * with `InvalidParams` (-32602). + * + * A registered model source takes its credential only through a + * `modelSource` target. See + * [Model source credentials](/specification/authentication#model-source-credentials) + * for its rules. * * Without a target, resource/scope matching is unchanged; the token may * satisfy every matching pending challenge. Older hosts ignore this field. diff --git a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json new file mode 100644 index 000000000..0776c9a10 --- /dev/null +++ b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json @@ -0,0 +1,43 @@ +{ + "description": "root/modelSourceRegistrationSet creates the registry when it is absent", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + ] + } +} diff --git a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json new file mode 100644 index 000000000..9a8e76a7c --- /dev/null +++ b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json @@ -0,0 +1,71 @@ +{ + "description": "root/modelSourceRegistrationSet appends a registration with a new id", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1" + } + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1" + } + ] + } +} diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json new file mode 100644 index 000000000..0365811fb --- /dev/null +++ b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json @@ -0,0 +1,90 @@ +{ + "description": "root/modelSourceRegistrationSet replaces the registration with the same id in place, as when the host reports its state", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1", + "state": { + "kind": "ready" + } + } + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1", + "state": { + "kind": "ready" + } + }, + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1" + } + ] + } +} diff --git a/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json b/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json new file mode 100644 index 000000000..5fbc57739 --- /dev/null +++ b/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json @@ -0,0 +1,59 @@ +{ + "description": "root/modelSourceRegistrationRemoved removes the registration with the given id", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationRemoved", + "id": "model-source-a" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1" + } + ] + } +} diff --git a/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json new file mode 100644 index 000000000..e5d1f86c0 --- /dev/null +++ b/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json @@ -0,0 +1,46 @@ +{ + "description": "root/modelSourceRegistrationRemoved is a no-op when no registration has the id", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationRemoved", + "id": "model-source-missing" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + ] + } +} diff --git a/types/test-cases/reducers/335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json new file mode 100644 index 000000000..7e1273658 --- /dev/null +++ b/types/test-cases/reducers/335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json @@ -0,0 +1,16 @@ +{ + "description": "root/modelSourceRegistrationRemoved is a no-op when the registry is absent", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationRemoved", + "id": "model-source-a" + } + ], + "expected": { + "agents": [] + } +} diff --git a/types/test-cases/round-trips/102-model-source-registry-snapshot.json b/types/test-cases/round-trips/102-model-source-registry-snapshot.json new file mode 100644 index 000000000..dc5fb541c --- /dev/null +++ b/types/test-cases/round-trips/102-model-source-registry-snapshot.json @@ -0,0 +1,354 @@ +{ + "name": "model-source-registry-snapshot", + "group": "A", + "description": "A root snapshot carries model source registrations with no reported state and in each lifecycle state, including an http endpoint and a host-registered source without clientId. The agent advertises the modelSourceRegistration capability, and the ready registration appears in its catalog.", + "type": "Snapshot", + "input": { + "resource": "ahp-root://", + "fromSeq": 4, + "state": { + "agents": [ + { + "provider": "example", + "displayName": "Example", + "description": "Serves registered model sources", + "capabilities": { + "modelSourceRegistration": { + "formats": [ + "example.com/model-source@1", + "example.com/model-source@0" + ] + } + }, + "modelSources": [ + { + "id": "source-ready", + "displayName": "OpenRouter" + } + ], + "models": [ + { + "id": "source-ready.8f3a", + "provider": "example", + "name": "Example model", + "vendor": "OpenRouter", + "modelSourceId": "source-ready" + } + ] + } + ], + "modelSourceRegistrations": [ + { + "id": "source-unreported", + "provider": "example", + "name": "Unreported", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1" + }, + { + "id": "source-starting", + "provider": "example", + "name": "Starting", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1", + "state": { + "kind": "starting" + } + }, + { + "id": "source-ready", + "provider": "example", + "name": "OpenRouter", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "sharing": "host", + "retention": "host", + "state": { + "kind": "ready" + }, + "_meta": { + "example.com/label": "Laptop" + } + }, + { + "id": "source-auth", + "provider": "example", + "name": "Azure endpoint", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1", + "sharing": "contributingClient", + "retention": "contributingClient", + "state": { + "kind": "authRequired", + "reason": "expired", + "resource": { + "resource": "https://example.openai.azure.com", + "resource_name": "Azure OpenAI", + "authorization_servers": [ + "https://login.microsoftonline.com/common/v2.0" + ], + "scopes_supported": [ + "https://cognitiveservices.azure.com/.default" + ] + }, + "description": "The access token expired." + } + }, + { + "id": "source-local", + "provider": "example", + "name": "Local server", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "http://localhost:11434/v1" + }, + "clientId": "client-1", + "state": { + "kind": "authRequired", + "reason": "required", + "resource": { + "resource": "http://localhost:11434/v1", + "resource_name": "Local server key" + } + } + }, + { + "id": "source-host", + "provider": "example", + "name": "Host-configured", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://models.internal.example/v1" + }, + "state": { + "kind": "error", + "error": { + "errorType": "policy", + "message": "The endpoint is not allowed by host policy." + } + } + } + ] + } + }, + "acceptableOutputs": [ + { + "resource": "ahp-root://", + "fromSeq": 4, + "state": { + "agents": [ + { + "provider": "example", + "displayName": "Example", + "description": "Serves registered model sources", + "capabilities": { + "modelSourceRegistration": { + "formats": [ + "example.com/model-source@1", + "example.com/model-source@0" + ] + } + }, + "modelSources": [ + { + "id": "source-ready", + "displayName": "OpenRouter" + } + ], + "models": [ + { + "id": "source-ready.8f3a", + "provider": "example", + "name": "Example model", + "vendor": "OpenRouter", + "modelSourceId": "source-ready" + } + ] + } + ], + "modelSourceRegistrations": [ + { + "id": "source-unreported", + "provider": "example", + "name": "Unreported", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1" + }, + { + "id": "source-starting", + "provider": "example", + "name": "Starting", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1", + "state": { + "kind": "starting" + } + }, + { + "id": "source-ready", + "provider": "example", + "name": "OpenRouter", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "sharing": "host", + "retention": "host", + "state": { + "kind": "ready" + }, + "_meta": { + "example.com/label": "Laptop" + } + }, + { + "id": "source-auth", + "provider": "example", + "name": "Azure endpoint", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "clientId": "client-1", + "sharing": "contributingClient", + "retention": "contributingClient", + "state": { + "kind": "authRequired", + "reason": "expired", + "resource": { + "resource": "https://example.openai.azure.com", + "resource_name": "Azure OpenAI", + "authorization_servers": [ + "https://login.microsoftonline.com/common/v2.0" + ], + "scopes_supported": [ + "https://cognitiveservices.azure.com/.default" + ] + }, + "description": "The access token expired." + } + }, + { + "id": "source-local", + "provider": "example", + "name": "Local server", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "http://localhost:11434/v1" + }, + "clientId": "client-1", + "state": { + "kind": "authRequired", + "reason": "required", + "resource": { + "resource": "http://localhost:11434/v1", + "resource_name": "Local server key" + } + } + }, + { + "id": "source-host", + "provider": "example", + "name": "Host-configured", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://models.internal.example/v1" + }, + "state": { + "kind": "error", + "error": { + "errorType": "policy", + "message": "The endpoint is not allowed by host policy." + } + } + } + ] + } + } + ] +} diff --git a/types/test-cases/round-trips/103-root-model-source-registration-set.json b/types/test-cases/round-trips/103-root-model-source-registration-set.json new file mode 100644 index 000000000..b3f2af90a --- /dev/null +++ b/types/test-cases/round-trips/103-root-model-source-registration-set.json @@ -0,0 +1,52 @@ +{ + "name": "root-model-source-registration-set", + "group": "A", + "description": "A client registers a model source with root/modelSourceRegistrationSet: its own clientId, requested sharing and retention, an open definition, and no state.", + "type": "StateAction", + "input": { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "source-new", + "provider": "example", + "name": "OpenRouter", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://openrouter.ai/api/v1", + "models": [ + "vendor/model-a", + "vendor/model-b" + ], + "headers": { + "x-title": "Example" + } + }, + "clientId": "client-1", + "sharing": "host", + "retention": "host" + } + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "source-new", + "provider": "example", + "name": "OpenRouter", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://openrouter.ai/api/v1", + "models": [ + "vendor/model-a", + "vendor/model-b" + ], + "headers": { + "x-title": "Example" + } + }, + "clientId": "client-1", + "sharing": "host", + "retention": "host" + } + } + ] +} diff --git a/types/test-cases/round-trips/104-root-model-source-registration-removed.json b/types/test-cases/round-trips/104-root-model-source-registration-removed.json new file mode 100644 index 000000000..0d6aa7316 --- /dev/null +++ b/types/test-cases/round-trips/104-root-model-source-registration-removed.json @@ -0,0 +1,16 @@ +{ + "name": "root-model-source-registration-removed", + "group": "A", + "description": "A client removes a model source registration by id with root/modelSourceRegistrationRemoved.", + "type": "StateAction", + "input": { + "type": "root/modelSourceRegistrationRemoved", + "id": "source-new" + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceRegistrationRemoved", + "id": "source-new" + } + ] +} diff --git a/types/test-cases/round-trips/105-authenticate-model-source-target.json b/types/test-cases/round-trips/105-authenticate-model-source-target.json new file mode 100644 index 000000000..edb08e35f --- /dev/null +++ b/types/test-cases/round-trips/105-authenticate-model-source-target.json @@ -0,0 +1,26 @@ +{ + "name": "authenticate-model-source-target", + "group": "A", + "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target. An API key carries no expiresIn or scopes.", + "type": "AuthenticateParams", + "input": { + "channel": "ahp-root://", + "resource": "https://openrouter.ai/api/v1", + "token": "test-api-key", + "target": { + "kind": "modelSource", + "modelSourceId": "source-new" + } + }, + "acceptableOutputs": [ + { + "channel": "ahp-root://", + "resource": "https://openrouter.ai/api/v1", + "token": "test-api-key", + "target": { + "kind": "modelSource", + "modelSourceId": "source-new" + } + } + ] +} diff --git a/types/version/registry.ts b/types/version/registry.ts index 826476201..8a2c118ee 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -186,6 +186,8 @@ export const ACTION_INTRODUCED_IN: { readonly [K in StateAction['type']]: string [ActionType.AnnotationsEntryRemoved]: '0.4.0', [ActionType.RootTerminalsChanged]: '0.1.0', [ActionType.RootConfigChanged]: '0.1.0', + [ActionType.RootModelSourceRegistrationSet]: '1.2.0', + [ActionType.RootModelSourceRegistrationRemoved]: '1.2.0', [ActionType.TerminalData]: '0.1.0', [ActionType.TerminalInput]: '0.1.0', [ActionType.TerminalResized]: '0.1.0', From ce8b39bf093b578c8a9bf0b5c99d6b7ea03361fa Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Mon, 23 Nov 2026 18:06:09 -0500 Subject: [PATCH 02/17] models: document registered sources on SessionModelInfo.modelSourceId Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/State.generated.cs | 3 ++- clients/go/ahptypes/state.generated.go | 3 ++- .../microsoft/agenthostprotocol/generated/State.generated.kt | 3 ++- clients/rust/crates/ahp-types/src/state.rs | 3 ++- .../Sources/AgentHostProtocol/Generated/State.generated.swift | 3 ++- schema/actions.schema.json | 2 +- schema/commands.schema.json | 2 +- schema/errors.schema.json | 2 +- schema/notifications.schema.json | 2 +- schema/state.schema.json | 2 +- types/channels-root/state.ts | 3 ++- 11 files changed, 17 insertions(+), 11 deletions(-) diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 98898a104..2168580e5 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2641,7 +2641,8 @@ public sealed record SessionModelInfo public string? Vendor { get; init; } /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} - /// in the agent's {@link AgentInfo.modelSources}. + /// in the agent's {@link AgentInfo.modelSources}. For a model from a + /// registered model source, this is the {@link ModelSourceRegistration.id}. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ModelSourceId { get; init; } } diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index e80a9d5e8..36d221775 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1204,7 +1204,8 @@ type SessionModelInfo struct { // recognize. Vendor *string `json:"vendor,omitempty"` // The source this model comes from. MUST match a {@link ModelSourceInfo.id} - // in the agent's {@link AgentInfo.modelSources}. + // in the agent's {@link AgentInfo.modelSources}. For a model from a + // registered model source, this is the {@link ModelSourceRegistration.id}. ModelSourceId *string `json:"modelSourceId,omitempty"` } 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 950bda29a..637063985 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 @@ -2107,7 +2107,8 @@ data class SessionModelInfo( val vendor: String? = null, /** * The source this model comes from. MUST match a {@link ModelSourceInfo.id} - * in the agent's {@link AgentInfo.modelSources}. + * in the agent's {@link AgentInfo.modelSources}. For a model from a + * registered model source, this is the {@link ModelSourceRegistration.id}. */ val modelSourceId: String? = null ) diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 067156268..37c8959d5 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2359,7 +2359,8 @@ pub struct SessionModelInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub vendor: Option, /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} - /// in the agent's {@link AgentInfo.modelSources}. + /// in the agent's {@link AgentInfo.modelSources}. For a model from a + /// registered model source, this is the {@link ModelSourceRegistration.id}. #[serde(default, skip_serializing_if = "Option::is_none")] pub model_source_id: Option, } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 6b8df0a9e..88cb202e6 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -2228,7 +2228,8 @@ public struct SessionModelInfo: Codable, Sendable, Equatable { /// recognize. public var vendor: String? /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} - /// in the agent's {@link AgentInfo.modelSources}. + /// in the agent's {@link AgentInfo.modelSources}. For a model from a + /// registered model source, this is the {@link ModelSourceRegistration.id}. public var modelSourceId: String? enum CodingKeys: String, CodingKey { diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 69283d4f0..f049e2d89 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -3501,7 +3501,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." } }, "required": [ diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 4ee1f0e0b..76541b5f9 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -2847,7 +2847,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." } }, "required": [ diff --git a/schema/errors.schema.json b/schema/errors.schema.json index d2cd333bd..a80d11d18 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -836,7 +836,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." } }, "required": [ diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index cadd14c02..85c48f1bd 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1138,7 +1138,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." } }, "required": [ diff --git a/schema/state.schema.json b/schema/state.schema.json index 79a92dc7d..e5bb21049 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -747,7 +747,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." } }, "required": [ diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 215cdd740..c1fe78cf7 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -289,7 +289,8 @@ export interface SessionModelInfo { vendor?: string; /** * The source this model comes from. MUST match a {@link ModelSourceInfo.id} - * in the agent's {@link AgentInfo.modelSources}. + * in the agent's {@link AgentInfo.modelSources}. For a model from a + * registered model source, this is the {@link ModelSourceRegistration.id}. */ modelSourceId?: string; } From f3a60a08ecf123931f16a457a4ad91305b3596f2 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 08:42:04 -0500 Subject: [PATCH 03/17] models: add credentialNonce and tighten registry rules - `ModelSourceRegistration.credentialNonce` and the required `ModelSourceAuthenticateTarget.credentialNonce`, so a delayed `authenticate` can't reach a changed definition. The host rejects a stale nonce with `Conflict`. - Specs follow #622: `Removed` is checked only against the stored registration, status updates are built from the current registration, revocation reports `reason: expired`, moving the endpoint mints new model IDs, clients send a stored secret only when the definition matches their copy, and the host writes status text and errors itself. - Untargeted model source credentials are rejected with `InvalidParams`, and `ProtectedResourceMetadata.resource` notes the model source scheme exception. - Renumber the registry round-trip fixtures after main's new fixture, align the Azure fixture's resource with its endpoint, and note the TypeScript `AuthenticateTarget` narrowing in the migration fragment. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Commands.generated.cs | 12 +++++-- .../Generated/State.generated.cs | 20 ++++++++--- clients/go/ahptypes/commands.generated.go | 11 ++++-- clients/go/ahptypes/state.generated.go | 20 ++++++++--- .../generated/Commands.generated.kt | 11 ++++-- .../generated/State.generated.kt | 18 ++++++++-- clients/rust/crates/ahp-types/src/commands.rs | 11 ++++-- clients/rust/crates/ahp-types/src/state.rs | 17 ++++++++-- .../Generated/Commands.generated.swift | 11 ++++-- .../Generated/State.generated.swift | 21 ++++++++++-- ...61123-model-source-registry-migration.json | 2 +- .../20261123-model-source-registry.json | 2 +- docs/specification/authentication.md | 19 +++++++---- docs/specification/root-channel.md | 27 +++++++++------ schema/actions.schema.json | 12 ++++--- schema/commands.schema.json | 23 +++++++++---- schema/errors.schema.json | 23 +++++++++---- schema/notifications.schema.json | 12 ++++--- schema/state.schema.json | 12 ++++--- types/channels-root/state.ts | 17 ++++++++-- types/common/commands.ts | 13 +++++-- types/common/state.ts | 2 ++ ...lsourceregistrationset-replaces-by-id.json | 6 ++-- ...> 103-model-source-registry-snapshot.json} | 34 ++++++++++++------- ...4-root-model-source-registration-set.json} | 0 ...ot-model-source-registration-removed.json} | 0 ...106-authenticate-model-source-target.json} | 8 +++-- 27 files changed, 271 insertions(+), 93 deletions(-) rename types/test-cases/round-trips/{102-model-source-registry-snapshot.json => 103-model-source-registry-snapshot.json} (92%) rename types/test-cases/round-trips/{103-root-model-source-registration-set.json => 104-root-model-source-registration-set.json} (100%) rename types/test-cases/round-trips/{104-root-model-source-registration-removed.json => 105-root-model-source-registration-removed.json} (100%) rename types/test-cases/round-trips/{105-authenticate-model-source-target.json => 106-authenticate-model-source-target.json} (63%) diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 2be9d7ec9..6de930c93 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1894,6 +1894,11 @@ public sealed record ModelSourceAuthenticateTarget /// The registration's `ModelSourceRegistration.id`. public required string ModelSourceId { get; init; } + + /// The registration's current `ModelSourceRegistration.credentialNonce`, as + /// published in root state. The host rejects a stale one with `Conflict` + /// (-32011). + public required string CredentialNonce { get; init; } } /// Pushes a credential for a protected resource. The `resource` field MUST @@ -1904,7 +1909,9 @@ public sealed record ModelSourceAuthenticateTarget /// `ModelSourceAuthRequiredState.resource` (each surfaced only once the /// corresponding MCP server, tool call, or model source actually challenges /// for auth). Servers MUST accept any `resource` value they have themselves -/// advertised through one of these mechanisms. +/// advertised through one of these mechanisms, subject to the `target` +/// rules. A `modelSource` target takes only the resource the host most +/// recently advertised for that registration. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the @@ -1972,7 +1979,8 @@ public sealed record AuthenticateParams /// with `InvalidParams` (-32602). /// /// A registered model source takes its credential only through a - /// `modelSource` target. See + /// `modelSource` target, and the host rejects an untargeted `resource` that + /// matches only model source challenges with `InvalidParams` (-32602). See /// [Model source credentials](/specification/authentication#model-source-credentials) /// for its rules. /// diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 2168580e5..092c2c466 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2143,7 +2143,9 @@ public sealed record Icon public sealed record ProtectedResourceMetadata { /// REQUIRED. The protected resource's resource identifier, a URL using the - /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + /// A registered model source's endpoint may use any scheme the agent + /// supports, because nothing fetches it. public required string Resource { get; init; } /// OPTIONAL. Human-readable name of the protected resource. @@ -2459,6 +2461,14 @@ public sealed record ModelSourceRegistration [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceState? State { get; init; } + /// Host-issued token that a client echoes in + /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers + /// the credential. The host changes it whenever it drops the credential + /// because the registration changed, and never reuses one for the same + /// `id`. Absent until the host reports a `state`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? CredentialNonce { get; init; } + /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. [JsonPropertyName("_meta")] @@ -2515,7 +2525,8 @@ public sealed record ModelSourceAuthRequirement /// takes a user-supplied secret omits them. public required ProtectedResourceMetadata Resource { get; init; } - /// Human-readable hint, for example the endpoint's error description. + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Description { get; init; } @@ -2543,7 +2554,8 @@ public sealed record ModelSourceAuthRequiredState /// takes a user-supplied secret omits them. public required ProtectedResourceMetadata Resource { get; init; } - /// Human-readable hint, for example the endpoint's error description. + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Description { get; init; } @@ -2561,7 +2573,7 @@ public sealed record ModelSourceErrorState { public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Error; - /// Error details. MUST NOT contain the credential. + /// Error details the host writes. MUST NOT contain the credential. public required ErrorInfo Error { get; init; } /// Unrecognized wire members retained for full-object edits. diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index 93df142da..ae523feb7 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1358,6 +1358,10 @@ type ModelSourceAuthenticateTarget struct { Kind AuthenticateTargetKind `json:"kind"` // The registration's `ModelSourceRegistration.id`. ModelSourceId string `json:"modelSourceId"` + // The registration's current `ModelSourceRegistration.credentialNonce`, as + // published in root state. The host rejects a stale one with `Conflict` + // (-32011). + CredentialNonce string `json:"credentialNonce"` } // Pushes a credential for a protected resource. The `resource` field MUST @@ -1368,7 +1372,9 @@ type ModelSourceAuthenticateTarget struct { // `ModelSourceAuthRequiredState.resource` (each surfaced only once the // corresponding MCP server, tool call, or model source actually challenges // for auth). Servers MUST accept any `resource` value they have themselves -// advertised through one of these mechanisms. +// advertised through one of these mechanisms, subject to the `target` +// rules. A `modelSource` target takes only the resource the host most +// recently advertised for that registration. // // Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) // (Bearer Token Usage) semantics. The client obtains the token from the @@ -1426,7 +1432,8 @@ type AuthenticateParams struct { // with `InvalidParams` (-32602). // // A registered model source takes its credential only through a - // `modelSource` target. See + // `modelSource` target, and the host rejects an untargeted `resource` that + // matches only model source challenges with `InvalidParams` (-32602). See // [Model source credentials](/specification/authentication#model-source-credentials) // for its rules. // diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 36d221775..c5fd3e1a4 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -767,6 +767,8 @@ func (v Icon) MarshalJSON() ([]byte, error) { type ProtectedResourceMetadata struct { // REQUIRED. The protected resource's resource identifier, a URL using the // `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + // A registered model source's endpoint may use any scheme the agent + // supports, because nothing fetches it. Resource string `json:"resource"` // OPTIONAL. Human-readable name of the protected resource. ResourceName *string `json:"resource_name,omitempty"` @@ -1012,6 +1014,12 @@ type ModelSourceRegistration struct { Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` // Host-reported status. Absent means the host hasn't reported one yet. State *ModelSourceState `json:"state,omitempty"` + // Host-issued token that a client echoes in + // {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers + // the credential. The host changes it whenever it drops the credential + // because the registration changed, and never reuses one for the same + // `id`. Absent until the host reports a `state`. + CredentialNonce *string `json:"credentialNonce,omitempty"` // Additional implementation-defined metadata for this registration. // MUST NOT contain a credential. Meta map[string]json.RawMessage `json:"_meta,omitempty"` @@ -1021,12 +1029,12 @@ type ModelSourceRegistration struct { func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistration - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "credentialNonce", "_meta") } func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistration - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "_meta") + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "credentialNonce", "_meta") } // The agent is reading and validating the definition, or listing the @@ -1085,7 +1093,8 @@ type ModelSourceAuthRequirement struct { // advertises `authorization_servers` and `scopes_supported`. A source that // takes a user-supplied secret omits them. Resource ProtectedResourceMetadata `json:"resource"` - // Human-readable hint, for example the endpoint's error description. + // Human-readable hint the host writes, for example "The endpoint rejected + // the API key." Description *string `json:"description,omitempty"` // Extra contains unrecognized wire members retained for full-object edits. Extra map[string]json.RawMessage `json:"-"` @@ -1117,7 +1126,8 @@ type ModelSourceAuthRequiredState struct { // advertises `authorization_servers` and `scopes_supported`. A source that // takes a user-supplied secret omits them. Resource ProtectedResourceMetadata `json:"resource"` - // Human-readable hint, for example the endpoint's error description. + // Human-readable hint the host writes, for example "The endpoint rejected + // the API key." Description *string `json:"description,omitempty"` Kind ModelSourceStatus `json:"kind"` // Extra contains unrecognized wire members retained for full-object edits. @@ -1139,7 +1149,7 @@ func (v ModelSourceAuthRequiredState) MarshalJSON() ([]byte, error) { // Stability: 1.0 - Early development. type ModelSourceErrorState struct { Kind ModelSourceStatus `json:"kind"` - // Error details. MUST NOT contain the credential. + // Error details the host writes. MUST NOT contain the credential. Error ErrorInfo `json:"error"` // Extra contains unrecognized wire members retained for full-object edits. Extra map[string]json.RawMessage `json:"-"` 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 20c95b3fd..55f5029df 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 @@ -1628,7 +1628,13 @@ data class ModelSourceAuthenticateTarget( /** * The registration's `ModelSourceRegistration.id`. */ - val modelSourceId: String + val modelSourceId: String, + /** + * The registration's current `ModelSourceRegistration.credentialNonce`, as + * published in root state. The host rejects a stale one with `Conflict` + * (-32011). + */ + val credentialNonce: String ) @Serializable @@ -1697,7 +1703,8 @@ data class AuthenticateParams( * with `InvalidParams` (-32602). * * A registered model source takes its credential only through a - * `modelSource` target. See + * `modelSource` target, and the host rejects an untargeted `resource` that + * matches only model source challenges with `InvalidParams` (-32602). See * [Model source credentials](/specification/authentication#model-source-credentials) * for its rules. * 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 637063985..8306b8532 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 @@ -1536,6 +1536,8 @@ data class ProtectedResourceMetadata( /** * REQUIRED. The protected resource's resource identifier, a URL using the * `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + * A registered model source's endpoint may use any scheme the agent + * supports, because nothing fetches it. */ val resource: String, /** @@ -1874,6 +1876,14 @@ data class ModelSourceRegistration( * Host-reported status. Absent means the host hasn't reported one yet. */ val state: ModelSourceState? = null, + /** + * Host-issued token that a client echoes in + * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers + * the credential. The host changes it whenever it drops the credential + * because the registration changed, and never reuses one for the same + * `id`. Absent until the host reports a `state`. + */ + val credentialNonce: String? = null, /** * Additional implementation-defined metadata for this registration. * MUST NOT contain a credential. @@ -1955,7 +1965,8 @@ data class ModelSourceAuthRequirement( */ val resource: ProtectedResourceMetadata, /** - * Human-readable hint, for example the endpoint's error description. + * Human-readable hint the host writes, for example "The endpoint rejected + * the API key." */ val description: String? = null, @Transient @@ -1993,7 +2004,8 @@ data class ModelSourceAuthRequiredState( */ val resource: ProtectedResourceMetadata, /** - * Human-readable hint, for example the endpoint's error description. + * Human-readable hint the host writes, for example "The endpoint rejected + * the API key." */ val description: String? = null, val kind: ModelSourceStatus, @@ -2017,7 +2029,7 @@ internal object ModelSourceAuthRequiredStateSerializer : UnknownMembersSerialize data class ModelSourceErrorState( val kind: ModelSourceStatus, /** - * Error details. MUST NOT contain the credential. + * Error details the host writes. MUST NOT contain the credential. */ val error: ErrorInfo, @Transient diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index 365d459e7..09697e58d 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1756,6 +1756,10 @@ pub struct McpServerAuthenticateTarget { pub struct ModelSourceAuthenticateTarget { /// The registration's `ModelSourceRegistration.id`. pub model_source_id: String, + /// The registration's current `ModelSourceRegistration.credentialNonce`, as + /// published in root state. The host rejects a stale one with `Conflict` + /// (-32011). + pub credential_nonce: String, } /// Pushes a credential for a protected resource. The `resource` field MUST @@ -1766,7 +1770,9 @@ pub struct ModelSourceAuthenticateTarget { /// `ModelSourceAuthRequiredState.resource` (each surfaced only once the /// corresponding MCP server, tool call, or model source actually challenges /// for auth). Servers MUST accept any `resource` value they have themselves -/// advertised through one of these mechanisms. +/// advertised through one of these mechanisms, subject to the `target` +/// rules. A `modelSource` target takes only the resource the host most +/// recently advertised for that registration. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the @@ -1829,7 +1835,8 @@ pub struct AuthenticateParams { /// with `InvalidParams` (-32602). /// /// A registered model source takes its credential only through a - /// `modelSource` target. See + /// `modelSource` target, and the host rejects an untargeted `resource` that + /// matches only model source challenges with `InvalidParams` (-32602). See /// [Model source credentials](/specification/authentication#model-source-credentials) /// for its rules. /// diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 37c8959d5..3982fd39c 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1894,6 +1894,8 @@ pub struct Icon { pub struct ProtectedResourceMetadata { /// REQUIRED. The protected resource's resource identifier, a URL using the /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + /// A registered model source's endpoint may use any scheme the agent + /// supports, because nothing fetches it. pub resource: String, /// OPTIONAL. Human-readable name of the protected resource. #[serde( @@ -2200,6 +2202,13 @@ pub struct ModelSourceRegistration { /// Host-reported status. Absent means the host hasn't reported one yet. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, + /// Host-issued token that a client echoes in + /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers + /// the credential. The host changes it whenever it drops the credential + /// because the registration changed, and never reuses one for the same + /// `id`. Absent until the host reports a `state`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_nonce: Option, /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] @@ -2251,7 +2260,8 @@ pub struct ModelSourceAuthRequirement { /// advertises `authorization_servers` and `scopes_supported`. A source that /// takes a user-supplied secret omits them. pub resource: ProtectedResourceMetadata, - /// Human-readable hint, for example the endpoint's error description. + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, /// Unrecognized wire members retained for full-object edits. @@ -2277,7 +2287,8 @@ pub struct ModelSourceAuthRequiredState { /// advertises `authorization_servers` and `scopes_supported`. A source that /// takes a user-supplied secret omits them. pub resource: ProtectedResourceMetadata, - /// Human-readable hint, for example the endpoint's error description. + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, /// Unrecognized wire members retained for full-object edits. @@ -2291,7 +2302,7 @@ pub struct ModelSourceAuthRequiredState { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceErrorState { - /// Error details. MUST NOT contain the credential. + /// Error details the host writes. MUST NOT contain the credential. pub error: ErrorInfo, /// Unrecognized wire members retained for full-object edits. #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index a97e42458..2bef32da9 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -1977,13 +1977,19 @@ public struct ModelSourceAuthenticateTarget: Codable, Sendable, Equatable { public var kind: AuthenticateTargetKind /// The registration's `ModelSourceRegistration.id`. public var modelSourceId: String + /// The registration's current `ModelSourceRegistration.credentialNonce`, as + /// published in root state. The host rejects a stale one with `Conflict` + /// (-32011). + public var credentialNonce: String public init( kind: AuthenticateTargetKind, - modelSourceId: String + modelSourceId: String, + credentialNonce: String ) { self.kind = kind self.modelSourceId = modelSourceId + self.credentialNonce = credentialNonce } } @@ -2038,7 +2044,8 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// with `InvalidParams` (-32602). /// /// A registered model source takes its credential only through a - /// `modelSource` target. See + /// `modelSource` target, and the host rejects an untargeted `resource` that + /// matches only model source challenges with `InvalidParams` (-32602). See /// [Model source credentials](/specification/authentication#model-source-credentials) /// for its rules. /// diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 88cb202e6..9dbd18a4f 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1476,6 +1476,8 @@ public struct Icon: Codable, Sendable, Equatable { public struct ProtectedResourceMetadata: Codable, Sendable, Equatable { /// REQUIRED. The protected resource's resource identifier, a URL using the /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + /// A registered model source's endpoint may use any scheme the agent + /// supports, because nothing fetches it. public var resource: String /// OPTIONAL. Human-readable name of the protected resource. public var resourceName: String? @@ -1866,6 +1868,12 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { public var retention: ModelSourceRetentionPolicy? /// Host-reported status. Absent means the host hasn't reported one yet. public var state: ModelSourceState? + /// Host-issued token that a client echoes in + /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers + /// the credential. The host changes it whenever it drops the credential + /// because the registration changed, and never reuses one for the same + /// `id`. Absent until the host reports a `state`. + public var credentialNonce: String? /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. public var meta: [String: AnyCodable]? @@ -1883,6 +1891,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { case sharing case retention case state + case credentialNonce case meta = "_meta" } @@ -1897,6 +1906,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { sharing: ModelSourceSharingPolicy? = nil, retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, + credentialNonce: String? = nil, meta: [String: AnyCodable]? = nil, extra: [String: AnyCodable] = [:] ) { @@ -1910,6 +1920,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.sharing = sharing self.retention = retention self.state = state + self.credentialNonce = credentialNonce self.meta = meta self.extra = extra } @@ -1926,6 +1937,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.sharing = try container.decodeIfPresent(ModelSourceSharingPolicy.self, forKey: .sharing) self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) + self.credentialNonce = try container.decodeIfPresent(String.self, forKey: .credentialNonce) self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -1942,6 +1954,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { try container.encodeIfPresent(self.sharing, forKey: .sharing) try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) + try container.encodeIfPresent(self.credentialNonce, forKey: .credentialNonce) try container.encodeIfPresent(self.meta, forKey: .meta) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -2031,7 +2044,8 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { /// advertises `authorization_servers` and `scopes_supported`. A source that /// takes a user-supplied secret omits them. public var resource: ProtectedResourceMetadata - /// Human-readable hint, for example the endpoint's error description. + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." public var description: String? /// Unrecognized wire members retained for full-object edits. public var extra: [String: AnyCodable] @@ -2087,7 +2101,8 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { /// advertises `authorization_servers` and `scopes_supported`. A source that /// takes a user-supplied secret omits them. public var resource: ProtectedResourceMetadata - /// Human-readable hint, for example the endpoint's error description. + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." public var description: String? public var kind: ModelSourceStatus /// Unrecognized wire members retained for full-object edits. @@ -2138,7 +2153,7 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct ModelSourceErrorState: Codable, Sendable, Equatable { public var kind: ModelSourceStatus - /// Error details. MUST NOT contain the credential. + /// Error details the host writes. MUST NOT contain the credential. public var error: ErrorInfo /// Unrecognized wire members retained for full-object edits. public var extra: [String: AnyCodable] diff --git a/docs/.changes/20261123-model-source-registry-migration.json b/docs/.changes/20261123-model-source-registry-migration.json index 168bc5820..607e2a110 100644 --- a/docs/.changes/20261123-model-source-registry-migration.json +++ b/docs/.changes/20261123-model-source-registry-migration.json @@ -1,6 +1,6 @@ { "type": "changed", - "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. Direct Rust struct literals for `RootState` must now include `model_source_registrations: None`, and those for `AgentCapabilities` must include `model_source_registration: None`.", + "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. `AuthenticateTarget` is now a union, so TypeScript code that reads `target.session` or `target.customizationId` must first narrow on `target.kind`. Direct Rust struct literals for `RootState` must now include `model_source_registrations: None`, and those for `AgentCapabilities` must include `model_source_registration: None`.", "targets": ["rust", "swift", "kotlin", "typescript"], "issues": [619] } diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index 6285f7daa..b96803439 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions, and deliver each source's credential with a `modelSource` `authenticate` target. Agents advertise the definition formats they read with `AgentCapabilities.modelSourceRegistration`.", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions, and deliver each source's credential with a `modelSource` `authenticate` target that echoes the registration's host-issued `credentialNonce`. Agents advertise the definition formats they read with `AgentCapabilities.modelSourceRegistration`.", "issues": [619] } diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index ec45cffa9..999047fa7 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -144,13 +144,13 @@ If the client retained the original token response, it MUST subtract elapsed tim When `target.kind` is `mcpServer`, the host MUST apply the token only to that MCP server in that session — never to sibling servers, other sessions, or agent-level resources — even when they share `resource` and scopes. `resource` MUST still equal the targeted server's advertised `McpAuthRequirement.resource.resource`. If the session or customization is unknown, or the customization is not an MCP server, the host MUST reject the request with `InvalidParams` (`-32602`). -Without `target`, hosts retain resource/scope matching for backwards compatibility; a token may satisfy every matching pending challenge, except a model source's. Older hosts ignore the unknown field and retain this untargeted behavior, so isolation is not guaranteed with older hosts. No capability or protocol version bump is required. +Without `target`, hosts retain resource/scope matching for backwards compatibility; a token may satisfy every matching pending challenge, except a model source's. The host rejects an untargeted `resource` that matches only model source challenges with `InvalidParams` (`-32602`). Older hosts ignore the unknown field and retain this untargeted behavior, so isolation is not guaranteed with older hosts. No capability or protocol version bump is required. If the token is invalid or the resource is unrecognized, the server MUST return a JSON-RPC error (e.g. `AuthRequired` `-32007` or `InvalidParams` `-32602`). ### Model source credentials -A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. When the source needs a credential, the host sets the registration's state to `ModelSourceAuthRequiredState`, which carries a `reason` and RFC 9728 `resource` metadata for the source's endpoint. A client answers with a `modelSource` target that names the registration: +A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. When the source needs a credential, the host sets the registration's state to `ModelSourceAuthRequiredState`, which carries a `reason` and RFC 9728 `resource` metadata for the source's endpoint. A client answers with a `modelSource` target that names the registration and echoes its current `credentialNonce`: ```jsonc // Model source credential delivery @@ -162,7 +162,11 @@ A client can [register a model source](/specification/root-channel#model-source- "channel": "ahp-root://", "resource": "https://api.example.com/v1", "token": "", - "target": { "kind": "modelSource", "modelSourceId": "2f6c0e1a-model-source" } + "target": { + "kind": "modelSource", + "modelSourceId": "2f6c0e1a-model-source", + "credentialNonce": "9b41d7" + } } } ``` @@ -176,12 +180,15 @@ When `target.kind` is `modelSource`, the host: - MUST apply the credential only to that registration, never to other registrations, MCP servers, or agent-level resources, even when they share `resource`; - MUST require `resource` to equal the `resource.resource` it most recently advertised for that registration; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); +- MUST reject a `credentialNonce` other than the one it most recently issued for that registration with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; - MUST reject a credential, including an empty `token` that would revoke one, from a client that may not supply one, with `PermissionDenied` (`-32009`). The contributing client may always supply one. For a registration with `host` sharing, or one the host registered, any client the host allows may supply one; -- MUST treat an empty `token` as revocation: it drops the credential, and the source returns to `authRequired` with `reason: required`. +- MUST treat an empty `token` as revocation: it drops the credential, and the source returns to `authRequired` with `reason: expired`, so no client sends the revoked secret again. + +`credentialNonce` keeps a delayed `authenticate` from reaching a definition it wasn't meant for: a key sent for an old definition with the same endpoint would otherwise still match the `id` and `resource`. The host issues a new nonce whenever it drops the credential because the registration changed, including when a removed registration is registered again under the same `id`, and never reuses one for the same `id`. It keeps the nonce across rotation, expiry, and revocation. -The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition` or `_meta`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host drops the credential when the registration is removed, when its definition or contributing client changes, and when the host restarts. +The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition` or `_meta`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. The host drops the credential when the registration is removed, when its `provider`, `format`, `definition`, or contributing client changes, and when the host restarts. -The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, and SHOULD check that `resource.resource` matches the endpoint in its own copy of the definition before sending a secret. +The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, but MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has taken over. If the credential fails during a turn that uses the source, the host SHOULD end the turn with a resumable error (`chat/error` with `part.resumable: true`) rather than wait. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first, including the sharing policy. The host never switches the turn to a different model. diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index 5d4ac5e48..6471c9605 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -75,7 +75,8 @@ Clients can register bring-your-own-key model sources with the host, so its agen "clientId": "laptop", "sharing": "host", "retention": "host", - "state": { "kind": "ready" } + "state": { "kind": "ready" }, + "credentialNonce": "9b41d7" } ``` @@ -83,17 +84,23 @@ Clients can register bring-your-own-key model sources with the host, so its agen #### Registering -A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId` and no `state`, and removes one with `root/modelSourceRegistrationRemoved`. The host reports status by dispatching `Set` again with a `state`: `starting`, `ready`, `authRequired`, or `error`. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed, because doing so clears the reported state. +A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId`, and with no `state` or `credentialNonce`. It removes one with `root/modelSourceRegistrationRemoved`. The host reports status by dispatching `Set` again with a `state` (`starting`, `ready`, `authRequired`, or `error`) and a `credentialNonce`. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed, because doing so clears the reported state. -The host rejects a client's `Set` or `Removed`, through `rejectionReason`, when: +The host builds each status `Set` from the registration as it currently stands. It discards an agent result for a definition the registration no longer has, and never dispatches a status `Set` for a removed registration, so a late result can't undo a client's change or bring back a removed source. + +A client may change or remove a registration when it's the contributing client, or when the registration has `host` sharing, which lets another of the user's clients take it over. It may not change one that belongs to another client with `contributingClient` sharing, or one the host registered, unless host policy allows it. + +The host rejects a client's `Set`, through `rejectionReason`, when: - the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; -- `clientId` isn't the dispatching client's ID, or `state` is present; -- `id` is already a declared `ModelSourceInfo.id` in that agent's catalog; -- the registration belongs to another client and has `contributingClient` sharing, or the host registered it, unless host policy allows the change; +- `clientId` isn't the dispatching client's ID, or `state` or `credentialNonce` is present; +- `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same registration doesn't count, so a ready registration can still be updated; +- a registration with this `id` already exists, and the dispatching client may not change it; - the host won't honor the requested `sharing` or `retention`. The client can register again with a narrower policy. -When a `Set` changes a registration's `provider`, `format`, `definition`, or `clientId`, the host drops its credential, and the source goes back through `starting`. A host may also register sources itself. Those registrations have no `clientId`, and both policies behave as `host`. +A client's `Removed` is a no-op when no registration has that `id`. Otherwise the host rejects it only when the dispatching client may not change that registration. The registration's state, policies, and catalog entry don't affect removal. + +When a `Set` changes a registration's `provider`, `format`, `definition`, or `clientId`, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A host may also register sources itself. Those registrations have no `clientId`, and both policies behave as `host`. #### Catalog @@ -106,15 +113,15 @@ The host checks every selection of a registered source's model: the model is lis The contributing client chooses two policies. Absent means `contributingClient`, the narrowest choice. - **Sharing.** With `contributingClient`, only turns and pending messages that client dispatches may select the source's models. With `host`, any client may, and so may work the host starts itself, such as automations. -- **Retention.** With `contributingClient`, the source is removed when its client leaves: new work that names its models fails, turns already running on it finish, and then the host removes the registration and drops its credential. With `host`, the registration and its in-memory credential stay until a client removes it, host policy expires it, or the host restarts. +- **Retention.** With `contributingClient`, the source is removed when its client leaves: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the registration and drops its credential. With `host`, the registration and its in-memory credential stay until a client removes it, host policy expires it, or the host restarts. The host never widens a policy, and it MAY expire `host`-retained registrations. Every client sees every registration, so clients SHOULD offer only the models they may select, using `sharing` and `clientId`. -A client that reconnects with the same `clientId` within the host's grace period keeps its registrations. A client that comes back with a new `clientId` registers again under the same `id`. For a `host`-shared registration, that takes it over: `clientId` changes, the credential is dropped, and the new contributing client supplies it. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back in `authRequired`. +A client that reconnects with the same `clientId` within the host's grace period keeps its registrations. A client that comes back with a new `clientId` registers again under the same `id`. For a `host`-shared registration, that takes it over: `clientId` changes, the credential is dropped, and the new contributing client supplies it. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back through `starting`, and reach `authRequired` only if they need a credential. #### Reserved model IDs -Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A host can meet this by minting IDs it never reuses, for example with a random component. +Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a `definition` change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when another client has taken the registration over. A host can meet this by minting IDs it never reuses, for example with a random component. #### Automations diff --git a/schema/actions.schema.json b/schema/actions.schema.json index f049e2d89..43260cce6 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -2860,7 +2860,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." }, "resource_name": { "type": "string", @@ -3594,6 +3594,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status. Absent means the host hasn't reported one yet." }, + "credentialNonce": { + "type": "string", + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -3646,7 +3650,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ @@ -3668,7 +3672,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" }, "kind": { "const": "authRequired" @@ -3689,7 +3693,7 @@ }, "error": { "$ref": "#/$defs/ErrorInfo", - "description": "Error details. MUST NOT contain the credential." + "description": "Error details the host writes. MUST NOT contain the credential." } }, "required": [ diff --git a/schema/commands.schema.json b/schema/commands.schema.json index fdccc7321..b60182a70 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1063,16 +1063,21 @@ "modelSourceId": { "type": "string", "description": "The registration's `ModelSourceRegistration.id`." + }, + "credentialNonce": { + "type": "string", + "description": "The registration's current `ModelSourceRegistration.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." } }, "required": [ "kind", - "modelSourceId" + "modelSourceId", + "credentialNonce" ] }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms, subject to the `target`\nrules. A `modelSource` target takes only the resource the host most\nrecently advertised for that registration.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -1107,7 +1112,7 @@ }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", @@ -2210,7 +2215,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." }, "resource_name": { "type": "string", @@ -2944,6 +2949,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status. Absent means the host hasn't reported one yet." }, + "credentialNonce": { + "type": "string", + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -2996,7 +3005,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ @@ -3018,7 +3027,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" }, "kind": { "const": "authRequired" @@ -3039,7 +3048,7 @@ }, "error": { "$ref": "#/$defs/ErrorInfo", - "description": "Error details. MUST NOT contain the credential." + "description": "Error details the host writes. MUST NOT contain the credential." } }, "required": [ diff --git a/schema/errors.schema.json b/schema/errors.schema.json index cca7951b5..787754594 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -195,7 +195,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." }, "resource_name": { "type": "string", @@ -929,6 +929,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status. Absent means the host hasn't reported one yet." }, + "credentialNonce": { + "type": "string", + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -981,7 +985,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ @@ -1003,7 +1007,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" }, "kind": { "const": "authRequired" @@ -1024,7 +1028,7 @@ }, "error": { "$ref": "#/$defs/ErrorInfo", - "description": "Error details. MUST NOT contain the credential." + "description": "Error details the host writes. MUST NOT contain the credential." } }, "required": [ @@ -7487,16 +7491,21 @@ "modelSourceId": { "type": "string", "description": "The registration's `ModelSourceRegistration.id`." + }, + "credentialNonce": { + "type": "string", + "description": "The registration's current `ModelSourceRegistration.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." } }, "required": [ "kind", - "modelSourceId" + "modelSourceId", + "credentialNonce" ] }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms, subject to the `target`\nrules. A `modelSource` target takes only the resource the host most\nrecently advertised for that registration.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -7531,7 +7540,7 @@ }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 85c48f1bd..4f55d7b20 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -497,7 +497,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." }, "resource_name": { "type": "string", @@ -1231,6 +1231,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status. Absent means the host hasn't reported one yet." }, + "credentialNonce": { + "type": "string", + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -1283,7 +1287,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ @@ -1305,7 +1309,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" }, "kind": { "const": "authRequired" @@ -1326,7 +1330,7 @@ }, "error": { "$ref": "#/$defs/ErrorInfo", - "description": "Error details. MUST NOT contain the credential." + "description": "Error details the host writes. MUST NOT contain the credential." } }, "required": [ diff --git a/schema/state.schema.json b/schema/state.schema.json index e5bb21049..88fad496a 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -106,7 +106,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." }, "resource_name": { "type": "string", @@ -840,6 +840,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status. Absent means the host hasn't reported one yet." }, + "credentialNonce": { + "type": "string", + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -892,7 +896,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ @@ -914,7 +918,7 @@ }, "description": { "type": "string", - "description": "Human-readable hint, for example the endpoint's error description." + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" }, "kind": { "const": "authRequired" @@ -935,7 +939,7 @@ }, "error": { "$ref": "#/$defs/ErrorInfo", - "description": "Error details. MUST NOT contain the credential." + "description": "Error details the host writes. MUST NOT contain the credential." } }, "required": [ diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index c1fe78cf7..9bf58133f 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -374,6 +374,16 @@ export interface ModelSourceRegistration { retention?: ModelSourceRetentionPolicy; /** Host-reported status. Absent means the host hasn't reported one yet. */ state?: ModelSourceState; + /** + * Host-issued token that a client echoes in + * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers + * the credential. The host changes it whenever it drops the credential + * because the registration changed, and never reuses one for the same + * `id`. Absent until the host reports a `state`. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + credentialNonce?: string; /** * Additional implementation-defined metadata for this registration. * MUST NOT contain a credential. @@ -473,7 +483,10 @@ export interface ModelSourceAuthRequirement { * takes a user-supplied secret omits them. */ resource: ProtectedResourceMetadata; - /** Human-readable hint, for example the endpoint's error description. */ + /** + * Human-readable hint the host writes, for example "The endpoint rejected + * the API key." + */ description?: string; } @@ -499,7 +512,7 @@ export interface ModelSourceAuthRequiredState extends ModelSourceAuthRequirement */ export interface ModelSourceErrorState { kind: ModelSourceStatus.Error; - /** Error details. MUST NOT contain the credential. */ + /** Error details the host writes. MUST NOT contain the credential. */ error: ErrorInfo; } diff --git a/types/common/commands.ts b/types/common/commands.ts index d3a8ea7fd..b221a15a6 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1494,6 +1494,12 @@ export interface ModelSourceAuthenticateTarget { kind: AuthenticateTargetKind.ModelSource; /** The registration's `ModelSourceRegistration.id`. */ modelSourceId: string; + /** + * The registration's current `ModelSourceRegistration.credentialNonce`, as + * published in root state. The host rejects a stale one with `Conflict` + * (-32011). + */ + credentialNonce: string; } /** @@ -1515,7 +1521,9 @@ export type AuthenticateTarget = * `ModelSourceAuthRequiredState.resource` (each surfaced only once the * corresponding MCP server, tool call, or model source actually challenges * for auth). Servers MUST accept any `resource` value they have themselves - * advertised through one of these mechanisms. + * advertised through one of these mechanisms, subject to the `target` + * rules. A `modelSource` target takes only the resource the host most + * recently advertised for that registration. * * Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) * (Bearer Token Usage) semantics. The client obtains the token from the @@ -1602,7 +1610,8 @@ export interface AuthenticateParams extends BaseParams { * with `InvalidParams` (-32602). * * A registered model source takes its credential only through a - * `modelSource` target. See + * `modelSource` target, and the host rejects an untargeted `resource` that + * matches only model source challenges with `InvalidParams` (-32602). See * [Model source credentials](/specification/authentication#model-source-credentials) * for its rules. * diff --git a/types/common/state.ts b/types/common/state.ts index 310537e5e..484ebcc5e 100644 --- a/types/common/state.ts +++ b/types/common/state.ts @@ -197,6 +197,8 @@ export interface ProtectedResourceMetadata { /** * REQUIRED. The protected resource's resource identifier, a URL using the * `https` scheme with no fragment component (e.g. `"https://api.github.com"`). + * A registered model source's endpoint may use any scheme the agent + * supports, because nothing fetches it. */ resource: string; diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json index 0365811fb..1225924aa 100644 --- a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json +++ b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json @@ -49,7 +49,8 @@ "clientId": "client-1", "state": { "kind": "ready" - } + }, + "credentialNonce": "nonce-a-1" } } ], @@ -70,7 +71,8 @@ "clientId": "client-1", "state": { "kind": "ready" - } + }, + "credentialNonce": "nonce-a-1" }, { "id": "model-source-b", diff --git a/types/test-cases/round-trips/102-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json similarity index 92% rename from types/test-cases/round-trips/102-model-source-registry-snapshot.json rename to types/test-cases/round-trips/103-model-source-registry-snapshot.json index dc5fb541c..33954860e 100644 --- a/types/test-cases/round-trips/102-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -73,7 +73,8 @@ "clientId": "client-1", "state": { "kind": "starting" - } + }, + "credentialNonce": "nonce-starting-1" }, { "id": "source-ready", @@ -101,6 +102,7 @@ "state": { "kind": "ready" }, + "credentialNonce": "nonce-ready-1", "_meta": { "example.com/label": "Laptop" } @@ -111,7 +113,7 @@ "name": "Azure endpoint", "format": "example.com/model-source@1", "definition": { - "baseUrl": "https://api.example.com/v1", + "baseUrl": "https://example.openai.azure.com/openai/v1", "wireFormat": "openai-chat", "models": [ { @@ -127,7 +129,7 @@ "kind": "authRequired", "reason": "expired", "resource": { - "resource": "https://example.openai.azure.com", + "resource": "https://example.openai.azure.com/openai/v1", "resource_name": "Azure OpenAI", "authorization_servers": [ "https://login.microsoftonline.com/common/v2.0" @@ -137,7 +139,8 @@ ] }, "description": "The access token expired." - } + }, + "credentialNonce": "nonce-auth-1" }, { "id": "source-local", @@ -155,7 +158,8 @@ "resource": "http://localhost:11434/v1", "resource_name": "Local server key" } - } + }, + "credentialNonce": "nonce-local-1" }, { "id": "source-host", @@ -171,7 +175,8 @@ "errorType": "policy", "message": "The endpoint is not allowed by host policy." } - } + }, + "credentialNonce": "nonce-host-1" } ] } @@ -247,7 +252,8 @@ "clientId": "client-1", "state": { "kind": "starting" - } + }, + "credentialNonce": "nonce-starting-1" }, { "id": "source-ready", @@ -275,6 +281,7 @@ "state": { "kind": "ready" }, + "credentialNonce": "nonce-ready-1", "_meta": { "example.com/label": "Laptop" } @@ -285,7 +292,7 @@ "name": "Azure endpoint", "format": "example.com/model-source@1", "definition": { - "baseUrl": "https://api.example.com/v1", + "baseUrl": "https://example.openai.azure.com/openai/v1", "wireFormat": "openai-chat", "models": [ { @@ -301,7 +308,7 @@ "kind": "authRequired", "reason": "expired", "resource": { - "resource": "https://example.openai.azure.com", + "resource": "https://example.openai.azure.com/openai/v1", "resource_name": "Azure OpenAI", "authorization_servers": [ "https://login.microsoftonline.com/common/v2.0" @@ -311,7 +318,8 @@ ] }, "description": "The access token expired." - } + }, + "credentialNonce": "nonce-auth-1" }, { "id": "source-local", @@ -329,7 +337,8 @@ "resource": "http://localhost:11434/v1", "resource_name": "Local server key" } - } + }, + "credentialNonce": "nonce-local-1" }, { "id": "source-host", @@ -345,7 +354,8 @@ "errorType": "policy", "message": "The endpoint is not allowed by host policy." } - } + }, + "credentialNonce": "nonce-host-1" } ] } diff --git a/types/test-cases/round-trips/103-root-model-source-registration-set.json b/types/test-cases/round-trips/104-root-model-source-registration-set.json similarity index 100% rename from types/test-cases/round-trips/103-root-model-source-registration-set.json rename to types/test-cases/round-trips/104-root-model-source-registration-set.json diff --git a/types/test-cases/round-trips/104-root-model-source-registration-removed.json b/types/test-cases/round-trips/105-root-model-source-registration-removed.json similarity index 100% rename from types/test-cases/round-trips/104-root-model-source-registration-removed.json rename to types/test-cases/round-trips/105-root-model-source-registration-removed.json diff --git a/types/test-cases/round-trips/105-authenticate-model-source-target.json b/types/test-cases/round-trips/106-authenticate-model-source-target.json similarity index 63% rename from types/test-cases/round-trips/105-authenticate-model-source-target.json rename to types/test-cases/round-trips/106-authenticate-model-source-target.json index edb08e35f..c6d87a403 100644 --- a/types/test-cases/round-trips/105-authenticate-model-source-target.json +++ b/types/test-cases/round-trips/106-authenticate-model-source-target.json @@ -1,7 +1,7 @@ { "name": "authenticate-model-source-target", "group": "A", - "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target. An API key carries no expiresIn or scopes.", + "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target that echoes the registration's credentialNonce. An API key carries no expiresIn or scopes.", "type": "AuthenticateParams", "input": { "channel": "ahp-root://", @@ -9,7 +9,8 @@ "token": "test-api-key", "target": { "kind": "modelSource", - "modelSourceId": "source-new" + "modelSourceId": "source-new", + "credentialNonce": "nonce-openrouter-1" } }, "acceptableOutputs": [ @@ -19,7 +20,8 @@ "token": "test-api-key", "target": { "kind": "modelSource", - "modelSourceId": "source-new" + "modelSourceId": "source-new", + "credentialNonce": "nonce-openrouter-1" } } ] From a781589e3207bf2a5be2a2d92b7a1d2af6df8cc9 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 09:24:18 -0500 Subject: [PATCH 04/17] models: follow MCP for registry ownership and status - Remove `ModelSourceSharingPolicy`, the `sharing` field, takeover, and the ownership checks on `Set`, `Removed`, and credential delivery. Any client may change or remove any registration and deliver or revoke its credential. `clientId` records who last wrote it. - Add the host-only `root/modelSourceStateChanged { id, state, credentialNonce }` action, modeled on `session/mcpServerStateChanged`, with reducers in TypeScript and every client. It is a no-op for an unknown `id` and changes only `state` and `credentialNonce`. - Only a change to `provider`, `format`, or `definition` drops the credential. The host issues a new nonce on every credential install or drop and ignores failures from requests made with an older key. - Automations may use registrations with `host` retention, or ones the host registered. - Update the specs, naming dictionary, fixtures, and changelog. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../protocol-naming.instructions.md | 2 +- .../Generated/Actions.generated.cs | 29 +++++- .../JsonSerializerContext.generated.cs | 2 +- .../Generated/State.generated.cs | 72 ++------------ .../Generated/ActionMetadata.generated.cs | 3 + .../dotnet/src/AgentHostProtocol/Reducers.cs | 12 +++ clients/go/ahp/reducers.go | 11 +++ clients/go/ahptypes/actions.generated.go | 30 +++++- clients/go/ahptypes/state.generated.go | 31 ++---- .../microsoft/agenthostprotocol/Reducers.kt | 15 +++ .../generated/Actions.generated.kt | 35 ++++++- .../generated/State.generated.kt | 47 ++------- clients/rust/crates/ahp-types/src/actions.rs | 40 ++++++-- clients/rust/crates/ahp-types/src/state.rs | 56 ++--------- clients/rust/crates/ahp/src/reducers.rs | 12 +++ .../Generated/Actions.generated.swift | 41 +++++++- .../Generated/State.generated.swift | 51 ++-------- .../AgentHostProtocol/NativeReducer.swift | 14 +++ .../Sources/AgentHostProtocol/Reducers.swift | 5 + .../20261123-model-source-registry.json | 2 +- docs/guide/actions.md | 3 +- docs/specification/authentication.md | 17 +++- docs/specification/root-channel.md | 39 ++++---- schema/actions.schema.json | 50 ++++++---- schema/commands.schema.json | 50 ++++++---- schema/errors.schema.json | 50 ++++++---- schema/notifications.schema.json | 18 +--- schema/state.schema.json | 18 +--- scripts/generate-csharp.ts | 3 +- scripts/generate-go.ts | 3 +- scripts/generate-kotlin.ts | 3 +- scripts/generate-rust.ts | 5 +- scripts/generate-swift.ts | 3 +- types/action-origin.generated.ts | 4 + types/channels-root/actions.ts | 28 +++++- types/channels-root/reducer.ts | 14 +++ types/channels-root/state.ts | 33 +++---- types/common/actions.ts | 3 + ...lsourceregistrationset-replaces-by-id.json | 24 ++--- ...estatechanged-updates-state-and-nonce.json | 96 +++++++++++++++++++ ...urcestatechanged-no-op-for-unknown-id.json | 50 ++++++++++ ...atechanged-no-op-when-registry-absent.json | 20 ++++ .../103-model-source-registry-snapshot.json | 4 - ...04-root-model-source-registration-set.json | 4 +- .../107-root-model-source-state-changed.json | 36 +++++++ types/version/registry.ts | 1 + 46 files changed, 696 insertions(+), 393 deletions(-) create mode 100644 types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json create mode 100644 types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json create mode 100644 types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-when-registry-absent.json create mode 100644 types/test-cases/round-trips/107-root-model-source-state-changed.json diff --git a/.github/instructions/protocol-naming.instructions.md b/.github/instructions/protocol-naming.instructions.md index 57c7f7b5d..3a1864d9d 100644 --- a/.github/instructions/protocol-naming.instructions.md +++ b/.github/instructions/protocol-naming.instructions.md @@ -40,7 +40,7 @@ but don't use them as precedent. | **model** | A model offered by an agent provider (`SessionModelInfo`). It is selected per message (`Message.model`). | | | **model source** (`modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `AgentInfo.modelSources` (`ModelSourceInfo`). Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | | **registration** (`ModelSourceRegistration`) | A model source a client or the host added to the host's registry in `RootState.modelSourceRegistrations`, with its definition and status. A ready registration joins its agent's catalog as a model source. | The **model source** it becomes in the catalog. | -| **contributing client** | The client that added a client-contributed entry, named by its `clientId`, such as the client that registered a model source. It supplies the source's credential and chooses its sharing and retention. | The **action origin**'s `clientId`, which names the client that dispatched one action. | +| **contributing client** | The client that added a client-contributed entry, named by its `clientId`. For a model source registration, it's the client that most recently registered or changed it, and it chooses the registration's retention. | The **action origin**'s `clientId`, which names the client that dispatched one action. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | | **pending message** | Input waiting to be consumed. Its `kind` is **steering** (injected into the active turn) or **queued** (starts a later turn). Both kinds live in `ChatState.queuedMessages`. | | | **working directories** | The session's set of directories. A chat may use a subset. | Don't use "workspace" for a protocol field. | diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index cf2e65f7d..1c4d300da 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -203,6 +203,8 @@ public ActionType(string value) public static readonly ActionType RootModelSourceRegistrationRemoved = new ActionType("root/modelSourceRegistrationRemoved"); + public static readonly ActionType RootModelSourceStateChanged = new ActionType("root/modelSourceStateChanged"); + public static readonly ActionType TerminalData = new ActionType("terminal/data"); public static readonly ActionType TerminalInput = new ActionType("terminal/input"); @@ -346,9 +348,10 @@ public sealed record RootConfigChangedAction /// Adds a model source registration, or replaces the one with the same `id`. /// -/// A client registers a source by dispatching this with its own `clientId` and -/// no `state`. The host reports status by dispatching it again with the same -/// registration and a `state`. +/// A client registers a source by dispatching this with its own `clientId`, and +/// with no `state` or `credentialNonce`. Replacing a registration clears its +/// status until the host reports again with +/// {@link RootModelSourceStateChangedAction}. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceRegistrationSetAction @@ -371,6 +374,25 @@ public sealed record RootModelSourceRegistrationRemovedAction public required string Id { get; init; } } +/// Updates a model source registration's status and credential nonce. A no-op +/// when no registration has `id`. Other fields of the registration are +/// preserved. Only the host dispatches it. +/// +/// Stability: 1.0 - Early development. +public sealed record RootModelSourceStateChangedAction +{ + public ActionType Type { get; init; } = ActionType.RootModelSourceStateChanged; + + /// The registration's `id`. + public required string Id { get; init; } + + /// The new status. + public required ModelSourceState State { get; init; } + + /// The registration's current credential nonce. + public required string CredentialNonce { get; init; } +} + /// Session backend initialized successfully. public sealed record SessionReadyAction { @@ -2891,6 +2913,7 @@ public StateActionConverter() ["root/configChanged"] = typeof(RootConfigChangedAction), ["root/modelSourceRegistrationSet"] = typeof(RootModelSourceRegistrationSetAction), ["root/modelSourceRegistrationRemoved"] = typeof(RootModelSourceRegistrationRemovedAction), + ["root/modelSourceStateChanged"] = typeof(RootModelSourceStateChangedAction), ["session/ready"] = typeof(SessionReadyAction), ["session/creationFailed"] = typeof(SessionCreationFailedAction), ["session/turnStarted"] = typeof(SessionTurnStartedAction), diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 00cec27a8..2707221e8 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -307,7 +307,6 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ModelSourceRegistration))] [JsonSerializable(typeof(ModelSourceRegistrationCapability))] [JsonSerializable(typeof(ModelSourceRetentionPolicy))] -[JsonSerializable(typeof(ModelSourceSharingPolicy))] [JsonSerializable(typeof(ModelSourceStartingState))] [JsonSerializable(typeof(ModelSourceState))] [JsonSerializable(typeof(ModelSourceStatus))] @@ -373,6 +372,7 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RootConfigState))] [JsonSerializable(typeof(RootModelSourceRegistrationRemovedAction))] [JsonSerializable(typeof(RootModelSourceRegistrationSetAction))] +[JsonSerializable(typeof(RootModelSourceStateChangedAction))] [JsonSerializable(typeof(RootState))] [JsonSerializable(typeof(RootTerminalsChangedAction))] [JsonSerializable(typeof(RuleCustomization))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 092c2c466..88051d1f2 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1469,61 +1469,6 @@ public override void Write(Utf8JsonWriter writer, ModelSourceStatus value, JsonS => writer.WriteStringValue(value.Value); } -/// Who may select a registered model source's models. -/// -/// Stability: 1.0 - Early development. -[JsonConverter(typeof(ModelSourceSharingPolicyConverter))] -public readonly struct ModelSourceSharingPolicy : IEquatable -{ - private readonly string? _value; - - /// Wraps a raw wire value — including one this build does not recognize. - /// The raw wire string. - public ModelSourceSharingPolicy(string value) - { - _value = value; - } - - /// The raw wire value. - public string Value => _value ?? string.Empty; - - /// Only turns and pending messages the contributing client dispatches. - public static readonly ModelSourceSharingPolicy ContributingClient = new ModelSourceSharingPolicy("contributingClient"); - - /// Any client, and work the host starts itself, such as automations. - public static readonly ModelSourceSharingPolicy Host = new ModelSourceSharingPolicy("host"); - - /// - public bool Equals(ModelSourceSharingPolicy other) => string.Equals(Value, other.Value, StringComparison.Ordinal); - - /// - public override bool Equals(object? obj) => obj is ModelSourceSharingPolicy other && Equals(other); - - /// - public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); - - /// - public override string ToString() => Value; - - /// Ordinal equality over the raw wire value. - public static bool operator ==(ModelSourceSharingPolicy left, ModelSourceSharingPolicy right) => left.Equals(right); - - /// Ordinal inequality over the raw wire value. - public static bool operator !=(ModelSourceSharingPolicy left, ModelSourceSharingPolicy right) => !left.Equals(right); -} - -/// Reads and writes as its raw wire string, preserving unrecognized values. -internal sealed class ModelSourceSharingPolicyConverter : JsonConverter -{ - /// - public override ModelSourceSharingPolicy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => new ModelSourceSharingPolicy(reader.GetString() ?? throw new JsonException("ModelSourceSharingPolicy expects a JSON string.")); - - /// - public override void Write(Utf8JsonWriter writer, ModelSourceSharingPolicy value, JsonSerializerOptions options) - => writer.WriteStringValue(value.Value); -} - /// How long a registered model source lasts once its contributing client leaves. /// /// Stability: 1.0 - Early development. @@ -2445,27 +2390,26 @@ public sealed record ModelSourceRegistration /// a credential. public required Dictionary Definition { get; init; } - /// The contributing client. Absent for a source the host registered itself. + /// The contributing client: the client that most recently registered or + /// changed the source. Absent for a source the host registered itself. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ClientId { get; init; } - /// Who may select the source's models. Absent means `contributingClient`. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public ModelSourceSharingPolicy? Sharing { get; init; } - /// What happens when the contributing client leaves. Absent means `contributingClient`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceRetentionPolicy? Retention { get; init; } - /// Host-reported status. Absent means the host hasn't reported one yet. + /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. + /// Absent until the host reports one, and after a client replaces the + /// registration until the host reports again. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceState? State { get; init; } /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential. The host changes it whenever it drops the credential - /// because the registration changed, and never reuses one for the same - /// `id`. Absent until the host reports a `state`. + /// the credential. The host issues a new one whenever the credential is + /// installed or dropped, and never reuses one for the same `id`. Set with + /// `state`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? CredentialNonce { get; init; } diff --git a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs index e7f995d71..dae5ba15f 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -217,6 +217,9 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootModelSourceRegistrationSetAction value: actionType = value.Type; return true; + case RootModelSourceStateChangedAction value: + actionType = value.Type; + return true; case RootTerminalsChangedAction value: actionType = value.Type; return true; diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index 6f0d8a74d..1251d4441 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -706,6 +706,18 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) state.ModelSourceRegistrations!.RemoveAt(index); return ReduceOutcome.Applied; } + case RootModelSourceStateChangedAction a: + { + int index = state.ModelSourceRegistrations?.FindIndex(r => r.Id == a.Id) ?? -1; + if (index < 0) + { + return ReduceOutcome.NoOp; + } + + List list = state.ModelSourceRegistrations!; + list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce }; + return ReduceOutcome.Applied; + } } return ReduceOutcome.OutOfScope; diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 5afe4f9bb..6c207ff17 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -554,6 +554,17 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R } } return ReduceOutcomeNoOp + case *ahptypes.RootModelSourceStateChangedAction: + for i := range state.ModelSourceRegistrations { + if state.ModelSourceRegistrations[i].Id == a.Id { + st := a.State + nonce := a.CredentialNonce + state.ModelSourceRegistrations[i].State = &st + state.ModelSourceRegistrations[i].CredentialNonce = &nonce + return ReduceOutcomeApplied + } + } + return ReduceOutcomeNoOp } return ReduceOutcomeOutOfScope } diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 92b2475a1..c23d9219f 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -108,6 +108,7 @@ const ( ActionTypeRootConfigChanged ActionType = "root/configChanged" ActionTypeRootModelSourceRegistrationSet ActionType = "root/modelSourceRegistrationSet" ActionTypeRootModelSourceRegistrationRemoved ActionType = "root/modelSourceRegistrationRemoved" + ActionTypeRootModelSourceStateChanged ActionType = "root/modelSourceStateChanged" ActionTypeTerminalData ActionType = "terminal/data" ActionTypeTerminalInput ActionType = "terminal/input" ActionTypeTerminalResized ActionType = "terminal/resized" @@ -180,9 +181,10 @@ type RootConfigChangedAction struct { // Adds a model source registration, or replaces the one with the same `id`. // -// A client registers a source by dispatching this with its own `clientId` and -// no `state`. The host reports status by dispatching it again with the same -// registration and a `state`. +// A client registers a source by dispatching this with its own `clientId`, and +// with no `state` or `credentialNonce`. Replacing a registration clears its +// status until the host reports again with +// {@link RootModelSourceStateChangedAction}. // // Stability: 1.0 - Early development. type RootModelSourceRegistrationSetAction struct { @@ -201,6 +203,21 @@ type RootModelSourceRegistrationRemovedAction struct { Id string `json:"id"` } +// Updates a model source registration's status and credential nonce. A no-op +// when no registration has `id`. Other fields of the registration are +// preserved. Only the host dispatches it. +// +// Stability: 1.0 - Early development. +type RootModelSourceStateChangedAction struct { + Type ActionType `json:"type"` + // The registration's `id`. + Id string `json:"id"` + // The new status. + State ModelSourceState `json:"state"` + // The registration's current credential nonce. + CredentialNonce string `json:"credentialNonce"` +} + // Session backend initialized successfully. type SessionReadyAction struct { Type ActionType `json:"type"` @@ -1888,6 +1905,7 @@ func (*RootActiveSessionsChangedAction) isStateAction() {} func (*RootConfigChangedAction) isStateAction() {} func (*RootModelSourceRegistrationSetAction) isStateAction() {} func (*RootModelSourceRegistrationRemovedAction) isStateAction() {} +func (*RootModelSourceStateChangedAction) isStateAction() {} func (*SessionReadyAction) isStateAction() {} func (*SessionCreationFailedAction) isStateAction() {} func (*SessionChatAddedAction) isStateAction() {} @@ -2038,6 +2056,12 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value + case "root/modelSourceStateChanged": + var value RootModelSourceStateChangedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value case "session/ready": var value SessionReadyAction if err := json.Unmarshal(data, &value); err != nil { diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index c5fd3e1a4..a3915ca79 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -452,18 +452,6 @@ const ( ModelSourceStatusError ModelSourceStatus = "error" ) -// Who may select a registered model source's models. -// -// Stability: 1.0 - Early development. -type ModelSourceSharingPolicy string - -const ( - // Only turns and pending messages the contributing client dispatches. - ModelSourceSharingPolicyContributingClient ModelSourceSharingPolicy = "contributingClient" - // Any client, and work the host starts itself, such as automations. - ModelSourceSharingPolicyHost ModelSourceSharingPolicy = "host" -) - // How long a registered model source lasts once its contributing client leaves. // // Stability: 1.0 - Early development. @@ -1006,19 +994,20 @@ type ModelSourceRegistration struct { // `format`. Its shape belongs to the agent that reads it. MUST NOT contain // a credential. Definition map[string]json.RawMessage `json:"definition"` - // The contributing client. Absent for a source the host registered itself. + // The contributing client: the client that most recently registered or + // changed the source. Absent for a source the host registered itself. ClientId *string `json:"clientId,omitempty"` - // Who may select the source's models. Absent means `contributingClient`. - Sharing *ModelSourceSharingPolicy `json:"sharing,omitempty"` // What happens when the contributing client leaves. Absent means `contributingClient`. Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` - // Host-reported status. Absent means the host hasn't reported one yet. + // Host-reported status, set with {@link RootModelSourceStateChangedAction}. + // Absent until the host reports one, and after a client replaces the + // registration until the host reports again. State *ModelSourceState `json:"state,omitempty"` // Host-issued token that a client echoes in // {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - // the credential. The host changes it whenever it drops the credential - // because the registration changed, and never reuses one for the same - // `id`. Absent until the host reports a `state`. + // the credential. The host issues a new one whenever the credential is + // installed or dropped, and never reuses one for the same `id`. Set with + // `state`. CredentialNonce *string `json:"credentialNonce,omitempty"` // Additional implementation-defined metadata for this registration. // MUST NOT contain a credential. @@ -1029,12 +1018,12 @@ type ModelSourceRegistration struct { func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistration - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "credentialNonce", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "_meta") } func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistration - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "sharing", "retention", "state", "credentialNonce", "_meta") + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "_meta") } // The agent is reading and validating the definition, or listing the diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index 3b69faff5..71df45584 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -594,6 +594,21 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when } } + is StateActionRootModelSourceStateChanged -> { + val list = state.modelSourceRegistrations + val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 + if (list == null || idx < 0) { + state + } else { + val updated = list.toMutableList() + updated[idx] = updated[idx].copy( + state = action.value.state, + credentialNonce = action.value.credentialNonce, + ) + state.copy(modelSourceRegistrations = updated) + } + } + else -> state } diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 334fc82aa..94ef1e7bb 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -118,6 +118,7 @@ value class ActionType(val rawValue: String) { val ROOT_CONFIG_CHANGED: ActionType = ActionType("root/configChanged") val ROOT_MODEL_SOURCE_REGISTRATION_SET: ActionType = ActionType("root/modelSourceRegistrationSet") val ROOT_MODEL_SOURCE_REGISTRATION_REMOVED: ActionType = ActionType("root/modelSourceRegistrationRemoved") + val ROOT_MODEL_SOURCE_STATE_CHANGED: ActionType = ActionType("root/modelSourceStateChanged") val TERMINAL_DATA: ActionType = ActionType("terminal/data") val TERMINAL_INPUT: ActionType = ActionType("terminal/input") val TERMINAL_RESIZED: ActionType = ActionType("terminal/resized") @@ -1487,9 +1488,10 @@ data class RootConfigChangedAction( /** * Adds a model source registration, or replaces the one with the same `id`. * - * A client registers a source by dispatching this with its own `clientId` and - * no `state`. The host reports status by dispatching it again with the same - * registration and a `state`. + * A client registers a source by dispatching this with its own `clientId`, and + * with no `state` or `credentialNonce`. Replacing a registration clears its + * status until the host reports again with + * {@link RootModelSourceStateChangedAction}. * * Stability: 1.0 - Early development. */ @@ -1517,6 +1519,30 @@ data class RootModelSourceRegistrationRemovedAction( val id: String ) +/** + * Updates a model source registration's status and credential nonce. A no-op + * when no registration has `id`. Other fields of the registration are + * preserved. Only the host dispatches it. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class RootModelSourceStateChangedAction( + val type: ActionType, + /** + * The registration's `id`. + */ + val id: String, + /** + * The new status. + */ + val state: ModelSourceState, + /** + * The registration's current credential nonce. + */ + val credentialNonce: String +) + @Serializable data class TerminalDataAction( val type: ActionType, @@ -1890,6 +1916,7 @@ sealed interface StateAction @JvmInline value class StateActionRootConfigChanged(val value: RootConfigChangedAction) : StateAction @JvmInline value class StateActionRootModelSourceRegistrationSet(val value: RootModelSourceRegistrationSetAction) : StateAction @JvmInline value class StateActionRootModelSourceRegistrationRemoved(val value: RootModelSourceRegistrationRemovedAction) : StateAction +@JvmInline value class StateActionRootModelSourceStateChanged(val value: RootModelSourceStateChangedAction) : StateAction @JvmInline value class StateActionTerminalData(val value: TerminalDataAction) : StateAction @JvmInline value class StateActionTerminalInput(val value: TerminalInputAction) : StateAction @JvmInline value class StateActionTerminalResized(val value: TerminalResizedAction) : StateAction @@ -2015,6 +2042,7 @@ internal object StateActionSerializer : KSerializer { "root/configChanged" -> StateActionRootConfigChanged(input.json.decodeFromJsonElement(RootConfigChangedAction.serializer(), element)) "root/modelSourceRegistrationSet" -> StateActionRootModelSourceRegistrationSet(input.json.decodeFromJsonElement(RootModelSourceRegistrationSetAction.serializer(), element)) "root/modelSourceRegistrationRemoved" -> StateActionRootModelSourceRegistrationRemoved(input.json.decodeFromJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), element)) + "root/modelSourceStateChanged" -> StateActionRootModelSourceStateChanged(input.json.decodeFromJsonElement(RootModelSourceStateChangedAction.serializer(), element)) "terminal/data" -> StateActionTerminalData(input.json.decodeFromJsonElement(TerminalDataAction.serializer(), element)) "terminal/input" -> StateActionTerminalInput(input.json.decodeFromJsonElement(TerminalInputAction.serializer(), element)) "terminal/resized" -> StateActionTerminalResized(input.json.decodeFromJsonElement(TerminalResizedAction.serializer(), element)) @@ -2133,6 +2161,7 @@ internal object StateActionSerializer : KSerializer { is StateActionRootConfigChanged -> output.json.encodeToJsonElement(RootConfigChangedAction.serializer(), value.value) is StateActionRootModelSourceRegistrationSet -> output.json.encodeToJsonElement(RootModelSourceRegistrationSetAction.serializer(), value.value) is StateActionRootModelSourceRegistrationRemoved -> output.json.encodeToJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), value.value) + is StateActionRootModelSourceStateChanged -> output.json.encodeToJsonElement(RootModelSourceStateChangedAction.serializer(), value.value) is StateActionTerminalData -> output.json.encodeToJsonElement(TerminalDataAction.serializer(), value.value) is StateActionTerminalInput -> output.json.encodeToJsonElement(TerminalInputAction.serializer(), value.value) is StateActionTerminalResized -> output.json.encodeToJsonElement(TerminalResizedAction.serializer(), value.value) 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 8306b8532..bdd41c6a0 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 @@ -959,36 +959,6 @@ internal object ModelSourceStatusSerializer : KSerializer { ModelSourceStatus(decoder.decodeString()) } -/** - * Who may select a registered model source's models. - * - * Stability: 1.0 - Early development. - */ -@Serializable(with = ModelSourceSharingPolicySerializer::class) -@JvmInline -value class ModelSourceSharingPolicy(val rawValue: String) { - companion object { - /** - * Only turns and pending messages the contributing client dispatches. - */ - val CONTRIBUTING_CLIENT: ModelSourceSharingPolicy = ModelSourceSharingPolicy("contributingClient") - /** - * Any client, and work the host starts itself, such as automations. - */ - val HOST: ModelSourceSharingPolicy = ModelSourceSharingPolicy("host") - } -} - -internal object ModelSourceSharingPolicySerializer : KSerializer { - override val descriptor: SerialDescriptor = - PrimitiveSerialDescriptor("ModelSourceSharingPolicy", PrimitiveKind.STRING) - override fun serialize(encoder: Encoder, value: ModelSourceSharingPolicy) { - encoder.encodeString(value.rawValue) - } - override fun deserialize(decoder: Decoder): ModelSourceSharingPolicy = - ModelSourceSharingPolicy(decoder.decodeString()) -} - /** * How long a registered model source lasts once its contributing client leaves. * @@ -1861,27 +1831,26 @@ data class ModelSourceRegistration( */ val definition: Map, /** - * The contributing client. Absent for a source the host registered itself. + * The contributing client: the client that most recently registered or + * changed the source. Absent for a source the host registered itself. */ val clientId: String? = null, - /** - * Who may select the source's models. Absent means `contributingClient`. - */ - val sharing: ModelSourceSharingPolicy? = null, /** * What happens when the contributing client leaves. Absent means `contributingClient`. */ val retention: ModelSourceRetentionPolicy? = null, /** - * Host-reported status. Absent means the host hasn't reported one yet. + * Host-reported status, set with {@link RootModelSourceStateChangedAction}. + * Absent until the host reports one, and after a client replaces the + * registration until the host reports again. */ val state: ModelSourceState? = null, /** * Host-issued token that a client echoes in * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential. The host changes it whenever it drops the credential - * because the registration changed, and never reuses one for the same - * `id`. Absent until the host reports a `state`. + * the credential. The host issues a new one whenever the credential is + * installed or dropped, and never reuses one for the same `id`. Set with + * `state`. */ val credentialNonce: String? = null, /** diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 22069a6f3..970119aa7 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -20,11 +20,11 @@ use crate::state::{ ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ChatSummary, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, Message, - ModelSelection, ModelSourceRegistration, PendingMessageKind, ResponsePart, SessionActiveClient, - SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, - TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributor, - ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, ToolResultContent, Turn, - UsageInfo, + ModelSelection, ModelSourceRegistration, ModelSourceState, PendingMessageKind, ResponsePart, + SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, + TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, + ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, + ToolResultContent, Turn, UsageInfo, }; // ─── ActionType ────────────────────────────────────────────────────── @@ -121,6 +121,7 @@ pub enum ActionType { RootConfigChanged, RootModelSourceRegistrationSet, RootModelSourceRegistrationRemoved, + RootModelSourceStateChanged, TerminalData, TerminalInput, TerminalResized, @@ -295,6 +296,9 @@ impl serde::Serialize for ActionType { Self::RootModelSourceRegistrationRemoved => { serializer.serialize_str("root/modelSourceRegistrationRemoved") } + Self::RootModelSourceStateChanged => { + serializer.serialize_str("root/modelSourceStateChanged") + } Self::TerminalData => serializer.serialize_str("terminal/data"), Self::TerminalInput => serializer.serialize_str("terminal/input"), Self::TerminalResized => serializer.serialize_str("terminal/resized"), @@ -431,6 +435,7 @@ impl<'de> serde::Deserialize<'de> for ActionType { "root/configChanged" => Self::RootConfigChanged, "root/modelSourceRegistrationSet" => Self::RootModelSourceRegistrationSet, "root/modelSourceRegistrationRemoved" => Self::RootModelSourceRegistrationRemoved, + "root/modelSourceStateChanged" => Self::RootModelSourceStateChanged, "terminal/data" => Self::TerminalData, "terminal/input" => Self::TerminalInput, "terminal/resized" => Self::TerminalResized, @@ -521,9 +526,10 @@ pub struct RootConfigChangedAction { /// Adds a model source registration, or replaces the one with the same `id`. /// -/// A client registers a source by dispatching this with its own `clientId` and -/// no `state`. The host reports status by dispatching it again with the same -/// registration and a `state`. +/// A client registers a source by dispatching this with its own `clientId`, and +/// with no `state` or `credentialNonce`. Replacing a registration clears its +/// status until the host reports again with +/// {@link RootModelSourceStateChangedAction}. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -544,6 +550,22 @@ pub struct RootModelSourceRegistrationRemovedAction { pub id: String, } +/// Updates a model source registration's status and credential nonce. A no-op +/// when no registration has `id`. Other fields of the registration are +/// preserved. Only the host dispatches it. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RootModelSourceStateChangedAction { + /// The registration's `id`. + pub id: String, + /// The new status. + pub state: ModelSourceState, + /// The registration's current credential nonce. + pub credential_nonce: String, +} + /// Session backend initialized successfully. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2495,6 +2517,8 @@ pub enum StateAction { RootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction), #[serde(rename = "root/modelSourceRegistrationRemoved")] RootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction), + #[serde(rename = "root/modelSourceStateChanged")] + RootModelSourceStateChanged(RootModelSourceStateChangedAction), #[serde(rename = "session/ready")] SessionReady(SessionReadyAction), #[serde(rename = "session/creationFailed")] diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 3982fd39c..c13005ed5 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1215,46 +1215,6 @@ impl<'de> serde::Deserialize<'de> for ModelSourceStatus { } } -/// Who may select a registered model source's models. -/// -/// Stability: 1.0 - Early development. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub enum ModelSourceSharingPolicy { - /// Only turns and pending messages the contributing client dispatches. - ContributingClient, - /// Any client, and work the host starts itself, such as automations. - Host, - /// Unknown raw value from a newer protocol version, preserved verbatim. - Unknown(String), -} - -impl serde::Serialize for ModelSourceSharingPolicy { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - match self { - Self::ContributingClient => serializer.serialize_str("contributingClient"), - Self::Host => serializer.serialize_str("host"), - Self::Unknown(value) => serializer.serialize_str(value), - } - } -} - -impl<'de> serde::Deserialize<'de> for ModelSourceSharingPolicy { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let raw = ::deserialize(deserializer)?; - Ok(match raw.as_str() { - "contributingClient" => Self::ContributingClient, - "host" => Self::Host, - _ => Self::Unknown(raw), - }) - } -} - /// How long a registered model source lasts once its contributing client leaves. /// /// Stability: 1.0 - Early development. @@ -2190,23 +2150,23 @@ pub struct ModelSourceRegistration { /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain /// a credential. pub definition: JsonObject, - /// The contributing client. Absent for a source the host registered itself. + /// The contributing client: the client that most recently registered or + /// changed the source. Absent for a source the host registered itself. #[serde(default, skip_serializing_if = "Option::is_none")] pub client_id: Option, - /// Who may select the source's models. Absent means `contributingClient`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub sharing: Option, /// What happens when the contributing client leaves. Absent means `contributingClient`. #[serde(default, skip_serializing_if = "Option::is_none")] pub retention: Option, - /// Host-reported status. Absent means the host hasn't reported one yet. + /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. + /// Absent until the host reports one, and after a client replaces the + /// registration until the host reports again. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential. The host changes it whenever it drops the credential - /// because the registration changed, and never reuses one for the same - /// `id`. Absent until the host reports a `state`. + /// the credential. The host issues a new one whenever the credential is + /// installed or dropped, and never reuses one for the same `id`. Set with + /// `state`. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_nonce: Option, /// Additional implementation-defined metadata for this registration. diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 5c88cc0b9..1012f58aa 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -740,6 +740,18 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu list.remove(idx); ReduceOutcome::Applied } + StateAction::RootModelSourceStateChanged(a) => { + let Some(registration) = state + .model_source_registrations + .as_mut() + .and_then(|list| list.iter_mut().find(|r| r.id == a.id)) + else { + return ReduceOutcome::NoOp; + }; + registration.state = Some(a.state.clone()); + registration.credential_nonce = Some(a.credential_nonce.clone()); + ReduceOutcome::Applied + } _ => ReduceOutcome::OutOfScope, } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index d6c7858a5..89e051488 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -95,6 +95,7 @@ public enum ActionType: Codable, Sendable, Equatable { case rootConfigChanged case rootModelSourceRegistrationSet case rootModelSourceRegistrationRemoved + case rootModelSourceStateChanged case terminalData case terminalInput case terminalResized @@ -212,6 +213,7 @@ public enum ActionType: Codable, Sendable, Equatable { case "root/configChanged": self = .rootConfigChanged case "root/modelSourceRegistrationSet": self = .rootModelSourceRegistrationSet case "root/modelSourceRegistrationRemoved": self = .rootModelSourceRegistrationRemoved + case "root/modelSourceStateChanged": self = .rootModelSourceStateChanged case "terminal/data": self = .terminalData case "terminal/input": self = .terminalInput case "terminal/resized": self = .terminalResized @@ -329,6 +331,7 @@ public enum ActionType: Codable, Sendable, Equatable { case .rootConfigChanged: try container.encode("root/configChanged") case .rootModelSourceRegistrationSet: try container.encode("root/modelSourceRegistrationSet") case .rootModelSourceRegistrationRemoved: try container.encode("root/modelSourceRegistrationRemoved") + case .rootModelSourceStateChanged: try container.encode("root/modelSourceStateChanged") case .terminalData: try container.encode("terminal/data") case .terminalInput: try container.encode("terminal/input") case .terminalResized: try container.encode("terminal/resized") @@ -2289,9 +2292,10 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { /// Adds a model source registration, or replaces the one with the same `id`. /// -/// A client registers a source by dispatching this with its own `clientId` and -/// no `state`. The host reports status by dispatching it again with the same -/// registration and a `state`. +/// A client registers a source by dispatching this with its own `clientId`, and +/// with no `state` or `credentialNonce`. Replacing a registration clears its +/// status until the host reports again with +/// {@link RootModelSourceStateChangedAction}. /// /// Stability: 1.0 - Early development. public struct RootModelSourceRegistrationSetAction: Codable, Sendable, Equatable { @@ -2326,6 +2330,33 @@ public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equat } } +/// Updates a model source registration's status and credential nonce. A no-op +/// when no registration has `id`. Other fields of the registration are +/// preserved. Only the host dispatches it. +/// +/// Stability: 1.0 - Early development. +public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The registration's `id`. + public var id: String + /// The new status. + public var state: ModelSourceState + /// The registration's current credential nonce. + public var credentialNonce: String + + public init( + type: ActionType, + id: String, + state: ModelSourceState, + credentialNonce: String + ) { + self.type = type + self.id = id + self.state = state + self.credentialNonce = credentialNonce + } +} + public struct TerminalDataAction: Codable, Sendable, Equatable { public var type: ActionType /// Output data (may contain ANSI escape sequences) @@ -2797,6 +2828,7 @@ public enum StateAction: Codable, Sendable, Equatable { case rootConfigChanged(RootConfigChangedAction) case rootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction) case rootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction) + case rootModelSourceStateChanged(RootModelSourceStateChangedAction) case terminalData(TerminalDataAction) case terminalInput(TerminalInputAction) case terminalResized(TerminalResizedAction) @@ -3008,6 +3040,8 @@ public enum StateAction: Codable, Sendable, Equatable { self = .rootModelSourceRegistrationSet(try RootModelSourceRegistrationSetAction(from: decoder)) case "root/modelSourceRegistrationRemoved": self = .rootModelSourceRegistrationRemoved(try RootModelSourceRegistrationRemovedAction(from: decoder)) + case "root/modelSourceStateChanged": + self = .rootModelSourceStateChanged(try RootModelSourceStateChangedAction(from: decoder)) case "terminal/data": self = .terminalData(try TerminalDataAction(from: decoder)) case "terminal/input": @@ -3146,6 +3180,7 @@ public enum StateAction: Codable, Sendable, Equatable { case .rootConfigChanged(let v): try v.encode(to: encoder) case .rootModelSourceRegistrationSet(let v): try v.encode(to: encoder) case .rootModelSourceRegistrationRemoved(let v): try v.encode(to: encoder) + case .rootModelSourceStateChanged(let v): try v.encode(to: encoder) case .terminalData(let v): try v.encode(to: encoder) case .terminalInput(let v): try v.encode(to: encoder) case .terminalResized(let v): try v.encode(to: encoder) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 9dbd18a4f..4675039d8 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -939,37 +939,6 @@ public enum ModelSourceStatus: Codable, Sendable, Equatable { } } -/// Who may select a registered model source's models. -/// -/// Stability: 1.0 - Early development. -public enum ModelSourceSharingPolicy: Codable, Sendable, Equatable { - /// Only turns and pending messages the contributing client dispatches. - case contributingClient - /// Any client, and work the host starts itself, such as automations. - case host - /// Unknown raw value from a newer protocol version, preserved verbatim. - case unknown(String) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - let raw = try container.decode(String.self) - switch raw { - case "contributingClient": self = .contributingClient - case "host": self = .host - default: self = .unknown(raw) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .contributingClient: try container.encode("contributingClient") - case .host: try container.encode("host") - case .unknown(let raw): try container.encode(raw) - } - } -} - /// How long a registered model source lasts once its contributing client leaves. /// /// Stability: 1.0 - Early development. @@ -1860,19 +1829,20 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain /// a credential. public var definition: [String: AnyCodable] - /// The contributing client. Absent for a source the host registered itself. + /// The contributing client: the client that most recently registered or + /// changed the source. Absent for a source the host registered itself. public var clientId: String? - /// Who may select the source's models. Absent means `contributingClient`. - public var sharing: ModelSourceSharingPolicy? /// What happens when the contributing client leaves. Absent means `contributingClient`. public var retention: ModelSourceRetentionPolicy? - /// Host-reported status. Absent means the host hasn't reported one yet. + /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. + /// Absent until the host reports one, and after a client replaces the + /// registration until the host reports again. public var state: ModelSourceState? /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential. The host changes it whenever it drops the credential - /// because the registration changed, and never reuses one for the same - /// `id`. Absent until the host reports a `state`. + /// the credential. The host issues a new one whenever the credential is + /// installed or dropped, and never reuses one for the same `id`. Set with + /// `state`. public var credentialNonce: String? /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. @@ -1888,7 +1858,6 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { case format case definition case clientId - case sharing case retention case state case credentialNonce @@ -1903,7 +1872,6 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { format: String, definition: [String: AnyCodable], clientId: String? = nil, - sharing: ModelSourceSharingPolicy? = nil, retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, credentialNonce: String? = nil, @@ -1917,7 +1885,6 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.format = format self.definition = definition self.clientId = clientId - self.sharing = sharing self.retention = retention self.state = state self.credentialNonce = credentialNonce @@ -1934,7 +1901,6 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.format = try container.decode(String.self, forKey: .format) self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) self.clientId = try container.decodeIfPresent(String.self, forKey: .clientId) - self.sharing = try container.decodeIfPresent(ModelSourceSharingPolicy.self, forKey: .sharing) self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) self.credentialNonce = try container.decodeIfPresent(String.self, forKey: .credentialNonce) @@ -1951,7 +1917,6 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { try container.encode(self.format, forKey: .format) try container.encode(self.definition, forKey: .definition) try container.encodeIfPresent(self.clientId, forKey: .clientId) - try container.encodeIfPresent(self.sharing, forKey: .sharing) try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) try container.encodeIfPresent(self.credentialNonce, forKey: .credentialNonce) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index c02b46ccb..f300f1294 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -109,6 +109,9 @@ public struct AHPRootReducer: Reducer { case .rootModelSourceRegistrationRemoved(let a): _ = applyModelSourceRegistrationRemoved(&state, id: a.id) + case .rootModelSourceStateChanged(let a): + _ = applyModelSourceStateChanged(&state, a) + default: break } @@ -135,6 +138,17 @@ func applyModelSourceRegistrationRemoved(_ state: inout RootState, id: String) - return true } +/// Updates the status and credential nonce of the registration with `action.id`. +/// Returns `false` when none matches. +func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelSourceStateChangedAction) -> Bool { + guard var list = state.modelSourceRegistrations, + let idx = list.firstIndex(where: { $0.id == action.id }) else { return false } + list[idx].state = action.state + list[idx].credentialNonce = action.credentialNonce + state.modelSourceRegistrations = list + return true +} + // MARK: - Chat Reducer (Protocol-based) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index 1093bf056..324f4ab3c 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -132,6 +132,11 @@ public func rootReducer(state: RootState, action: StateAction) -> RootState { guard applyModelSourceRegistrationRemoved(&next, id: a.id) else { return state } return next + case .rootModelSourceStateChanged(let a): + var next = state + guard applyModelSourceStateChanged(&next, a) else { return state } + return next + default: return state } diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index b96803439..badee8069 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions, and deliver each source's credential with a `modelSource` `authenticate` target that echoes the registration's host-issued `credentialNonce`. Agents advertise the definition formats they read with `AgentCapabilities.modelSourceRegistration`.", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions, and deliver each source's credential with a `modelSource` `authenticate` target that echoes the registration's host-issued `credentialNonce`. The host reports each registration's status with the host-only `root/modelSourceStateChanged` action. Agents advertise the definition formats they read with `AgentCapabilities.modelSourceRegistration`.", "issues": [619] } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index d9b03501c..f69e56123 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -23,7 +23,7 @@ Individual action payloads do **not** carry their own `session: URI` or `termina ## Root Actions -These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged` and the model source registry actions are client-dispatchable; the rest are server-originated. +These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceRegistrationSet`, and `root/modelSourceRegistrationRemoved` are client-dispatchable; the rest are server-originated. | Type | Client-dispatchable? | When | |---|---|---| @@ -33,6 +33,7 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/configChanged` | **Yes** | Host-level configuration values changed | | `root/modelSourceRegistrationSet` | **Yes** | A [model source registration](/specification/root-channel#model-source-registry) was added, or replaced by `id` | | `root/modelSourceRegistrationRemoved` | **Yes** | A model source registration was removed by `id` | +| `root/modelSourceStateChanged` | No | The host reported a registration's status and credential nonce | ## Automation Catalogue Actions diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index 999047fa7..ba1a50228 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -181,16 +181,23 @@ When `target.kind` is `modelSource`, the host: - MUST require `resource` to equal the `resource.resource` it most recently advertised for that registration; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); - MUST reject a `credentialNonce` other than the one it most recently issued for that registration with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; -- MUST reject a credential, including an empty `token` that would revoke one, from a client that may not supply one, with `PermissionDenied` (`-32009`). The contributing client may always supply one. For a registration with `host` sharing, or one the host registered, any client the host allows may supply one; - MUST treat an empty `token` as revocation: it drops the credential, and the source returns to `authRequired` with `reason: expired`, so no client sends the revoked secret again. -`credentialNonce` keeps a delayed `authenticate` from reaching a definition it wasn't meant for: a key sent for an old definition with the same endpoint would otherwise still match the `id` and `resource`. The host issues a new nonce whenever it drops the credential because the registration changed, including when a removed registration is registered again under the same `id`, and never reuses one for the same `id`. It keeps the nonce across rotation, expiry, and revocation. +Any client may deliver or revoke a registration's credential, as any client may answer an MCP server's challenge. -The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition` or `_meta`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. The host drops the credential when the registration is removed, when its `provider`, `format`, `definition`, or contributing client changes, and when the host restarts. +`credentialNonce` fences every credential change. The host issues a new nonce whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation, and when a change to `provider`, `format`, or `definition` drops it. That includes a removed registration that's registered again under the same `id`, and the host never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: -The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, but MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has taken over. +- a key meant for an old definition never reaches a new one, even when the endpoint didn't change; +- a rotation that crosses a revocation can't undo the revocation; +- when two clients answer the same `authRequired`, the first wins, and the second gets `Conflict`, re-reads state, and finds the source ready. -If the credential fails during a turn that uses the source, the host SHOULD end the turn with a resumable error (`chat/error` with `part.resumable: true`) rather than wait. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first, including the sharing policy. The host never switches the turn to a different model. +The host also tags each request with the nonce of the key it used, and ignores a failure from a request made with an older key, so a late failure can't drop a key that has since replaced it. + +The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition` or `_meta`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. The host drops the credential when the registration is removed, when its `provider`, `format`, or `definition` changes, and when the host restarts. + +The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, but MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. + +If the credential fails during a turn that uses the source, the host SHOULD end the turn with a resumable error (`chat/error` with `part.resumable: true`) rather than wait. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first. The host never switches the turn to a different model. ### Why keyed by `resource` and optional `target`? diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index 6471c9605..856c3b77e 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -73,7 +73,6 @@ Clients can register bring-your-own-key model sources with the host, so its agen "format": "example.com/model-source@1", "definition": { "baseUrl": "https://openrouter.ai/api/v1" }, "clientId": "laptop", - "sharing": "host", "retention": "host", "state": { "kind": "ready" }, "credentialNonce": "9b41d7" @@ -84,48 +83,49 @@ Clients can register bring-your-own-key model sources with the host, so its agen #### Registering -A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId`, and with no `state` or `credentialNonce`. It removes one with `root/modelSourceRegistrationRemoved`. The host reports status by dispatching `Set` again with a `state` (`starting`, `ready`, `authRequired`, or `error`) and a `credentialNonce`. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed, because doing so clears the reported state. - -The host builds each status `Set` from the registration as it currently stands. It discards an agent result for a definition the registration no longer has, and never dispatches a status `Set` for a removed registration, so a late result can't undo a client's change or bring back a removed source. - -A client may change or remove a registration when it's the contributing client, or when the registration has `host` sharing, which lets another of the user's clients take it over. It may not change one that belongs to another client with `contributingClient` sharing, or one the host registered, unless host policy allows it. +A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId`, and with no `state` or `credentialNonce`. It removes one with `root/modelSourceRegistrationRemoved`. Like MCP servers, registrations have no per-client ownership: any client can change or remove any registration, and the client that changes one becomes its contributing client. A host MAY reject client changes to a registration it created itself. The host rejects a client's `Set`, through `rejectionReason`, when: - the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; - `clientId` isn't the dispatching client's ID, or `state` or `credentialNonce` is present; - `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same registration doesn't count, so a ready registration can still be updated; -- a registration with this `id` already exists, and the dispatching client may not change it; -- the host won't honor the requested `sharing` or `retention`. The client can register again with a narrower policy. +- the host won't honor the requested `retention`. The client can register again with `contributingClient` retention. + +A client's `Removed` is a no-op when no registration has that `id`. + +When a `Set` changes a registration's `provider`, `format`, or `definition`, the host drops its credential, and the source goes back through `starting`. A change to `name`, `icons`, `clientId`, or `retention` keeps the credential. A host may also register sources itself. Those registrations have no `clientId`, and their retention behaves as `host`. + +#### Status -A client's `Removed` is a no-op when no registration has that `id`. Otherwise the host rejects it only when the dispatching client may not change that registration. The registration's state, policies, and catalog entry don't affect removal. +The host reports status with `root/modelSourceStateChanged`, which sets a registration's `state` (`starting`, `ready`, `authRequired`, or `error`) and its `credentialNonce`, as `session/mcpServerStateChanged` does for MCP servers. It never reports status by dispatching the registration back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed registration or overwrite a newer definition. The host also discards an agent result for a definition the registration no longer has. -When a `Set` changes a registration's `provider`, `format`, `definition`, or `clientId`, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A host may also register sources itself. Those registrations have no `clientId`, and both policies behave as `host`. +A client's `Set` replaces the whole registration, so it clears the status until the host reports again. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed. #### Catalog When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `name`, and its models in `models` with `modelSourceId` set to that `id`. The host lists the models only while the registration is `ready`. It MAY list the `ModelSourceInfo` in other states. -The host checks every selection of a registered source's model: the model is listed, the chat is backed by the registration's agent provider, and the sharing policy allows it. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. +Any client can select a registered source's models, in any session whose agent is the registration's `provider`. The host checks every selection: the model is listed, and the chat is backed by the registration's agent provider. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. -#### Sharing and retention +#### Retention -The contributing client chooses two policies. Absent means `contributingClient`, the narrowest choice. +The contributing client chooses what happens when it leaves. Absent means `contributingClient`, the narrower choice. -- **Sharing.** With `contributingClient`, only turns and pending messages that client dispatches may select the source's models. With `host`, any client may, and so may work the host starts itself, such as automations. -- **Retention.** With `contributingClient`, the source is removed when its client leaves: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the registration and drops its credential. With `host`, the registration and its in-memory credential stay until a client removes it, host policy expires it, or the host restarts. +- With `contributingClient`, the source goes away with its client, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the registration and drops its credential. +- With `host`, the source stays, like a host-declared MCP server, with its credential in memory, until a client removes it, host policy expires it, or the host restarts. -The host never widens a policy, and it MAY expire `host`-retained registrations. Every client sees every registration, so clients SHOULD offer only the models they may select, using `sharing` and `clientId`. +The host MAY expire `host`-retained registrations. Every client sees every registration, including its definition, which suits hosts whose connected clients all belong to one user. -A client that reconnects with the same `clientId` within the host's grace period keeps its registrations. A client that comes back with a new `clientId` registers again under the same `id`. For a `host`-shared registration, that takes it over: `clientId` changes, the credential is dropped, and the new contributing client supplies it. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back through `starting`, and reach `authRequired` only if they need a credential. +A client that reconnects with the same `clientId` within the host's grace period keeps its registrations. A client that comes back with a new `clientId` and the same configuration registers again under the same `id`, which makes it the contributing client and keeps the credential. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back through `starting`, and reach `authRequired` only if they need a credential. #### Reserved model IDs -Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a `definition` change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when another client has taken the registration over. A host can meet this by minting IDs it never reuses, for example with a random component. +Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a `definition` change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when a different client made the change. A host can meet this by minting IDs it never reuses, for example with a random component. #### Automations -An automation may name a registered source's model when the registration has `host` sharing and `host` retention, or was registered by the host. The host SHOULD reject an automation create or update that names any other registration's model. If the source isn't `ready` when a run starts, the run fails through the automation run lifecycle. +An automation may name a registered source's model when the registration has `host` retention, or was registered by the host. The host SHOULD reject an automation create or update that names a model from a `contributingClient`-retained registration, because the automation would outlive the source. If the source isn't `ready` when a run starts, the run fails through the automation run lifecycle. ### Paginating the catalogue @@ -195,6 +195,7 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | | `root/modelSourceRegistrationSet` | Server / Client | Adds or replaces a registration in `modelSourceRegistrations` by `id` | | `root/modelSourceRegistrationRemoved` | Server / Client | Removes a registration by `id` | +| `root/modelSourceStateChanged` | Server | Sets a registration's `state` and `credentialNonce`. A no-op for an unknown `id` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 43260cce6..f8da27746 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -129,7 +129,7 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId` and\nno `state`. The host reports status by dispatching it again with the same\nregistration and a `state`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state` or `credentialNonce`. Replacing a registration clears its\nstatus until the host reports again with\n{@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" @@ -161,6 +161,33 @@ "id" ] }, + "RootModelSourceStateChangedAction": { + "type": "object", + "description": "Updates a model source registration's status and credential nonce. A no-op\nwhen no registration has `id`. Other fields of the registration are\npreserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceStateChanged" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "The new status." + }, + "credentialNonce": { + "type": "string", + "description": "The registration's current credential nonce." + } + }, + "required": [ + "type", + "id", + "state", + "credentialNonce" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -3580,11 +3607,7 @@ }, "clientId": { "type": "string", - "description": "The contributing client. Absent for a source the host registered itself." - }, - "sharing": { - "$ref": "#/$defs/ModelSourceSharingPolicy", - "description": "Who may select the source's models. Absent means `contributingClient`." + "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -3592,11 +3615,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status. Absent means the host hasn't reported one yet." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." }, "_meta": { "type": "object", @@ -9720,6 +9743,9 @@ { "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" }, + { + "$ref": "#/$defs/RootModelSourceStateChangedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -10117,14 +10143,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceSharingPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "Who may select a registered model source's models." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index b60182a70..e2f22d68e 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -2935,11 +2935,7 @@ }, "clientId": { "type": "string", - "description": "The contributing client. Absent for a source the host registered itself." - }, - "sharing": { - "$ref": "#/$defs/ModelSourceSharingPolicy", - "description": "Who may select the source's models. Absent means `contributingClient`." + "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -2947,11 +2943,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status. Absent means the host hasn't reported one yet." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." }, "_meta": { "type": "object", @@ -8577,7 +8573,7 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId` and\nno `state`. The host reports status by dispatching it again with the same\nregistration and a `state`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state` or `credentialNonce`. Replacing a registration clears its\nstatus until the host reports again with\n{@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" @@ -8609,6 +8605,33 @@ "id" ] }, + "RootModelSourceStateChangedAction": { + "type": "object", + "description": "Updates a model source registration's status and credential nonce. A no-op\nwhen no registration has `id`. Other fields of the registration are\npreserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceStateChanged" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "The new status." + }, + "credentialNonce": { + "type": "string", + "description": "The registration's current credential nonce." + } + }, + "required": [ + "type", + "id", + "state", + "credentialNonce" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -11107,6 +11130,9 @@ { "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" }, + { + "$ref": "#/$defs/RootModelSourceStateChangedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -11554,14 +11580,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceSharingPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "Who may select a registered model source's models." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 787754594..b29b9295f 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -915,11 +915,7 @@ }, "clientId": { "type": "string", - "description": "The contributing client. Absent for a source the host registered itself." - }, - "sharing": { - "$ref": "#/$defs/ModelSourceSharingPolicy", - "description": "Who may select the source's models. Absent means `contributingClient`." + "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -927,11 +923,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status. Absent means the host hasn't reported one yet." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." }, "_meta": { "type": "object", @@ -8492,14 +8488,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceSharingPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "Who may select a registered model source's models." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", @@ -9305,6 +9293,9 @@ { "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" }, + { + "$ref": "#/$defs/RootModelSourceStateChangedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -9842,7 +9833,7 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId` and\nno `state`. The host reports status by dispatching it again with the same\nregistration and a `state`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state` or `credentialNonce`. Replacing a registration clears its\nstatus until the host reports again with\n{@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" @@ -9874,6 +9865,33 @@ "id" ] }, + "RootModelSourceStateChangedAction": { + "type": "object", + "description": "Updates a model source registration's status and credential nonce. A no-op\nwhen no registration has `id`. Other fields of the registration are\npreserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceStateChanged" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "description": "The new status." + }, + "credentialNonce": { + "type": "string", + "description": "The registration's current credential nonce." + } + }, + "required": [ + "type", + "id", + "state", + "credentialNonce" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 4f55d7b20..7ff39ae35 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1217,11 +1217,7 @@ }, "clientId": { "type": "string", - "description": "The contributing client. Absent for a source the host registered itself." - }, - "sharing": { - "$ref": "#/$defs/ModelSourceSharingPolicy", - "description": "Who may select the source's models. Absent means `contributingClient`." + "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -1229,11 +1225,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status. Absent means the host hasn't reported one yet." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." }, "_meta": { "type": "object", @@ -6806,14 +6802,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceSharingPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "Who may select a registered model source's models." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/schema/state.schema.json b/schema/state.schema.json index 88fad496a..579745b34 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -826,11 +826,7 @@ }, "clientId": { "type": "string", - "description": "The contributing client. Absent for a source the host registered itself." - }, - "sharing": { - "$ref": "#/$defs/ModelSourceSharingPolicy", - "description": "Who may select the source's models. Absent means `contributingClient`." + "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -838,11 +834,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status. Absent means the host hasn't reported one yet." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host changes it whenever it drops the credential\nbecause the registration changed, and never reuses one for the same\n`id`. Absent until the host reports a `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." }, "_meta": { "type": "object", @@ -6967,14 +6963,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceSharingPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "Who may select a registered model source's models." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index 96f137134..d5f428e60 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -773,7 +773,7 @@ const STATE_ENUMS = [ 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', 'AutomationDisableConditionKind', @@ -1680,6 +1680,7 @@ const ACTION_VARIANTS: { type: string; variantName: string; tsInterface: string { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, // Session turn/tool-call/error/usage/reasoning actions have no TypeScript interfaces in diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index dbd125b4a..c1a582da3 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -758,7 +758,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1661,6 +1661,7 @@ const ACTION_VARIANTS: { { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, { type: 'session/chatAdded', variantName: 'SessionChatAdded', tsInterface: 'SessionChatAddedAction' }, diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index 2f5020712..aee14c9a9 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1012,7 +1012,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1661,6 +1661,7 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'root/configChanged', caseName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', caseName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, { type: 'root/modelSourceRegistrationRemoved', caseName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceStateChanged', caseName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'terminal/data', caseName: 'TerminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'TerminalInput', tsInterface: 'TerminalInputAction' }, { type: 'terminal/resized', caseName: 'TerminalResized', tsInterface: 'TerminalResizedAction' }, diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index f2ad9a405..1434bd586 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -854,7 +854,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1655,6 +1655,7 @@ const ACTION_VARIANTS: { { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, { type: 'session/chatAdded', variantName: 'SessionChatAdded', tsInterface: 'SessionChatAddedAction' }, @@ -1837,7 +1838,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSourceRegistration, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSourceRegistration, ModelSourceState, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 77eaa9809..c34d6e6c3 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -735,7 +735,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceSharingPolicy', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1571,6 +1571,7 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'root/configChanged', caseName: 'rootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', caseName: 'rootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, { type: 'root/modelSourceRegistrationRemoved', caseName: 'rootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceStateChanged', caseName: 'rootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'terminal/data', caseName: 'terminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'terminalInput', tsInterface: 'TerminalInputAction' }, { type: 'terminal/resized', caseName: 'terminalResized', tsInterface: 'TerminalResizedAction' }, diff --git a/types/action-origin.generated.ts b/types/action-origin.generated.ts index 91c83192c..16d5a810d 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -9,6 +9,7 @@ import type { RootConfigChangedAction, RootModelSourceRegistrationSetAction, RootModelSourceRegistrationRemovedAction, + RootModelSourceStateChangedAction, SessionReadyAction, SessionCreationFailedAction, SessionChatAddedAction, @@ -127,6 +128,7 @@ export type RootAction = | RootConfigChangedAction | RootModelSourceRegistrationSetAction | RootModelSourceRegistrationRemovedAction + | RootModelSourceStateChangedAction ; /** Union of root actions that clients may dispatch. */ @@ -141,6 +143,7 @@ export type ServerRootAction = | RootAgentsChangedAction | RootActiveSessionsChangedAction | RootTerminalsChangedAction + | RootModelSourceStateChangedAction ; /** Union of all session-scoped actions. */ @@ -475,6 +478,7 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.RootConfigChanged]: true, [ActionType.RootModelSourceRegistrationSet]: true, [ActionType.RootModelSourceRegistrationRemoved]: true, + [ActionType.RootModelSourceStateChanged]: false, [ActionType.SessionReady]: false, [ActionType.SessionCreationFailed]: false, [ActionType.SessionChatAdded]: false, diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 619b47f69..bf77e6a7f 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -4,7 +4,7 @@ * @module channels-root/actions */ -import type { AgentInfo, ModelSourceRegistration } from './state.js'; +import type { AgentInfo, ModelSourceRegistration, ModelSourceState } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import { ActionType } from '../common/actions.js'; @@ -70,9 +70,10 @@ export interface RootConfigChangedAction { /** * Adds a model source registration, or replaces the one with the same `id`. * - * A client registers a source by dispatching this with its own `clientId` and - * no `state`. The host reports status by dispatching it again with the same - * registration and a `state`. + * A client registers a source by dispatching this with its own `clientId`, and + * with no `state` or `credentialNonce`. Replacing a registration clears its + * status until the host reports again with + * {@link RootModelSourceStateChangedAction}. * * @category Root Actions * @stability 1.0 @@ -99,3 +100,22 @@ export interface RootModelSourceRegistrationRemovedAction { /** The registration's `id`. */ id: string; } + +/** + * Updates a model source registration's status and credential nonce. A no-op + * when no registration has `id`. Other fields of the registration are + * preserved. Only the host dispatches it. + * + * @category Root Actions + * @stability 1.0 + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ +export interface RootModelSourceStateChangedAction { + type: ActionType.RootModelSourceStateChanged; + /** The registration's `id`. */ + id: string; + /** The new status. */ + state: ModelSourceState; + /** The registration's current credential nonce. */ + credentialNonce: string; +} diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index 5ac2d62ca..4e85299f8 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -61,6 +61,20 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st return { ...state, modelSourceRegistrations: next }; } + case ActionType.RootModelSourceStateChanged: { + const list = state.modelSourceRegistrations; + if (!list) { + return state; + } + const idx = list.findIndex(r => r.id === action.id); + if (idx < 0) { + return state; + } + const next = list.slice(); + next[idx] = { ...list[idx], state: action.state, credentialNonce: action.credentialNonce }; + return { ...state, modelSourceRegistrations: next }; + } + default: softAssertNever(action, log); return state; diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 9bf58133f..db5c80630 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -366,20 +366,25 @@ export interface ModelSourceRegistration { * a credential. */ definition: Record; - /** The contributing client. Absent for a source the host registered itself. */ + /** + * The contributing client: the client that most recently registered or + * changed the source. Absent for a source the host registered itself. + */ clientId?: string; - /** Who may select the source's models. Absent means `contributingClient`. */ - sharing?: ModelSourceSharingPolicy; /** What happens when the contributing client leaves. Absent means `contributingClient`. */ retention?: ModelSourceRetentionPolicy; - /** Host-reported status. Absent means the host hasn't reported one yet. */ + /** + * Host-reported status, set with {@link RootModelSourceStateChangedAction}. + * Absent until the host reports one, and after a client replaces the + * registration until the host reports again. + */ state?: ModelSourceState; /** * Host-issued token that a client echoes in * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential. The host changes it whenever it drops the credential - * because the registration changed, and never reuses one for the same - * `id`. Absent until the host reports a `state`. + * the credential. The host issues a new one whenever the credential is + * installed or dropped, and never reuses one for the same `id`. Set with + * `state`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ @@ -391,20 +396,6 @@ export interface ModelSourceRegistration { _meta?: Record; } -/** - * Who may select a registered model source's models. - * - * @category Root State - * @stability 1.0 - * @nonexhaustive - */ -export const enum ModelSourceSharingPolicy { - /** Only turns and pending messages the contributing client dispatches. */ - ContributingClient = 'contributingClient', - /** Any client, and work the host starts itself, such as automations. */ - Host = 'host', -} - /** * How long a registered model source lasts once its contributing client leaves. * diff --git a/types/common/actions.ts b/types/common/actions.ts index 3cd9b0fa5..3769be11e 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -15,6 +15,7 @@ import type { RootConfigChangedAction, RootModelSourceRegistrationSetAction, RootModelSourceRegistrationRemovedAction, + RootModelSourceStateChangedAction, } from '../channels-root/actions.js'; import type { @@ -244,6 +245,7 @@ export const enum ActionType { RootConfigChanged = 'root/configChanged', RootModelSourceRegistrationSet = 'root/modelSourceRegistrationSet', RootModelSourceRegistrationRemoved = 'root/modelSourceRegistrationRemoved', + RootModelSourceStateChanged = 'root/modelSourceStateChanged', TerminalData = 'terminal/data', TerminalInput = 'terminal/input', TerminalResized = 'terminal/resized', @@ -307,6 +309,7 @@ export type StateAction = | RootConfigChangedAction | RootModelSourceRegistrationSetAction | RootModelSourceRegistrationRemovedAction + | RootModelSourceStateChangedAction | SessionReadyAction | SessionCreationFailedAction | SessionChatAddedAction diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json index 1225924aa..cfba1cd12 100644 --- a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json +++ b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceRegistrationSet replaces the registration with the same id in place, as when the host reports its state", + "description": "root/modelSourceRegistrationSet replaces the registration with the same id in place. A client's replacement carries no state or credentialNonce, so it clears the reported status until the host reports again, and its clientId becomes the contributing client", "reducer": "root", "initial": { "agents": [], @@ -15,7 +15,11 @@ "model-a" ] }, - "clientId": "client-1" + "clientId": "client-1", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1" }, { "id": "model-source-b", @@ -38,7 +42,7 @@ "registration": { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "name": "Source a (renamed)", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -46,11 +50,7 @@ "model-a" ] }, - "clientId": "client-1", - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1" + "clientId": "client-2" } } ], @@ -60,7 +60,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "name": "Source a (renamed)", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -68,11 +68,7 @@ "model-a" ] }, - "clientId": "client-1", - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1" + "clientId": "client-2" }, { "id": "model-source-b", diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json new file mode 100644 index 000000000..ce4ecdcba --- /dev/null +++ b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json @@ -0,0 +1,96 @@ +{ + "description": "root/modelSourceStateChanged replaces only the matching registration's state and credentialNonce, preserving its other fields and the registry order", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1", + "retention": "host", + "state": { + "kind": "starting" + }, + "credentialNonce": "nonce-b-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-b", + "state": { + "kind": "authRequired", + "reason": "required", + "resource": { + "resource": "https://apib.example.com/v1", + "resource_name": "Source b API key" + } + }, + "credentialNonce": "nonce-b-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "name": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + "model-b" + ] + }, + "clientId": "client-1", + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "required", + "resource": { + "resource": "https://apib.example.com/v1", + "resource_name": "Source b API key" + } + }, + "credentialNonce": "nonce-b-2" + } + ] + } +} diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json new file mode 100644 index 000000000..e42927d51 --- /dev/null +++ b/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json @@ -0,0 +1,50 @@ +{ + "description": "root/modelSourceStateChanged is a no-op when no registration has the id, so a late status report can't bring back a removed registration", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-removed", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-removed-1" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1" + } + ] + } +} diff --git a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-when-registry-absent.json b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-when-registry-absent.json new file mode 100644 index 000000000..8b7eb8e1a --- /dev/null +++ b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-when-registry-absent.json @@ -0,0 +1,20 @@ +{ + "description": "root/modelSourceStateChanged is a no-op when the registry is absent", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-a", + "state": { + "kind": "starting" + }, + "credentialNonce": "nonce-a-1" + } + ], + "expected": { + "agents": [] + } +} diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 33954860e..028f1671c 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -97,7 +97,6 @@ "src": "https://example.com/openrouter.svg" } ], - "sharing": "host", "retention": "host", "state": { "kind": "ready" @@ -123,7 +122,6 @@ ] }, "clientId": "client-1", - "sharing": "contributingClient", "retention": "contributingClient", "state": { "kind": "authRequired", @@ -276,7 +274,6 @@ "src": "https://example.com/openrouter.svg" } ], - "sharing": "host", "retention": "host", "state": { "kind": "ready" @@ -302,7 +299,6 @@ ] }, "clientId": "client-1", - "sharing": "contributingClient", "retention": "contributingClient", "state": { "kind": "authRequired", diff --git a/types/test-cases/round-trips/104-root-model-source-registration-set.json b/types/test-cases/round-trips/104-root-model-source-registration-set.json index b3f2af90a..2e4bcd92e 100644 --- a/types/test-cases/round-trips/104-root-model-source-registration-set.json +++ b/types/test-cases/round-trips/104-root-model-source-registration-set.json @@ -1,7 +1,7 @@ { "name": "root-model-source-registration-set", "group": "A", - "description": "A client registers a model source with root/modelSourceRegistrationSet: its own clientId, requested sharing and retention, an open definition, and no state.", + "description": "A client registers a model source with root/modelSourceRegistrationSet: its own clientId, requested retention, an open definition, and no state.", "type": "StateAction", "input": { "type": "root/modelSourceRegistrationSet", @@ -21,7 +21,6 @@ } }, "clientId": "client-1", - "sharing": "host", "retention": "host" } }, @@ -44,7 +43,6 @@ } }, "clientId": "client-1", - "sharing": "host", "retention": "host" } } diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json new file mode 100644 index 000000000..8c4066a09 --- /dev/null +++ b/types/test-cases/round-trips/107-root-model-source-state-changed.json @@ -0,0 +1,36 @@ +{ + "name": "root-model-source-state-changed", + "group": "A", + "description": "The host reports a registration's status and issues a credential nonce with root/modelSourceStateChanged, here asking for an API key.", + "type": "StateAction", + "input": { + "type": "root/modelSourceStateChanged", + "id": "source-new", + "state": { + "kind": "authRequired", + "reason": "required", + "resource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + }, + "description": "The endpoint needs an API key." + }, + "credentialNonce": "nonce-openrouter-1" + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceStateChanged", + "id": "source-new", + "state": { + "kind": "authRequired", + "reason": "required", + "resource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + }, + "description": "The endpoint needs an API key." + }, + "credentialNonce": "nonce-openrouter-1" + } + ] +} diff --git a/types/version/registry.ts b/types/version/registry.ts index 8a2c118ee..15179c526 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -188,6 +188,7 @@ export const ACTION_INTRODUCED_IN: { readonly [K in StateAction['type']]: string [ActionType.RootConfigChanged]: '0.1.0', [ActionType.RootModelSourceRegistrationSet]: '1.2.0', [ActionType.RootModelSourceRegistrationRemoved]: '1.2.0', + [ActionType.RootModelSourceStateChanged]: '1.2.0', [ActionType.TerminalData]: '0.1.0', [ActionType.TerminalInput]: '0.1.0', [ActionType.TerminalResized]: '0.1.0', From 2f076e5db98f685d38d9eb779c7232508c74eaad Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 09:37:43 -0500 Subject: [PATCH 05/17] models: keep registered models listed across re-auth Once a registration has been ready, the host keeps its models in the catalog through `starting` and `authRequired`, and withdraws them on removal, when the contributing client leaves under `contributingClient` retention, on `error`, or when a change mints new model IDs. A turn that starts without a usable credential ends with a resumable error. The snapshot fixture now lists the models of a source whose key expired. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/State.generated.cs | 3 ++- clients/go/ahptypes/state.generated.go | 3 ++- .../generated/State.generated.kt | 3 ++- clients/rust/crates/ahp-types/src/state.rs | 3 ++- .../Generated/State.generated.swift | 3 ++- docs/specification/authentication.md | 2 +- docs/specification/root-channel.md | 2 +- schema/actions.schema.json | 2 +- schema/commands.schema.json | 2 +- schema/errors.schema.json | 2 +- schema/notifications.schema.json | 2 +- schema/state.schema.json | 2 +- types/channels-root/state.ts | 3 ++- .../103-model-source-registry-snapshot.json | 24 ++++++++++++++++++- 14 files changed, 42 insertions(+), 14 deletions(-) diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 88051d1f2..0e4a0b449 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2438,7 +2438,8 @@ public sealed record ModelSourceStartingState } /// The source is usable, and its models are in the catalog of the agent named -/// by the registration's `provider`. +/// by the registration's `provider`. They stay listed through later `starting` +/// and `authRequired` states. /// /// Stability: 1.0 - Early development. public sealed record ModelSourceReadyState diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index a3915ca79..7f0bb7644 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1047,7 +1047,8 @@ func (v ModelSourceStartingState) MarshalJSON() ([]byte, error) { } // The source is usable, and its models are in the catalog of the agent named -// by the registration's `provider`. +// by the registration's `provider`. They stay listed through later `starting` +// and `authRequired` states. // // Stability: 1.0 - Early development. type ModelSourceReadyState struct { 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 bdd41c6a0..678d74096 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 @@ -1891,7 +1891,8 @@ internal object ModelSourceStartingStateSerializer : UnknownMembersSerializer Date: Tue, 24 Nov 2026 10:55:56 -0500 Subject: [PATCH 06/17] models: move the credential resource onto the registration - `ModelSourceRegistration.credentialResource` is host-reported RFC 9728 metadata for the endpoint the credential is for, kept in every state while the source takes a credential. `ModelSourceAuthRequirement` keeps only `reason` and `description`. - `root/modelSourceStateChanged` gains an optional `credentialResource` and sets it with `state` and `credentialNonce`. Absent clears it. Reducers in TypeScript and every client follow. - A client-dispatched `Set` must not include `credentialResource`, and `authenticate` matches `resource` against it. - `credentialNonce` is the registration's generation: the host issues a new one when a registration is added or its provider, format, or definition changes, and discards any agent result tagged with an older one. - Box the Rust `RootModelSourceRegistrationSet` variant, since the larger registration trips `large_enum_variant`. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Actions.generated.cs | 17 ++-- .../Generated/Commands.generated.cs | 18 ++--- .../Generated/State.generated.cs | 52 ++++++------- .../dotnet/src/AgentHostProtocol/Reducers.cs | 2 +- clients/go/ahp/reducers.go | 1 + clients/go/ahptypes/actions.generated.go | 15 ++-- clients/go/ahptypes/commands.generated.go | 18 ++--- clients/go/ahptypes/state.generated.go | 60 +++++++------- .../microsoft/agenthostprotocol/Reducers.kt | 1 + .../generated/Actions.generated.kt | 19 +++-- .../generated/Commands.generated.kt | 2 +- .../generated/State.generated.kt | 54 +++++++------ clients/rust/crates/ahp-types/src/actions.rs | 28 ++++--- clients/rust/crates/ahp-types/src/commands.rs | 18 ++--- clients/rust/crates/ahp-types/src/state.rs | 49 ++++++------ clients/rust/crates/ahp/src/reducers.rs | 1 + .../Generated/Actions.generated.swift | 19 +++-- .../Generated/Commands.generated.swift | 2 +- .../Generated/State.generated.swift | 63 +++++++-------- .../AgentHostProtocol/NativeReducer.swift | 5 +- docs/guide/actions.md | 2 +- docs/specification/authentication.md | 14 ++-- docs/specification/root-channel.md | 22 ++++-- schema/actions.schema.json | 30 ++++--- schema/commands.schema.json | 34 ++++---- schema/errors.schema.json | 34 ++++---- schema/notifications.schema.json | 22 ++---- schema/state.schema.json | 22 ++---- scripts/generate-rust.ts | 4 +- types/channels-root/actions.ts | 18 +++-- types/channels-root/reducer.ts | 8 +- types/channels-root/state.ts | 45 +++++++---- types/common/commands.ts | 18 ++--- ...changed-updates-host-reported-fields.json} | 26 +++---- ...atechanged-clears-credential-resource.json | 63 +++++++++++++++ .../103-model-source-registry-snapshot.json | 78 ++++++++++--------- .../107-root-model-source-state-changed.json | 22 +++--- 37 files changed, 506 insertions(+), 400 deletions(-) rename types/test-cases/reducers/{336-root-modelsourcestatechanged-updates-state-and-nonce.json => 336-root-modelsourcestatechanged-updates-host-reported-fields.json} (80%) create mode 100644 types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 1c4d300da..12f9846e5 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -349,9 +349,9 @@ public sealed record RootConfigChangedAction /// Adds a model source registration, or replaces the one with the same `id`. /// /// A client registers a source by dispatching this with its own `clientId`, and -/// with no `state` or `credentialNonce`. Replacing a registration clears its -/// status until the host reports again with -/// {@link RootModelSourceStateChangedAction}. +/// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a +/// registration clears those host-reported fields until the host reports again +/// with {@link RootModelSourceStateChangedAction}. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceRegistrationSetAction @@ -374,9 +374,9 @@ public sealed record RootModelSourceRegistrationRemovedAction public required string Id { get; init; } } -/// Updates a model source registration's status and credential nonce. A no-op -/// when no registration has `id`. Other fields of the registration are -/// preserved. Only the host dispatches it. +/// Updates a model source registration's status, credential nonce, and +/// credential resource together. A no-op when no registration has `id`. Other +/// fields of the registration are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceStateChangedAction @@ -391,6 +391,11 @@ public sealed record RootModelSourceStateChangedAction /// The registration's current credential nonce. public required string CredentialNonce { get; init; } + + /// Replaces the registration's `credentialResource`. Absent clears it, for a + /// source that needs no credential. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ProtectedResourceMetadata? CredentialResource { get; init; } } /// Session backend initialized successfully. diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 6de930c93..6c296d684 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1904,14 +1904,14 @@ public sealed record ModelSourceAuthenticateTarget /// Pushes a credential for a protected resource. The `resource` field MUST /// match a protected-resource identifier the client has discovered from the /// server — whether declared statically in `AgentInfo.protectedResources`, -/// or discovered dynamically from a live `McpServerAuthRequiredState.resource`, -/// `ToolCallAuthRequiredState.auth.resource`, or -/// `ModelSourceAuthRequiredState.resource` (each surfaced only once the -/// corresponding MCP server, tool call, or model source actually challenges -/// for auth). Servers MUST accept any `resource` value they have themselves -/// advertised through one of these mechanisms, subject to the `target` -/// rules. A `modelSource` target takes only the resource the host most -/// recently advertised for that registration. +/// or discovered dynamically from a live `McpServerAuthRequiredState.resource` +/// or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the +/// corresponding MCP server or tool call actually challenges for auth), or +/// from a registered model source's `ModelSourceRegistration.credentialResource`. +/// Servers MUST accept any `resource` value they have themselves advertised +/// through one of these mechanisms, subject to the `target` rules. A +/// `modelSource` target takes only the registration's current +/// `credentialResource.resource`. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the @@ -1932,7 +1932,7 @@ public sealed record AuthenticateParams /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - /// or `ModelSourceAuthRequiredState.resource`. + /// or `ModelSourceRegistration.credentialResource`. public required string Resource { get; init; } /// Bearer token obtained from the resource's authorization server, or an diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 0e4a0b449..500e926eb 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2407,12 +2407,30 @@ public sealed record ModelSourceRegistration /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential. The host issues a new one whenever the credential is - /// installed or dropped, and never reuses one for the same `id`. Set with - /// `state`. + /// the credential, and that tags every agent operation on the registration. + /// The host issues a new one when the registration is added, when its + /// `provider`, `format`, or `definition` changes, and whenever the + /// credential is installed or dropped. It never reuses one for the same + /// `id`. Set with `state`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? CredentialNonce { get; init; } + /// RFC 9728 metadata for the endpoint the credential is for. Present + /// whenever the source takes a credential, in every state, so any client + /// can deliver, rotate, or revoke one. Absent for a source that needs no + /// credential. Set with `state`. + /// + /// `credentialResource.resource` is the endpoint URL as the definition + /// names it, in any scheme the agent supports (for example + /// `http://localhost:11434/v1`). It's the value a client passes back as + /// `authenticate({ resource })`, and nothing fetches it. + /// `credentialResource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ProtectedResourceMetadata? CredentialResource { get; init; } + /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. [JsonPropertyName("_meta")] @@ -2451,8 +2469,9 @@ public sealed record ModelSourceReadyState public Dictionary? Extra { get; set; } } -/// What a model source needs in order to become ready. Deliberately carries no -/// credential. +/// Why a model source needs a credential before it can be ready. Deliberately +/// carries no credential. The endpoint the credential is for is the +/// registration's {@link ModelSourceRegistration.credentialResource}. /// /// Stability: 1.0 - Early development. public sealed record ModelSourceAuthRequirement @@ -2460,16 +2479,6 @@ public sealed record ModelSourceAuthRequirement /// Why a credential is needed. public AuthRequiredReason Reason { get; init; } - /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the - /// endpoint URL as the definition names it, in any scheme the agent - /// supports (for example `http://localhost:11434/v1`). It's the value a - /// client passes back as `authenticate({ resource })`, and nothing fetches - /// it. `resource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. - public required ProtectedResourceMetadata Resource { get; init; } - /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2481,7 +2490,8 @@ public sealed record ModelSourceAuthRequirement } /// The source needs a credential before it can be used. A client answers with -/// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +/// `authenticate`, the registration's `credentialResource.resource`, and a +/// {@link ModelSourceAuthenticateTarget}. /// /// Stability: 1.0 - Early development. public sealed record ModelSourceAuthRequiredState @@ -2489,16 +2499,6 @@ public sealed record ModelSourceAuthRequiredState /// Why a credential is needed. public AuthRequiredReason Reason { get; init; } - /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the - /// endpoint URL as the definition names it, in any scheme the agent - /// supports (for example `http://localhost:11434/v1`). It's the value a - /// client passes back as `authenticate({ resource })`, and nothing fetches - /// it. `resource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. - public required ProtectedResourceMetadata Resource { get; init; } - /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index 1251d4441..64524fe2e 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -715,7 +715,7 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) } List list = state.ModelSourceRegistrations!; - list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce }; + list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce, CredentialResource = a.CredentialResource }; return ReduceOutcome.Applied; } } diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 6c207ff17..880b066e4 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -561,6 +561,7 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R nonce := a.CredentialNonce state.ModelSourceRegistrations[i].State = &st state.ModelSourceRegistrations[i].CredentialNonce = &nonce + state.ModelSourceRegistrations[i].CredentialResource = a.CredentialResource return ReduceOutcomeApplied } } diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index c23d9219f..3ecc2fb9f 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -182,9 +182,9 @@ type RootConfigChangedAction struct { // Adds a model source registration, or replaces the one with the same `id`. // // A client registers a source by dispatching this with its own `clientId`, and -// with no `state` or `credentialNonce`. Replacing a registration clears its -// status until the host reports again with -// {@link RootModelSourceStateChangedAction}. +// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a +// registration clears those host-reported fields until the host reports again +// with {@link RootModelSourceStateChangedAction}. // // Stability: 1.0 - Early development. type RootModelSourceRegistrationSetAction struct { @@ -203,9 +203,9 @@ type RootModelSourceRegistrationRemovedAction struct { Id string `json:"id"` } -// Updates a model source registration's status and credential nonce. A no-op -// when no registration has `id`. Other fields of the registration are -// preserved. Only the host dispatches it. +// Updates a model source registration's status, credential nonce, and +// credential resource together. A no-op when no registration has `id`. Other +// fields of the registration are preserved. Only the host dispatches it. // // Stability: 1.0 - Early development. type RootModelSourceStateChangedAction struct { @@ -216,6 +216,9 @@ type RootModelSourceStateChangedAction struct { State ModelSourceState `json:"state"` // The registration's current credential nonce. CredentialNonce string `json:"credentialNonce"` + // Replaces the registration's `credentialResource`. Absent clears it, for a + // source that needs no credential. + CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` } // Session backend initialized successfully. diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index ae523feb7..add5801f4 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1367,14 +1367,14 @@ type ModelSourceAuthenticateTarget struct { // Pushes a credential for a protected resource. The `resource` field MUST // match a protected-resource identifier the client has discovered from the // server — whether declared statically in `AgentInfo.protectedResources`, -// or discovered dynamically from a live `McpServerAuthRequiredState.resource`, -// `ToolCallAuthRequiredState.auth.resource`, or -// `ModelSourceAuthRequiredState.resource` (each surfaced only once the -// corresponding MCP server, tool call, or model source actually challenges -// for auth). Servers MUST accept any `resource` value they have themselves -// advertised through one of these mechanisms, subject to the `target` -// rules. A `modelSource` target takes only the resource the host most -// recently advertised for that registration. +// or discovered dynamically from a live `McpServerAuthRequiredState.resource` +// or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the +// corresponding MCP server or tool call actually challenges for auth), or +// from a registered model source's `ModelSourceRegistration.credentialResource`. +// Servers MUST accept any `resource` value they have themselves advertised +// through one of these mechanisms, subject to the `target` rules. A +// `modelSource` target takes only the registration's current +// `credentialResource.resource`. // // Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) // (Bearer Token Usage) semantics. The client obtains the token from the @@ -1391,7 +1391,7 @@ type AuthenticateParams struct { // server has advertised — via `ProtectedResourceMetadata` in // `AgentInfo.protectedResources`, or via a live // `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - // or `ModelSourceAuthRequiredState.resource`. + // or `ModelSourceRegistration.credentialResource`. Resource string `json:"resource"` // Bearer token obtained from the resource's authorization server, or an // opaque secret for a model source. An empty string revokes the credential. diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 7f0bb7644..fc5e4e1f3 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1005,10 +1005,26 @@ type ModelSourceRegistration struct { State *ModelSourceState `json:"state,omitempty"` // Host-issued token that a client echoes in // {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - // the credential. The host issues a new one whenever the credential is - // installed or dropped, and never reuses one for the same `id`. Set with - // `state`. + // the credential, and that tags every agent operation on the registration. + // The host issues a new one when the registration is added, when its + // `provider`, `format`, or `definition` changes, and whenever the + // credential is installed or dropped. It never reuses one for the same + // `id`. Set with `state`. CredentialNonce *string `json:"credentialNonce,omitempty"` + // RFC 9728 metadata for the endpoint the credential is for. Present + // whenever the source takes a credential, in every state, so any client + // can deliver, rotate, or revoke one. Absent for a source that needs no + // credential. Set with `state`. + // + // `credentialResource.resource` is the endpoint URL as the definition + // names it, in any scheme the agent supports (for example + // `http://localhost:11434/v1`). It's the value a client passes back as + // `authenticate({ resource })`, and nothing fetches it. + // `credentialResource.resource_name` labels the prompt (for example + // "OpenRouter API key"). A source that accepts OAuth access tokens + // advertises `authorization_servers` and `scopes_supported`. A source that + // takes a user-supplied secret omits them. + CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` // Additional implementation-defined metadata for this registration. // MUST NOT contain a credential. Meta map[string]json.RawMessage `json:"_meta,omitempty"` @@ -1018,12 +1034,12 @@ type ModelSourceRegistration struct { func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistration - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") } func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistration - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "_meta") + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") } // The agent is reading and validating the definition, or listing the @@ -1067,22 +1083,14 @@ func (v ModelSourceReadyState) MarshalJSON() ([]byte, error) { return marshalWithExtra(wire(v), v.Extra, "kind") } -// What a model source needs in order to become ready. Deliberately carries no -// credential. +// Why a model source needs a credential before it can be ready. Deliberately +// carries no credential. The endpoint the credential is for is the +// registration's {@link ModelSourceRegistration.credentialResource}. // // Stability: 1.0 - Early development. type ModelSourceAuthRequirement struct { // Why a credential is needed. Reason AuthRequiredReason `json:"reason"` - // RFC 9728 metadata for the source's endpoint. `resource.resource` is the - // endpoint URL as the definition names it, in any scheme the agent - // supports (for example `http://localhost:11434/v1`). It's the value a - // client passes back as `authenticate({ resource })`, and nothing fetches - // it. `resource.resource_name` labels the prompt (for example - // "OpenRouter API key"). A source that accepts OAuth access tokens - // advertises `authorization_servers` and `scopes_supported`. A source that - // takes a user-supplied secret omits them. - Resource ProtectedResourceMetadata `json:"resource"` // Human-readable hint the host writes, for example "The endpoint rejected // the API key." Description *string `json:"description,omitempty"` @@ -1092,30 +1100,22 @@ type ModelSourceAuthRequirement struct { func (v *ModelSourceAuthRequirement) UnmarshalJSON(data []byte) error { type wire ModelSourceAuthRequirement - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "resource", "description") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "description") } func (v ModelSourceAuthRequirement) MarshalJSON() ([]byte, error) { type wire ModelSourceAuthRequirement - return marshalWithExtra(wire(v), v.Extra, "reason", "resource", "description") + return marshalWithExtra(wire(v), v.Extra, "reason", "description") } // The source needs a credential before it can be used. A client answers with -// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +// `authenticate`, the registration's `credentialResource.resource`, and a +// {@link ModelSourceAuthenticateTarget}. // // Stability: 1.0 - Early development. type ModelSourceAuthRequiredState struct { // Why a credential is needed. Reason AuthRequiredReason `json:"reason"` - // RFC 9728 metadata for the source's endpoint. `resource.resource` is the - // endpoint URL as the definition names it, in any scheme the agent - // supports (for example `http://localhost:11434/v1`). It's the value a - // client passes back as `authenticate({ resource })`, and nothing fetches - // it. `resource.resource_name` labels the prompt (for example - // "OpenRouter API key"). A source that accepts OAuth access tokens - // advertises `authorization_servers` and `scopes_supported`. A source that - // takes a user-supplied secret omits them. - Resource ProtectedResourceMetadata `json:"resource"` // Human-readable hint the host writes, for example "The endpoint rejected // the API key." Description *string `json:"description,omitempty"` @@ -1126,12 +1126,12 @@ type ModelSourceAuthRequiredState struct { func (v *ModelSourceAuthRequiredState) UnmarshalJSON(data []byte) error { type wire ModelSourceAuthRequiredState - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "resource", "description", "kind") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "description", "kind") } func (v ModelSourceAuthRequiredState) MarshalJSON() ([]byte, error) { type wire ModelSourceAuthRequiredState - return marshalWithExtra(wire(v), v.Extra, "reason", "resource", "description", "kind") + return marshalWithExtra(wire(v), v.Extra, "reason", "description", "kind") } // The source failed, or the host declined it, for example by policy. diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index 71df45584..ed9288234 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -604,6 +604,7 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when updated[idx] = updated[idx].copy( state = action.value.state, credentialNonce = action.value.credentialNonce, + credentialResource = action.value.credentialResource, ) state.copy(modelSourceRegistrations = updated) } diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 94ef1e7bb..e008606ca 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -1489,9 +1489,9 @@ data class RootConfigChangedAction( * Adds a model source registration, or replaces the one with the same `id`. * * A client registers a source by dispatching this with its own `clientId`, and - * with no `state` or `credentialNonce`. Replacing a registration clears its - * status until the host reports again with - * {@link RootModelSourceStateChangedAction}. + * with no `state`, `credentialNonce`, or `credentialResource`. Replacing a + * registration clears those host-reported fields until the host reports again + * with {@link RootModelSourceStateChangedAction}. * * Stability: 1.0 - Early development. */ @@ -1520,9 +1520,9 @@ data class RootModelSourceRegistrationRemovedAction( ) /** - * Updates a model source registration's status and credential nonce. A no-op - * when no registration has `id`. Other fields of the registration are - * preserved. Only the host dispatches it. + * Updates a model source registration's status, credential nonce, and + * credential resource together. A no-op when no registration has `id`. Other + * fields of the registration are preserved. Only the host dispatches it. * * Stability: 1.0 - Early development. */ @@ -1540,7 +1540,12 @@ data class RootModelSourceStateChangedAction( /** * The registration's current credential nonce. */ - val credentialNonce: String + val credentialNonce: String, + /** + * Replaces the registration's `credentialResource`. Absent clears it, for a + * source that needs no credential. + */ + val credentialResource: ProtectedResourceMetadata? = null ) @Serializable 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 55f5029df..d8b6f43c8 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 @@ -1654,7 +1654,7 @@ data class AuthenticateParams( * server has advertised — via `ProtectedResourceMetadata` in * `AgentInfo.protectedResources`, or via a live * `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - * or `ModelSourceAuthRequiredState.resource`. + * or `ModelSourceRegistration.credentialResource`. */ val resource: String, /** 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 678d74096..9a2d8ab89 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 @@ -1848,11 +1848,29 @@ data class ModelSourceRegistration( /** * Host-issued token that a client echoes in * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential. The host issues a new one whenever the credential is - * installed or dropped, and never reuses one for the same `id`. Set with - * `state`. + * the credential, and that tags every agent operation on the registration. + * The host issues a new one when the registration is added, when its + * `provider`, `format`, or `definition` changes, and whenever the + * credential is installed or dropped. It never reuses one for the same + * `id`. Set with `state`. */ val credentialNonce: String? = null, + /** + * RFC 9728 metadata for the endpoint the credential is for. Present + * whenever the source takes a credential, in every state, so any client + * can deliver, rotate, or revoke one. Absent for a source that needs no + * credential. Set with `state`. + * + * `credentialResource.resource` is the endpoint URL as the definition + * names it, in any scheme the agent supports (for example + * `http://localhost:11434/v1`). It's the value a client passes back as + * `authenticate({ resource })`, and nothing fetches it. + * `credentialResource.resource_name` labels the prompt (for example + * "OpenRouter API key"). A source that accepts OAuth access tokens + * advertises `authorization_servers` and `scopes_supported`. A source that + * takes a user-supplied secret omits them. + */ + val credentialResource: ProtectedResourceMetadata? = null, /** * Additional implementation-defined metadata for this registration. * MUST NOT contain a credential. @@ -1911,8 +1929,9 @@ internal object ModelSourceReadyStateSerializer : UnknownMembersSerializer, } /// Session backend initialized successfully. @@ -2514,7 +2518,7 @@ pub enum StateAction { #[serde(rename = "root/configChanged")] RootConfigChanged(RootConfigChangedAction), #[serde(rename = "root/modelSourceRegistrationSet")] - RootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction), + RootModelSourceRegistrationSet(Box), #[serde(rename = "root/modelSourceRegistrationRemoved")] RootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction), #[serde(rename = "root/modelSourceStateChanged")] diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index 09697e58d..d00a9173c 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1765,14 +1765,14 @@ pub struct ModelSourceAuthenticateTarget { /// Pushes a credential for a protected resource. The `resource` field MUST /// match a protected-resource identifier the client has discovered from the /// server — whether declared statically in `AgentInfo.protectedResources`, -/// or discovered dynamically from a live `McpServerAuthRequiredState.resource`, -/// `ToolCallAuthRequiredState.auth.resource`, or -/// `ModelSourceAuthRequiredState.resource` (each surfaced only once the -/// corresponding MCP server, tool call, or model source actually challenges -/// for auth). Servers MUST accept any `resource` value they have themselves -/// advertised through one of these mechanisms, subject to the `target` -/// rules. A `modelSource` target takes only the resource the host most -/// recently advertised for that registration. +/// or discovered dynamically from a live `McpServerAuthRequiredState.resource` +/// or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the +/// corresponding MCP server or tool call actually challenges for auth), or +/// from a registered model source's `ModelSourceRegistration.credentialResource`. +/// Servers MUST accept any `resource` value they have themselves advertised +/// through one of these mechanisms, subject to the `target` rules. A +/// `modelSource` target takes only the registration's current +/// `credentialResource.resource`. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the @@ -1792,7 +1792,7 @@ pub struct AuthenticateParams { /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - /// or `ModelSourceAuthRequiredState.resource`. + /// or `ModelSourceRegistration.credentialResource`. pub resource: String, /// Bearer token obtained from the resource's authorization server, or an /// opaque secret for a model source. An empty string revokes the credential. diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index db941ed0b..01e382811 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2164,11 +2164,28 @@ pub struct ModelSourceRegistration { pub state: Option, /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential. The host issues a new one whenever the credential is - /// installed or dropped, and never reuses one for the same `id`. Set with - /// `state`. + /// the credential, and that tags every agent operation on the registration. + /// The host issues a new one when the registration is added, when its + /// `provider`, `format`, or `definition` changes, and whenever the + /// credential is installed or dropped. It never reuses one for the same + /// `id`. Set with `state`. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_nonce: Option, + /// RFC 9728 metadata for the endpoint the credential is for. Present + /// whenever the source takes a credential, in every state, so any client + /// can deliver, rotate, or revoke one. Absent for a source that needs no + /// credential. Set with `state`. + /// + /// `credentialResource.resource` is the endpoint URL as the definition + /// names it, in any scheme the agent supports (for example + /// `http://localhost:11434/v1`). It's the value a client passes back as + /// `authenticate({ resource })`, and nothing fetches it. + /// `credentialResource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_resource: Option, /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] @@ -2203,8 +2220,9 @@ pub struct ModelSourceReadyState { pub extra: serde_json::Map, } -/// What a model source needs in order to become ready. Deliberately carries no -/// credential. +/// Why a model source needs a credential before it can be ready. Deliberately +/// carries no credential. The endpoint the credential is for is the +/// registration's {@link ModelSourceRegistration.credentialResource}. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2212,15 +2230,6 @@ pub struct ModelSourceReadyState { pub struct ModelSourceAuthRequirement { /// Why a credential is needed. pub reason: AuthRequiredReason, - /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the - /// endpoint URL as the definition names it, in any scheme the agent - /// supports (for example `http://localhost:11434/v1`). It's the value a - /// client passes back as `authenticate({ resource })`, and nothing fetches - /// it. `resource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. - pub resource: ProtectedResourceMetadata, /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2231,7 +2240,8 @@ pub struct ModelSourceAuthRequirement { } /// The source needs a credential before it can be used. A client answers with -/// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +/// `authenticate`, the registration's `credentialResource.resource`, and a +/// {@link ModelSourceAuthenticateTarget}. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2239,15 +2249,6 @@ pub struct ModelSourceAuthRequirement { pub struct ModelSourceAuthRequiredState { /// Why a credential is needed. pub reason: AuthRequiredReason, - /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the - /// endpoint URL as the definition names it, in any scheme the agent - /// supports (for example `http://localhost:11434/v1`). It's the value a - /// client passes back as `authenticate({ resource })`, and nothing fetches - /// it. `resource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. - pub resource: ProtectedResourceMetadata, /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 1012f58aa..72e60c799 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -750,6 +750,7 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu }; registration.state = Some(a.state.clone()); registration.credential_nonce = Some(a.credential_nonce.clone()); + registration.credential_resource = a.credential_resource.clone(); ReduceOutcome::Applied } _ => ReduceOutcome::OutOfScope, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index 89e051488..1b8fc467d 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -2293,9 +2293,9 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { /// Adds a model source registration, or replaces the one with the same `id`. /// /// A client registers a source by dispatching this with its own `clientId`, and -/// with no `state` or `credentialNonce`. Replacing a registration clears its -/// status until the host reports again with -/// {@link RootModelSourceStateChangedAction}. +/// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a +/// registration clears those host-reported fields until the host reports again +/// with {@link RootModelSourceStateChangedAction}. /// /// Stability: 1.0 - Early development. public struct RootModelSourceRegistrationSetAction: Codable, Sendable, Equatable { @@ -2330,9 +2330,9 @@ public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equat } } -/// Updates a model source registration's status and credential nonce. A no-op -/// when no registration has `id`. Other fields of the registration are -/// preserved. Only the host dispatches it. +/// Updates a model source registration's status, credential nonce, and +/// credential resource together. A no-op when no registration has `id`. Other +/// fields of the registration are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { @@ -2343,17 +2343,22 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { public var state: ModelSourceState /// The registration's current credential nonce. public var credentialNonce: String + /// Replaces the registration's `credentialResource`. Absent clears it, for a + /// source that needs no credential. + public var credentialResource: ProtectedResourceMetadata? public init( type: ActionType, id: String, state: ModelSourceState, - credentialNonce: String + credentialNonce: String, + credentialResource: ProtectedResourceMetadata? = nil ) { self.type = type self.id = id self.state = state self.credentialNonce = credentialNonce + self.credentialResource = credentialResource } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 2bef32da9..873b8a719 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -2003,7 +2003,7 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - /// or `ModelSourceAuthRequiredState.resource`. + /// or `ModelSourceRegistration.credentialResource`. public var resource: String /// Bearer token obtained from the resource's authorization server, or an /// opaque secret for a model source. An empty string revokes the credential. diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 5d3e22f3e..d2c5c01d7 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1840,10 +1840,26 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { public var state: ModelSourceState? /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential. The host issues a new one whenever the credential is - /// installed or dropped, and never reuses one for the same `id`. Set with - /// `state`. + /// the credential, and that tags every agent operation on the registration. + /// The host issues a new one when the registration is added, when its + /// `provider`, `format`, or `definition` changes, and whenever the + /// credential is installed or dropped. It never reuses one for the same + /// `id`. Set with `state`. public var credentialNonce: String? + /// RFC 9728 metadata for the endpoint the credential is for. Present + /// whenever the source takes a credential, in every state, so any client + /// can deliver, rotate, or revoke one. Absent for a source that needs no + /// credential. Set with `state`. + /// + /// `credentialResource.resource` is the endpoint URL as the definition + /// names it, in any scheme the agent supports (for example + /// `http://localhost:11434/v1`). It's the value a client passes back as + /// `authenticate({ resource })`, and nothing fetches it. + /// `credentialResource.resource_name` labels the prompt (for example + /// "OpenRouter API key"). A source that accepts OAuth access tokens + /// advertises `authorization_servers` and `scopes_supported`. A source that + /// takes a user-supplied secret omits them. + public var credentialResource: ProtectedResourceMetadata? /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. public var meta: [String: AnyCodable]? @@ -1861,6 +1877,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { case retention case state case credentialNonce + case credentialResource case meta = "_meta" } @@ -1875,6 +1892,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, credentialNonce: String? = nil, + credentialResource: ProtectedResourceMetadata? = nil, meta: [String: AnyCodable]? = nil, extra: [String: AnyCodable] = [:] ) { @@ -1888,6 +1906,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.retention = retention self.state = state self.credentialNonce = credentialNonce + self.credentialResource = credentialResource self.meta = meta self.extra = extra } @@ -1904,6 +1923,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) self.credentialNonce = try container.decodeIfPresent(String.self, forKey: .credentialNonce) + self.credentialResource = try container.decodeIfPresent(ProtectedResourceMetadata.self, forKey: .credentialResource) self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -1920,6 +1940,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) try container.encodeIfPresent(self.credentialNonce, forKey: .credentialNonce) + try container.encodeIfPresent(self.credentialResource, forKey: .credentialResource) try container.encodeIfPresent(self.meta, forKey: .meta) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -1994,22 +2015,14 @@ public struct ModelSourceReadyState: Codable, Sendable, Equatable { } } -/// What a model source needs in order to become ready. Deliberately carries no -/// credential. +/// Why a model source needs a credential before it can be ready. Deliberately +/// carries no credential. The endpoint the credential is for is the +/// registration's {@link ModelSourceRegistration.credentialResource}. /// /// Stability: 1.0 - Early development. public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { /// Why a credential is needed. public var reason: AuthRequiredReason - /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the - /// endpoint URL as the definition names it, in any scheme the agent - /// supports (for example `http://localhost:11434/v1`). It's the value a - /// client passes back as `authenticate({ resource })`, and nothing fetches - /// it. `resource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. - public var resource: ProtectedResourceMetadata /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." public var description: String? @@ -2018,18 +2031,15 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { enum CodingKeys: String, CodingKey, CaseIterable { case reason - case resource case description } public init( reason: AuthRequiredReason, - resource: ProtectedResourceMetadata, description: String? = nil, extra: [String: AnyCodable] = [:] ) { self.reason = reason - self.resource = resource self.description = description self.extra = extra } @@ -2037,7 +2047,6 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.reason = try container.decode(AuthRequiredReason.self, forKey: .reason) - self.resource = try container.decode(ProtectedResourceMetadata.self, forKey: .resource) self.description = try container.decodeIfPresent(String.self, forKey: .description) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -2045,28 +2054,19 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.reason, forKey: .reason) - try container.encode(self.resource, forKey: .resource) try container.encodeIfPresent(self.description, forKey: .description) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } /// The source needs a credential before it can be used. A client answers with -/// `authenticate` and a {@link ModelSourceAuthenticateTarget}. +/// `authenticate`, the registration's `credentialResource.resource`, and a +/// {@link ModelSourceAuthenticateTarget}. /// /// Stability: 1.0 - Early development. public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { /// Why a credential is needed. public var reason: AuthRequiredReason - /// RFC 9728 metadata for the source's endpoint. `resource.resource` is the - /// endpoint URL as the definition names it, in any scheme the agent - /// supports (for example `http://localhost:11434/v1`). It's the value a - /// client passes back as `authenticate({ resource })`, and nothing fetches - /// it. `resource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. - public var resource: ProtectedResourceMetadata /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." public var description: String? @@ -2076,20 +2076,17 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { enum CodingKeys: String, CodingKey, CaseIterable { case reason - case resource case description case kind } public init( reason: AuthRequiredReason, - resource: ProtectedResourceMetadata, description: String? = nil, kind: ModelSourceStatus, extra: [String: AnyCodable] = [:] ) { self.reason = reason - self.resource = resource self.description = description self.kind = kind self.extra = extra @@ -2098,7 +2095,6 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.reason = try container.decode(AuthRequiredReason.self, forKey: .reason) - self.resource = try container.decode(ProtectedResourceMetadata.self, forKey: .resource) self.description = try container.decodeIfPresent(String.self, forKey: .description) self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) @@ -2107,7 +2103,6 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.reason, forKey: .reason) - try container.encode(self.resource, forKey: .resource) try container.encodeIfPresent(self.description, forKey: .description) try container.encode(self.kind, forKey: .kind) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index f300f1294..f28b1ae79 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -138,13 +138,14 @@ func applyModelSourceRegistrationRemoved(_ state: inout RootState, id: String) - return true } -/// Updates the status and credential nonce of the registration with `action.id`. -/// Returns `false` when none matches. +/// Updates the status, credential nonce, and credential resource of the +/// registration with `action.id`. Returns `false` when none matches. func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelSourceStateChangedAction) -> Bool { guard var list = state.modelSourceRegistrations, let idx = list.firstIndex(where: { $0.id == action.id }) else { return false } list[idx].state = action.state list[idx].credentialNonce = action.credentialNonce + list[idx].credentialResource = action.credentialResource state.modelSourceRegistrations = list return true } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index f69e56123..4710c8cdb 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -33,7 +33,7 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/configChanged` | **Yes** | Host-level configuration values changed | | `root/modelSourceRegistrationSet` | **Yes** | A [model source registration](/specification/root-channel#model-source-registry) was added, or replaced by `id` | | `root/modelSourceRegistrationRemoved` | **Yes** | A model source registration was removed by `id` | -| `root/modelSourceStateChanged` | No | The host reported a registration's status and credential nonce | +| `root/modelSourceStateChanged` | No | The host reported a registration's status, credential nonce, and credential resource | ## Automation Catalogue Actions diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index ae33a4032..cfd1e9976 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -150,7 +150,7 @@ If the token is invalid or the resource is unrecognized, the server MUST return ### Model source credentials -A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. When the source needs a credential, the host sets the registration's state to `ModelSourceAuthRequiredState`, which carries a `reason` and RFC 9728 `resource` metadata for the source's endpoint. A client answers with a `modelSource` target that names the registration and echoes its current `credentialNonce`: +A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the registration carries a host-reported `credentialResource` with RFC 9728 metadata for the source's endpoint, in every state. When the source needs a credential, the host also sets the registration's state to `ModelSourceAuthRequiredState`, which carries a `reason`. A client answers with a `modelSource` target that names the registration and echoes its current `credentialNonce`: ```jsonc // Model source credential delivery @@ -173,27 +173,29 @@ A client can [register a model source](/specification/root-channel#model-source- The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the registration's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `expiresIn` and `scopes`. `resource.resource_name` labels the prompt, for example "OpenRouter API key". -`resource.resource` is the endpoint URL as the definition names it, in any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Whether the agent sends a credential over plain `http` is the host's network policy. +`credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Whether the agent sends a credential over plain `http` is the host's network policy. When `target.kind` is `modelSource`, the host: - MUST apply the credential only to that registration, never to other registrations, MCP servers, or agent-level resources, even when they share `resource`; -- MUST require `resource` to equal the `resource.resource` it most recently advertised for that registration; +- MUST require `resource` to equal the registration's current `credentialResource.resource`; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); - MUST reject a `credentialNonce` other than the one it most recently issued for that registration with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; - MUST treat an empty `token` as revocation: it drops the credential, and the source returns to `authRequired` with `reason: expired`, so no client sends the revoked secret again. Any client may deliver or revoke a registration's credential, as any client may answer an MCP server's challenge. -`credentialNonce` fences every credential change. The host issues a new nonce whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation, and when a change to `provider`, `format`, or `definition` drops it. That includes a removed registration that's registered again under the same `id`, and the host never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: +`credentialNonce` fences every credential change, and works as the registration's generation. The host issues a new nonce whenever a registration is added, including one registered again under a removed `id`, and whenever its `provider`, `format`, or `definition` changes, whether or not it held a credential. It also issues one whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation. It never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: - a key meant for an old definition never reaches a new one, even when the endpoint didn't change; - a rotation that crosses a revocation can't undo the revocation; - when two clients answer the same `authRequired`, the first wins, and the second gets `Conflict`, re-reads state, and finds the source ready. -The host also tags each request with the nonce of the key it used, and ignores a failure from a request made with an older key, so a late failure can't drop a key that has since replaced it. +The host tags every agent operation on the registration with the current nonce and discards any result, success or failure, that carries an older one. A late failure can't drop a key that has since replaced it, and a late success can't mark a changed or re-registered source `ready`, even after an edit that changes the definition back. -The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition` or `_meta`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. The host drops the credential when the registration is removed, when its `provider`, `format`, or `definition` changes, and when the host restarts. +`credentialResource` and `credentialNonce` stay in root state for as long as the source takes a credential, not only while it's `authRequired`. Any client, including one that connected after the source became ready, can build an `authenticate` request at any time: to rotate a short-lived token before it expires, or to revoke a key with an empty token. + +The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition`, `_meta`, or `credentialResource`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. The host drops the credential when the registration is removed, when its `provider`, `format`, or `definition` changes, and when the host restarts. The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, but MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index 3140e5d12..e03ff37c6 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -75,7 +75,11 @@ Clients can register bring-your-own-key model sources with the host, so its agen "clientId": "laptop", "retention": "host", "state": { "kind": "ready" }, - "credentialNonce": "9b41d7" + "credentialNonce": "9b41d7", + "credentialResource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + } } ``` @@ -83,24 +87,28 @@ Clients can register bring-your-own-key model sources with the host, so its agen #### Registering -A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId`, and with no `state` or `credentialNonce`. It removes one with `root/modelSourceRegistrationRemoved`. Like MCP servers, registrations have no per-client ownership: any client can change or remove any registration, and the client that changes one becomes its contributing client. A host MAY reject client changes to a registration it created itself. +A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId`, and with no `state`, `credentialNonce`, or `credentialResource`. It removes one with `root/modelSourceRegistrationRemoved`. Like MCP servers, registrations have no per-client ownership: any client can change or remove any registration, and the client that changes one becomes its contributing client. A host MAY reject client changes to a registration it created itself. The host rejects a client's `Set`, through `rejectionReason`, when: - the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; -- `clientId` isn't the dispatching client's ID, or `state` or `credentialNonce` is present; +- `clientId` isn't the dispatching client's ID, or `state`, `credentialNonce`, or `credentialResource` is present; - `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same registration doesn't count, so a ready registration can still be updated; - the host won't honor the requested `retention`. The client can register again with `contributingClient` retention. A client's `Removed` is a no-op when no registration has that `id`. -When a `Set` changes a registration's `provider`, `format`, or `definition`, the host drops its credential, and the source goes back through `starting`. A change to `name`, `icons`, `clientId`, or `retention` keeps the credential. A host may also register sources itself. Those registrations have no `clientId`, and their retention behaves as `host`. +When a `Set` changes a registration's `provider`, `format`, or `definition`, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A change to `name`, `icons`, `clientId`, or `retention` keeps the credential and the nonce. A host may also register sources itself. Those registrations have no `clientId`, and their retention behaves as `host`. #### Status -The host reports status with `root/modelSourceStateChanged`, which sets a registration's `state` (`starting`, `ready`, `authRequired`, or `error`) and its `credentialNonce`, as `session/mcpServerStateChanged` does for MCP servers. It never reports status by dispatching the registration back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed registration or overwrite a newer definition. The host also discards an agent result for a definition the registration no longer has. +The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets three host-reported fields together: the registration's `state` (`starting`, `ready`, `authRequired`, or `error`), its `credentialNonce`, and its `credentialResource`, which an absent value clears. It never reports status by dispatching the registration back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed registration or overwrite a newer definition. + +`credentialNonce` is the registration's generation. The host issues a new one when a registration is added, including under a removed `id`, when its `provider`, `format`, or `definition` changes, and whenever it installs or drops a credential. It tags every agent operation on the registration, such as validation, model discovery, and inference, with the current nonce, and discards any result, success or failure, that carries an older one. A slow result from before a change therefore can't mark the current registration `ready`, even when the definition has changed back to the same value. + +`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for. The host reports it in every state while the source takes a credential, so any client can deliver, rotate, or revoke one, and leaves it absent for a source that needs none. See [Model source credentials](/specification/authentication#model-source-credentials). -A client's `Set` replaces the whole registration, so it clears the status until the host reports again. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed. +A client's `Set` replaces the whole registration, so it clears the host-reported fields until the host reports again. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed. #### Catalog @@ -195,7 +203,7 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | | `root/modelSourceRegistrationSet` | Server / Client | Adds or replaces a registration in `modelSourceRegistrations` by `id` | | `root/modelSourceRegistrationRemoved` | Server / Client | Removes a registration by `id` | -| `root/modelSourceStateChanged` | Server | Sets a registration's `state` and `credentialNonce`. A no-op for an unknown `id` | +| `root/modelSourceStateChanged` | Server | Sets a registration's `state`, `credentialNonce`, and `credentialResource`. A no-op for an unknown `id` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index c4ae3a3b4..18a8b800b 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -129,7 +129,7 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state` or `credentialNonce`. Replacing a registration clears its\nstatus until the host reports again with\n{@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state`, `credentialNonce`, or `credentialResource`. Replacing a\nregistration clears those host-reported fields until the host reports again\nwith {@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" @@ -163,7 +163,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's status and credential nonce. A no-op\nwhen no registration has `id`. Other fields of the registration are\npreserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source registration's status, credential nonce, and\ncredential resource together. A no-op when no registration has `id`. Other\nfields of the registration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -179,6 +179,10 @@ "credentialNonce": { "type": "string", "description": "The registration's current credential nonce." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." } }, "required": [ @@ -3619,7 +3623,11 @@ }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, "_meta": { "type": "object", @@ -3661,38 +3669,29 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ - "reason", - "resource" + "reason" ] }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" @@ -3703,7 +3702,6 @@ }, "required": [ "reason", - "resource", "kind" ] }, diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 5d067a0b9..e87655125 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1077,7 +1077,7 @@ }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms, subject to the `target`\nrules. A `modelSource` target takes only the resource the host most\nrecently advertised for that registration.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSourceRegistration.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -1092,7 +1092,7 @@ }, "resource": { "type": "string", - "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceAuthRequiredState.resource`." + "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceRegistration.credentialResource`." }, "token": { "type": "string", @@ -2947,7 +2947,11 @@ }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, "_meta": { "type": "object", @@ -2989,38 +2993,29 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ - "reason", - "resource" + "reason" ] }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" @@ -3031,7 +3026,6 @@ }, "required": [ "reason", - "resource", "kind" ] }, @@ -8573,7 +8567,7 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state` or `credentialNonce`. Replacing a registration clears its\nstatus until the host reports again with\n{@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state`, `credentialNonce`, or `credentialResource`. Replacing a\nregistration clears those host-reported fields until the host reports again\nwith {@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" @@ -8607,7 +8601,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's status and credential nonce. A no-op\nwhen no registration has `id`. Other fields of the registration are\npreserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source registration's status, credential nonce, and\ncredential resource together. A no-op when no registration has `id`. Other\nfields of the registration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -8623,6 +8617,10 @@ "credentialNonce": { "type": "string", "description": "The registration's current credential nonce." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." } }, "required": [ diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 58fc920c3..3ad70b5f8 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -927,7 +927,11 @@ }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, "_meta": { "type": "object", @@ -969,38 +973,29 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ - "reason", - "resource" + "reason" ] }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" @@ -1011,7 +1006,6 @@ }, "required": [ "reason", - "resource", "kind" ] }, @@ -7501,7 +7495,7 @@ }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`,\n`ToolCallAuthRequiredState.auth.resource`, or\n`ModelSourceAuthRequiredState.resource` (each surfaced only once the\ncorresponding MCP server, tool call, or model source actually challenges\nfor auth). Servers MUST accept any `resource` value they have themselves\nadvertised through one of these mechanisms, subject to the `target`\nrules. A `modelSource` target takes only the resource the host most\nrecently advertised for that registration.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSourceRegistration.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -7516,7 +7510,7 @@ }, "resource": { "type": "string", - "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceAuthRequiredState.resource`." + "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceRegistration.credentialResource`." }, "token": { "type": "string", @@ -9833,7 +9827,7 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state` or `credentialNonce`. Replacing a registration clears its\nstatus until the host reports again with\n{@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state`, `credentialNonce`, or `credentialResource`. Replacing a\nregistration clears those host-reported fields until the host reports again\nwith {@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" @@ -9867,7 +9861,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's status and credential nonce. A no-op\nwhen no registration has `id`. Other fields of the registration are\npreserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source registration's status, credential nonce, and\ncredential resource together. A no-op when no registration has `id`. Other\nfields of the registration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -9883,6 +9877,10 @@ "credentialNonce": { "type": "string", "description": "The registration's current credential nonce." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." } }, "required": [ diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 985da5e71..96add4c9a 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1229,7 +1229,11 @@ }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, "_meta": { "type": "object", @@ -1271,38 +1275,29 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ - "reason", - "resource" + "reason" ] }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" @@ -1313,7 +1308,6 @@ }, "required": [ "reason", - "resource", "kind" ] }, diff --git a/schema/state.schema.json b/schema/state.schema.json index 0053d6062..e29897f4c 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -838,7 +838,11 @@ }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential. The host issues a new one whenever the credential is\ninstalled or dropped, and never reuses one for the same `id`. Set with\n`state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + }, + "credentialResource": { + "$ref": "#/$defs/ProtectedResourceMetadata", + "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, "_meta": { "type": "object", @@ -880,38 +884,29 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "What a model source needs in order to become ready. Deliberately carries no\ncredential.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" } }, "required": [ - "reason", - "resource" + "reason" ] }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate` and a {@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/AuthRequiredReason", "description": "Why a credential is needed." }, - "resource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the source's endpoint. `resource.resource` is the\nendpoint URL as the definition names it, in any scheme the agent\nsupports (for example `http://localhost:11434/v1`). It's the value a\nclient passes back as `authenticate({ resource })`, and nothing fetches\nit. `resource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." - }, "description": { "type": "string", "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" @@ -922,7 +917,6 @@ }, "required": [ "reason", - "resource", "kind" ] }, diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 1434bd586..6f9fc0694 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -1653,7 +1653,7 @@ const ACTION_VARIANTS: { { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, - { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction', boxed: true }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, @@ -1838,7 +1838,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSourceRegistration, ModelSourceState, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSourceRegistration, ModelSourceState, ProtectedResourceMetadata, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index bf77e6a7f..7a9aed412 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -6,6 +6,7 @@ import type { AgentInfo, ModelSourceRegistration, ModelSourceState } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; +import type { ProtectedResourceMetadata } from '../common/state.js'; import { ActionType } from '../common/actions.js'; // ─── Root Actions ──────────────────────────────────────────────────────────── @@ -71,9 +72,9 @@ export interface RootConfigChangedAction { * Adds a model source registration, or replaces the one with the same `id`. * * A client registers a source by dispatching this with its own `clientId`, and - * with no `state` or `credentialNonce`. Replacing a registration clears its - * status until the host reports again with - * {@link RootModelSourceStateChangedAction}. + * with no `state`, `credentialNonce`, or `credentialResource`. Replacing a + * registration clears those host-reported fields until the host reports again + * with {@link RootModelSourceStateChangedAction}. * * @category Root Actions * @stability 1.0 @@ -102,9 +103,9 @@ export interface RootModelSourceRegistrationRemovedAction { } /** - * Updates a model source registration's status and credential nonce. A no-op - * when no registration has `id`. Other fields of the registration are - * preserved. Only the host dispatches it. + * Updates a model source registration's status, credential nonce, and + * credential resource together. A no-op when no registration has `id`. Other + * fields of the registration are preserved. Only the host dispatches it. * * @category Root Actions * @stability 1.0 @@ -118,4 +119,9 @@ export interface RootModelSourceStateChangedAction { state: ModelSourceState; /** The registration's current credential nonce. */ credentialNonce: string; + /** + * Replaces the registration's `credentialResource`. Absent clears it, for a + * source that needs no credential. + */ + credentialResource?: ProtectedResourceMetadata; } diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index 4e85299f8..7d9efe481 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -71,7 +71,13 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st return state; } const next = list.slice(); - next[idx] = { ...list[idx], state: action.state, credentialNonce: action.credentialNonce }; + const updated = { ...list[idx], state: action.state, credentialNonce: action.credentialNonce }; + if (action.credentialResource) { + updated.credentialResource = action.credentialResource; + } else { + delete updated.credentialResource; + } + next[idx] = updated; return { ...state, modelSourceRegistrations: next }; } diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 0217586d4..d7045d03a 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -382,13 +382,33 @@ export interface ModelSourceRegistration { /** * Host-issued token that a client echoes in * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential. The host issues a new one whenever the credential is - * installed or dropped, and never reuses one for the same `id`. Set with - * `state`. + * the credential, and that tags every agent operation on the registration. + * The host issues a new one when the registration is added, when its + * `provider`, `format`, or `definition` changes, and whenever the + * credential is installed or dropped. It never reuses one for the same + * `id`. Set with `state`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ credentialNonce?: string; + /** + * RFC 9728 metadata for the endpoint the credential is for. Present + * whenever the source takes a credential, in every state, so any client + * can deliver, rotate, or revoke one. Absent for a source that needs no + * credential. Set with `state`. + * + * `credentialResource.resource` is the endpoint URL as the definition + * names it, in any scheme the agent supports (for example + * `http://localhost:11434/v1`). It's the value a client passes back as + * `authenticate({ resource })`, and nothing fetches it. + * `credentialResource.resource_name` labels the prompt (for example + * "OpenRouter API key"). A source that accepts OAuth access tokens + * advertises `authorization_servers` and `scopes_supported`. A source that + * takes a user-supplied secret omits them. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + credentialResource?: ProtectedResourceMetadata; /** * Additional implementation-defined metadata for this registration. * MUST NOT contain a credential. @@ -454,8 +474,9 @@ export interface ModelSourceReadyState { } /** - * What a model source needs in order to become ready. Deliberately carries no - * credential. + * Why a model source needs a credential before it can be ready. Deliberately + * carries no credential. The endpoint the credential is for is the + * registration's {@link ModelSourceRegistration.credentialResource}. * * @category Root State * @stability 1.0 @@ -464,17 +485,6 @@ export interface ModelSourceReadyState { export interface ModelSourceAuthRequirement { /** Why a credential is needed. */ reason: AuthRequiredReason; - /** - * RFC 9728 metadata for the source's endpoint. `resource.resource` is the - * endpoint URL as the definition names it, in any scheme the agent - * supports (for example `http://localhost:11434/v1`). It's the value a - * client passes back as `authenticate({ resource })`, and nothing fetches - * it. `resource.resource_name` labels the prompt (for example - * "OpenRouter API key"). A source that accepts OAuth access tokens - * advertises `authorization_servers` and `scopes_supported`. A source that - * takes a user-supplied secret omits them. - */ - resource: ProtectedResourceMetadata; /** * Human-readable hint the host writes, for example "The endpoint rejected * the API key." @@ -484,7 +494,8 @@ export interface ModelSourceAuthRequirement { /** * The source needs a credential before it can be used. A client answers with - * `authenticate` and a {@link ModelSourceAuthenticateTarget}. + * `authenticate`, the registration's `credentialResource.resource`, and a + * {@link ModelSourceAuthenticateTarget}. * * @category Root State * @stability 1.0 diff --git a/types/common/commands.ts b/types/common/commands.ts index b221a15a6..13ebcd0bc 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1516,14 +1516,14 @@ export type AuthenticateTarget = * Pushes a credential for a protected resource. The `resource` field MUST * match a protected-resource identifier the client has discovered from the * server — whether declared statically in `AgentInfo.protectedResources`, - * or discovered dynamically from a live `McpServerAuthRequiredState.resource`, - * `ToolCallAuthRequiredState.auth.resource`, or - * `ModelSourceAuthRequiredState.resource` (each surfaced only once the - * corresponding MCP server, tool call, or model source actually challenges - * for auth). Servers MUST accept any `resource` value they have themselves - * advertised through one of these mechanisms, subject to the `target` - * rules. A `modelSource` target takes only the resource the host most - * recently advertised for that registration. + * or discovered dynamically from a live `McpServerAuthRequiredState.resource` + * or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the + * corresponding MCP server or tool call actually challenges for auth), or + * from a registered model source's `ModelSourceRegistration.credentialResource`. + * Servers MUST accept any `resource` value they have themselves advertised + * through one of these mechanisms, subject to the `target` rules. A + * `modelSource` target takes only the registration's current + * `credentialResource.resource`. * * Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) * (Bearer Token Usage) semantics. The client obtains the token from the @@ -1558,7 +1558,7 @@ export interface AuthenticateParams extends BaseParams { * server has advertised — via `ProtectedResourceMetadata` in * `AgentInfo.protectedResources`, or via a live * `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - * or `ModelSourceAuthRequiredState.resource`. + * or `ModelSourceRegistration.credentialResource`. */ resource: string; /** diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json similarity index 80% rename from types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json rename to types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json index ce4ecdcba..a454529ac 100644 --- a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-state-and-nonce.json +++ b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceStateChanged replaces only the matching registration's state and credentialNonce, preserving its other fields and the registry order", + "description": "root/modelSourceStateChanged sets the matching registration's state, credentialNonce, and credentialResource together, preserving its other fields and the registry order", "reducer": "root", "initial": { "agents": [], @@ -43,13 +43,13 @@ "id": "model-source-b", "state": { "kind": "authRequired", - "reason": "required", - "resource": { - "resource": "https://apib.example.com/v1", - "resource_name": "Source b API key" - } + "reason": "required" }, - "credentialNonce": "nonce-b-2" + "credentialNonce": "nonce-b-2", + "credentialResource": { + "resource": "https://apib.example.com/v1", + "resource_name": "Source b API key" + } } ], "expected": { @@ -83,13 +83,13 @@ "retention": "host", "state": { "kind": "authRequired", - "reason": "required", - "resource": { - "resource": "https://apib.example.com/v1", - "resource_name": "Source b API key" - } + "reason": "required" }, - "credentialNonce": "nonce-b-2" + "credentialNonce": "nonce-b-2", + "credentialResource": { + "resource": "https://apib.example.com/v1", + "resource_name": "Source b API key" + } } ] } diff --git a/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json b/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json new file mode 100644 index 000000000..a82f5d9b4 --- /dev/null +++ b/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json @@ -0,0 +1,63 @@ +{ + "description": "root/modelSourceStateChanged without credentialResource clears the registration's existing one, for a source that turns out to need no credential", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1", + "state": { + "kind": "authRequired", + "reason": "required" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + } + } + ] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-a", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "name": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + }, + "clientId": "client-1", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-2" + } + ] + } +} diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 7701804ee..557dc680a 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot carries model source registrations with no reported state and in each lifecycle state, including an http endpoint and a host-registered source without clientId. The agent advertises the modelSourceRegistration capability, and its catalog lists the ready registration and the authRequired one whose key expired, since models stay listed after a registration has been ready.", + "description": "A root snapshot carries model source registrations with no reported state and in each lifecycle state, including an http endpoint and a host-registered source without clientId. Sources that take a credential carry a host-reported credentialResource in every state, including ready. The agent advertises the modelSourceRegistration capability, and its catalog lists the ready registration and the authRequired one whose key expired, since models stay listed after a registration has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -113,6 +113,10 @@ "kind": "ready" }, "credentialNonce": "nonce-ready-1", + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, "_meta": { "example.com/label": "Laptop" } @@ -137,19 +141,19 @@ "state": { "kind": "authRequired", "reason": "expired", - "resource": { - "resource": "https://example.openai.azure.com/openai/v1", - "resource_name": "Azure OpenAI", - "authorization_servers": [ - "https://login.microsoftonline.com/common/v2.0" - ], - "scopes_supported": [ - "https://cognitiveservices.azure.com/.default" - ] - }, "description": "The access token expired." }, - "credentialNonce": "nonce-auth-1" + "credentialNonce": "nonce-auth-1", + "credentialResource": { + "resource": "https://example.openai.azure.com/openai/v1", + "resource_name": "Azure OpenAI", + "authorization_servers": [ + "https://login.microsoftonline.com/common/v2.0" + ], + "scopes_supported": [ + "https://cognitiveservices.azure.com/.default" + ] + } }, { "id": "source-local", @@ -162,13 +166,13 @@ "clientId": "client-1", "state": { "kind": "authRequired", - "reason": "required", - "resource": { - "resource": "http://localhost:11434/v1", - "resource_name": "Local server key" - } + "reason": "required" }, - "credentialNonce": "nonce-local-1" + "credentialNonce": "nonce-local-1", + "credentialResource": { + "resource": "http://localhost:11434/v1", + "resource_name": "Local server key" + } }, { "id": "source-host", @@ -301,6 +305,10 @@ "kind": "ready" }, "credentialNonce": "nonce-ready-1", + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, "_meta": { "example.com/label": "Laptop" } @@ -325,19 +333,19 @@ "state": { "kind": "authRequired", "reason": "expired", - "resource": { - "resource": "https://example.openai.azure.com/openai/v1", - "resource_name": "Azure OpenAI", - "authorization_servers": [ - "https://login.microsoftonline.com/common/v2.0" - ], - "scopes_supported": [ - "https://cognitiveservices.azure.com/.default" - ] - }, "description": "The access token expired." }, - "credentialNonce": "nonce-auth-1" + "credentialNonce": "nonce-auth-1", + "credentialResource": { + "resource": "https://example.openai.azure.com/openai/v1", + "resource_name": "Azure OpenAI", + "authorization_servers": [ + "https://login.microsoftonline.com/common/v2.0" + ], + "scopes_supported": [ + "https://cognitiveservices.azure.com/.default" + ] + } }, { "id": "source-local", @@ -350,13 +358,13 @@ "clientId": "client-1", "state": { "kind": "authRequired", - "reason": "required", - "resource": { - "resource": "http://localhost:11434/v1", - "resource_name": "Local server key" - } + "reason": "required" }, - "credentialNonce": "nonce-local-1" + "credentialNonce": "nonce-local-1", + "credentialResource": { + "resource": "http://localhost:11434/v1", + "resource_name": "Local server key" + } }, { "id": "source-host", diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json index 8c4066a09..a98c189e8 100644 --- a/types/test-cases/round-trips/107-root-model-source-state-changed.json +++ b/types/test-cases/round-trips/107-root-model-source-state-changed.json @@ -1,7 +1,7 @@ { "name": "root-model-source-state-changed", "group": "A", - "description": "The host reports a registration's status and issues a credential nonce with root/modelSourceStateChanged, here asking for an API key.", + "description": "The host reports a registration's status with root/modelSourceStateChanged, issuing a credential nonce and the credentialResource the key is for, here asking for an API key.", "type": "StateAction", "input": { "type": "root/modelSourceStateChanged", @@ -9,13 +9,13 @@ "state": { "kind": "authRequired", "reason": "required", - "resource": { - "resource": "https://openrouter.ai/api/v1", - "resource_name": "OpenRouter API key" - }, "description": "The endpoint needs an API key." }, - "credentialNonce": "nonce-openrouter-1" + "credentialNonce": "nonce-openrouter-1", + "credentialResource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + } }, "acceptableOutputs": [ { @@ -24,13 +24,13 @@ "state": { "kind": "authRequired", "reason": "required", - "resource": { - "resource": "https://openrouter.ai/api/v1", - "resource_name": "OpenRouter API key" - }, "description": "The endpoint needs an API key." }, - "credentialNonce": "nonce-openrouter-1" + "credentialNonce": "nonce-openrouter-1", + "credentialResource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + } } ] } From 5d7790d4d6bac57bdb3602cdfa3614a5d37fb842 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 11:15:08 -0500 Subject: [PATCH 07/17] models: name the registration's display field displayName Address review feedback on #627: - Rename `ModelSourceRegistration.name` to `displayName`. The naming dictionary reserves `name` for stable or machine-oriented names, and the field is published as `ModelSourceInfo.displayName`. - Point the authentication spec's Token Delivery paragraph at `ModelSourceRegistration.credentialResource.resource`, since `ModelSourceAuthRequiredState` no longer carries a resource. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/State.generated.cs | 4 ++-- clients/go/ahptypes/state.generated.go | 8 +++---- .../generated/State.generated.kt | 4 ++-- clients/rust/crates/ahp-types/src/state.rs | 4 ++-- .../Generated/State.generated.swift | 14 +++++------ docs/specification/authentication.md | 2 +- docs/specification/root-channel.md | 6 ++--- schema/actions.schema.json | 6 ++--- schema/commands.schema.json | 6 ++--- schema/errors.schema.json | 6 ++--- schema/notifications.schema.json | 6 ++--- schema/state.schema.json | 6 ++--- types/channels-root/state.ts | 4 ++-- ...gistrationset-adds-to-absent-registry.json | 4 ++-- ...lsourceregistrationset-appends-new-id.json | 8 +++---- ...lsourceregistrationset-replaces-by-id.json | 10 ++++---- ...urceregistrationremoved-removes-by-id.json | 6 ++--- ...istrationremoved-no-op-for-unknown-id.json | 4 ++-- ...echanged-updates-host-reported-fields.json | 8 +++---- ...urcestatechanged-no-op-for-unknown-id.json | 4 ++-- ...atechanged-clears-credential-resource.json | 4 ++-- .../103-model-source-registry-snapshot.json | 24 +++++++++---------- ...04-root-model-source-registration-set.json | 4 ++-- 23 files changed, 76 insertions(+), 76 deletions(-) diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 500e926eb..41ebd9c28 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2374,8 +2374,8 @@ public sealed record ModelSourceRegistration /// Agent provider whose agent reads the definition and serves the models. public required string Provider { get; init; } - /// Display name, published as {@link ModelSourceInfo.displayName}. - public required string Name { get; init; } + /// Human-readable name, published as {@link ModelSourceInfo.displayName}. + public required string DisplayName { get; init; } /// Icons for UI display. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index fc5e4e1f3..e0ff45534 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -983,8 +983,8 @@ type ModelSourceRegistration struct { Id string `json:"id"` // Agent provider whose agent reads the definition and serves the models. Provider string `json:"provider"` - // Display name, published as {@link ModelSourceInfo.displayName}. - Name string `json:"name"` + // Human-readable name, published as {@link ModelSourceInfo.displayName}. + DisplayName string `json:"displayName"` // Icons for UI display. Icons []Icon `json:"icons,omitempty"` // Definition format, one of the agent's @@ -1034,12 +1034,12 @@ type ModelSourceRegistration struct { func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistration - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") } func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistration - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "name", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") } // The agent is reading and validating the definition, or listing the 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 9a2d8ab89..ccf7c745e 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 @@ -1812,9 +1812,9 @@ data class ModelSourceRegistration( */ val provider: String, /** - * Display name, published as {@link ModelSourceInfo.displayName}. + * Human-readable name, published as {@link ModelSourceInfo.displayName}. */ - val name: String, + val displayName: String, /** * Icons for UI display. */ diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 01e382811..46ebbd2c1 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2138,8 +2138,8 @@ pub struct ModelSourceRegistration { pub id: String, /// Agent provider whose agent reads the definition and serves the models. pub provider: String, - /// Display name, published as {@link ModelSourceInfo.displayName}. - pub name: String, + /// Human-readable name, published as {@link ModelSourceInfo.displayName}. + pub display_name: String, /// Icons for UI display. #[serde(default, skip_serializing_if = "Option::is_none")] pub icons: Option>, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index d2c5c01d7..0cc1394b6 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1818,8 +1818,8 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { public var id: String /// Agent provider whose agent reads the definition and serves the models. public var provider: String - /// Display name, published as {@link ModelSourceInfo.displayName}. - public var name: String + /// Human-readable name, published as {@link ModelSourceInfo.displayName}. + public var displayName: String /// Icons for UI display. public var icons: [Icon]? /// Definition format, one of the agent's @@ -1869,7 +1869,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { enum CodingKeys: String, CodingKey, CaseIterable { case id case provider - case name + case displayName case icons case format case definition @@ -1884,7 +1884,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { public init( id: String, provider: String, - name: String, + displayName: String, icons: [Icon]? = nil, format: String, definition: [String: AnyCodable], @@ -1898,7 +1898,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { ) { self.id = id self.provider = provider - self.name = name + self.displayName = displayName self.icons = icons self.format = format self.definition = definition @@ -1915,7 +1915,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(String.self, forKey: .id) self.provider = try container.decode(String.self, forKey: .provider) - self.name = try container.decode(String.self, forKey: .name) + self.displayName = try container.decode(String.self, forKey: .displayName) self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) self.format = try container.decode(String.self, forKey: .format) self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) @@ -1932,7 +1932,7 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.id, forKey: .id) try container.encode(self.provider, forKey: .provider) - try container.encode(self.name, forKey: .name) + try container.encode(self.displayName, forKey: .displayName) try container.encodeIfPresent(self.icons, forKey: .icons) try container.encode(self.format, forKey: .format) try container.encode(self.definition, forKey: .definition) diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index cfd1e9976..321437d1e 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -87,7 +87,7 @@ Different agents MAY require authentication with different providers. For exampl ## Token Delivery -Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `ModelSourceAuthRequiredState.resource` (see [Model source credentials](#model-source-credentials)): +Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `ModelSourceRegistration.credentialResource.resource`, which stays available while the source is ready for rotation and revocation (see [Model source credentials](#model-source-credentials)): ```jsonc // Client → Server diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index e03ff37c6..a5b66450b 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -69,7 +69,7 @@ Clients can register bring-your-own-key model sources with the host, so its agen { "id": "2f6c0e1a-model-source", "provider": "example", - "name": "OpenRouter", + "displayName": "OpenRouter", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://openrouter.ai/api/v1" }, "clientId": "laptop", @@ -98,7 +98,7 @@ The host rejects a client's `Set`, through `rejectionReason`, when: A client's `Removed` is a no-op when no registration has that `id`. -When a `Set` changes a registration's `provider`, `format`, or `definition`, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A change to `name`, `icons`, `clientId`, or `retention` keeps the credential and the nonce. A host may also register sources itself. Those registrations have no `clientId`, and their retention behaves as `host`. +When a `Set` changes a registration's `provider`, `format`, or `definition`, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A change to `displayName`, `icons`, `clientId`, or `retention` keeps the credential and the nonce. A host may also register sources itself. Those registrations have no `clientId`, and their retention behaves as `host`. #### Status @@ -112,7 +112,7 @@ A client's `Set` replaces the whole registration, so it clears the host-reported #### Catalog -When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `name`, and its models in `models` with `modelSourceId` set to that `id`. Once the registration has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the registration is removed, when its contributing client leaves under `contributingClient` retention, when it enters `error`, or when a change to `provider`, `format`, or `definition` mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). A turn that uses a listed model while the source has no usable credential ends with a resumable error, as described in [Model source credentials](/specification/authentication#model-source-credentials). The host MAY list the `ModelSourceInfo` in any state. +When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `displayName`, and its models in `models` with `modelSourceId` set to that `id`. Once the registration has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the registration is removed, when its contributing client leaves under `contributingClient` retention, when it enters `error`, or when a change to `provider`, `format`, or `definition` mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). A turn that uses a listed model while the source has no usable credential ends with a resumable error, as described in [Model source credentials](/specification/authentication#model-source-credentials). The host MAY list the `ModelSourceInfo` in any state. Any client can select a registered source's models, in any session whose agent is the registration's `provider`. The host checks every selection: the model is listed, and the chat is backed by the registration's agent provider. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 18a8b800b..16491ffc8 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -3589,9 +3589,9 @@ "type": "string", "description": "Agent provider whose agent reads the definition and serves the models." }, - "name": { + "displayName": { "type": "string", - "description": "Display name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." }, "icons": { "type": "array", @@ -3638,7 +3638,7 @@ "required": [ "id", "provider", - "name", + "displayName", "format", "definition" ] diff --git a/schema/commands.schema.json b/schema/commands.schema.json index e87655125..fc9ea826f 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -2913,9 +2913,9 @@ "type": "string", "description": "Agent provider whose agent reads the definition and serves the models." }, - "name": { + "displayName": { "type": "string", - "description": "Display name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." }, "icons": { "type": "array", @@ -2962,7 +2962,7 @@ "required": [ "id", "provider", - "name", + "displayName", "format", "definition" ] diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 3ad70b5f8..80fdc0c30 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -893,9 +893,9 @@ "type": "string", "description": "Agent provider whose agent reads the definition and serves the models." }, - "name": { + "displayName": { "type": "string", - "description": "Display name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." }, "icons": { "type": "array", @@ -942,7 +942,7 @@ "required": [ "id", "provider", - "name", + "displayName", "format", "definition" ] diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 96add4c9a..68db28ae3 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1195,9 +1195,9 @@ "type": "string", "description": "Agent provider whose agent reads the definition and serves the models." }, - "name": { + "displayName": { "type": "string", - "description": "Display name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." }, "icons": { "type": "array", @@ -1244,7 +1244,7 @@ "required": [ "id", "provider", - "name", + "displayName", "format", "definition" ] diff --git a/schema/state.schema.json b/schema/state.schema.json index e29897f4c..86fc9b7f2 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -804,9 +804,9 @@ "type": "string", "description": "Agent provider whose agent reads the definition and serves the models." }, - "name": { + "displayName": { "type": "string", - "description": "Display name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." }, "icons": { "type": "array", @@ -853,7 +853,7 @@ "required": [ "id", "provider", - "name", + "displayName", "format", "definition" ] diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index d7045d03a..cdd008ef4 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -351,8 +351,8 @@ export interface ModelSourceRegistration { id: string; /** Agent provider whose agent reads the definition and serves the models. */ provider: string; - /** Display name, published as {@link ModelSourceInfo.displayName}. */ - name: string; + /** Human-readable name, published as {@link ModelSourceInfo.displayName}. */ + displayName: string; /** Icons for UI display. */ icons?: Icon[]; /** diff --git a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json index 0776c9a10..0a537fa31 100644 --- a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json +++ b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json @@ -10,7 +10,7 @@ "registration": { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -28,7 +28,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", diff --git a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json index 9a8e76a7c..db1128831 100644 --- a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json +++ b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -25,7 +25,7 @@ "registration": { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", @@ -43,7 +43,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -56,7 +56,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json index cfba1cd12..37f19b231 100644 --- a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json +++ b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -24,7 +24,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", @@ -42,7 +42,7 @@ "registration": { "id": "model-source-a", "provider": "copilot", - "name": "Source a (renamed)", + "displayName": "Source a (renamed)", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -60,7 +60,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a (renamed)", + "displayName": "Source a (renamed)", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -73,7 +73,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", diff --git a/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json b/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json index 5fbc57739..dfff67bb5 100644 --- a/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json +++ b/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -20,7 +20,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", @@ -44,7 +44,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", diff --git a/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json index e5d1f86c0..d50f02309 100644 --- a/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -31,7 +31,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json index a454529ac..cbef1af00 100644 --- a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json +++ b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -20,7 +20,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", @@ -58,7 +58,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -71,7 +71,7 @@ { "id": "model-source-b", "provider": "copilot", - "name": "Source b", + "displayName": "Source b", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apib.example.com/v1", diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json index e42927d51..f9ede0026 100644 --- a/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -35,7 +35,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", diff --git a/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json b/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json index a82f5d9b4..1314040d1 100644 --- a/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json +++ b/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json @@ -7,7 +7,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", @@ -44,7 +44,7 @@ { "id": "model-source-a", "provider": "copilot", - "name": "Source a", + "displayName": "Source a", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://apia.example.com/v1", diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 557dc680a..735675977 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -52,7 +52,7 @@ { "id": "source-unreported", "provider": "example", - "name": "Unreported", + "displayName": "Unreported", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://api.example.com/v1", @@ -69,7 +69,7 @@ { "id": "source-starting", "provider": "example", - "name": "Starting", + "displayName": "Starting", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://api.example.com/v1", @@ -90,7 +90,7 @@ { "id": "source-ready", "provider": "example", - "name": "OpenRouter", + "displayName": "OpenRouter", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://api.example.com/v1", @@ -124,7 +124,7 @@ { "id": "source-auth", "provider": "example", - "name": "Azure endpoint", + "displayName": "Azure endpoint", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://example.openai.azure.com/openai/v1", @@ -158,7 +158,7 @@ { "id": "source-local", "provider": "example", - "name": "Local server", + "displayName": "Local server", "format": "example.com/model-source@1", "definition": { "baseUrl": "http://localhost:11434/v1" @@ -177,7 +177,7 @@ { "id": "source-host", "provider": "example", - "name": "Host-configured", + "displayName": "Host-configured", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://models.internal.example/v1" @@ -244,7 +244,7 @@ { "id": "source-unreported", "provider": "example", - "name": "Unreported", + "displayName": "Unreported", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://api.example.com/v1", @@ -261,7 +261,7 @@ { "id": "source-starting", "provider": "example", - "name": "Starting", + "displayName": "Starting", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://api.example.com/v1", @@ -282,7 +282,7 @@ { "id": "source-ready", "provider": "example", - "name": "OpenRouter", + "displayName": "OpenRouter", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://api.example.com/v1", @@ -316,7 +316,7 @@ { "id": "source-auth", "provider": "example", - "name": "Azure endpoint", + "displayName": "Azure endpoint", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://example.openai.azure.com/openai/v1", @@ -350,7 +350,7 @@ { "id": "source-local", "provider": "example", - "name": "Local server", + "displayName": "Local server", "format": "example.com/model-source@1", "definition": { "baseUrl": "http://localhost:11434/v1" @@ -369,7 +369,7 @@ { "id": "source-host", "provider": "example", - "name": "Host-configured", + "displayName": "Host-configured", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://models.internal.example/v1" diff --git a/types/test-cases/round-trips/104-root-model-source-registration-set.json b/types/test-cases/round-trips/104-root-model-source-registration-set.json index 2e4bcd92e..07158eafe 100644 --- a/types/test-cases/round-trips/104-root-model-source-registration-set.json +++ b/types/test-cases/round-trips/104-root-model-source-registration-set.json @@ -8,7 +8,7 @@ "registration": { "id": "source-new", "provider": "example", - "name": "OpenRouter", + "displayName": "OpenRouter", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://openrouter.ai/api/v1", @@ -30,7 +30,7 @@ "registration": { "id": "source-new", "provider": "example", - "name": "OpenRouter", + "displayName": "OpenRouter", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://openrouter.ai/api/v1", From e06ed620552617975ec2fe464cf83441beeedcf8 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 13:16:24 -0500 Subject: [PATCH 08/17] models: contributors, credential identity, and turn rules for the registry Implement the reworked registry from #622: - `ModelSourceRegistration.contributingClientIds` replaces `clientId`. `root/modelSourceRegistrationSet` gains `clientId` and adds, joins an unchanged routing (keeping every host-reported field), or replaces a changed one. Definitions compare as JSON values, ignoring key order and comparing numbers by value. The new client-dispatchable `root/modelSourceContributorRemoved` withdraws one contribution. - Host-reported `credentialOrigins` and `credentialId` on the registration and on `root/modelSourceStateChanged`, and an optional `credentialId` on the `modelSource` authenticate target. - `ModelSourceAuthRequiredReason` (required, expired, rejected, revoked) replaces the shared `AuthRequiredReason` for model sources. - `ModelSourceRegistrationCapability` gains `gracePeriod` and `principalPolicy` (`ModelSourcePrincipalPolicy`: shared, isolated). - `ErrorInfo.errorType` documents the well-known `modelSourceUnavailable` value. - Reducers in TypeScript and every client, regenerated fixtures for every branch, and the root channel, authentication, naming, and guide docs. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../protocol-naming.instructions.md | 3 +- .../Generated/Actions.generated.cs | 73 +++++- .../Generated/Commands.generated.cs | 9 + .../JsonSerializerContext.generated.cs | 3 + .../Generated/State.generated.cs | 202 +++++++++++++-- .../Generated/ActionMetadata.generated.cs | 3 + .../dotnet/src/AgentHostProtocol/Reducers.cs | 115 ++++++++- clients/go/ahp/reducers.go | 121 +++++++-- clients/go/ahptypes/actions.generated.go | 69 ++++- clients/go/ahptypes/commands.generated.go | 7 + clients/go/ahptypes/state.generated.go | 112 +++++++-- .../microsoft/agenthostprotocol/Reducers.kt | 55 +++- .../generated/Actions.generated.kt | 82 +++++- .../generated/Commands.generated.kt | 11 +- .../generated/State.generated.kt | 152 +++++++++-- clients/rust/crates/ahp-types/src/actions.rs | 72 +++++- clients/rust/crates/ahp-types/src/commands.rs | 8 + clients/rust/crates/ahp-types/src/state.rs | 170 +++++++++++-- clients/rust/crates/ahp/src/reducers.rs | 116 ++++++++- .../Generated/ActionOrigin.generated.swift | 2 + .../Generated/Actions.generated.swift | 88 ++++++- .../Generated/Commands.generated.swift | 11 +- .../Generated/State.generated.swift | 184 ++++++++++++-- .../AgentHostProtocol/NativeReducer.swift | 56 ++++- .../Sources/AgentHostProtocol/Reducers.swift | 7 +- .../20261123-model-source-registry.json | 2 +- docs/guide/actions.md | 7 +- docs/specification/authentication.md | 60 ++++- docs/specification/root-channel.md | 78 ++++-- schema/actions.schema.json | 115 +++++++-- schema/commands.schema.json | 119 +++++++-- schema/errors.schema.json | 119 +++++++-- schema/notifications.schema.json | 69 +++-- schema/state.schema.json | 67 +++-- scripts/generate-csharp.ts | 3 +- scripts/generate-go.ts | 3 +- scripts/generate-kotlin.ts | 3 +- scripts/generate-rust.ts | 5 +- scripts/generate-swift.ts | 3 +- types/action-origin.generated.ts | 4 + types/channels-root/actions.ts | 70 +++++- types/channels-root/reducer.ts | 87 ++++++- types/channels-root/state.ts | 122 +++++++-- types/common/actions.ts | 3 + types/common/commands.ts | 9 + types/common/state.ts | 10 +- ...gistrationset-adds-to-absent-registry.json | 34 ++- ...lsourceregistrationset-appends-new-id.json | 64 +++-- ...t-host-registers-without-contributors.json | 57 +++++ ...lsourceregistrationset-replaces-by-id.json | 88 ------- ...gistrationset-joins-unchanged-routing.json | 152 +++++++++++ ...t-existing-contributor-not-duplicated.json | 111 ++++++++ ...ins-registration-without-contributors.json | 109 ++++++++ ...rationset-replaces-changed-definition.json | 140 +++++++++++ ...gistrationset-replaces-changed-format.json | 95 +++++++ ...rceregistrationremoved-removes-by-id.json} | 48 +++- ...strationremoved-no-op-for-unknown-id.json} | 30 ++- ...onremoved-no-op-when-registry-absent.json} | 0 ...ibutorremoved-removes-one-contributor.json | 90 +++++++ ...d-last-contributor-keeps-registration.json | 86 +++++++ ...butorremoved-no-op-for-unknown-client.json | 89 +++++++ ...torremoved-no-op-without-contributors.json | 61 +++++ ...ntributorremoved-no-op-for-unknown-id.json | 65 +++++ ...torremoved-no-op-when-registry-absent.json | 17 ++ ...changed-updates-host-reported-fields.json} | 80 ++++-- ...tatechanged-clears-credential-fields.json} | 41 ++- ...rcestatechanged-no-op-for-unknown-id.json} | 30 ++- ...techanged-no-op-when-registry-absent.json} | 0 ...et-joins-numerically-equal-definition.json | 79 ++++++ .../103-model-source-registry-snapshot.json | 236 ++++++++++++++++-- ...04-root-model-source-registration-set.json | 10 +- .../106-authenticate-model-source-target.json | 8 +- .../107-root-model-source-state-changed.json | 26 +- ...root-model-source-contributor-removed.json | 18 ++ types/version/registry.ts | 1 + 75 files changed, 3965 insertions(+), 589 deletions(-) create mode 100644 types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json delete mode 100644 types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json create mode 100644 types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json create mode 100644 types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json create mode 100644 types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json create mode 100644 types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json create mode 100644 types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json rename types/test-cases/reducers/{333-root-modelsourceregistrationremoved-removes-by-id.json => 338-root-modelsourceregistrationremoved-removes-by-id.json} (56%) rename types/test-cases/reducers/{334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json => 339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json} (63%) rename types/test-cases/reducers/{335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json => 340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json} (100%) create mode 100644 types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json create mode 100644 types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json create mode 100644 types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json create mode 100644 types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json create mode 100644 types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json create mode 100644 types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json rename types/test-cases/reducers/{336-root-modelsourcestatechanged-updates-host-reported-fields.json => 347-root-modelsourcestatechanged-updates-host-reported-fields.json} (54%) rename types/test-cases/reducers/{339-root-modelsourcestatechanged-clears-credential-resource.json => 348-root-modelsourcestatechanged-clears-credential-fields.json} (60%) rename types/test-cases/reducers/{337-root-modelsourcestatechanged-no-op-for-unknown-id.json => 349-root-modelsourcestatechanged-no-op-for-unknown-id.json} (66%) rename types/test-cases/reducers/{338-root-modelsourcestatechanged-no-op-when-registry-absent.json => 350-root-modelsourcestatechanged-no-op-when-registry-absent.json} (100%) create mode 100644 types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json create mode 100644 types/test-cases/round-trips/108-root-model-source-contributor-removed.json diff --git a/.github/instructions/protocol-naming.instructions.md b/.github/instructions/protocol-naming.instructions.md index 3a1864d9d..683972e53 100644 --- a/.github/instructions/protocol-naming.instructions.md +++ b/.github/instructions/protocol-naming.instructions.md @@ -40,7 +40,8 @@ but don't use them as precedent. | **model** | A model offered by an agent provider (`SessionModelInfo`). It is selected per message (`Message.model`). | | | **model source** (`modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `AgentInfo.modelSources` (`ModelSourceInfo`). Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | | **registration** (`ModelSourceRegistration`) | A model source a client or the host added to the host's registry in `RootState.modelSourceRegistrations`, with its definition and status. A ready registration joins its agent's catalog as a model source. | The **model source** it becomes in the catalog. | -| **contributing client** | The client that added a client-contributed entry, named by its `clientId`. For a model source registration, it's the client that most recently registered or changed it, and it chooses the registration's retention. | The **action origin**'s `clientId`, which names the client that dispatched one action. | +| **contributing client** | A client that added a client-contributed entry, named by its `clientId`. A model source registration can have several, listed in `contributingClientIds`; each adds and withdraws only its own contribution. | The **action origin**'s `clientId`, which names the client that dispatched one action. | +| **principal** | The user or account a host has verified a client acts for. AHP doesn't define how a host verifies one (`ModelSourcePrincipalPolicy`). | A **client** (`clientId`), which identifies a connection's client and isn't verified. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | | **pending message** | Input waiting to be consumed. Its `kind` is **steering** (injected into the active turn) or **queued** (starts a later turn). Both kinds live in `ChatState.queuedMessages`. | | | **working directories** | The session's set of directories. A chat may use a subset. | Don't use "workspace" for a protocol field. | diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 12f9846e5..feeca37a0 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -201,6 +201,8 @@ public ActionType(string value) public static readonly ActionType RootModelSourceRegistrationSet = new ActionType("root/modelSourceRegistrationSet"); + public static readonly ActionType RootModelSourceContributorRemoved = new ActionType("root/modelSourceContributorRemoved"); + public static readonly ActionType RootModelSourceRegistrationRemoved = new ActionType("root/modelSourceRegistrationRemoved"); public static readonly ActionType RootModelSourceStateChanged = new ActionType("root/modelSourceStateChanged"); @@ -346,24 +348,63 @@ public sealed record RootConfigChangedAction public bool? Replace { get; init; } } -/// Adds a model source registration, or replaces the one with the same `id`. +/// Contributes a model source registration for `clientId`. A registration's +/// routing is its `provider`, `format`, and `definition`, with definitions +/// compared as JSON values: object key order is ignored, and numbers compare +/// by numeric value, so `1` equals `1.0`. +/// +/// - **Add.** When no registration has the `id`, appends it, with +/// `contributingClientIds` set to `[clientId]`, or absent without a +/// `clientId`. +/// - **Join.** When one has, and its routing is unchanged, keeps its +/// host-reported fields (`state`, `credentialNonce`, `credentialResource`, +/// `credentialOrigins`, and `credentialId`), adds `clientId` to +/// `contributingClientIds` if it isn't there, and takes the other fields +/// from the action. +/// - **Replace.** When the routing changed, replaces the registration, with +/// `contributingClientIds` set to `[clientId]`, or absent without a +/// `clientId`. Its host-reported fields are absent until the host reports +/// again with {@link RootModelSourceStateChangedAction}. /// -/// A client registers a source by dispatching this with its own `clientId`, and -/// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a -/// registration clears those host-reported fields until the host reports again -/// with {@link RootModelSourceStateChangedAction}. +/// A client dispatches this with its own `clientId`, and without +/// `contributingClientIds` or any host-reported field. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceRegistrationSetAction { public ActionType Type { get; init; } = ActionType.RootModelSourceRegistrationSet; - /// The registration to add or replace, matched by `id`. + /// The registration to contribute, matched by `id`. public required ModelSourceRegistration Registration { get; init; } + + /// The contributing client. Absent when the host registers the source + /// itself. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? ClientId { get; init; } } -/// Removes the model source registration with the given `id`. A no-op when -/// none matches. +/// Withdraws one client's contribution to a model source registration: +/// removes `clientId` from `contributingClientIds`, leaving the field absent +/// when no contributor remains. A no-op when no registration has `id`, or +/// `clientId` doesn't contribute it. It never removes the registration. +/// +/// A client dispatches this with its own `clientId`. The host dispatches it +/// when a contributing client leaves. +/// +/// Stability: 1.0 - Early development. +public sealed record RootModelSourceContributorRemovedAction +{ + public ActionType Type { get; init; } = ActionType.RootModelSourceContributorRemoved; + + /// The registration's `id`. + public required string Id { get; init; } + + /// The contributing client to remove. + public required string ClientId { get; init; } +} + +/// Removes the model source registration with the given `id` for every +/// contributor. A no-op when none matches. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceRegistrationRemovedAction @@ -374,9 +415,10 @@ public sealed record RootModelSourceRegistrationRemovedAction public required string Id { get; init; } } -/// Updates a model source registration's status, credential nonce, and -/// credential resource together. A no-op when no registration has `id`. Other -/// fields of the registration are preserved. Only the host dispatches it. +/// Updates a model source registration's host-reported fields together: +/// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and +/// `credentialId`. A no-op when no registration has `id`. Other fields of the +/// registration are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceStateChangedAction @@ -396,6 +438,14 @@ public sealed record RootModelSourceStateChangedAction /// source that needs no credential. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } + + /// Replaces the registration's `credentialOrigins`. Absent clears it. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? CredentialOrigins { get; init; } + + /// Replaces the registration's `credentialId`. Absent clears it. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? CredentialId { get; init; } } /// Session backend initialized successfully. @@ -2917,6 +2967,7 @@ public StateActionConverter() ["root/activeSessionsChanged"] = typeof(RootActiveSessionsChangedAction), ["root/configChanged"] = typeof(RootConfigChangedAction), ["root/modelSourceRegistrationSet"] = typeof(RootModelSourceRegistrationSetAction), + ["root/modelSourceContributorRemoved"] = typeof(RootModelSourceContributorRemovedAction), ["root/modelSourceRegistrationRemoved"] = typeof(RootModelSourceRegistrationRemovedAction), ["root/modelSourceStateChanged"] = typeof(RootModelSourceStateChangedAction), ["session/ready"] = typeof(SessionReadyAction), diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 6c296d684..2f2d44139 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1899,6 +1899,15 @@ public sealed record ModelSourceAuthenticateTarget /// published in root state. The host rejects a stale one with `Conflict` /// (-32011). public required string CredentialNonce { get; init; } + + /// A client-chosen, non-secret ID for the credential, such as a hash of + /// where the client stores the key. The host publishes it as the + /// registration's `ModelSourceRegistration.credentialId`, so a client can + /// tell whether the host holds its current key. Clients SHOULD include it + /// when delivering a credential, and omit it when revoking one. MUST NOT be + /// derived from the secret. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? CredentialId { get; init; } } /// Pushes a credential for a protected resource. The `resource` field MUST diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 2707221e8..25e0fea3e 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -299,10 +299,12 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(MessageResourceAttachment))] [JsonSerializable(typeof(ModelSelection))] [JsonSerializable(typeof(ModelSourceAuthenticateTarget))] +[JsonSerializable(typeof(ModelSourceAuthRequiredReason))] [JsonSerializable(typeof(ModelSourceAuthRequiredState))] [JsonSerializable(typeof(ModelSourceAuthRequirement))] [JsonSerializable(typeof(ModelSourceErrorState))] [JsonSerializable(typeof(ModelSourceInfo))] +[JsonSerializable(typeof(ModelSourcePrincipalPolicy))] [JsonSerializable(typeof(ModelSourceReadyState))] [JsonSerializable(typeof(ModelSourceRegistration))] [JsonSerializable(typeof(ModelSourceRegistrationCapability))] @@ -370,6 +372,7 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RootAgentsChangedAction))] [JsonSerializable(typeof(RootConfigChangedAction))] [JsonSerializable(typeof(RootConfigState))] +[JsonSerializable(typeof(RootModelSourceContributorRemovedAction))] [JsonSerializable(typeof(RootModelSourceRegistrationRemovedAction))] [JsonSerializable(typeof(RootModelSourceRegistrationSetAction))] [JsonSerializable(typeof(RootModelSourceStateChangedAction))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 41ebd9c28..0148843db 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1469,7 +1469,9 @@ public override void Write(Utf8JsonWriter writer, ModelSourceStatus value, JsonS => writer.WriteStringValue(value.Value); } -/// How long a registered model source lasts once its contributing client leaves. +/// How long a registered model source lasts once its last contributing client +/// leaves. When the last contributor withdraws instead, the source goes away +/// whatever its retention. /// /// Stability: 1.0 - Early development. [JsonConverter(typeof(ModelSourceRetentionPolicyConverter))] @@ -1487,10 +1489,10 @@ public ModelSourceRetentionPolicy(string value) /// The raw wire value. public string Value => _value ?? string.Empty; - /// Removed when the contributing client leaves, once running turns finish. + /// Removed when the last contributing client leaves, once running turns finish. public static readonly ModelSourceRetentionPolicy ContributingClient = new ModelSourceRetentionPolicy("contributingClient"); - /// Kept until a client removes it or host policy expires it. + /// Kept until it's removed, its last contributor withdraws, or host policy expires it. public static readonly ModelSourceRetentionPolicy Host = new ModelSourceRetentionPolicy("host"); /// @@ -1524,6 +1526,129 @@ public override void Write(Utf8JsonWriter writer, ModelSourceRetentionPolicy val => writer.WriteStringValue(value.Value); } +/// Why a model source needs a credential. Specific to model sources: the +/// shared `AuthRequiredReason` folds rejection and revocation into `expired`. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(ModelSourceAuthRequiredReasonConverter))] +public readonly struct ModelSourceAuthRequiredReason : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public ModelSourceAuthRequiredReason(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// The host holds no credential yet. + public static readonly ModelSourceAuthRequiredReason Required = new ModelSourceAuthRequiredReason("required"); + + /// The credential's lifetime or lease lapsed. A client may renew it. + public static readonly ModelSourceAuthRequiredReason Expired = new ModelSourceAuthRequiredReason("expired"); + + /// The endpoint refused the credential. Clients don't send a credential with + /// the same {@link ModelSourceRegistration.credentialId} again. + public static readonly ModelSourceAuthRequiredReason Rejected = new ModelSourceAuthRequiredReason("rejected"); + + /// A client revoked the credential. Clients don't send one again without a user's action. + public static readonly ModelSourceAuthRequiredReason Revoked = new ModelSourceAuthRequiredReason("revoked"); + + /// + public bool Equals(ModelSourceAuthRequiredReason other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is ModelSourceAuthRequiredReason other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(ModelSourceAuthRequiredReason left, ModelSourceAuthRequiredReason right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(ModelSourceAuthRequiredReason left, ModelSourceAuthRequiredReason right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class ModelSourceAuthRequiredReasonConverter : JsonConverter +{ + /// + public override ModelSourceAuthRequiredReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new ModelSourceAuthRequiredReason(reader.GetString() ?? throw new JsonException("ModelSourceAuthRequiredReason expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, ModelSourceAuthRequiredReason value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + +/// Whether clients acting for different principals share a host's model +/// source registry. +/// +/// Stability: 1.0 - Early development. +[JsonConverter(typeof(ModelSourcePrincipalPolicyConverter))] +public readonly struct ModelSourcePrincipalPolicy : IEquatable +{ + private readonly string? _value; + + /// Wraps a raw wire value — including one this build does not recognize. + /// The raw wire string. + public ModelSourcePrincipalPolicy(string value) + { + _value = value; + } + + /// The raw wire value. + public string Value => _value ?? string.Empty; + + /// Every connected client may change, supply credentials for, and select + /// every registration. + public static readonly ModelSourcePrincipalPolicy Shared = new ModelSourcePrincipalPolicy("shared"); + + /// The host verifies principals, and limits changes, credentials, and + /// selection of each registration to clients of the principal that + /// registered it. Root state still lists every registration to every + /// client. + public static readonly ModelSourcePrincipalPolicy Isolated = new ModelSourcePrincipalPolicy("isolated"); + + /// + public bool Equals(ModelSourcePrincipalPolicy other) => string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is ModelSourcePrincipalPolicy other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Ordinal equality over the raw wire value. + public static bool operator ==(ModelSourcePrincipalPolicy left, ModelSourcePrincipalPolicy right) => left.Equals(right); + + /// Ordinal inequality over the raw wire value. + public static bool operator !=(ModelSourcePrincipalPolicy left, ModelSourcePrincipalPolicy right) => !left.Equals(right); +} + +/// Reads and writes as its raw wire string, preserving unrecognized values. +internal sealed class ModelSourcePrincipalPolicyConverter : JsonConverter +{ + /// + public override ModelSourcePrincipalPolicy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new ModelSourcePrincipalPolicy(reader.GetString() ?? throw new JsonException("ModelSourcePrincipalPolicy expects a JSON string.")); + + /// + public override void Write(Utf8JsonWriter writer, ModelSourcePrincipalPolicy value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} + /// Computation lifecycle of a {@link ChangesetState}. [JsonConverter(typeof(ChangesetStatusConverter))] public readonly struct ChangesetStatus : IEquatable @@ -2351,17 +2476,28 @@ public sealed record ModelSourceRegistrationCapability { /// Definition formats the agent reads, most preferred first. Format names /// are defined by agent implementations and SHOULD be namespaced, for - /// example `example.com/model-source@1`. + /// example `example.com/model-source@1`. AHP doesn't define, standardize, + /// or name any format. public required List Formats { get; init; } + /// How long, in milliseconds, the host keeps a disconnected client's + /// contributions before it treats the client as having left. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? GracePeriod { get; init; } + + /// Whether clients acting for different principals share the registry. + /// Absent means `shared`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ModelSourcePrincipalPolicy? PrincipalPolicy { get; init; } + /// Unrecognized wire members retained for full-object edits. [JsonExtensionData] public Dictionary? Extra { get; set; } } -/// A model source registered on this host by a client, or by the host itself. -/// Its definition is in a format the agent named by `provider` reads. It never -/// contains a credential. +/// A model source registered on this host by one or more clients, or by the +/// host itself. Its definition is in a format the agent named by `provider` +/// reads. It never contains a credential. /// /// Stability: 1.0 - Early development. public sealed record ModelSourceRegistration @@ -2386,21 +2522,24 @@ public sealed record ModelSourceRegistration public required string Format { get; init; } /// How to reach the source: endpoint, wire format, models, and so on, in - /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain - /// a credential. + /// `format`. Its shape belongs to the agent that reads it, and AHP doesn't + /// define it. MUST NOT contain a credential. public required Dictionary Definition { get; init; } - /// The contributing client: the client that most recently registered or - /// changed the source. Absent for a source the host registered itself. + /// The clients that contribute this registration, in the order they joined. + /// The reducer maintains it from {@link RootModelSourceRegistrationSetAction} + /// and {@link RootModelSourceContributorRemovedAction}. Absent when no + /// client contributes it: a source the host registered itself, or a + /// `host`-retained one whose contributors have all left. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? ClientId { get; init; } + public List? ContributingClientIds { get; init; } - /// What happens when the contributing client leaves. Absent means `contributingClient`. + /// What happens when the last contributing client leaves. Absent means `contributingClient`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceRetentionPolicy? Retention { get; init; } /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after a client replaces the + /// Absent until the host reports one, and after a `Set` replaces the /// registration until the host reports again. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceState? State { get; init; } @@ -2431,6 +2570,21 @@ public sealed record ModelSourceRegistration [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } + /// Every origin the host sends the credential to, such as + /// `https://api.example.com`. Present whenever `credentialResource` is. A + /// client checks each one against its own copy of the definition before it + /// sends a key. Set with `state`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? CredentialOrigins { get; init; } + + /// The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of + /// the credential the host most recently accepted. While the state is + /// `starting` or `ready`, the host holds it. While it's `authRequired`, the + /// `reason` says what happened to it. Absent until the host accepts a + /// credential. Set with `state`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? CredentialId { get; init; } + /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. [JsonPropertyName("_meta")] @@ -2477,7 +2631,7 @@ public sealed record ModelSourceReadyState public sealed record ModelSourceAuthRequirement { /// Why a credential is needed. - public AuthRequiredReason Reason { get; init; } + public ModelSourceAuthRequiredReason Reason { get; init; } /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." @@ -2497,7 +2651,7 @@ public sealed record ModelSourceAuthRequirement public sealed record ModelSourceAuthRequiredState { /// Why a credential is needed. - public AuthRequiredReason Reason { get; init; } + public ModelSourceAuthRequiredReason Reason { get; init; } /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." @@ -2532,7 +2686,9 @@ public sealed record ModelSourceInfo { /// Model source identifier, unique within the agent's /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSourceRegistration.id}. + /// the {@link ModelSourceRegistration.id}. A source is registered when + /// {@link RootState.modelSourceRegistrations} has an entry with this `id` + /// whose `provider` is the agent. public required string Id { get; init; } /// Human-readable name @@ -2599,7 +2755,9 @@ public sealed record SessionModelInfo /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// An agent's own sources use it too, so it doesn't by itself mark a + /// registered source. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ModelSourceId { get; init; } } @@ -6679,7 +6837,13 @@ public sealed record UsageInfo public sealed record ErrorInfo { - /// Error type identifier + /// Error type identifier. Well-known values: + /// + /// - `modelSourceUnavailable`: a registered model source the turn uses + /// can't serve it, for example because its credential is missing, + /// expired, rejected, or revoked, or the source was removed. The error + /// part is resumable. See + /// [Model source credentials](/specification/authentication#model-source-credentials). public required string ErrorType { get; init; } /// Human-readable error message diff --git a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs index dae5ba15f..8fedcd680 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -211,6 +211,9 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootConfigChangedAction value: actionType = value.Type; return true; + case RootModelSourceContributorRemovedAction value: + actionType = value.Type; + return true; case RootModelSourceRegistrationRemovedAction value: actionType = value.Type; return true; diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index 64524fe2e..e009ffa9f 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -684,15 +684,45 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) { List list = state.ModelSourceRegistrations ??= new List(); int index = list.FindIndex(r => r.Id == a.Registration.Id); + ModelSourceRegistration? existing = index >= 0 && SameModelSourceRouting(list[index], a.Registration) ? list[index] : null; + var contributors = new List(existing?.ContributingClientIds ?? new List()); + if (a.ClientId is not null && !contributors.Contains(a.ClientId)) + { + contributors.Add(a.ClientId); + } + + ModelSourceRegistration merged = a.Registration with + { + ContributingClientIds = contributors.Count > 0 ? contributors : null, + State = existing?.State, + CredentialNonce = existing?.CredentialNonce, + CredentialResource = existing?.CredentialResource, + CredentialOrigins = existing?.CredentialOrigins, + CredentialId = existing?.CredentialId, + }; if (index < 0) { - list.Add(a.Registration); + list.Add(merged); } else { - list[index] = a.Registration; + list[index] = merged; + } + + return ReduceOutcome.Applied; + } + case RootModelSourceContributorRemovedAction a: + { + int index = state.ModelSourceRegistrations?.FindIndex(r => r.Id == a.Id) ?? -1; + List? contributors = index < 0 ? null : state.ModelSourceRegistrations![index].ContributingClientIds; + if (contributors is null || !contributors.Contains(a.ClientId)) + { + return ReduceOutcome.NoOp; } + List remaining = contributors.FindAll(id => id != a.ClientId); + List list = state.ModelSourceRegistrations!; + list[index] = list[index] with { ContributingClientIds = remaining.Count > 0 ? remaining : null }; return ReduceOutcome.Applied; } case RootModelSourceRegistrationRemovedAction a: @@ -715,7 +745,7 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) } List list = state.ModelSourceRegistrations!; - list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce, CredentialResource = a.CredentialResource }; + list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce, CredentialResource = a.CredentialResource, CredentialOrigins = a.CredentialOrigins, CredentialId = a.CredentialId }; return ReduceOutcome.Applied; } } @@ -723,6 +753,84 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) return ReduceOutcome.OutOfScope; } + // Whether two registrations have the same provider, format, and definition, + // comparing definitions as JSON values. + private static bool SameModelSourceRouting(ModelSourceRegistration a, ModelSourceRegistration b) + { + if (a.Provider != b.Provider || a.Format != b.Format || a.Definition.Count != b.Definition.Count) + { + return false; + } + + foreach (KeyValuePair entry in a.Definition) + { + if (!b.Definition.TryGetValue(entry.Key, out JsonElement other) || !JsonValuesEqual(entry.Value, other)) + { + return false; + } + } + + return true; + } + + // Compares JSON values regardless of object key order, with numbers compared + // by numeric value, so `1` equals `1.0`. + private static bool JsonValuesEqual(JsonElement a, JsonElement b) + { + if (a.ValueKind != b.ValueKind) + { + return false; + } + + switch (a.ValueKind) + { + case JsonValueKind.Object: + { + int count = 0; + foreach (JsonProperty property in a.EnumerateObject()) + { + count++; + if (!b.TryGetProperty(property.Name, out JsonElement other) || !JsonValuesEqual(property.Value, other)) + { + return false; + } + } + + foreach (JsonProperty _ in b.EnumerateObject()) + { + count--; + } + + return count == 0; + } + case JsonValueKind.Array: + { + if (a.GetArrayLength() != b.GetArrayLength()) + { + return false; + } + + using JsonElement.ArrayEnumerator left = a.EnumerateArray(); + using JsonElement.ArrayEnumerator right = b.EnumerateArray(); + while (left.MoveNext() && right.MoveNext()) + { + if (!JsonValuesEqual(left.Current, right.Current)) + { + return false; + } + } + + return true; + } + case JsonValueKind.Number: + return a.GetDouble() == b.GetDouble(); + case JsonValueKind.String: + return a.GetString() == b.GetString(); + default: + return true; + } + } + // Shared config merge for the root, session, and chat `configChanged` actions: // when `replace` is set (or no values exist yet) start fresh, otherwise // mutate the existing map in place; then overlay the incoming entries. @@ -2664,6 +2772,7 @@ public static ReduceOutcome ApplyToAutomationRun( { "root/configChanged", "root/modelSourceRegistrationSet", + "root/modelSourceContributorRemoved", "root/modelSourceRegistrationRemoved", // Chat-channel actions (post-#213) "chat/turnStarted", diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 880b066e4..1b4ab7a77 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -2,6 +2,7 @@ package ahp import ( "encoding/json" + "reflect" "time" "github.com/microsoft/agent-host-protocol/clients/go/ahptypes" @@ -538,38 +539,116 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R } return ReduceOutcomeApplied case *ahptypes.RootModelSourceRegistrationSetAction: - for i := range state.ModelSourceRegistrations { - if state.ModelSourceRegistrations[i].Id == a.Registration.Id { - state.ModelSourceRegistrations[i] = a.Registration - return ReduceOutcomeApplied + updated := a.Registration + var contributors []string + idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, updated.Id) + if idx >= 0 && sameModelSourceRouting(state.ModelSourceRegistrations[idx], updated) { + copyModelSourceHostFields(&updated, state.ModelSourceRegistrations[idx]) + contributors = append(contributors, state.ModelSourceRegistrations[idx].ContributingClientIds...) + } else { + copyModelSourceHostFields(&updated, ahptypes.ModelSourceRegistration{}) + } + if a.ClientId != nil && !containsString(contributors, *a.ClientId) { + contributors = append(contributors, *a.ClientId) + } + updated.ContributingClientIds = contributors + if idx >= 0 { + state.ModelSourceRegistrations[idx] = updated + } else { + state.ModelSourceRegistrations = append(state.ModelSourceRegistrations, updated) + } + return ReduceOutcomeApplied + case *ahptypes.RootModelSourceContributorRemovedAction: + idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, a.Id) + if idx < 0 || !containsString(state.ModelSourceRegistrations[idx].ContributingClientIds, a.ClientId) { + return ReduceOutcomeNoOp + } + var remaining []string + for _, id := range state.ModelSourceRegistrations[idx].ContributingClientIds { + if id != a.ClientId { + remaining = append(remaining, id) } } - state.ModelSourceRegistrations = append(state.ModelSourceRegistrations, a.Registration) + state.ModelSourceRegistrations[idx].ContributingClientIds = remaining return ReduceOutcomeApplied case *ahptypes.RootModelSourceRegistrationRemovedAction: - for i := range state.ModelSourceRegistrations { - if state.ModelSourceRegistrations[i].Id == a.Id { - state.ModelSourceRegistrations = append(state.ModelSourceRegistrations[:i], state.ModelSourceRegistrations[i+1:]...) - return ReduceOutcomeApplied - } + idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, a.Id) + if idx < 0 { + return ReduceOutcomeNoOp } - return ReduceOutcomeNoOp + state.ModelSourceRegistrations = append(state.ModelSourceRegistrations[:idx], state.ModelSourceRegistrations[idx+1:]...) + return ReduceOutcomeApplied case *ahptypes.RootModelSourceStateChangedAction: - for i := range state.ModelSourceRegistrations { - if state.ModelSourceRegistrations[i].Id == a.Id { - st := a.State - nonce := a.CredentialNonce - state.ModelSourceRegistrations[i].State = &st - state.ModelSourceRegistrations[i].CredentialNonce = &nonce - state.ModelSourceRegistrations[i].CredentialResource = a.CredentialResource - return ReduceOutcomeApplied - } + idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, a.Id) + if idx < 0 { + return ReduceOutcomeNoOp } - return ReduceOutcomeNoOp + st := a.State + nonce := a.CredentialNonce + copyModelSourceHostFields(&state.ModelSourceRegistrations[idx], ahptypes.ModelSourceRegistration{ + State: &st, + CredentialNonce: &nonce, + CredentialResource: a.CredentialResource, + CredentialOrigins: a.CredentialOrigins, + CredentialId: a.CredentialId, + }) + return ReduceOutcomeApplied } return ReduceOutcomeOutOfScope } +func modelSourceRegistrationIndex(list []ahptypes.ModelSourceRegistration, id string) int { + for i := range list { + if list[i].Id == id { + return i + } + } + return -1 +} + +// copyModelSourceHostFields copies the host-reported fields of from onto to, +// clearing the ones from lacks. +func copyModelSourceHostFields(to *ahptypes.ModelSourceRegistration, from ahptypes.ModelSourceRegistration) { + to.State = from.State + to.CredentialNonce = from.CredentialNonce + to.CredentialResource = from.CredentialResource + to.CredentialOrigins = from.CredentialOrigins + to.CredentialId = from.CredentialId +} + +// sameModelSourceRouting reports whether two registrations have the same +// provider, format, and definition, comparing definitions as JSON values. +func sameModelSourceRouting(a, b ahptypes.ModelSourceRegistration) bool { + return a.Provider == b.Provider && a.Format == b.Format && jsonValuesEqual(a.Definition, b.Definition) +} + +// jsonValuesEqual compares two values by their JSON meaning, ignoring object +// key order and formatting. +func jsonValuesEqual(a, b any) bool { + return reflect.DeepEqual(normalizeJSON(a), normalizeJSON(b)) +} + +func normalizeJSON(v any) any { + raw, err := json.Marshal(v) + if err != nil { + return nil + } + var out any + if err := json.Unmarshal(raw, &out); err != nil { + return nil + } + return out +} + +func containsString(list []string, value string) bool { + for _, item := range list { + if item == value { + return true + } + } + return false +} + // ─── Chat Reducer ────────────────────────────────────────────────────── // ApplyActionToChat applies action to the [ahptypes.ChatState] in diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 3ecc2fb9f..7f72eb368 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -107,6 +107,7 @@ const ( ActionTypeRootTerminalsChanged ActionType = "root/terminalsChanged" ActionTypeRootConfigChanged ActionType = "root/configChanged" ActionTypeRootModelSourceRegistrationSet ActionType = "root/modelSourceRegistrationSet" + ActionTypeRootModelSourceContributorRemoved ActionType = "root/modelSourceContributorRemoved" ActionTypeRootModelSourceRegistrationRemoved ActionType = "root/modelSourceRegistrationRemoved" ActionTypeRootModelSourceStateChanged ActionType = "root/modelSourceStateChanged" ActionTypeTerminalData ActionType = "terminal/data" @@ -179,22 +180,56 @@ type RootConfigChangedAction struct { Replace *bool `json:"replace,omitempty"` } -// Adds a model source registration, or replaces the one with the same `id`. +// Contributes a model source registration for `clientId`. A registration's +// routing is its `provider`, `format`, and `definition`, with definitions +// compared as JSON values: object key order is ignored, and numbers compare +// by numeric value, so `1` equals `1.0`. // -// A client registers a source by dispatching this with its own `clientId`, and -// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a -// registration clears those host-reported fields until the host reports again -// with {@link RootModelSourceStateChangedAction}. +// - **Add.** When no registration has the `id`, appends it, with +// `contributingClientIds` set to `[clientId]`, or absent without a +// `clientId`. +// - **Join.** When one has, and its routing is unchanged, keeps its +// host-reported fields (`state`, `credentialNonce`, `credentialResource`, +// `credentialOrigins`, and `credentialId`), adds `clientId` to +// `contributingClientIds` if it isn't there, and takes the other fields +// from the action. +// - **Replace.** When the routing changed, replaces the registration, with +// `contributingClientIds` set to `[clientId]`, or absent without a +// `clientId`. Its host-reported fields are absent until the host reports +// again with {@link RootModelSourceStateChangedAction}. +// +// A client dispatches this with its own `clientId`, and without +// `contributingClientIds` or any host-reported field. // // Stability: 1.0 - Early development. type RootModelSourceRegistrationSetAction struct { Type ActionType `json:"type"` - // The registration to add or replace, matched by `id`. + // The registration to contribute, matched by `id`. Registration ModelSourceRegistration `json:"registration"` + // The contributing client. Absent when the host registers the source + // itself. + ClientId *string `json:"clientId,omitempty"` +} + +// Withdraws one client's contribution to a model source registration: +// removes `clientId` from `contributingClientIds`, leaving the field absent +// when no contributor remains. A no-op when no registration has `id`, or +// `clientId` doesn't contribute it. It never removes the registration. +// +// A client dispatches this with its own `clientId`. The host dispatches it +// when a contributing client leaves. +// +// Stability: 1.0 - Early development. +type RootModelSourceContributorRemovedAction struct { + Type ActionType `json:"type"` + // The registration's `id`. + Id string `json:"id"` + // The contributing client to remove. + ClientId string `json:"clientId"` } -// Removes the model source registration with the given `id`. A no-op when -// none matches. +// Removes the model source registration with the given `id` for every +// contributor. A no-op when none matches. // // Stability: 1.0 - Early development. type RootModelSourceRegistrationRemovedAction struct { @@ -203,9 +238,10 @@ type RootModelSourceRegistrationRemovedAction struct { Id string `json:"id"` } -// Updates a model source registration's status, credential nonce, and -// credential resource together. A no-op when no registration has `id`. Other -// fields of the registration are preserved. Only the host dispatches it. +// Updates a model source registration's host-reported fields together: +// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and +// `credentialId`. A no-op when no registration has `id`. Other fields of the +// registration are preserved. Only the host dispatches it. // // Stability: 1.0 - Early development. type RootModelSourceStateChangedAction struct { @@ -219,6 +255,10 @@ type RootModelSourceStateChangedAction struct { // Replaces the registration's `credentialResource`. Absent clears it, for a // source that needs no credential. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` + // Replaces the registration's `credentialOrigins`. Absent clears it. + CredentialOrigins []URI `json:"credentialOrigins,omitempty"` + // Replaces the registration's `credentialId`. Absent clears it. + CredentialId *string `json:"credentialId,omitempty"` } // Session backend initialized successfully. @@ -1907,6 +1947,7 @@ func (*RootAgentsChangedAction) isStateAction() {} func (*RootActiveSessionsChangedAction) isStateAction() {} func (*RootConfigChangedAction) isStateAction() {} func (*RootModelSourceRegistrationSetAction) isStateAction() {} +func (*RootModelSourceContributorRemovedAction) isStateAction() {} func (*RootModelSourceRegistrationRemovedAction) isStateAction() {} func (*RootModelSourceStateChangedAction) isStateAction() {} func (*SessionReadyAction) isStateAction() {} @@ -2053,6 +2094,12 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value + case "root/modelSourceContributorRemoved": + var value RootModelSourceContributorRemovedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value case "root/modelSourceRegistrationRemoved": var value RootModelSourceRegistrationRemovedAction if err := json.Unmarshal(data, &value); err != nil { diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index add5801f4..ec443791a 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1362,6 +1362,13 @@ type ModelSourceAuthenticateTarget struct { // published in root state. The host rejects a stale one with `Conflict` // (-32011). CredentialNonce string `json:"credentialNonce"` + // A client-chosen, non-secret ID for the credential, such as a hash of + // where the client stores the key. The host publishes it as the + // registration's `ModelSourceRegistration.credentialId`, so a client can + // tell whether the host holds its current key. Clients SHOULD include it + // when delivering a credential, and omit it when revoking one. MUST NOT be + // derived from the secret. + CredentialId *string `json:"credentialId,omitempty"` } // Pushes a credential for a protected resource. The `resource` field MUST diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index e0ff45534..9654864e5 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -452,18 +452,55 @@ const ( ModelSourceStatusError ModelSourceStatus = "error" ) -// How long a registered model source lasts once its contributing client leaves. +// How long a registered model source lasts once its last contributing client +// leaves. When the last contributor withdraws instead, the source goes away +// whatever its retention. // // Stability: 1.0 - Early development. type ModelSourceRetentionPolicy string const ( - // Removed when the contributing client leaves, once running turns finish. + // Removed when the last contributing client leaves, once running turns finish. ModelSourceRetentionPolicyContributingClient ModelSourceRetentionPolicy = "contributingClient" - // Kept until a client removes it or host policy expires it. + // Kept until it's removed, its last contributor withdraws, or host policy expires it. ModelSourceRetentionPolicyHost ModelSourceRetentionPolicy = "host" ) +// Why a model source needs a credential. Specific to model sources: the +// shared `AuthRequiredReason` folds rejection and revocation into `expired`. +// +// Stability: 1.0 - Early development. +type ModelSourceAuthRequiredReason string + +const ( + // The host holds no credential yet. + ModelSourceAuthRequiredReasonRequired ModelSourceAuthRequiredReason = "required" + // The credential's lifetime or lease lapsed. A client may renew it. + ModelSourceAuthRequiredReasonExpired ModelSourceAuthRequiredReason = "expired" + // The endpoint refused the credential. Clients don't send a credential with + // the same {@link ModelSourceRegistration.credentialId} again. + ModelSourceAuthRequiredReasonRejected ModelSourceAuthRequiredReason = "rejected" + // A client revoked the credential. Clients don't send one again without a user's action. + ModelSourceAuthRequiredReasonRevoked ModelSourceAuthRequiredReason = "revoked" +) + +// Whether clients acting for different principals share a host's model +// source registry. +// +// Stability: 1.0 - Early development. +type ModelSourcePrincipalPolicy string + +const ( + // Every connected client may change, supply credentials for, and select + // every registration. + ModelSourcePrincipalPolicyShared ModelSourcePrincipalPolicy = "shared" + // The host verifies principals, and limits changes, credentials, and + // selection of each registration to clients of the principal that + // registered it. Root state still lists every registration to every + // client. + ModelSourcePrincipalPolicyIsolated ModelSourcePrincipalPolicy = "isolated" +) + // Computation lifecycle of a {@link ChangesetState}. type ChangesetStatus string @@ -955,25 +992,32 @@ type MultipleWorkingDirectoriesCapability struct { type ModelSourceRegistrationCapability struct { // Definition formats the agent reads, most preferred first. Format names // are defined by agent implementations and SHOULD be namespaced, for - // example `example.com/model-source@1`. + // example `example.com/model-source@1`. AHP doesn't define, standardize, + // or name any format. Formats []string `json:"formats"` + // How long, in milliseconds, the host keeps a disconnected client's + // contributions before it treats the client as having left. + GracePeriod *int64 `json:"gracePeriod,omitempty"` + // Whether clients acting for different principals share the registry. + // Absent means `shared`. + PrincipalPolicy *ModelSourcePrincipalPolicy `json:"principalPolicy,omitempty"` // Extra contains unrecognized wire members retained for full-object edits. Extra map[string]json.RawMessage `json:"-"` } func (v *ModelSourceRegistrationCapability) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistrationCapability - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "formats") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "formats", "gracePeriod", "principalPolicy") } func (v ModelSourceRegistrationCapability) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistrationCapability - return marshalWithExtra(wire(v), v.Extra, "formats") + return marshalWithExtra(wire(v), v.Extra, "formats", "gracePeriod", "principalPolicy") } -// A model source registered on this host by a client, or by the host itself. -// Its definition is in a format the agent named by `provider` reads. It never -// contains a credential. +// A model source registered on this host by one or more clients, or by the +// host itself. Its definition is in a format the agent named by `provider` +// reads. It never contains a credential. // // Stability: 1.0 - Early development. type ModelSourceRegistration struct { @@ -991,16 +1035,19 @@ type ModelSourceRegistration struct { // {@link ModelSourceRegistrationCapability.formats}. Format string `json:"format"` // How to reach the source: endpoint, wire format, models, and so on, in - // `format`. Its shape belongs to the agent that reads it. MUST NOT contain - // a credential. + // `format`. Its shape belongs to the agent that reads it, and AHP doesn't + // define it. MUST NOT contain a credential. Definition map[string]json.RawMessage `json:"definition"` - // The contributing client: the client that most recently registered or - // changed the source. Absent for a source the host registered itself. - ClientId *string `json:"clientId,omitempty"` - // What happens when the contributing client leaves. Absent means `contributingClient`. + // The clients that contribute this registration, in the order they joined. + // The reducer maintains it from {@link RootModelSourceRegistrationSetAction} + // and {@link RootModelSourceContributorRemovedAction}. Absent when no + // client contributes it: a source the host registered itself, or a + // `host`-retained one whose contributors have all left. + ContributingClientIds []string `json:"contributingClientIds,omitempty"` + // What happens when the last contributing client leaves. Absent means `contributingClient`. Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` // Host-reported status, set with {@link RootModelSourceStateChangedAction}. - // Absent until the host reports one, and after a client replaces the + // Absent until the host reports one, and after a `Set` replaces the // registration until the host reports again. State *ModelSourceState `json:"state,omitempty"` // Host-issued token that a client echoes in @@ -1025,6 +1072,17 @@ type ModelSourceRegistration struct { // advertises `authorization_servers` and `scopes_supported`. A source that // takes a user-supplied secret omits them. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` + // Every origin the host sends the credential to, such as + // `https://api.example.com`. Present whenever `credentialResource` is. A + // client checks each one against its own copy of the definition before it + // sends a key. Set with `state`. + CredentialOrigins []URI `json:"credentialOrigins,omitempty"` + // The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of + // the credential the host most recently accepted. While the state is + // `starting` or `ready`, the host holds it. While it's `authRequired`, the + // `reason` says what happened to it. Absent until the host accepts a + // credential. Set with `state`. + CredentialId *string `json:"credentialId,omitempty"` // Additional implementation-defined metadata for this registration. // MUST NOT contain a credential. Meta map[string]json.RawMessage `json:"_meta,omitempty"` @@ -1034,12 +1092,12 @@ type ModelSourceRegistration struct { func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistration - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "contributingClientIds", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "credentialId", "_meta") } func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistration - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "clientId", "retention", "state", "credentialNonce", "credentialResource", "_meta") + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "contributingClientIds", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "credentialId", "_meta") } // The agent is reading and validating the definition, or listing the @@ -1090,7 +1148,7 @@ func (v ModelSourceReadyState) MarshalJSON() ([]byte, error) { // Stability: 1.0 - Early development. type ModelSourceAuthRequirement struct { // Why a credential is needed. - Reason AuthRequiredReason `json:"reason"` + Reason ModelSourceAuthRequiredReason `json:"reason"` // Human-readable hint the host writes, for example "The endpoint rejected // the API key." Description *string `json:"description,omitempty"` @@ -1115,7 +1173,7 @@ func (v ModelSourceAuthRequirement) MarshalJSON() ([]byte, error) { // Stability: 1.0 - Early development. type ModelSourceAuthRequiredState struct { // Why a credential is needed. - Reason AuthRequiredReason `json:"reason"` + Reason ModelSourceAuthRequiredReason `json:"reason"` // Human-readable hint the host writes, for example "The endpoint rejected // the API key." Description *string `json:"description,omitempty"` @@ -1160,7 +1218,9 @@ func (v ModelSourceErrorState) MarshalJSON() ([]byte, error) { type ModelSourceInfo struct { // Model source identifier, unique within the agent's // {@link AgentInfo.modelSources}. For a registered model source, this is - // the {@link ModelSourceRegistration.id}. + // the {@link ModelSourceRegistration.id}. A source is registered when + // {@link RootState.modelSourceRegistrations} has an entry with this `id` + // whose `provider` is the agent. Id string `json:"id"` // Human-readable name DisplayName string `json:"displayName"` @@ -1206,6 +1266,8 @@ type SessionModelInfo struct { // The source this model comes from. MUST match a {@link ModelSourceInfo.id} // in the agent's {@link AgentInfo.modelSources}. For a model from a // registered model source, this is the {@link ModelSourceRegistration.id}. + // An agent's own sources use it too, so it doesn't by itself mark a + // registered source. ModelSourceId *string `json:"modelSourceId,omitempty"` } @@ -4538,7 +4600,13 @@ type UsageInfo struct { } type ErrorInfo struct { - // Error type identifier + // Error type identifier. Well-known values: + // + // - `modelSourceUnavailable`: a registered model source the turn uses + // can't serve it, for example because its credential is missing, + // expired, rejected, or revoked, or the source was removed. The error + // part is resumable. See + // [Model source credentials](/specification/authentication#model-source-credentials). ErrorType string `json:"errorType"` // Human-readable error message Message string `json:"message"` diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index ed9288234..ae2c45a49 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -10,8 +10,11 @@ package com.microsoft.agenthostprotocol import com.microsoft.agenthostprotocol.generated.* import java.time.Instant import java.time.format.DateTimeFormatterBuilder +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.doubleOrNull // ─── Reducer Interface ────────────────────────────────────────────────────── @@ -577,13 +580,39 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when is StateActionRootModelSourceRegistrationSet -> { val registration = action.value.registration + val clientId = action.value.clientId val list = state.modelSourceRegistrations.orEmpty() val idx = list.indexOfFirst { it.id == registration.id } + val existing = list.getOrNull(idx)?.takeIf { sameModelSourceRouting(it, registration) } + val contributors = existing?.contributingClientIds.orEmpty().toMutableList() + if (clientId != null && clientId !in contributors) contributors.add(clientId) + val merged = registration.copy( + contributingClientIds = contributors.takeIf { it.isNotEmpty() }, + state = existing?.state, + credentialNonce = existing?.credentialNonce, + credentialResource = existing?.credentialResource, + credentialOrigins = existing?.credentialOrigins, + credentialId = existing?.credentialId, + ) val updated = list.toMutableList() - if (idx < 0) updated.add(registration) else updated[idx] = registration + if (idx < 0) updated.add(merged) else updated[idx] = merged state.copy(modelSourceRegistrations = updated) } + is StateActionRootModelSourceContributorRemoved -> { + val list = state.modelSourceRegistrations + val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 + val contributors = list?.getOrNull(idx)?.contributingClientIds.orEmpty() + if (list == null || action.value.clientId !in contributors) { + state + } else { + val remaining = contributors.filter { it != action.value.clientId } + val updated = list.toMutableList() + updated[idx] = updated[idx].copy(contributingClientIds = remaining.takeIf { it.isNotEmpty() }) + state.copy(modelSourceRegistrations = updated) + } + } + is StateActionRootModelSourceRegistrationRemoved -> { val list = state.modelSourceRegistrations val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 @@ -605,6 +634,8 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when state = action.value.state, credentialNonce = action.value.credentialNonce, credentialResource = action.value.credentialResource, + credentialOrigins = action.value.credentialOrigins, + credentialId = action.value.credentialId, ) state.copy(modelSourceRegistrations = updated) } @@ -613,6 +644,28 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when else -> state } +/** + * Whether two registrations have the same `provider`, `format`, and + * `definition`, comparing definitions as JSON values. + */ +private fun sameModelSourceRouting(a: ModelSourceRegistration, b: ModelSourceRegistration): Boolean = + a.provider == b.provider && a.format == b.format && jsonValuesEqual(JsonObject(a.definition), JsonObject(b.definition)) + +/** + * Compares JSON values regardless of object key order, with numbers compared + * by numeric value, so `1` equals `1.0`. + */ +private fun jsonValuesEqual(a: JsonElement, b: JsonElement): Boolean = when { + a is JsonObject && b is JsonObject -> + a.size == b.size && a.all { (key, value) -> b[key]?.let { jsonValuesEqual(value, it) } == true } + a is JsonArray && b is JsonArray -> + a.size == b.size && a.indices.all { jsonValuesEqual(a[it], b[it]) } + a is JsonPrimitive && b is JsonPrimitive && !a.isString && !b.isString && + a.doubleOrNull != null && b.doubleOrNull != null -> + a.doubleOrNull == b.doubleOrNull + else -> a == b +} + // ─── Session Reducer ──────────────────────────────────────────────────────── /** diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index e008606ca..20609600d 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -117,6 +117,7 @@ value class ActionType(val rawValue: String) { val ROOT_TERMINALS_CHANGED: ActionType = ActionType("root/terminalsChanged") val ROOT_CONFIG_CHANGED: ActionType = ActionType("root/configChanged") val ROOT_MODEL_SOURCE_REGISTRATION_SET: ActionType = ActionType("root/modelSourceRegistrationSet") + val ROOT_MODEL_SOURCE_CONTRIBUTOR_REMOVED: ActionType = ActionType("root/modelSourceContributorRemoved") val ROOT_MODEL_SOURCE_REGISTRATION_REMOVED: ActionType = ActionType("root/modelSourceRegistrationRemoved") val ROOT_MODEL_SOURCE_STATE_CHANGED: ActionType = ActionType("root/modelSourceStateChanged") val TERMINAL_DATA: ActionType = ActionType("terminal/data") @@ -1486,12 +1487,26 @@ data class RootConfigChangedAction( ) /** - * Adds a model source registration, or replaces the one with the same `id`. + * Contributes a model source registration for `clientId`. A registration's + * routing is its `provider`, `format`, and `definition`, with definitions + * compared as JSON values: object key order is ignored, and numbers compare + * by numeric value, so `1` equals `1.0`. * - * A client registers a source by dispatching this with its own `clientId`, and - * with no `state`, `credentialNonce`, or `credentialResource`. Replacing a - * registration clears those host-reported fields until the host reports again - * with {@link RootModelSourceStateChangedAction}. + * - **Add.** When no registration has the `id`, appends it, with + * `contributingClientIds` set to `[clientId]`, or absent without a + * `clientId`. + * - **Join.** When one has, and its routing is unchanged, keeps its + * host-reported fields (`state`, `credentialNonce`, `credentialResource`, + * `credentialOrigins`, and `credentialId`), adds `clientId` to + * `contributingClientIds` if it isn't there, and takes the other fields + * from the action. + * - **Replace.** When the routing changed, replaces the registration, with + * `contributingClientIds` set to `[clientId]`, or absent without a + * `clientId`. Its host-reported fields are absent until the host reports + * again with {@link RootModelSourceStateChangedAction}. + * + * A client dispatches this with its own `clientId`, and without + * `contributingClientIds` or any host-reported field. * * Stability: 1.0 - Early development. */ @@ -1499,14 +1514,43 @@ data class RootConfigChangedAction( data class RootModelSourceRegistrationSetAction( val type: ActionType, /** - * The registration to add or replace, matched by `id`. + * The registration to contribute, matched by `id`. + */ + val registration: ModelSourceRegistration, + /** + * The contributing client. Absent when the host registers the source + * itself. */ - val registration: ModelSourceRegistration + val clientId: String? = null ) /** - * Removes the model source registration with the given `id`. A no-op when - * none matches. + * Withdraws one client's contribution to a model source registration: + * removes `clientId` from `contributingClientIds`, leaving the field absent + * when no contributor remains. A no-op when no registration has `id`, or + * `clientId` doesn't contribute it. It never removes the registration. + * + * A client dispatches this with its own `clientId`. The host dispatches it + * when a contributing client leaves. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class RootModelSourceContributorRemovedAction( + val type: ActionType, + /** + * The registration's `id`. + */ + val id: String, + /** + * The contributing client to remove. + */ + val clientId: String +) + +/** + * Removes the model source registration with the given `id` for every + * contributor. A no-op when none matches. * * Stability: 1.0 - Early development. */ @@ -1520,9 +1564,10 @@ data class RootModelSourceRegistrationRemovedAction( ) /** - * Updates a model source registration's status, credential nonce, and - * credential resource together. A no-op when no registration has `id`. Other - * fields of the registration are preserved. Only the host dispatches it. + * Updates a model source registration's host-reported fields together: + * `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and + * `credentialId`. A no-op when no registration has `id`. Other fields of the + * registration are preserved. Only the host dispatches it. * * Stability: 1.0 - Early development. */ @@ -1545,7 +1590,15 @@ data class RootModelSourceStateChangedAction( * Replaces the registration's `credentialResource`. Absent clears it, for a * source that needs no credential. */ - val credentialResource: ProtectedResourceMetadata? = null + val credentialResource: ProtectedResourceMetadata? = null, + /** + * Replaces the registration's `credentialOrigins`. Absent clears it. + */ + val credentialOrigins: List? = null, + /** + * Replaces the registration's `credentialId`. Absent clears it. + */ + val credentialId: String? = null ) @Serializable @@ -1920,6 +1973,7 @@ sealed interface StateAction @JvmInline value class StateActionRootTerminalsChanged(val value: RootTerminalsChangedAction) : StateAction @JvmInline value class StateActionRootConfigChanged(val value: RootConfigChangedAction) : StateAction @JvmInline value class StateActionRootModelSourceRegistrationSet(val value: RootModelSourceRegistrationSetAction) : StateAction +@JvmInline value class StateActionRootModelSourceContributorRemoved(val value: RootModelSourceContributorRemovedAction) : StateAction @JvmInline value class StateActionRootModelSourceRegistrationRemoved(val value: RootModelSourceRegistrationRemovedAction) : StateAction @JvmInline value class StateActionRootModelSourceStateChanged(val value: RootModelSourceStateChangedAction) : StateAction @JvmInline value class StateActionTerminalData(val value: TerminalDataAction) : StateAction @@ -2046,6 +2100,7 @@ internal object StateActionSerializer : KSerializer { "root/terminalsChanged" -> StateActionRootTerminalsChanged(input.json.decodeFromJsonElement(RootTerminalsChangedAction.serializer(), element)) "root/configChanged" -> StateActionRootConfigChanged(input.json.decodeFromJsonElement(RootConfigChangedAction.serializer(), element)) "root/modelSourceRegistrationSet" -> StateActionRootModelSourceRegistrationSet(input.json.decodeFromJsonElement(RootModelSourceRegistrationSetAction.serializer(), element)) + "root/modelSourceContributorRemoved" -> StateActionRootModelSourceContributorRemoved(input.json.decodeFromJsonElement(RootModelSourceContributorRemovedAction.serializer(), element)) "root/modelSourceRegistrationRemoved" -> StateActionRootModelSourceRegistrationRemoved(input.json.decodeFromJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), element)) "root/modelSourceStateChanged" -> StateActionRootModelSourceStateChanged(input.json.decodeFromJsonElement(RootModelSourceStateChangedAction.serializer(), element)) "terminal/data" -> StateActionTerminalData(input.json.decodeFromJsonElement(TerminalDataAction.serializer(), element)) @@ -2165,6 +2220,7 @@ internal object StateActionSerializer : KSerializer { is StateActionRootTerminalsChanged -> output.json.encodeToJsonElement(RootTerminalsChangedAction.serializer(), value.value) is StateActionRootConfigChanged -> output.json.encodeToJsonElement(RootConfigChangedAction.serializer(), value.value) is StateActionRootModelSourceRegistrationSet -> output.json.encodeToJsonElement(RootModelSourceRegistrationSetAction.serializer(), value.value) + is StateActionRootModelSourceContributorRemoved -> output.json.encodeToJsonElement(RootModelSourceContributorRemovedAction.serializer(), value.value) is StateActionRootModelSourceRegistrationRemoved -> output.json.encodeToJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), value.value) is StateActionRootModelSourceStateChanged -> output.json.encodeToJsonElement(RootModelSourceStateChangedAction.serializer(), value.value) is StateActionTerminalData -> output.json.encodeToJsonElement(TerminalDataAction.serializer(), value.value) diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt index d8b6f43c8..4b9ed735f 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 @@ -1634,7 +1634,16 @@ data class ModelSourceAuthenticateTarget( * published in root state. The host rejects a stale one with `Conflict` * (-32011). */ - val credentialNonce: String + val credentialNonce: String, + /** + * A client-chosen, non-secret ID for the credential, such as a hash of + * where the client stores the key. The host publishes it as the + * registration's `ModelSourceRegistration.credentialId`, so a client can + * tell whether the host holds its current key. Clients SHOULD include it + * when delivering a credential, and omit it when revoking one. MUST NOT be + * derived from the secret. + */ + val credentialId: String? = null ) @Serializable 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 ccf7c745e..d035c48c0 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 @@ -960,7 +960,9 @@ internal object ModelSourceStatusSerializer : KSerializer { } /** - * How long a registered model source lasts once its contributing client leaves. + * How long a registered model source lasts once its last contributing client + * leaves. When the last contributor withdraws instead, the source goes away + * whatever its retention. * * Stability: 1.0 - Early development. */ @@ -969,11 +971,11 @@ internal object ModelSourceStatusSerializer : KSerializer { value class ModelSourceRetentionPolicy(val rawValue: String) { companion object { /** - * Removed when the contributing client leaves, once running turns finish. + * Removed when the last contributing client leaves, once running turns finish. */ val CONTRIBUTING_CLIENT: ModelSourceRetentionPolicy = ModelSourceRetentionPolicy("contributingClient") /** - * Kept until a client removes it or host policy expires it. + * Kept until it's removed, its last contributor withdraws, or host policy expires it. */ val HOST: ModelSourceRetentionPolicy = ModelSourceRetentionPolicy("host") } @@ -989,6 +991,81 @@ internal object ModelSourceRetentionPolicySerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("ModelSourceAuthRequiredReason", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: ModelSourceAuthRequiredReason) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): ModelSourceAuthRequiredReason = + ModelSourceAuthRequiredReason(decoder.decodeString()) +} + +/** + * Whether clients acting for different principals share a host's model + * source registry. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = ModelSourcePrincipalPolicySerializer::class) +@JvmInline +value class ModelSourcePrincipalPolicy(val rawValue: String) { + companion object { + /** + * Every connected client may change, supply credentials for, and select + * every registration. + */ + val SHARED: ModelSourcePrincipalPolicy = ModelSourcePrincipalPolicy("shared") + /** + * The host verifies principals, and limits changes, credentials, and + * selection of each registration to clients of the principal that + * registered it. Root state still lists every registration to every + * client. + */ + val ISOLATED: ModelSourcePrincipalPolicy = ModelSourcePrincipalPolicy("isolated") + } +} + +internal object ModelSourcePrincipalPolicySerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("ModelSourcePrincipalPolicy", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: ModelSourcePrincipalPolicy) { + encoder.encodeString(value.rawValue) + } + override fun deserialize(decoder: Decoder): ModelSourcePrincipalPolicy = + ModelSourcePrincipalPolicy(decoder.decodeString()) +} + /** * Computation lifecycle of a {@link ChangesetState}. */ @@ -1778,9 +1855,20 @@ data class ModelSourceRegistrationCapability( /** * Definition formats the agent reads, most preferred first. Format names * are defined by agent implementations and SHOULD be namespaced, for - * example `example.com/model-source@1`. + * example `example.com/model-source@1`. AHP doesn't define, standardize, + * or name any format. */ val formats: List, + /** + * How long, in milliseconds, the host keeps a disconnected client's + * contributions before it treats the client as having left. + */ + val gracePeriod: Long? = null, + /** + * Whether clients acting for different principals share the registry. + * Absent means `shared`. + */ + val principalPolicy: ModelSourcePrincipalPolicy? = null, @Transient val extra: Map = emptyMap() ) @@ -1792,9 +1880,9 @@ internal object ModelSourceRegistrationCapabilitySerializer : UnknownMembersSeri ) /** - * A model source registered on this host by a client, or by the host itself. - * Its definition is in a format the agent named by `provider` reads. It never - * contains a credential. + * A model source registered on this host by one or more clients, or by the + * host itself. Its definition is in a format the agent named by `provider` + * reads. It never contains a credential. * * Stability: 1.0 - Early development. */ @@ -1826,22 +1914,25 @@ data class ModelSourceRegistration( val format: String, /** * How to reach the source: endpoint, wire format, models, and so on, in - * `format`. Its shape belongs to the agent that reads it. MUST NOT contain - * a credential. + * `format`. Its shape belongs to the agent that reads it, and AHP doesn't + * define it. MUST NOT contain a credential. */ val definition: Map, /** - * The contributing client: the client that most recently registered or - * changed the source. Absent for a source the host registered itself. + * The clients that contribute this registration, in the order they joined. + * The reducer maintains it from {@link RootModelSourceRegistrationSetAction} + * and {@link RootModelSourceContributorRemovedAction}. Absent when no + * client contributes it: a source the host registered itself, or a + * `host`-retained one whose contributors have all left. */ - val clientId: String? = null, + val contributingClientIds: List? = null, /** - * What happens when the contributing client leaves. Absent means `contributingClient`. + * What happens when the last contributing client leaves. Absent means `contributingClient`. */ val retention: ModelSourceRetentionPolicy? = null, /** * Host-reported status, set with {@link RootModelSourceStateChangedAction}. - * Absent until the host reports one, and after a client replaces the + * Absent until the host reports one, and after a `Set` replaces the * registration until the host reports again. */ val state: ModelSourceState? = null, @@ -1871,6 +1962,21 @@ data class ModelSourceRegistration( * takes a user-supplied secret omits them. */ val credentialResource: ProtectedResourceMetadata? = null, + /** + * Every origin the host sends the credential to, such as + * `https://api.example.com`. Present whenever `credentialResource` is. A + * client checks each one against its own copy of the definition before it + * sends a key. Set with `state`. + */ + val credentialOrigins: List? = null, + /** + * The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of + * the credential the host most recently accepted. While the state is + * `starting` or `ready`, the host holds it. While it's `authRequired`, the + * `reason` says what happened to it. Absent until the host accepts a + * credential. Set with `state`. + */ + val credentialId: String? = null, /** * Additional implementation-defined metadata for this registration. * MUST NOT contain a credential. @@ -1941,7 +2047,7 @@ data class ModelSourceAuthRequirement( /** * Why a credential is needed. */ - val reason: AuthRequiredReason, + val reason: ModelSourceAuthRequiredReason, /** * Human-readable hint the host writes, for example "The endpoint rejected * the API key." @@ -1970,7 +2076,7 @@ data class ModelSourceAuthRequiredState( /** * Why a credential is needed. */ - val reason: AuthRequiredReason, + val reason: ModelSourceAuthRequiredReason, /** * Human-readable hint the host writes, for example "The endpoint rejected * the API key." @@ -2015,7 +2121,9 @@ data class ModelSourceInfo( /** * Model source identifier, unique within the agent's * {@link AgentInfo.modelSources}. For a registered model source, this is - * the {@link ModelSourceRegistration.id}. + * the {@link ModelSourceRegistration.id}. A source is registered when + * {@link RootState.modelSourceRegistrations} has an entry with this `id` + * whose `provider` is the agent. */ val id: String, /** @@ -2089,6 +2197,8 @@ data class SessionModelInfo( * The source this model comes from. MUST match a {@link ModelSourceInfo.id} * in the agent's {@link AgentInfo.modelSources}. For a model from a * registered model source, this is the {@link ModelSourceRegistration.id}. + * An agent's own sources use it too, so it doesn't by itself mark a + * registered source. */ val modelSourceId: String? = null ) @@ -6066,7 +6176,13 @@ data class UsageInfo( @Serializable(with = ErrorInfoSerializer::class) data class ErrorInfo( /** - * Error type identifier + * Error type identifier. Well-known values: + * + * - `modelSourceUnavailable`: a registered model source the turn uses + * can't serve it, for example because its credential is missing, + * expired, rejected, or revoked, or the source was removed. The error + * part is resumable. See + * [Model source credentials](/specification/authentication#model-source-credentials). */ val errorType: String, /** diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index b90149c8f..d91148af3 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -120,6 +120,7 @@ pub enum ActionType { RootTerminalsChanged, RootConfigChanged, RootModelSourceRegistrationSet, + RootModelSourceContributorRemoved, RootModelSourceRegistrationRemoved, RootModelSourceStateChanged, TerminalData, @@ -293,6 +294,9 @@ impl serde::Serialize for ActionType { Self::RootModelSourceRegistrationSet => { serializer.serialize_str("root/modelSourceRegistrationSet") } + Self::RootModelSourceContributorRemoved => { + serializer.serialize_str("root/modelSourceContributorRemoved") + } Self::RootModelSourceRegistrationRemoved => { serializer.serialize_str("root/modelSourceRegistrationRemoved") } @@ -434,6 +438,7 @@ impl<'de> serde::Deserialize<'de> for ActionType { "root/terminalsChanged" => Self::RootTerminalsChanged, "root/configChanged" => Self::RootConfigChanged, "root/modelSourceRegistrationSet" => Self::RootModelSourceRegistrationSet, + "root/modelSourceContributorRemoved" => Self::RootModelSourceContributorRemoved, "root/modelSourceRegistrationRemoved" => Self::RootModelSourceRegistrationRemoved, "root/modelSourceStateChanged" => Self::RootModelSourceStateChanged, "terminal/data" => Self::TerminalData, @@ -524,23 +529,59 @@ pub struct RootConfigChangedAction { pub replace: Option, } -/// Adds a model source registration, or replaces the one with the same `id`. +/// Contributes a model source registration for `clientId`. A registration's +/// routing is its `provider`, `format`, and `definition`, with definitions +/// compared as JSON values: object key order is ignored, and numbers compare +/// by numeric value, so `1` equals `1.0`. +/// +/// - **Add.** When no registration has the `id`, appends it, with +/// `contributingClientIds` set to `[clientId]`, or absent without a +/// `clientId`. +/// - **Join.** When one has, and its routing is unchanged, keeps its +/// host-reported fields (`state`, `credentialNonce`, `credentialResource`, +/// `credentialOrigins`, and `credentialId`), adds `clientId` to +/// `contributingClientIds` if it isn't there, and takes the other fields +/// from the action. +/// - **Replace.** When the routing changed, replaces the registration, with +/// `contributingClientIds` set to `[clientId]`, or absent without a +/// `clientId`. Its host-reported fields are absent until the host reports +/// again with {@link RootModelSourceStateChangedAction}. /// -/// A client registers a source by dispatching this with its own `clientId`, and -/// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a -/// registration clears those host-reported fields until the host reports again -/// with {@link RootModelSourceStateChangedAction}. +/// A client dispatches this with its own `clientId`, and without +/// `contributingClientIds` or any host-reported field. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceRegistrationSetAction { - /// The registration to add or replace, matched by `id`. + /// The registration to contribute, matched by `id`. pub registration: ModelSourceRegistration, + /// The contributing client. Absent when the host registers the source + /// itself. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, } -/// Removes the model source registration with the given `id`. A no-op when -/// none matches. +/// Withdraws one client's contribution to a model source registration: +/// removes `clientId` from `contributingClientIds`, leaving the field absent +/// when no contributor remains. A no-op when no registration has `id`, or +/// `clientId` doesn't contribute it. It never removes the registration. +/// +/// A client dispatches this with its own `clientId`. The host dispatches it +/// when a contributing client leaves. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RootModelSourceContributorRemovedAction { + /// The registration's `id`. + pub id: String, + /// The contributing client to remove. + pub client_id: String, +} + +/// Removes the model source registration with the given `id` for every +/// contributor. A no-op when none matches. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -550,9 +591,10 @@ pub struct RootModelSourceRegistrationRemovedAction { pub id: String, } -/// Updates a model source registration's status, credential nonce, and -/// credential resource together. A no-op when no registration has `id`. Other -/// fields of the registration are preserved. Only the host dispatches it. +/// Updates a model source registration's host-reported fields together: +/// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and +/// `credentialId`. A no-op when no registration has `id`. Other fields of the +/// registration are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -568,6 +610,12 @@ pub struct RootModelSourceStateChangedAction { /// source that needs no credential. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, + /// Replaces the registration's `credentialOrigins`. Absent clears it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_origins: Option>, + /// Replaces the registration's `credentialId`. Absent clears it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_id: Option, } /// Session backend initialized successfully. @@ -2519,6 +2567,8 @@ pub enum StateAction { RootConfigChanged(RootConfigChangedAction), #[serde(rename = "root/modelSourceRegistrationSet")] RootModelSourceRegistrationSet(Box), + #[serde(rename = "root/modelSourceContributorRemoved")] + RootModelSourceContributorRemoved(RootModelSourceContributorRemovedAction), #[serde(rename = "root/modelSourceRegistrationRemoved")] RootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction), #[serde(rename = "root/modelSourceStateChanged")] diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index d00a9173c..d8758c178 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1760,6 +1760,14 @@ pub struct ModelSourceAuthenticateTarget { /// published in root state. The host rejects a stale one with `Conflict` /// (-32011). pub credential_nonce: String, + /// A client-chosen, non-secret ID for the credential, such as a hash of + /// where the client stores the key. The host publishes it as the + /// registration's `ModelSourceRegistration.credentialId`, so a client can + /// tell whether the host holds its current key. Clients SHOULD include it + /// when delivering a credential, and omit it when revoking one. MUST NOT be + /// derived from the secret. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_id: Option, } /// Pushes a credential for a protected resource. The `resource` field MUST diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 46ebbd2c1..d2bd8b6c7 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -11,8 +11,6 @@ use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use serde_repr::{Deserialize_repr, Serialize_repr}; -use crate::notifications::AuthRequiredReason; - // ─── Enums ──────────────────────────────────────────────────────────── /// How the server resumes sending data on a windowed subscription after @@ -1215,14 +1213,16 @@ impl<'de> serde::Deserialize<'de> for ModelSourceStatus { } } -/// How long a registered model source lasts once its contributing client leaves. +/// How long a registered model source lasts once its last contributing client +/// leaves. When the last contributor withdraws instead, the source goes away +/// whatever its retention. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ModelSourceRetentionPolicy { - /// Removed when the contributing client leaves, once running turns finish. + /// Removed when the last contributing client leaves, once running turns finish. ContributingClient, - /// Kept until a client removes it or host policy expires it. + /// Kept until it's removed, its last contributor withdraws, or host policy expires it. Host, /// Unknown raw value from a newer protocol version, preserved verbatim. Unknown(String), @@ -1255,6 +1255,101 @@ impl<'de> serde::Deserialize<'de> for ModelSourceRetentionPolicy { } } +/// Why a model source needs a credential. Specific to model sources: the +/// shared `AuthRequiredReason` folds rejection and revocation into `expired`. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelSourceAuthRequiredReason { + /// The host holds no credential yet. + Required, + /// The credential's lifetime or lease lapsed. A client may renew it. + Expired, + /// The endpoint refused the credential. Clients don't send a credential with + /// the same {@link ModelSourceRegistration.credentialId} again. + Rejected, + /// A client revoked the credential. Clients don't send one again without a user's action. + Revoked, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for ModelSourceAuthRequiredReason { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::Required => serializer.serialize_str("required"), + Self::Expired => serializer.serialize_str("expired"), + Self::Rejected => serializer.serialize_str("rejected"), + Self::Revoked => serializer.serialize_str("revoked"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for ModelSourceAuthRequiredReason { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "required" => Self::Required, + "expired" => Self::Expired, + "rejected" => Self::Rejected, + "revoked" => Self::Revoked, + _ => Self::Unknown(raw), + }) + } +} + +/// Whether clients acting for different principals share a host's model +/// source registry. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelSourcePrincipalPolicy { + /// Every connected client may change, supply credentials for, and select + /// every registration. + Shared, + /// The host verifies principals, and limits changes, credentials, and + /// selection of each registration to clients of the principal that + /// registered it. Root state still lists every registration to every + /// client. + Isolated, + /// Unknown raw value from a newer protocol version, preserved verbatim. + Unknown(String), +} + +impl serde::Serialize for ModelSourcePrincipalPolicy { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Self::Shared => serializer.serialize_str("shared"), + Self::Isolated => serializer.serialize_str("isolated"), + Self::Unknown(value) => serializer.serialize_str(value), + } + } +} + +impl<'de> serde::Deserialize<'de> for ModelSourcePrincipalPolicy { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let raw = ::deserialize(deserializer)?; + Ok(match raw.as_str() { + "shared" => Self::Shared, + "isolated" => Self::Isolated, + _ => Self::Unknown(raw), + }) + } +} + /// Computation lifecycle of a {@link ChangesetState}. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ChangesetStatus { @@ -2117,16 +2212,25 @@ pub struct MultipleWorkingDirectoriesCapability { pub struct ModelSourceRegistrationCapability { /// Definition formats the agent reads, most preferred first. Format names /// are defined by agent implementations and SHOULD be namespaced, for - /// example `example.com/model-source@1`. + /// example `example.com/model-source@1`. AHP doesn't define, standardize, + /// or name any format. pub formats: Vec, + /// How long, in milliseconds, the host keeps a disconnected client's + /// contributions before it treats the client as having left. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grace_period: Option, + /// Whether clients acting for different principals share the registry. + /// Absent means `shared`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub principal_policy: Option, /// Unrecognized wire members retained for full-object edits. #[serde(flatten)] pub extra: serde_json::Map, } -/// A model source registered on this host by a client, or by the host itself. -/// Its definition is in a format the agent named by `provider` reads. It never -/// contains a credential. +/// A model source registered on this host by one or more clients, or by the +/// host itself. Its definition is in a format the agent named by `provider` +/// reads. It never contains a credential. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2147,18 +2251,21 @@ pub struct ModelSourceRegistration { /// {@link ModelSourceRegistrationCapability.formats}. pub format: String, /// How to reach the source: endpoint, wire format, models, and so on, in - /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain - /// a credential. + /// `format`. Its shape belongs to the agent that reads it, and AHP doesn't + /// define it. MUST NOT contain a credential. pub definition: JsonObject, - /// The contributing client: the client that most recently registered or - /// changed the source. Absent for a source the host registered itself. + /// The clients that contribute this registration, in the order they joined. + /// The reducer maintains it from {@link RootModelSourceRegistrationSetAction} + /// and {@link RootModelSourceContributorRemovedAction}. Absent when no + /// client contributes it: a source the host registered itself, or a + /// `host`-retained one whose contributors have all left. #[serde(default, skip_serializing_if = "Option::is_none")] - pub client_id: Option, - /// What happens when the contributing client leaves. Absent means `contributingClient`. + pub contributing_client_ids: Option>, + /// What happens when the last contributing client leaves. Absent means `contributingClient`. #[serde(default, skip_serializing_if = "Option::is_none")] pub retention: Option, /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after a client replaces the + /// Absent until the host reports one, and after a `Set` replaces the /// registration until the host reports again. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, @@ -2186,6 +2293,19 @@ pub struct ModelSourceRegistration { /// takes a user-supplied secret omits them. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, + /// Every origin the host sends the credential to, such as + /// `https://api.example.com`. Present whenever `credentialResource` is. A + /// client checks each one against its own copy of the definition before it + /// sends a key. Set with `state`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_origins: Option>, + /// The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of + /// the credential the host most recently accepted. While the state is + /// `starting` or `ready`, the host holds it. While it's `authRequired`, the + /// `reason` says what happened to it. Absent until the host accepts a + /// credential. Set with `state`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_id: Option, /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] @@ -2229,7 +2349,7 @@ pub struct ModelSourceReadyState { #[serde(rename_all = "camelCase")] pub struct ModelSourceAuthRequirement { /// Why a credential is needed. - pub reason: AuthRequiredReason, + pub reason: ModelSourceAuthRequiredReason, /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2248,7 +2368,7 @@ pub struct ModelSourceAuthRequirement { #[serde(rename_all = "camelCase")] pub struct ModelSourceAuthRequiredState { /// Why a credential is needed. - pub reason: AuthRequiredReason, + pub reason: ModelSourceAuthRequiredReason, /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2278,7 +2398,9 @@ pub struct ModelSourceErrorState { pub struct ModelSourceInfo { /// Model source identifier, unique within the agent's /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSourceRegistration.id}. + /// the {@link ModelSourceRegistration.id}. A source is registered when + /// {@link RootState.modelSourceRegistrations} has an entry with this `id` + /// whose `provider` is the agent. pub id: String, /// Human-readable name pub display_name: String, @@ -2334,6 +2456,8 @@ pub struct SessionModelInfo { /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} /// in the agent's {@link AgentInfo.modelSources}. For a model from a /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// An agent's own sources use it too, so it doesn't by itself mark a + /// registered source. #[serde(default, skip_serializing_if = "Option::is_none")] pub model_source_id: Option, } @@ -5947,7 +6071,13 @@ pub struct UsageInfo { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorInfo { - /// Error type identifier + /// Error type identifier. Well-known values: + /// + /// - `modelSourceUnavailable`: a registered model source the turn uses + /// can't serve it, for example because its credential is missing, + /// expired, rejected, or revoked, or the source was removed. The error + /// part is resumable. See + /// [Model source credentials](/specification/authentication#model-source-credentials). pub error_type: String, /// Human-readable error message pub message: String, diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 72e60c799..1aa21611a 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -62,14 +62,15 @@ use ahp_types::state::{ ChangesetOperationStatus, ChangesetState, ChangesetStatus, ChatConfigState, ChatInputRequest, ChatState, ChildCustomization, ConfirmationOption, Customization, CustomizationEnablement, ErrorResponsePart, InputRequestResponsePart, McpServerCustomization, McpServerStartingState, - McpServerState, McpServerStoppedState, PendingMessage, PendingMessageKind, ResourceWatchState, - ResponsePart, RootState, SessionInputRequest, SessionLifecycle, SessionState, SessionStatus, - TerminalCommandPart, TerminalContentPart, TerminalExitedLifecycleState, TerminalLifecycleState, - TerminalState, TerminalUnclassifiedPart, ToolCallAuthRequiredState, ToolCallCancellationReason, - ToolCallCancelledState, ToolCallCompletedState, ToolCallConfirmationReason, - ToolCallContributor, ToolCallPendingConfirmationState, ToolCallPendingResultConfirmationState, - ToolCallResponsePart, ToolCallRunningState, ToolCallState, ToolCallStatus, - ToolCallStreamingState, ToolInput, Turn, TurnState, + McpServerState, McpServerStoppedState, ModelSourceRegistration, PendingMessage, + PendingMessageKind, ResourceWatchState, ResponsePart, RootState, SessionInputRequest, + SessionLifecycle, SessionState, SessionStatus, TerminalCommandPart, TerminalContentPart, + TerminalExitedLifecycleState, TerminalLifecycleState, TerminalState, TerminalUnclassifiedPart, + ToolCallAuthRequiredState, ToolCallCancellationReason, ToolCallCancelledState, + ToolCallCompletedState, ToolCallConfirmationReason, ToolCallContributor, + ToolCallPendingConfirmationState, ToolCallPendingResultConfirmationState, ToolCallResponsePart, + ToolCallRunningState, ToolCallState, ToolCallStatus, ToolCallStreamingState, ToolInput, Turn, + TurnState, }; use jiff::{SignedDuration, Timestamp}; @@ -723,10 +724,48 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu let list = state .model_source_registrations .get_or_insert_with(Vec::new); - if let Some(idx) = list.iter().position(|r| r.id == a.registration.id) { - list[idx] = a.registration.clone(); - } else { - list.push(a.registration.clone()); + let idx = list.iter().position(|r| r.id == a.registration.id); + let mut updated = a.registration.clone(); + let mut contributors = Vec::new(); + match idx + .map(|i| &list[i]) + .filter(|existing| same_model_source_routing(existing, &a.registration)) + { + Some(existing) => { + copy_model_source_host_fields(&mut updated, existing); + contributors.extend(existing.contributing_client_ids.iter().flatten().cloned()); + } + None => clear_model_source_host_fields(&mut updated), + } + if let Some(client_id) = &a.client_id { + if !contributors.contains(client_id) { + contributors.push(client_id.clone()); + } + } + updated.contributing_client_ids = (!contributors.is_empty()).then_some(contributors); + match idx { + Some(i) => list[i] = updated, + None => list.push(updated), + } + ReduceOutcome::Applied + } + StateAction::RootModelSourceContributorRemoved(a) => { + let Some(registration) = state + .model_source_registrations + .as_mut() + .and_then(|list| list.iter_mut().find(|r| r.id == a.id)) + else { + return ReduceOutcome::NoOp; + }; + let Some(contributors) = registration.contributing_client_ids.as_mut() else { + return ReduceOutcome::NoOp; + }; + if !contributors.contains(&a.client_id) { + return ReduceOutcome::NoOp; + } + contributors.retain(|c| *c != a.client_id); + if contributors.is_empty() { + registration.contributing_client_ids = None; } ReduceOutcome::Applied } @@ -751,12 +790,65 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu registration.state = Some(a.state.clone()); registration.credential_nonce = Some(a.credential_nonce.clone()); registration.credential_resource = a.credential_resource.clone(); + registration.credential_origins = a.credential_origins.clone(); + registration.credential_id = a.credential_id.clone(); ReduceOutcome::Applied } _ => ReduceOutcome::OutOfScope, } } +/// Whether two registrations have the same `provider`, `format`, and +/// `definition`, comparing definitions as JSON values. +fn same_model_source_routing(a: &ModelSourceRegistration, b: &ModelSourceRegistration) -> bool { + a.provider == b.provider + && a.format == b.format + && a.definition.len() == b.definition.len() + && a.definition.iter().all(|(key, value)| { + b.definition + .get(key) + .is_some_and(|other| json_values_equal(value, other)) + }) +} + +/// Compares JSON values regardless of object key order, with numbers compared +/// by numeric value, so `1` equals `1.0`. +fn json_values_equal(a: &serde_json::Value, b: &serde_json::Value) -> bool { + use serde_json::Value; + match (a, b) { + (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(), + (Value::Array(x), Value::Array(y)) => { + x.len() == y.len() && x.iter().zip(y).all(|(l, r)| json_values_equal(l, r)) + } + (Value::Object(x), Value::Object(y)) => { + x.len() == y.len() + && x.iter().all(|(key, value)| { + y.get(key) + .is_some_and(|other| json_values_equal(value, other)) + }) + } + _ => a == b, + } +} + +/// Copies the host-reported fields of `from` onto `to`. +fn copy_model_source_host_fields(to: &mut ModelSourceRegistration, from: &ModelSourceRegistration) { + to.state = from.state.clone(); + to.credential_nonce = from.credential_nonce.clone(); + to.credential_resource = from.credential_resource.clone(); + to.credential_origins = from.credential_origins.clone(); + to.credential_id = from.credential_id.clone(); +} + +/// Clears the host-reported fields of `registration`. +fn clear_model_source_host_fields(registration: &mut ModelSourceRegistration) { + registration.state = None; + registration.credential_nonce = None; + registration.credential_resource = None; + registration.credential_origins = None; + registration.credential_id = None; +} + // ─── Session Reducer ────────────────────────────────────────────────── /// Apply a [`StateAction`] to a [`SessionState`] in place. diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift index 7a03d5848..313800b15 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift @@ -6,6 +6,7 @@ import Foundation public let clientDispatchableActions: Set = [ "root/configChanged", "root/modelSourceRegistrationSet", + "root/modelSourceContributorRemoved", "root/modelSourceRegistrationRemoved", "session/titleChanged", "session/activeClientSet", @@ -61,6 +62,7 @@ public func isClientDispatchable(_ action: StateAction) -> Bool { switch action { case .rootConfigChanged, .rootModelSourceRegistrationSet, + .rootModelSourceContributorRemoved, .rootModelSourceRegistrationRemoved, .sessionTitleChanged, .sessionActiveClientSet, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index 1b8fc467d..e9d2bf078 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -94,6 +94,7 @@ public enum ActionType: Codable, Sendable, Equatable { case rootTerminalsChanged case rootConfigChanged case rootModelSourceRegistrationSet + case rootModelSourceContributorRemoved case rootModelSourceRegistrationRemoved case rootModelSourceStateChanged case terminalData @@ -212,6 +213,7 @@ public enum ActionType: Codable, Sendable, Equatable { case "root/terminalsChanged": self = .rootTerminalsChanged case "root/configChanged": self = .rootConfigChanged case "root/modelSourceRegistrationSet": self = .rootModelSourceRegistrationSet + case "root/modelSourceContributorRemoved": self = .rootModelSourceContributorRemoved case "root/modelSourceRegistrationRemoved": self = .rootModelSourceRegistrationRemoved case "root/modelSourceStateChanged": self = .rootModelSourceStateChanged case "terminal/data": self = .terminalData @@ -330,6 +332,7 @@ public enum ActionType: Codable, Sendable, Equatable { case .rootTerminalsChanged: try container.encode("root/terminalsChanged") case .rootConfigChanged: try container.encode("root/configChanged") case .rootModelSourceRegistrationSet: try container.encode("root/modelSourceRegistrationSet") + case .rootModelSourceContributorRemoved: try container.encode("root/modelSourceContributorRemoved") case .rootModelSourceRegistrationRemoved: try container.encode("root/modelSourceRegistrationRemoved") case .rootModelSourceStateChanged: try container.encode("root/modelSourceStateChanged") case .terminalData: try container.encode("terminal/data") @@ -2290,30 +2293,76 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { } } -/// Adds a model source registration, or replaces the one with the same `id`. +/// Contributes a model source registration for `clientId`. A registration's +/// routing is its `provider`, `format`, and `definition`, with definitions +/// compared as JSON values: object key order is ignored, and numbers compare +/// by numeric value, so `1` equals `1.0`. /// -/// A client registers a source by dispatching this with its own `clientId`, and -/// with no `state`, `credentialNonce`, or `credentialResource`. Replacing a -/// registration clears those host-reported fields until the host reports again -/// with {@link RootModelSourceStateChangedAction}. +/// - **Add.** When no registration has the `id`, appends it, with +/// `contributingClientIds` set to `[clientId]`, or absent without a +/// `clientId`. +/// - **Join.** When one has, and its routing is unchanged, keeps its +/// host-reported fields (`state`, `credentialNonce`, `credentialResource`, +/// `credentialOrigins`, and `credentialId`), adds `clientId` to +/// `contributingClientIds` if it isn't there, and takes the other fields +/// from the action. +/// - **Replace.** When the routing changed, replaces the registration, with +/// `contributingClientIds` set to `[clientId]`, or absent without a +/// `clientId`. Its host-reported fields are absent until the host reports +/// again with {@link RootModelSourceStateChangedAction}. +/// +/// A client dispatches this with its own `clientId`, and without +/// `contributingClientIds` or any host-reported field. /// /// Stability: 1.0 - Early development. public struct RootModelSourceRegistrationSetAction: Codable, Sendable, Equatable { public var type: ActionType - /// The registration to add or replace, matched by `id`. + /// The registration to contribute, matched by `id`. public var registration: ModelSourceRegistration + /// The contributing client. Absent when the host registers the source + /// itself. + public var clientId: String? public init( type: ActionType, - registration: ModelSourceRegistration + registration: ModelSourceRegistration, + clientId: String? = nil ) { self.type = type self.registration = registration + self.clientId = clientId + } +} + +/// Withdraws one client's contribution to a model source registration: +/// removes `clientId` from `contributingClientIds`, leaving the field absent +/// when no contributor remains. A no-op when no registration has `id`, or +/// `clientId` doesn't contribute it. It never removes the registration. +/// +/// A client dispatches this with its own `clientId`. The host dispatches it +/// when a contributing client leaves. +/// +/// Stability: 1.0 - Early development. +public struct RootModelSourceContributorRemovedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The registration's `id`. + public var id: String + /// The contributing client to remove. + public var clientId: String + + public init( + type: ActionType, + id: String, + clientId: String + ) { + self.type = type + self.id = id + self.clientId = clientId } } -/// Removes the model source registration with the given `id`. A no-op when -/// none matches. +/// Removes the model source registration with the given `id` for every +/// contributor. A no-op when none matches. /// /// Stability: 1.0 - Early development. public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equatable { @@ -2330,9 +2379,10 @@ public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equat } } -/// Updates a model source registration's status, credential nonce, and -/// credential resource together. A no-op when no registration has `id`. Other -/// fields of the registration are preserved. Only the host dispatches it. +/// Updates a model source registration's host-reported fields together: +/// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and +/// `credentialId`. A no-op when no registration has `id`. Other fields of the +/// registration are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { @@ -2346,19 +2396,27 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { /// Replaces the registration's `credentialResource`. Absent clears it, for a /// source that needs no credential. public var credentialResource: ProtectedResourceMetadata? + /// Replaces the registration's `credentialOrigins`. Absent clears it. + public var credentialOrigins: [String]? + /// Replaces the registration's `credentialId`. Absent clears it. + public var credentialId: String? public init( type: ActionType, id: String, state: ModelSourceState, credentialNonce: String, - credentialResource: ProtectedResourceMetadata? = nil + credentialResource: ProtectedResourceMetadata? = nil, + credentialOrigins: [String]? = nil, + credentialId: String? = nil ) { self.type = type self.id = id self.state = state self.credentialNonce = credentialNonce self.credentialResource = credentialResource + self.credentialOrigins = credentialOrigins + self.credentialId = credentialId } } @@ -2832,6 +2890,7 @@ public enum StateAction: Codable, Sendable, Equatable { case rootTerminalsChanged(RootTerminalsChangedAction) case rootConfigChanged(RootConfigChangedAction) case rootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction) + case rootModelSourceContributorRemoved(RootModelSourceContributorRemovedAction) case rootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction) case rootModelSourceStateChanged(RootModelSourceStateChangedAction) case terminalData(TerminalDataAction) @@ -3043,6 +3102,8 @@ public enum StateAction: Codable, Sendable, Equatable { self = .rootConfigChanged(try RootConfigChangedAction(from: decoder)) case "root/modelSourceRegistrationSet": self = .rootModelSourceRegistrationSet(try RootModelSourceRegistrationSetAction(from: decoder)) + case "root/modelSourceContributorRemoved": + self = .rootModelSourceContributorRemoved(try RootModelSourceContributorRemovedAction(from: decoder)) case "root/modelSourceRegistrationRemoved": self = .rootModelSourceRegistrationRemoved(try RootModelSourceRegistrationRemovedAction(from: decoder)) case "root/modelSourceStateChanged": @@ -3184,6 +3245,7 @@ public enum StateAction: Codable, Sendable, Equatable { case .rootTerminalsChanged(let v): try v.encode(to: encoder) case .rootConfigChanged(let v): try v.encode(to: encoder) case .rootModelSourceRegistrationSet(let v): try v.encode(to: encoder) + case .rootModelSourceContributorRemoved(let v): try v.encode(to: encoder) case .rootModelSourceRegistrationRemoved(let v): try v.encode(to: encoder) case .rootModelSourceStateChanged(let v): try v.encode(to: encoder) case .terminalData(let v): try v.encode(to: encoder) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 873b8a719..05dc762a5 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -1981,15 +1981,24 @@ public struct ModelSourceAuthenticateTarget: Codable, Sendable, Equatable { /// published in root state. The host rejects a stale one with `Conflict` /// (-32011). public var credentialNonce: String + /// A client-chosen, non-secret ID for the credential, such as a hash of + /// where the client stores the key. The host publishes it as the + /// registration's `ModelSourceRegistration.credentialId`, so a client can + /// tell whether the host holds its current key. Clients SHOULD include it + /// when delivering a credential, and omit it when revoking one. MUST NOT be + /// derived from the secret. + public var credentialId: String? public init( kind: AuthenticateTargetKind, modelSourceId: String, - credentialNonce: String + credentialNonce: String, + credentialId: String? = nil ) { self.kind = kind self.modelSourceId = modelSourceId self.credentialNonce = credentialNonce + self.credentialId = credentialId } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 0cc1394b6..67a7087d0 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -939,13 +939,15 @@ public enum ModelSourceStatus: Codable, Sendable, Equatable { } } -/// How long a registered model source lasts once its contributing client leaves. +/// How long a registered model source lasts once its last contributing client +/// leaves. When the last contributor withdraws instead, the source goes away +/// whatever its retention. /// /// Stability: 1.0 - Early development. public enum ModelSourceRetentionPolicy: Codable, Sendable, Equatable { - /// Removed when the contributing client leaves, once running turns finish. + /// Removed when the last contributing client leaves, once running turns finish. case contributingClient - /// Kept until a client removes it or host policy expires it. + /// Kept until it's removed, its last contributor withdraws, or host policy expires it. case host /// Unknown raw value from a newer protocol version, preserved verbatim. case unknown(String) @@ -970,6 +972,83 @@ public enum ModelSourceRetentionPolicy: Codable, Sendable, Equatable { } } +/// Why a model source needs a credential. Specific to model sources: the +/// shared `AuthRequiredReason` folds rejection and revocation into `expired`. +/// +/// Stability: 1.0 - Early development. +public enum ModelSourceAuthRequiredReason: Codable, Sendable, Equatable { + /// The host holds no credential yet. + case required + /// The credential's lifetime or lease lapsed. A client may renew it. + case expired + /// The endpoint refused the credential. Clients don't send a credential with + /// the same {@link ModelSourceRegistration.credentialId} again. + case rejected + /// A client revoked the credential. Clients don't send one again without a user's action. + case revoked + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "required": self = .required + case "expired": self = .expired + case "rejected": self = .rejected + case "revoked": self = .revoked + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .required: try container.encode("required") + case .expired: try container.encode("expired") + case .rejected: try container.encode("rejected") + case .revoked: try container.encode("revoked") + case .unknown(let raw): try container.encode(raw) + } + } +} + +/// Whether clients acting for different principals share a host's model +/// source registry. +/// +/// Stability: 1.0 - Early development. +public enum ModelSourcePrincipalPolicy: Codable, Sendable, Equatable { + /// Every connected client may change, supply credentials for, and select + /// every registration. + case shared + /// The host verifies principals, and limits changes, credentials, and + /// selection of each registration to clients of the principal that + /// registered it. Root state still lists every registration to every + /// client. + case isolated + /// Unknown raw value from a newer protocol version, preserved verbatim. + case unknown(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + switch raw { + case "shared": self = .shared + case "isolated": self = .isolated + default: self = .unknown(raw) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .shared: try container.encode("shared") + case .isolated: try container.encode("isolated") + case .unknown(let raw): try container.encode(raw) + } + } +} + /// Computation lifecycle of a {@link ChangesetState}. public enum ChangesetStatus: Codable, Sendable, Equatable { /// The server is computing this changeset for the first time. @@ -1776,39 +1855,56 @@ public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { /// Definition formats the agent reads, most preferred first. Format names /// are defined by agent implementations and SHOULD be namespaced, for - /// example `example.com/model-source@1`. + /// example `example.com/model-source@1`. AHP doesn't define, standardize, + /// or name any format. public var formats: [String] + /// How long, in milliseconds, the host keeps a disconnected client's + /// contributions before it treats the client as having left. + public var gracePeriod: Int? + /// Whether clients acting for different principals share the registry. + /// Absent means `shared`. + public var principalPolicy: ModelSourcePrincipalPolicy? /// Unrecognized wire members retained for full-object edits. public var extra: [String: AnyCodable] enum CodingKeys: String, CodingKey, CaseIterable { case formats + case gracePeriod + case principalPolicy } public init( formats: [String], + gracePeriod: Int? = nil, + principalPolicy: ModelSourcePrincipalPolicy? = nil, extra: [String: AnyCodable] = [:] ) { self.formats = formats + self.gracePeriod = gracePeriod + self.principalPolicy = principalPolicy self.extra = extra } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.formats = try container.decode([String].self, forKey: .formats) + self.gracePeriod = try container.decodeIfPresent(Int.self, forKey: .gracePeriod) + self.principalPolicy = try container.decodeIfPresent(ModelSourcePrincipalPolicy.self, forKey: .principalPolicy) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.formats, forKey: .formats) + try container.encodeIfPresent(self.gracePeriod, forKey: .gracePeriod) + try container.encodeIfPresent(self.principalPolicy, forKey: .principalPolicy) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } -/// A model source registered on this host by a client, or by the host itself. -/// Its definition is in a format the agent named by `provider` reads. It never -/// contains a credential. +/// A model source registered on this host by one or more clients, or by the +/// host itself. Its definition is in a format the agent named by `provider` +/// reads. It never contains a credential. /// /// Stability: 1.0 - Early development. public struct ModelSourceRegistration: Codable, Sendable, Equatable { @@ -1826,16 +1922,19 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { /// {@link ModelSourceRegistrationCapability.formats}. public var format: String /// How to reach the source: endpoint, wire format, models, and so on, in - /// `format`. Its shape belongs to the agent that reads it. MUST NOT contain - /// a credential. + /// `format`. Its shape belongs to the agent that reads it, and AHP doesn't + /// define it. MUST NOT contain a credential. public var definition: [String: AnyCodable] - /// The contributing client: the client that most recently registered or - /// changed the source. Absent for a source the host registered itself. - public var clientId: String? - /// What happens when the contributing client leaves. Absent means `contributingClient`. + /// The clients that contribute this registration, in the order they joined. + /// The reducer maintains it from {@link RootModelSourceRegistrationSetAction} + /// and {@link RootModelSourceContributorRemovedAction}. Absent when no + /// client contributes it: a source the host registered itself, or a + /// `host`-retained one whose contributors have all left. + public var contributingClientIds: [String]? + /// What happens when the last contributing client leaves. Absent means `contributingClient`. public var retention: ModelSourceRetentionPolicy? /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after a client replaces the + /// Absent until the host reports one, and after a `Set` replaces the /// registration until the host reports again. public var state: ModelSourceState? /// Host-issued token that a client echoes in @@ -1860,6 +1959,17 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { /// advertises `authorization_servers` and `scopes_supported`. A source that /// takes a user-supplied secret omits them. public var credentialResource: ProtectedResourceMetadata? + /// Every origin the host sends the credential to, such as + /// `https://api.example.com`. Present whenever `credentialResource` is. A + /// client checks each one against its own copy of the definition before it + /// sends a key. Set with `state`. + public var credentialOrigins: [String]? + /// The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of + /// the credential the host most recently accepted. While the state is + /// `starting` or `ready`, the host holds it. While it's `authRequired`, the + /// `reason` says what happened to it. Absent until the host accepts a + /// credential. Set with `state`. + public var credentialId: String? /// Additional implementation-defined metadata for this registration. /// MUST NOT contain a credential. public var meta: [String: AnyCodable]? @@ -1873,11 +1983,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { case icons case format case definition - case clientId + case contributingClientIds case retention case state case credentialNonce case credentialResource + case credentialOrigins + case credentialId case meta = "_meta" } @@ -1888,11 +2000,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { icons: [Icon]? = nil, format: String, definition: [String: AnyCodable], - clientId: String? = nil, + contributingClientIds: [String]? = nil, retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, credentialNonce: String? = nil, credentialResource: ProtectedResourceMetadata? = nil, + credentialOrigins: [String]? = nil, + credentialId: String? = nil, meta: [String: AnyCodable]? = nil, extra: [String: AnyCodable] = [:] ) { @@ -1902,11 +2016,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.icons = icons self.format = format self.definition = definition - self.clientId = clientId + self.contributingClientIds = contributingClientIds self.retention = retention self.state = state self.credentialNonce = credentialNonce self.credentialResource = credentialResource + self.credentialOrigins = credentialOrigins + self.credentialId = credentialId self.meta = meta self.extra = extra } @@ -1919,11 +2035,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) self.format = try container.decode(String.self, forKey: .format) self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) - self.clientId = try container.decodeIfPresent(String.self, forKey: .clientId) + self.contributingClientIds = try container.decodeIfPresent([String].self, forKey: .contributingClientIds) self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) self.credentialNonce = try container.decodeIfPresent(String.self, forKey: .credentialNonce) self.credentialResource = try container.decodeIfPresent(ProtectedResourceMetadata.self, forKey: .credentialResource) + self.credentialOrigins = try container.decodeIfPresent([String].self, forKey: .credentialOrigins) + self.credentialId = try container.decodeIfPresent(String.self, forKey: .credentialId) self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -1936,11 +2054,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { try container.encodeIfPresent(self.icons, forKey: .icons) try container.encode(self.format, forKey: .format) try container.encode(self.definition, forKey: .definition) - try container.encodeIfPresent(self.clientId, forKey: .clientId) + try container.encodeIfPresent(self.contributingClientIds, forKey: .contributingClientIds) try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) try container.encodeIfPresent(self.credentialNonce, forKey: .credentialNonce) try container.encodeIfPresent(self.credentialResource, forKey: .credentialResource) + try container.encodeIfPresent(self.credentialOrigins, forKey: .credentialOrigins) + try container.encodeIfPresent(self.credentialId, forKey: .credentialId) try container.encodeIfPresent(self.meta, forKey: .meta) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -2022,7 +2142,7 @@ public struct ModelSourceReadyState: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { /// Why a credential is needed. - public var reason: AuthRequiredReason + public var reason: ModelSourceAuthRequiredReason /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." public var description: String? @@ -2035,7 +2155,7 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { } public init( - reason: AuthRequiredReason, + reason: ModelSourceAuthRequiredReason, description: String? = nil, extra: [String: AnyCodable] = [:] ) { @@ -2046,7 +2166,7 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.reason = try container.decode(AuthRequiredReason.self, forKey: .reason) + self.reason = try container.decode(ModelSourceAuthRequiredReason.self, forKey: .reason) self.description = try container.decodeIfPresent(String.self, forKey: .description) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -2066,7 +2186,7 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { /// Why a credential is needed. - public var reason: AuthRequiredReason + public var reason: ModelSourceAuthRequiredReason /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." public var description: String? @@ -2081,7 +2201,7 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { } public init( - reason: AuthRequiredReason, + reason: ModelSourceAuthRequiredReason, description: String? = nil, kind: ModelSourceStatus, extra: [String: AnyCodable] = [:] @@ -2094,7 +2214,7 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.reason = try container.decode(AuthRequiredReason.self, forKey: .reason) + self.reason = try container.decode(ModelSourceAuthRequiredReason.self, forKey: .reason) self.description = try container.decodeIfPresent(String.self, forKey: .description) self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) @@ -2152,7 +2272,9 @@ public struct ModelSourceErrorState: Codable, Sendable, Equatable { public struct ModelSourceInfo: Codable, Sendable, Equatable { /// Model source identifier, unique within the agent's /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSourceRegistration.id}. + /// the {@link ModelSourceRegistration.id}. A source is registered when + /// {@link RootState.modelSourceRegistrations} has an entry with this `id` + /// whose `provider` is the agent. public var id: String /// Human-readable name public var displayName: String @@ -2206,6 +2328,8 @@ public struct SessionModelInfo: Codable, Sendable, Equatable { /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} /// in the agent's {@link AgentInfo.modelSources}. For a model from a /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// An agent's own sources use it too, so it doesn't by itself mark a + /// registered source. public var modelSourceId: String? enum CodingKeys: String, CodingKey { @@ -7683,7 +7807,13 @@ public struct UsageInfo: Codable, Sendable, Equatable { } public struct ErrorInfo: Codable, Sendable, Equatable { - /// Error type identifier + /// Error type identifier. Well-known values: + /// + /// - `modelSourceUnavailable`: a registered model source the turn uses + /// can't serve it, for example because its credential is missing, + /// expired, rejected, or revoked, or the source was removed. The error + /// part is resumable. See + /// [Model source credentials](/specification/authentication#model-source-credentials). public var errorType: String /// Human-readable error message public var message: String diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index f28b1ae79..de385d4d8 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -104,7 +104,10 @@ public struct AHPRootReducer: Reducer { state.config = config case .rootModelSourceRegistrationSet(let a): - applyModelSourceRegistrationSet(&state, a.registration) + applyModelSourceRegistrationSet(&state, a.registration, clientId: a.clientId) + + case .rootModelSourceContributorRemoved(let a): + _ = applyModelSourceContributorRemoved(&state, id: a.id, clientId: a.clientId) case .rootModelSourceRegistrationRemoved(let a): _ = applyModelSourceRegistrationRemoved(&state, id: a.id) @@ -118,17 +121,52 @@ public struct AHPRootReducer: Reducer { } } -/// Adds `registration` to the registry, or replaces the entry with the same `id`. -func applyModelSourceRegistrationSet(_ state: inout RootState, _ registration: ModelSourceRegistration) { +/// Contributes `registration` for `clientId`: adds it, joins an entry with the +/// same `id` and routing (keeping its host-reported fields), or replaces an +/// entry whose routing changed. +func applyModelSourceRegistrationSet(_ state: inout RootState, _ registration: ModelSourceRegistration, clientId: String?) { var list = state.modelSourceRegistrations ?? [] - if let idx = list.firstIndex(where: { $0.id == registration.id }) { - list[idx] = registration + let idx = list.firstIndex(where: { $0.id == registration.id }) + let existing = idx.map { list[$0] }.flatMap { sameModelSourceRouting($0, registration) ? $0 : nil } + var merged = registration + var contributors = existing?.contributingClientIds ?? [] + if let clientId, !contributors.contains(clientId) { + contributors.append(clientId) + } + merged.contributingClientIds = contributors.isEmpty ? nil : contributors + merged.state = existing?.state + merged.credentialNonce = existing?.credentialNonce + merged.credentialResource = existing?.credentialResource + merged.credentialOrigins = existing?.credentialOrigins + merged.credentialId = existing?.credentialId + if let idx { + list[idx] = merged } else { - list.append(registration) + list.append(merged) } state.modelSourceRegistrations = list } +/// Removes `clientId` from the contributors of the registration with `id`. +/// Returns `false` when no registration has `id`, or `clientId` doesn't +/// contribute it. +func applyModelSourceContributorRemoved(_ state: inout RootState, id: String, clientId: String) -> Bool { + guard var list = state.modelSourceRegistrations, + let idx = list.firstIndex(where: { $0.id == id }), + let contributors = list[idx].contributingClientIds, + contributors.contains(clientId) else { return false } + let remaining = contributors.filter { $0 != clientId } + list[idx].contributingClientIds = remaining.isEmpty ? nil : remaining + state.modelSourceRegistrations = list + return true +} + +/// Whether two registrations have the same `provider`, `format`, and +/// `definition`. `AnyCodable` dictionaries compare regardless of key order. +private func sameModelSourceRouting(_ a: ModelSourceRegistration, _ b: ModelSourceRegistration) -> Bool { + a.provider == b.provider && a.format == b.format && a.definition == b.definition +} + /// Removes the registration with `id`. Returns `false` when none matches. func applyModelSourceRegistrationRemoved(_ state: inout RootState, id: String) -> Bool { guard var list = state.modelSourceRegistrations, @@ -138,14 +176,16 @@ func applyModelSourceRegistrationRemoved(_ state: inout RootState, id: String) - return true } -/// Updates the status, credential nonce, and credential resource of the -/// registration with `action.id`. Returns `false` when none matches. +/// Updates the host-reported fields of the registration with `action.id`. +/// Returns `false` when none matches. func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelSourceStateChangedAction) -> Bool { guard var list = state.modelSourceRegistrations, let idx = list.firstIndex(where: { $0.id == action.id }) else { return false } list[idx].state = action.state list[idx].credentialNonce = action.credentialNonce list[idx].credentialResource = action.credentialResource + list[idx].credentialOrigins = action.credentialOrigins + list[idx].credentialId = action.credentialId state.modelSourceRegistrations = list return true } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index 324f4ab3c..13380aea0 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -124,7 +124,12 @@ public func rootReducer(state: RootState, action: StateAction) -> RootState { case .rootModelSourceRegistrationSet(let a): var next = state - applyModelSourceRegistrationSet(&next, a.registration) + applyModelSourceRegistrationSet(&next, a.registration, clientId: a.clientId) + return next + + case .rootModelSourceContributorRemoved(let a): + var next = state + guard applyModelSourceContributorRemoved(&next, id: a.id, clientId: a.clientId) else { return state } return next case .rootModelSourceRegistrationRemoved(let a): diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index badee8069..4a40f38fd 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet` and `root/modelSourceRegistrationRemoved` actions, and deliver each source's credential with a `modelSource` `authenticate` target that echoes the registration's host-issued `credentialNonce`. The host reports each registration's status with the host-only `root/modelSourceStateChanged` action. Agents advertise the definition formats they read with `AgentCapabilities.modelSourceRegistration`.", + "message": "Model source registry: clients can contribute bring-your-own-key model sources to the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet`, `root/modelSourceContributorRemoved`, and `root/modelSourceRegistrationRemoved` actions. Several clients can contribute one registration, listed in `contributingClientIds`, and a client that joins an unchanged definition keeps its status and credential. Clients deliver each source's credential with a `modelSource` `authenticate` target that echoes the registration's host-issued `credentialNonce` and names the key with a non-secret `credentialId`. The host reports status, `credentialResource`, `credentialOrigins`, and `credentialId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`), and ends turns on an unavailable source with the resumable `modelSourceUnavailable` error. Agents advertise the definition formats they read, the contributor grace period, and the principal policy with `AgentCapabilities.modelSourceRegistration`.", "issues": [619] } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 4710c8cdb..10eb9f699 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -23,7 +23,7 @@ Individual action payloads do **not** carry their own `session: URI` or `termina ## Root Actions -These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceRegistrationSet`, and `root/modelSourceRegistrationRemoved` are client-dispatchable; the rest are server-originated. +These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceRegistrationSet`, `root/modelSourceContributorRemoved`, and `root/modelSourceRegistrationRemoved` are client-dispatchable; the rest are server-originated. | Type | Client-dispatchable? | When | |---|---|---| @@ -31,9 +31,10 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/activeSessionsChanged` | No | Count of active sessions changed | | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | -| `root/modelSourceRegistrationSet` | **Yes** | A [model source registration](/specification/root-channel#model-source-registry) was added, or replaced by `id` | +| `root/modelSourceRegistrationSet` | **Yes** | A client contributed a [model source registration](/specification/root-channel#model-source-registry): added, joined, or replaced by `id` | +| `root/modelSourceContributorRemoved` | **Yes** | A client withdrew its contribution to a registration, or left | | `root/modelSourceRegistrationRemoved` | **Yes** | A model source registration was removed by `id` | -| `root/modelSourceStateChanged` | No | The host reported a registration's status, credential nonce, and credential resource | +| `root/modelSourceStateChanged` | No | The host reported a registration's status and credential fields | ## Automation Catalogue Actions diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index 321437d1e..976049911 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -150,7 +150,14 @@ If the token is invalid or the resource is unrecognized, the server MUST return ### Model source credentials -A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the registration carries a host-reported `credentialResource` with RFC 9728 metadata for the source's endpoint, in every state. When the source needs a credential, the host also sets the registration's state to `ModelSourceAuthRequiredState`, which carries a `reason`. A client answers with a `modelSource` target that names the registration and echoes its current `credentialNonce`: +A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the registration carries host-reported credential fields in every state: + +- `credentialResource`: RFC 9728 metadata for the endpoint the credential is for; +- `credentialOrigins`: every origin the host sends the credential to; +- `credentialNonce`: the registration's current generation; +- `credentialId`: the client-supplied ID of the key the host most recently accepted. + +When the source needs a credential, the host also sets the registration's state to `ModelSourceAuthRequiredState`, with a `reason`. A client answers with a `modelSource` target that names the registration, echoes its current `credentialNonce`, and names the key with a non-secret `credentialId`: ```jsonc // Model source credential delivery @@ -165,15 +172,18 @@ A client can [register a model source](/specification/root-channel#model-source- "target": { "kind": "modelSource", "modelSourceId": "2f6c0e1a-model-source", - "credentialNonce": "9b41d7" + "credentialNonce": "9b41d7", + "credentialId": "keychain-5c2a" } } } ``` -The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the registration's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `expiresIn` and `scopes`. `resource.resource_name` labels the prompt, for example "OpenRouter API key". +The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the registration's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `scopes`. `credentialResource.resource_name` labels the prompt, for example "OpenRouter API key". -`credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Whether the agent sends a credential over plain `http` is the host's network policy. +`credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Where the host actually sends the credential is governed by `credentialOrigins` and the egress rules below. + +`credentialId` is chosen by the client, for example a hash of where it stores the key. It MUST NOT be derived from the secret, because every client can read it. Clients SHOULD include it when they deliver a credential, and omit it when they revoke one. It lets a client that reloads, or one on another device, tell whether the host holds its current key. When `target.kind` is `modelSource`, the host: @@ -181,9 +191,10 @@ When `target.kind` is `modelSource`, the host: - MUST require `resource` to equal the registration's current `credentialResource.resource`; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); - MUST reject a `credentialNonce` other than the one it most recently issued for that registration with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; -- MUST treat an empty `token` as revocation: it drops the credential, and the source returns to `authRequired` with `reason: expired`, so no client sends the revoked secret again. +- MUST publish the target's `credentialId` as the registration's `credentialId` when it accepts a credential; +- MUST treat an empty `token` as revocation: it stops using the credential at once, drops it, and reports `authRequired` with `reason: revoked`. -Any client may deliver or revoke a registration's credential, as any client may answer an MCP server's challenge. +Any client may deliver or revoke a registration's credential, as any client may answer an MCP server's challenge. A host whose `principalPolicy` is `isolated` rejects a credential for another principal's registration with `PermissionDenied` (`-32009`). `credentialNonce` fences every credential change, and works as the registration's generation. The host issues a new nonce whenever a registration is added, including one registered again under a removed `id`, and whenever its `provider`, `format`, or `definition` changes, whether or not it held a credential. It also issues one whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation. It never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: @@ -193,13 +204,42 @@ Any client may deliver or revoke a registration's credential, as any client may The host tags every agent operation on the registration with the current nonce and discards any result, success or failure, that carries an older one. A late failure can't drop a key that has since replaced it, and a late success can't mark a changed or re-registered source `ready`, even after an edit that changes the definition back. -`credentialResource` and `credentialNonce` stay in root state for as long as the source takes a credential, not only while it's `authRequired`. Any client, including one that connected after the source became ready, can build an `authenticate` request at any time: to rotate a short-lived token before it expires, or to revoke a key with an empty token. +#### Reasons + +An `authRequired` state's `reason` is a `ModelSourceAuthRequiredReason`, specific to model sources. The shared `AuthRequiredReason` folds rejection and revocation into `expired`, so a client that renews automatically could undo a user's revocation. + +| `reason` | Meaning | What a client may send | +| --- | --- | --- | +| `required` | The host holds no credential yet. | Its key. | +| `expired` | The credential's lifetime or lease lapsed. | A renewed credential: a fresh token, or the same static key with a new lease. | +| `rejected` | The endpoint refused the credential. `credentialId` still names it. | Only a key whose `credentialId` differs. Otherwise it asks the user for a new one. | +| `revoked` | A client revoked the credential. | Nothing, until a user asks. | + +`expiresIn` keeps its meaning for short-lived tokens. With a static key, it's a lease: the host drops the key when the lease elapses and reports `expired`, and a client renews the lease by sending the key again. An API key without a lease omits `expiresIn`. + +#### Delivering + +Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers a credential only in answer to the registration's current state, reading it from its own secure storage or token provider each time: + +- when the state is `authRequired`, as the table above allows; +- when the state is `starting` or `ready`, and the registration's `credentialId` names a key this client has since replaced, for example one it delivered before the user changed it. A client whose key simply differs leaves the host's credential alone, so two devices with different working keys don't replace each other's in turn; +- when a lease or token it delivered is about to expire. + +Clients SHOULD NOT prompt the user for a key they don't have. A client MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy, and every origin in `credentialOrigins` is one its own copy of the definition sends the key to. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. + +#### Handling and egress + +The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition`, `_meta`, or credential fields, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. + +The host attaches the credential only to that source's requests, as its definition specifies, and only to origins in `credentialOrigins`, never to another origin, including on redirect. It drops the credential when the registration is removed, when its `provider`, `format`, or `definition` changes, when it's revoked, when its lease lapses, and when the host restarts. + +Endpoints in a definition, including loopback and private addresses, are resolved and reached from the host machine: `localhost` in a source registered with a remote host is that host, not the client's machine. Hosts SHOULD apply an egress policy to registered endpoints: deny link-local and cloud metadata addresses, and require `https` for any credentialed endpoint that isn't a loopback address, unless the host has opted in to plain `http`. -The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition`, `_meta`, or `credentialResource`, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. The host drops the credential when the registration is removed, when its `provider`, `format`, or `definition` changes, and when the host restarts. +#### Turns -The host asks for a new credential by setting the registration's state to `authRequired` again, which survives reconnects. When `reason` is `expired`, the client MUST NOT replay the same secret: it renews the token or asks the user for a new key. A client that has the source configured answers from its own secure storage, but MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. +When a turn can't use its source, because the credential is missing, expired, rejected, or revoked, or because the source was withdrawn or removed, the host ends the turn with `chat/error`. The error part's `error.errorType` is `modelSourceUnavailable`, and `resumable` is `true`. A client tells why from the registration of the turn's model: its `state`, or its absence. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first. The host never switches the turn to a different model. -If the credential fails during a turn that uses the source, or a turn starts while the source has no usable credential, the host SHOULD end the turn with a resumable error (`chat/error` with `part.resumable: true`) rather than wait. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first. The host never switches the turn to a different model. +When the last contributing client leaves a `contributingClient`-retained source, turns already running on it finish, and no new ones start. When a client's withdrawal leaves a source with no contributors, when any client removes it, or when a client revokes its credential, the host stops using the credential immediately and ends every running turn that uses it with the `modelSourceUnavailable` error. ### Why keyed by `resource` and optional `target`? diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index a5b66450b..b9f512240 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -63,7 +63,7 @@ A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, ### Model source registry -Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSourceRegistrations`](/reference/root#modelsourceregistration), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads. +Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSourceRegistrations`](/reference/root#modelsourceregistration), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads, how long the host keeps a disconnected client's contributions (`gracePeriod`), and whether clients of different principals share the registry (`principalPolicy`). ```json { @@ -72,64 +72,89 @@ Clients can register bring-your-own-key model sources with the host, so its agen "displayName": "OpenRouter", "format": "example.com/model-source@1", "definition": { "baseUrl": "https://openrouter.ai/api/v1" }, - "clientId": "laptop", + "contributingClientIds": ["laptop-window-1", "laptop-window-2"], "retention": "host", "state": { "kind": "ready" }, "credentialNonce": "9b41d7", "credentialResource": { "resource": "https://openrouter.ai/api/v1", "resource_name": "OpenRouter API key" - } + }, + "credentialOrigins": ["https://openrouter.ai"], + "credentialId": "keychain-5c2a" } ``` -`definition` says how to reach the source, in `format`. Its shape belongs to the agent that reads it, and it MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). +`definition` says how to reach the source, in `format`. AHP doesn't define, standardize, or name any definition format: `format` and `definition` are opaque to AHP and belong to the agent that reads them. A definition MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). + +#### Contributing + +Several clients, such as two windows or two devices, can want the same source. Each one contributes it with `root/modelSourceRegistrationSet` and its own `clientId`, and each one withdraws only its own contribution with `root/modelSourceContributorRemoved`. `root/modelSourceRegistrationRemoved` removes a registration for every contributor. -#### Registering +A registration's routing is its `provider`, `format`, and `definition`, with definitions compared as JSON values: object key order is ignored, and numbers compare by numeric value, so `1` equals `1.0`. The reducers apply the actions as follows: -A client registers a source by dispatching `root/modelSourceRegistrationSet` with its own `clientId`, and with no `state`, `credentialNonce`, or `credentialResource`. It removes one with `root/modelSourceRegistrationRemoved`. Like MCP servers, registrations have no per-client ownership: any client can change or remove any registration, and the client that changes one becomes its contributing client. A host MAY reject client changes to a registration it created itself. +- **Add.** When no registration has the `id`, `Set` appends it, with `contributingClientIds` set to `[clientId]`, or absent when there's no `clientId`. +- **Join.** When one has, and its routing is unchanged, `Set` keeps its host-reported fields (`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and `credentialId`), adds `clientId` to `contributingClientIds` if it isn't there, and takes `displayName`, `icons`, `retention`, and `_meta` from the action. Joining doesn't disturb the status, nonce, or credential. +- **Replace.** When the routing changed, `Set` replaces the registration, with `contributingClientIds` set to `[clientId]`. Its host-reported fields are absent until the host reports again. +- **Withdraw.** `root/modelSourceContributorRemoved` removes `clientId` from `contributingClientIds`, leaving the field absent when no contributor remains. It never removes the registration. +- **Remove.** `Removed` deletes the registration by `id`. Both are no-ops when nothing matches. + +A client dispatches `Set` with its own `clientId`, and without `contributingClientIds` or any host-reported field, when it starts with the source configured and isn't already a contributor. When contributors disagree on `displayName`, `icons`, `retention`, or `_meta`, the last `Set` wins. A client SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one registration. A client SHOULD NOT replace a registration whose routing differs from its own copy unless the user changed the source in its configuration, or two clients with different configurations would replace each other indefinitely. When the user removes a source, the client withdraws its own contribution, and dispatches `Removed` only to remove the source for everyone. The host rejects a client's `Set`, through `rejectionReason`, when: - the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; -- `clientId` isn't the dispatching client's ID, or `state`, `credentialNonce`, or `credentialResource` is present; -- `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same registration doesn't count, so a ready registration can still be updated; -- the host won't honor the requested `retention`. The client can register again with `contributingClient` retention. +- `clientId` is absent or isn't the dispatching client's ID; +- the registration includes `contributingClientIds` or any host-reported field; +- `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same registration doesn't count, so a ready registration can still be joined or changed; +- the host won't honor the requested `retention`. The client can register again with `contributingClient` retention; +- the host registered the source itself; +- the host's `principalPolicy` is `isolated`, and the registration belongs to another principal. -A client's `Removed` is a no-op when no registration has that `id`. +The host rejects a client's `root/modelSourceContributorRemoved` whose `clientId` isn't the dispatching client's ID. A host MAY reject a client's `Removed` for a source it registered itself or one that belongs to another principal. -When a `Set` changes a registration's `provider`, `format`, or `definition`, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A change to `displayName`, `icons`, `clientId`, or `retention` keeps the credential and the nonce. A host may also register sources itself. Those registrations have no `clientId`, and their retention behaves as `host`. +When a client's own withdrawal leaves a registration with no contributors, the host removes it with `Removed`, whatever its retention. When a `Set` replaces a registration's routing, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A join, or a change to `displayName`, `icons`, `retention`, or `_meta`, keeps the credential and the nonce. A host may also register sources itself. Those registrations have no contributing clients, and their retention behaves as `host`. #### Status -The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets three host-reported fields together: the registration's `state` (`starting`, `ready`, `authRequired`, or `error`), its `credentialNonce`, and its `credentialResource`, which an absent value clears. It never reports status by dispatching the registration back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed registration or overwrite a newer definition. +The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets the host-reported fields together: the registration's `state` (`starting`, `ready`, `authRequired`, or `error`), its `credentialNonce`, and its `credentialResource`, `credentialOrigins`, and `credentialId`, which an absent value clears. It never reports status by dispatching the registration back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed registration or overwrite a newer definition. -`credentialNonce` is the registration's generation. The host issues a new one when a registration is added, including under a removed `id`, when its `provider`, `format`, or `definition` changes, and whenever it installs or drops a credential. It tags every agent operation on the registration, such as validation, model discovery, and inference, with the current nonce, and discards any result, success or failure, that carries an older one. A slow result from before a change therefore can't mark the current registration `ready`, even when the definition has changed back to the same value. +An `authRequired` state carries a `reason` specific to model sources: `required` (no credential yet), `expired` (its lifetime or lease lapsed), `rejected` (the endpoint refused it), or `revoked` (a client revoked it). See [Model source credentials](/specification/authentication#model-source-credentials) for what clients do with each. -`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for. The host reports it in every state while the source takes a credential, so any client can deliver, rotate, or revoke one, and leaves it absent for a source that needs none. See [Model source credentials](/specification/authentication#model-source-credentials). +`credentialNonce` is the registration's generation. The host issues a new one when a registration is added, including under a removed `id`, when its routing changes, and whenever it installs or drops a credential. It tags every agent operation on the registration, such as validation, model discovery, and inference, with the current nonce, and discards any result, success or failure, that carries an older one. A slow result from before a change therefore can't mark the current registration `ready`, even when the definition has changed back to the same value. -A client's `Set` replaces the whole registration, so it clears the host-reported fields until the host reports again. A client SHOULD NOT dispatch `Set` for a registration that hasn't changed. +`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for, and `credentialOrigins` lists every origin the host sends the credential to. The host reports both in every state while the source takes a credential, so any client can check, deliver, rotate, or revoke one, and leaves them absent for a source that needs none. `credentialId` names the key the host most recently accepted. #### Catalog -When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `displayName`, and its models in `models` with `modelSourceId` set to that `id`. Once the registration has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the registration is removed, when its contributing client leaves under `contributingClient` retention, when it enters `error`, or when a change to `provider`, `format`, or `definition` mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). A turn that uses a listed model while the source has no usable credential ends with a resumable error, as described in [Model source credentials](/specification/authentication#model-source-credentials). The host MAY list the `ModelSourceInfo` in any state. +When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `displayName`, and its models in `models` with `modelSourceId` set to that `id`. `modelSourceId` alone doesn't mark a registered source, because an agent's own sources use it too. A source is registered when `modelSourceRegistrations` has an entry with that `id` whose `provider` is the agent. + +Once the registration has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the registration is removed, when its last contributing client leaves under `contributingClient` retention, when it enters `error`, or when a routing change mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). The host MAY list the `ModelSourceInfo` in any state. -Any client can select a registered source's models, in any session whose agent is the registration's `provider`. The host checks every selection: the model is listed, and the chat is backed by the registration's agent provider. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. +Any client can select a registered source's models, in any session whose agent is the registration's `provider`. The host checks every selection: the model is listed, the chat is backed by the registration's agent provider, and, under `isolated`, the turn's client acts for the registration's principal. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. A turn that can't use its source ends with the resumable `modelSourceUnavailable` error, as described in [Model source credentials](/specification/authentication#model-source-credentials). #### Retention -The contributing client chooses what happens when it leaves. Absent means `contributingClient`, the narrower choice. +The contributing clients choose what happens when the last of them leaves. Absent means `contributingClient`, the narrower choice. -- With `contributingClient`, the source goes away with its client, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the registration and drops its credential. -- With `host`, the source stays, like a host-declared MCP server, with its credential in memory, until a client removes it, host policy expires it, or the host restarts. +A contributing client leaves when its connection closes and it doesn't reconnect with the same `clientId` within the host's `gracePeriod`. The host then dispatches `root/modelSourceContributorRemoved` for it. While other contributors remain, nothing else changes. When the last contributor leaves: -The host MAY expire `host`-retained registrations. Every client sees every registration, including its definition, which suits hosts whose connected clients all belong to one user. +- With `contributingClient`, the source goes away, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the registration and drops its credential. +- With `host`, the source stays, like a host-declared MCP server, with its credential in memory and no contributors, until a client removes it, a client that joins later withdraws, or host policy expires it. A restart drops its credential, as described below. -A client that reconnects with the same `clientId` within the host's grace period keeps its registrations. A client that comes back with a new `clientId` and the same configuration registers again under the same `id`, which makes it the contributing client and keeps the credential. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back through `starting`, and reach `authRequired` only if they need a credential. +Explicit withdrawal is different from leaving: when the last contributor withdraws, the source goes away whatever its retention, so `host` retention doesn't leave sources nobody wants. The host MAY expire `host`-retained registrations. + +A client that reconnects with the same `clientId` within the grace period is still listed. A client that comes back with a new `clientId` and the same configuration joins with `Set`, which keeps the status, nonce, and credential. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back through `starting`, and reach `authRequired` with `reason: required` only if they need a credential. + +#### Principals + +AHP doesn't verify which client is which, so with `principalPolicy` `shared`, or absent, every connected client may change, supply credentials for, and select every registration, as with MCP servers. Where a host can verify principals, it MAY restrict changes, credentials, and use of a registration to clients of the principal that registered it, and advertises `isolated`. Root state still lists every registration to every client, so a definition is never private. A host whose connections carry credentials scoped to one client, such as a relay that forwards each client's own sign-in, SHOULD NOT let one client's registration be used by another: it uses `isolated`, or doesn't advertise `modelSourceRegistration`. #### Reserved model IDs -Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a `definition` change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when a different client made the change. A host can meet this by minting IDs it never reuses, for example with a random component. +Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a `definition` change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when a different client made the change. + +A host SHOULD derive each model's ID deterministically from the registration (its `id`, `provider`, and `format`), the endpoint, and the endpoint's model identifier, for example with a hash. The same model then gets the same ID when its source is registered again or the host restarts, without a stored table, and a moved endpoint gets a new one. #### Automations @@ -186,7 +211,7 @@ target channel instead. | `root/sessionSummaryChanged` | server → client notification | Session catalogue entry mutated. | | `root/progress` | server → client notification | Generic progress for a long-running operation a client opted into (e.g. an SDK download). | | `unsubscribe` | client → server notification | Stop receiving root-channel messages. | -| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceRegistrationSet`, or `root/modelSourceRegistrationRemoved`. | +| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceRegistrationSet`, `root/modelSourceContributorRemoved`, or `root/modelSourceRegistrationRemoved`. | `auth/required` may also be emitted on `ahp-root://` when the auth requirement is root-scoped; see [Authentication](/specification/authentication). @@ -201,9 +226,10 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/activeSessionsChanged` | Server | Replaces `activeSessions` | | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | -| `root/modelSourceRegistrationSet` | Server / Client | Adds or replaces a registration in `modelSourceRegistrations` by `id` | +| `root/modelSourceRegistrationSet` | Server / Client | Adds, joins, or replaces a registration in `modelSourceRegistrations` by `id`, maintaining `contributingClientIds` | +| `root/modelSourceContributorRemoved` | Server / Client | Removes one client from a registration's `contributingClientIds` | | `root/modelSourceRegistrationRemoved` | Server / Client | Removes a registration by `id` | -| `root/modelSourceStateChanged` | Server | Sets a registration's `state`, `credentialNonce`, and `credentialResource`. A no-op for an unknown `id` | +| `root/modelSourceStateChanged` | Server | Sets a registration's host-reported fields. A no-op for an unknown `id` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 16491ffc8..df640d286 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -129,14 +129,18 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state`, `credentialNonce`, or `credentialResource`. Replacing a\nregistration clears those host-reported fields until the host reports again\nwith {@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", + "description": "Contributes a model source registration for `clientId`. A registration's\nrouting is its `provider`, `format`, and `definition`, with definitions\ncompared as JSON values: object key order is ignored, and numbers compare\nby numeric value, so `1` equals `1.0`.\n\n- **Add.** When no registration has the `id`, appends it, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`.\n- **Join.** When one has, and its routing is unchanged, keeps its\n host-reported fields (`state`, `credentialNonce`, `credentialResource`,\n `credentialOrigins`, and `credentialId`), adds `clientId` to\n `contributingClientIds` if it isn't there, and takes the other fields\n from the action.\n- **Replace.** When the routing changed, replaces the registration, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`. Its host-reported fields are absent until the host reports\n again with {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this with its own `clientId`, and without\n`contributingClientIds` or any host-reported field.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" }, "registration": { "$ref": "#/$defs/ModelSourceRegistration", - "description": "The registration to add or replace, matched by `id`." + "description": "The registration to contribute, matched by `id`." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent when the host registers the source\nitself." } }, "required": [ @@ -144,9 +148,31 @@ "registration" ] }, + "RootModelSourceContributorRemovedAction": { + "type": "object", + "description": "Withdraws one client's contribution to a model source registration:\nremoves `clientId` from `contributingClientIds`, leaving the field absent\nwhen no contributor remains. A no-op when no registration has `id`, or\n`clientId` doesn't contribute it. It never removes the registration.\n\nA client dispatches this with its own `clientId`. The host dispatches it\nwhen a contributing client leaves.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceContributorRemoved" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + }, + "clientId": { + "type": "string", + "description": "The contributing client to remove." + } + }, + "required": [ + "type", + "id", + "clientId" + ] + }, "RootModelSourceRegistrationRemovedAction": { "type": "object", - "description": "Removes the model source registration with the given `id`. A no-op when\nnone matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source registration with the given `id` for every\ncontributor. A no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationRemoved" @@ -163,7 +189,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's status, credential nonce, and\ncredential resource together. A no-op when no registration has `id`. Other\nfields of the registration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source registration's host-reported fields together:\n`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`credentialId`. A no-op when no registration has `id`. Other fields of the\nregistration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -183,6 +209,17 @@ "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." + }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Replaces the registration's `credentialOrigins`. Absent clears it." + }, + "credentialId": { + "type": "string", + "description": "Replaces the registration's `credentialId`. Absent clears it." } }, "required": [ @@ -3237,7 +3274,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier" + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -3470,7 +3507,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -3532,7 +3569,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -3570,7 +3607,16 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + }, + "gracePeriod": { + "type": "integer", + "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "minimum": 0 + }, + "principalPolicy": { + "$ref": "#/$defs/ModelSourcePrincipalPolicy", + "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." } }, "required": [ @@ -3579,7 +3625,7 @@ }, "ModelSourceRegistration": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -3607,19 +3653,22 @@ "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." }, - "clientId": { - "type": "string", - "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." + "contributingClientIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", @@ -3629,6 +3678,17 @@ "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + }, + "credentialId": { + "type": "string", + "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -3672,7 +3732,7 @@ "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -3689,7 +3749,7 @@ "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -9738,6 +9798,9 @@ { "$ref": "#/$defs/RootModelSourceRegistrationSetAction" }, + { + "$ref": "#/$defs/RootModelSourceContributorRemovedAction" + }, { "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" }, @@ -10141,21 +10204,31 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourcePrincipalPolicy": { + "enum": [ + "shared", + "isolated" + ], + "type": "string", + "description": "Whether clients acting for different principals share a host's model\nsource registry." + }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", "host" ], "type": "string", - "description": "How long a registered model source lasts once its contributing client leaves." + "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." }, - "AuthRequiredReason": { + "ModelSourceAuthRequiredReason": { "enum": [ "required", - "expired" + "expired", + "rejected", + "revoked" ], "type": "string", - "description": "Reason why authentication is required." + "description": "Why a model source needs a credential. Specific to model sources: the\nshared `AuthRequiredReason` folds rejection and revocation into `expired`." }, "SessionLifecycle": { "enum": [ diff --git a/schema/commands.schema.json b/schema/commands.schema.json index fc9ea826f..4d0f11411 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1067,6 +1067,10 @@ "credentialNonce": { "type": "string", "description": "The registration's current `ModelSourceRegistration.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." + }, + "credentialId": { + "type": "string", + "description": "A client-chosen, non-secret ID for the credential, such as a hash of\nwhere the client stores the key. The host publishes it as the\nregistration's `ModelSourceRegistration.credentialId`, so a client can\ntell whether the host holds its current key. Clients SHOULD include it\nwhen delivering a credential, and omit it when revoking one. MUST NOT be\nderived from the secret." } }, "required": [ @@ -2561,7 +2565,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier" + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -2794,7 +2798,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -2856,7 +2860,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -2894,7 +2898,16 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + }, + "gracePeriod": { + "type": "integer", + "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "minimum": 0 + }, + "principalPolicy": { + "$ref": "#/$defs/ModelSourcePrincipalPolicy", + "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." } }, "required": [ @@ -2903,7 +2916,7 @@ }, "ModelSourceRegistration": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -2931,19 +2944,22 @@ "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." }, - "clientId": { - "type": "string", - "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." + "contributingClientIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", @@ -2953,6 +2969,17 @@ "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + }, + "credentialId": { + "type": "string", + "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -2996,7 +3023,7 @@ "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -3013,7 +3040,7 @@ "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -8567,14 +8594,18 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state`, `credentialNonce`, or `credentialResource`. Replacing a\nregistration clears those host-reported fields until the host reports again\nwith {@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", + "description": "Contributes a model source registration for `clientId`. A registration's\nrouting is its `provider`, `format`, and `definition`, with definitions\ncompared as JSON values: object key order is ignored, and numbers compare\nby numeric value, so `1` equals `1.0`.\n\n- **Add.** When no registration has the `id`, appends it, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`.\n- **Join.** When one has, and its routing is unchanged, keeps its\n host-reported fields (`state`, `credentialNonce`, `credentialResource`,\n `credentialOrigins`, and `credentialId`), adds `clientId` to\n `contributingClientIds` if it isn't there, and takes the other fields\n from the action.\n- **Replace.** When the routing changed, replaces the registration, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`. Its host-reported fields are absent until the host reports\n again with {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this with its own `clientId`, and without\n`contributingClientIds` or any host-reported field.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" }, "registration": { "$ref": "#/$defs/ModelSourceRegistration", - "description": "The registration to add or replace, matched by `id`." + "description": "The registration to contribute, matched by `id`." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent when the host registers the source\nitself." } }, "required": [ @@ -8582,9 +8613,31 @@ "registration" ] }, + "RootModelSourceContributorRemovedAction": { + "type": "object", + "description": "Withdraws one client's contribution to a model source registration:\nremoves `clientId` from `contributingClientIds`, leaving the field absent\nwhen no contributor remains. A no-op when no registration has `id`, or\n`clientId` doesn't contribute it. It never removes the registration.\n\nA client dispatches this with its own `clientId`. The host dispatches it\nwhen a contributing client leaves.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceContributorRemoved" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + }, + "clientId": { + "type": "string", + "description": "The contributing client to remove." + } + }, + "required": [ + "type", + "id", + "clientId" + ] + }, "RootModelSourceRegistrationRemovedAction": { "type": "object", - "description": "Removes the model source registration with the given `id`. A no-op when\nnone matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source registration with the given `id` for every\ncontributor. A no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationRemoved" @@ -8601,7 +8654,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's status, credential nonce, and\ncredential resource together. A no-op when no registration has `id`. Other\nfields of the registration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source registration's host-reported fields together:\n`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`credentialId`. A no-op when no registration has `id`. Other fields of the\nregistration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -8621,6 +8674,17 @@ "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." + }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Replaces the registration's `credentialOrigins`. Absent clears it." + }, + "credentialId": { + "type": "string", + "description": "Replaces the registration's `credentialId`. Absent clears it." } }, "required": [ @@ -11125,6 +11189,9 @@ { "$ref": "#/$defs/RootModelSourceRegistrationSetAction" }, + { + "$ref": "#/$defs/RootModelSourceContributorRemovedAction" + }, { "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" }, @@ -11578,13 +11645,21 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourcePrincipalPolicy": { + "enum": [ + "shared", + "isolated" + ], + "type": "string", + "description": "Whether clients acting for different principals share a host's model\nsource registry." + }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", "host" ], "type": "string", - "description": "How long a registered model source lasts once its contributing client leaves." + "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." }, "ModelSourceState": { "oneOf": [ @@ -11603,13 +11678,15 @@ ], "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, - "AuthRequiredReason": { + "ModelSourceAuthRequiredReason": { "enum": [ "required", - "expired" + "expired", + "rejected", + "revoked" ], "type": "string", - "description": "Reason why authentication is required." + "description": "Why a model source needs a credential. Specific to model sources: the\nshared `AuthRequiredReason` folds rejection and revocation into `expired`." }, "SessionStatus": { "type": "integer", diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 80fdc0c30..5b28ab34a 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -541,7 +541,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier" + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -774,7 +774,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -836,7 +836,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -874,7 +874,16 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + }, + "gracePeriod": { + "type": "integer", + "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "minimum": 0 + }, + "principalPolicy": { + "$ref": "#/$defs/ModelSourcePrincipalPolicy", + "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." } }, "required": [ @@ -883,7 +892,7 @@ }, "ModelSourceRegistration": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -911,19 +920,22 @@ "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." }, - "clientId": { - "type": "string", - "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." + "contributingClientIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", @@ -933,6 +945,17 @@ "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + }, + "credentialId": { + "type": "string", + "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -976,7 +999,7 @@ "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -993,7 +1016,7 @@ "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -7485,6 +7508,10 @@ "credentialNonce": { "type": "string", "description": "The registration's current `ModelSourceRegistration.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." + }, + "credentialId": { + "type": "string", + "description": "A client-chosen, non-secret ID for the credential, such as a hash of\nwhere the client stores the key. The host publishes it as the\nregistration's `ModelSourceRegistration.credentialId`, so a client can\ntell whether the host holds its current key. Clients SHOULD include it\nwhen delivering a credential, and omit it when revoking one. MUST NOT be\nderived from the secret." } }, "required": [ @@ -8482,13 +8509,21 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourcePrincipalPolicy": { + "enum": [ + "shared", + "isolated" + ], + "type": "string", + "description": "Whether clients acting for different principals share a host's model\nsource registry." + }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", "host" ], "type": "string", - "description": "How long a registered model source lasts once its contributing client leaves." + "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." }, "ModelSourceState": { "oneOf": [ @@ -8507,13 +8542,15 @@ ], "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, - "AuthRequiredReason": { + "ModelSourceAuthRequiredReason": { "enum": [ "required", - "expired" + "expired", + "rejected", + "revoked" ], "type": "string", - "description": "Reason why authentication is required." + "description": "Why a model source needs a credential. Specific to model sources: the\nshared `AuthRequiredReason` folds rejection and revocation into `expired`." }, "SessionStatus": { "type": "integer", @@ -9284,6 +9321,9 @@ { "$ref": "#/$defs/RootModelSourceRegistrationSetAction" }, + { + "$ref": "#/$defs/RootModelSourceContributorRemovedAction" + }, { "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" }, @@ -9827,14 +9867,18 @@ }, "RootModelSourceRegistrationSetAction": { "type": "object", - "description": "Adds a model source registration, or replaces the one with the same `id`.\n\nA client registers a source by dispatching this with its own `clientId`, and\nwith no `state`, `credentialNonce`, or `credentialResource`. Replacing a\nregistration clears those host-reported fields until the host reports again\nwith {@link RootModelSourceStateChangedAction}.\n\nStability: 1.0 - Early development.", + "description": "Contributes a model source registration for `clientId`. A registration's\nrouting is its `provider`, `format`, and `definition`, with definitions\ncompared as JSON values: object key order is ignored, and numbers compare\nby numeric value, so `1` equals `1.0`.\n\n- **Add.** When no registration has the `id`, appends it, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`.\n- **Join.** When one has, and its routing is unchanged, keeps its\n host-reported fields (`state`, `credentialNonce`, `credentialResource`,\n `credentialOrigins`, and `credentialId`), adds `clientId` to\n `contributingClientIds` if it isn't there, and takes the other fields\n from the action.\n- **Replace.** When the routing changed, replaces the registration, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`. Its host-reported fields are absent until the host reports\n again with {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this with its own `clientId`, and without\n`contributingClientIds` or any host-reported field.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationSet" }, "registration": { "$ref": "#/$defs/ModelSourceRegistration", - "description": "The registration to add or replace, matched by `id`." + "description": "The registration to contribute, matched by `id`." + }, + "clientId": { + "type": "string", + "description": "The contributing client. Absent when the host registers the source\nitself." } }, "required": [ @@ -9842,9 +9886,31 @@ "registration" ] }, + "RootModelSourceContributorRemovedAction": { + "type": "object", + "description": "Withdraws one client's contribution to a model source registration:\nremoves `clientId` from `contributingClientIds`, leaving the field absent\nwhen no contributor remains. A no-op when no registration has `id`, or\n`clientId` doesn't contribute it. It never removes the registration.\n\nA client dispatches this with its own `clientId`. The host dispatches it\nwhen a contributing client leaves.\n\nStability: 1.0 - Early development.", + "properties": { + "type": { + "const": "root/modelSourceContributorRemoved" + }, + "id": { + "type": "string", + "description": "The registration's `id`." + }, + "clientId": { + "type": "string", + "description": "The contributing client to remove." + } + }, + "required": [ + "type", + "id", + "clientId" + ] + }, "RootModelSourceRegistrationRemovedAction": { "type": "object", - "description": "Removes the model source registration with the given `id`. A no-op when\nnone matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source registration with the given `id` for every\ncontributor. A no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRegistrationRemoved" @@ -9861,7 +9927,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's status, credential nonce, and\ncredential resource together. A no-op when no registration has `id`. Other\nfields of the registration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source registration's host-reported fields together:\n`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`credentialId`. A no-op when no registration has `id`. Other fields of the\nregistration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -9881,6 +9947,17 @@ "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." + }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Replaces the registration's `credentialOrigins`. Absent clears it." + }, + "credentialId": { + "type": "string", + "description": "Replaces the registration's `credentialId`. Absent clears it." } }, "required": [ diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 68db28ae3..4d02e8ad4 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -843,7 +843,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier" + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -1076,7 +1076,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -1138,7 +1138,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -1176,7 +1176,16 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + }, + "gracePeriod": { + "type": "integer", + "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "minimum": 0 + }, + "principalPolicy": { + "$ref": "#/$defs/ModelSourcePrincipalPolicy", + "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." } }, "required": [ @@ -1185,7 +1194,7 @@ }, "ModelSourceRegistration": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -1213,19 +1222,22 @@ "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." }, - "clientId": { - "type": "string", - "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." + "contributingClientIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", @@ -1235,6 +1247,17 @@ "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + }, + "credentialId": { + "type": "string", + "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -1278,7 +1301,7 @@ "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -1295,7 +1318,7 @@ "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -6796,13 +6819,21 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourcePrincipalPolicy": { + "enum": [ + "shared", + "isolated" + ], + "type": "string", + "description": "Whether clients acting for different principals share a host's model\nsource registry." + }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", "host" ], "type": "string", - "description": "How long a registered model source lasts once its contributing client leaves." + "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." }, "ModelSourceState": { "oneOf": [ @@ -6821,6 +6852,16 @@ ], "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, + "ModelSourceAuthRequiredReason": { + "enum": [ + "required", + "expired", + "rejected", + "revoked" + ], + "type": "string", + "description": "Why a model source needs a credential. Specific to model sources: the\nshared `AuthRequiredReason` folds rejection and revocation into `expired`." + }, "SessionLifecycle": { "enum": [ "creating", diff --git a/schema/state.schema.json b/schema/state.schema.json index 86fc9b7f2..dcef0b4b8 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -452,7 +452,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier" + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -685,7 +685,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -747,7 +747,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -785,7 +785,16 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`." + "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + }, + "gracePeriod": { + "type": "integer", + "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "minimum": 0 + }, + "principalPolicy": { + "$ref": "#/$defs/ModelSourcePrincipalPolicy", + "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." } }, "required": [ @@ -794,7 +803,7 @@ }, "ModelSourceRegistration": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nIts definition is in a format the agent named by `provider` reads. It never\ncontains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -822,19 +831,22 @@ "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it. MUST NOT contain\na credential." + "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." }, - "clientId": { - "type": "string", - "description": "The contributing client: the client that most recently registered or\nchanged the source. Absent for a source the host registered itself." + "contributingClientIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the contributing client leaves. Absent means `contributingClient`." + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a client replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." }, "credentialNonce": { "type": "string", @@ -844,6 +856,17 @@ "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, + "credentialOrigins": { + "type": "array", + "items": { + "$ref": "#/$defs/URI" + }, + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + }, + "credentialId": { + "type": "string", + "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + }, "_meta": { "type": "object", "additionalProperties": {}, @@ -887,7 +910,7 @@ "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -904,7 +927,7 @@ "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { - "$ref": "#/$defs/AuthRequiredReason", + "$ref": "#/$defs/ModelSourceAuthRequiredReason", "description": "Why a credential is needed." }, "description": { @@ -6957,21 +6980,31 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourcePrincipalPolicy": { + "enum": [ + "shared", + "isolated" + ], + "type": "string", + "description": "Whether clients acting for different principals share a host's model\nsource registry." + }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", "host" ], "type": "string", - "description": "How long a registered model source lasts once its contributing client leaves." + "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." }, - "AuthRequiredReason": { + "ModelSourceAuthRequiredReason": { "enum": [ "required", - "expired" + "expired", + "rejected", + "revoked" ], "type": "string", - "description": "Reason why authentication is required." + "description": "Why a model source needs a credential. Specific to model sources: the\nshared `AuthRequiredReason` folds rejection and revocation into `expired`." }, "SessionStatus": { "type": "integer", diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index d5f428e60..2f90278db 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -773,7 +773,7 @@ const STATE_ENUMS = [ 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', 'AutomationDisableConditionKind', @@ -1679,6 +1679,7 @@ const ACTION_VARIANTS: { type: string; variantName: string; tsInterface: string { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceContributorRemoved', variantName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index c1a582da3..b98fe8c08 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -758,7 +758,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1660,6 +1660,7 @@ const ACTION_VARIANTS: { { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceContributorRemoved', variantName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index aee14c9a9..b16bedda3 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1012,7 +1012,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1660,6 +1660,7 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'root/terminalsChanged', caseName: 'RootTerminalsChanged', tsInterface: 'RootTerminalsChangedAction' }, { type: 'root/configChanged', caseName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', caseName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceContributorRemoved', caseName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, { type: 'root/modelSourceRegistrationRemoved', caseName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'root/modelSourceStateChanged', caseName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'terminal/data', caseName: 'TerminalData', tsInterface: 'TerminalDataAction' }, diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 6f9fc0694..7f93f7918 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -854,7 +854,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1511,8 +1511,6 @@ pub enum ToolInput { function generateStateFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; - lines.push('use crate::notifications::AuthRequiredReason;'); - lines.push(''); lines.push('// ─── Enums ────────────────────────────────────────────────────────────\n'); for (const enumName of STATE_ENUMS) { @@ -1654,6 +1652,7 @@ const ACTION_VARIANTS: { { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction', boxed: true }, + { type: 'root/modelSourceContributorRemoved', variantName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index c34d6e6c3..25fe1bc33 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -735,7 +735,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1570,6 +1570,7 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'root/terminalsChanged', caseName: 'rootTerminalsChanged', tsInterface: 'RootTerminalsChangedAction' }, { type: 'root/configChanged', caseName: 'rootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceRegistrationSet', caseName: 'rootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, + { type: 'root/modelSourceContributorRemoved', caseName: 'rootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, { type: 'root/modelSourceRegistrationRemoved', caseName: 'rootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, { type: 'root/modelSourceStateChanged', caseName: 'rootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'terminal/data', caseName: 'terminalData', tsInterface: 'TerminalDataAction' }, diff --git a/types/action-origin.generated.ts b/types/action-origin.generated.ts index 16d5a810d..95b98ac1d 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -8,6 +8,7 @@ import type { RootTerminalsChangedAction, RootConfigChangedAction, RootModelSourceRegistrationSetAction, + RootModelSourceContributorRemovedAction, RootModelSourceRegistrationRemovedAction, RootModelSourceStateChangedAction, SessionReadyAction, @@ -127,6 +128,7 @@ export type RootAction = | RootTerminalsChangedAction | RootConfigChangedAction | RootModelSourceRegistrationSetAction + | RootModelSourceContributorRemovedAction | RootModelSourceRegistrationRemovedAction | RootModelSourceStateChangedAction ; @@ -135,6 +137,7 @@ export type RootAction = export type ClientRootAction = | RootConfigChangedAction | RootModelSourceRegistrationSetAction + | RootModelSourceContributorRemovedAction | RootModelSourceRegistrationRemovedAction ; @@ -477,6 +480,7 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.RootTerminalsChanged]: false, [ActionType.RootConfigChanged]: true, [ActionType.RootModelSourceRegistrationSet]: true, + [ActionType.RootModelSourceContributorRemoved]: true, [ActionType.RootModelSourceRegistrationRemoved]: true, [ActionType.RootModelSourceStateChanged]: false, [ActionType.SessionReady]: false, diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 7a9aed412..32f9003f2 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -6,7 +6,7 @@ import type { AgentInfo, ModelSourceRegistration, ModelSourceState } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; -import type { ProtectedResourceMetadata } from '../common/state.js'; +import type { ProtectedResourceMetadata, URI } from '../common/state.js'; import { ActionType } from '../common/actions.js'; // ─── Root Actions ──────────────────────────────────────────────────────────── @@ -69,12 +69,26 @@ export interface RootConfigChangedAction { } /** - * Adds a model source registration, or replaces the one with the same `id`. + * Contributes a model source registration for `clientId`. A registration's + * routing is its `provider`, `format`, and `definition`, with definitions + * compared as JSON values: object key order is ignored, and numbers compare + * by numeric value, so `1` equals `1.0`. * - * A client registers a source by dispatching this with its own `clientId`, and - * with no `state`, `credentialNonce`, or `credentialResource`. Replacing a - * registration clears those host-reported fields until the host reports again - * with {@link RootModelSourceStateChangedAction}. + * - **Add.** When no registration has the `id`, appends it, with + * `contributingClientIds` set to `[clientId]`, or absent without a + * `clientId`. + * - **Join.** When one has, and its routing is unchanged, keeps its + * host-reported fields (`state`, `credentialNonce`, `credentialResource`, + * `credentialOrigins`, and `credentialId`), adds `clientId` to + * `contributingClientIds` if it isn't there, and takes the other fields + * from the action. + * - **Replace.** When the routing changed, replaces the registration, with + * `contributingClientIds` set to `[clientId]`, or absent without a + * `clientId`. Its host-reported fields are absent until the host reports + * again with {@link RootModelSourceStateChangedAction}. + * + * A client dispatches this with its own `clientId`, and without + * `contributingClientIds` or any host-reported field. * * @category Root Actions * @stability 1.0 @@ -83,13 +97,40 @@ export interface RootConfigChangedAction { */ export interface RootModelSourceRegistrationSetAction { type: ActionType.RootModelSourceRegistrationSet; - /** The registration to add or replace, matched by `id`. */ + /** The registration to contribute, matched by `id`. */ registration: ModelSourceRegistration; + /** + * The contributing client. Absent when the host registers the source + * itself. + */ + clientId?: string; +} + +/** + * Withdraws one client's contribution to a model source registration: + * removes `clientId` from `contributingClientIds`, leaving the field absent + * when no contributor remains. A no-op when no registration has `id`, or + * `clientId` doesn't contribute it. It never removes the registration. + * + * A client dispatches this with its own `clientId`. The host dispatches it + * when a contributing client leaves. + * + * @category Root Actions + * @stability 1.0 + * @clientDispatchable + * @see {@link /specification/root-channel#model-source-registry | Model source registry} + */ +export interface RootModelSourceContributorRemovedAction { + type: ActionType.RootModelSourceContributorRemoved; + /** The registration's `id`. */ + id: string; + /** The contributing client to remove. */ + clientId: string; } /** - * Removes the model source registration with the given `id`. A no-op when - * none matches. + * Removes the model source registration with the given `id` for every + * contributor. A no-op when none matches. * * @category Root Actions * @stability 1.0 @@ -103,9 +144,10 @@ export interface RootModelSourceRegistrationRemovedAction { } /** - * Updates a model source registration's status, credential nonce, and - * credential resource together. A no-op when no registration has `id`. Other - * fields of the registration are preserved. Only the host dispatches it. + * Updates a model source registration's host-reported fields together: + * `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and + * `credentialId`. A no-op when no registration has `id`. Other fields of the + * registration are preserved. Only the host dispatches it. * * @category Root Actions * @stability 1.0 @@ -124,4 +166,8 @@ export interface RootModelSourceStateChangedAction { * source that needs no credential. */ credentialResource?: ProtectedResourceMetadata; + /** Replaces the registration's `credentialOrigins`. Absent clears it. */ + credentialOrigins?: URI[]; + /** Replaces the registration's `credentialId`. Absent clears it. */ + credentialId?: string; } diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index 7d9efe481..ccbb79a50 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -5,7 +5,7 @@ */ import { ActionType } from '../common/actions.js'; -import type { RootState } from './state.js'; +import type { ModelSourceRegistration, RootState } from './state.js'; import type { RootAction } from '../action-origin.generated.js'; import { softAssertNever } from '../common/reducer-helpers.js'; @@ -38,15 +38,44 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st case ActionType.RootModelSourceRegistrationSet: { const list = state.modelSourceRegistrations ?? []; const idx = list.findIndex(r => r.id === action.registration.id); + const existing = idx < 0 ? undefined : list[idx]; + const joining = existing !== undefined && sameRouting(existing, action.registration); + const updated: ModelSourceRegistration = { ...action.registration }; + copyHostReported(updated, joining ? existing : {}); + const contributors = joining ? [...(existing.contributingClientIds ?? [])] : []; + if (action.clientId !== undefined && !contributors.includes(action.clientId)) { + contributors.push(action.clientId); + } + setContributors(updated, contributors); const next = list.slice(); if (idx < 0) { - next.push(action.registration); + next.push(updated); } else { - next[idx] = action.registration; + next[idx] = updated; } return { ...state, modelSourceRegistrations: next }; } + case ActionType.RootModelSourceContributorRemoved: { + const list = state.modelSourceRegistrations; + if (!list) { + return state; + } + const idx = list.findIndex(r => r.id === action.id); + if (idx < 0) { + return state; + } + const contributors = list[idx].contributingClientIds ?? []; + if (!contributors.includes(action.clientId)) { + return state; + } + const updated = { ...list[idx] }; + setContributors(updated, contributors.filter(id => id !== action.clientId)); + const next = list.slice(); + next[idx] = updated; + return { ...state, modelSourceRegistrations: next }; + } + case ActionType.RootModelSourceRegistrationRemoved: { const list = state.modelSourceRegistrations; if (!list) { @@ -70,13 +99,9 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st if (idx < 0) { return state; } + const updated = { ...list[idx] }; + copyHostReported(updated, action); const next = list.slice(); - const updated = { ...list[idx], state: action.state, credentialNonce: action.credentialNonce }; - if (action.credentialResource) { - updated.credentialResource = action.credentialResource; - } else { - delete updated.credentialResource; - } next[idx] = updated; return { ...state, modelSourceRegistrations: next }; } @@ -86,3 +111,47 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st return state; } } + +// ─── Model source registry helpers ─────────────────────────────────────────── + +const HOST_REPORTED_FIELDS = ['state', 'credentialNonce', 'credentialResource', 'credentialOrigins', 'credentialId'] as const; + +type HostReportedFields = Partial>; + +/** Copies each host-reported field from `from` onto `to`, removing the ones `from` lacks. */ +function copyHostReported(to: ModelSourceRegistration, from: HostReportedFields): void { + for (const field of HOST_REPORTED_FIELDS) { + if (from[field] === undefined) { + delete to[field]; + } else { + Object.assign(to, { [field]: from[field] }); + } + } +} + +/** Sets `contributingClientIds`, leaving it absent when there are none. */ +function setContributors(registration: ModelSourceRegistration, contributors: string[]): void { + if (contributors.length > 0) { + registration.contributingClientIds = contributors; + } else { + delete registration.contributingClientIds; + } +} + +/** Whether two registrations have the same `provider`, `format`, and `definition`. */ +function sameRouting(a: ModelSourceRegistration, b: ModelSourceRegistration): boolean { + return a.provider === b.provider + && a.format === b.format + && JSON.stringify(canonicalJson(a.definition)) === JSON.stringify(canonicalJson(b.definition)); +} + +/** Returns `value` with every object's keys sorted, so equal JSON values serialize identically. */ +function canonicalJson(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(canonicalJson); + } + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)).map(([key, entry]) => [key, canonicalJson(entry)])); + } + return value; +} diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index cdd008ef4..386d75c70 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -12,8 +12,8 @@ import type { Icon, JsonPrimitive, ProtectedResourceMetadata, + URI, } from '../common/state.js'; -import type { AuthRequiredReason } from '../common/notifications.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import type { Customization } from '../channels-session/state.js'; @@ -230,7 +230,9 @@ export interface ModelSourceInfo { /** * Model source identifier, unique within the agent's * {@link AgentInfo.modelSources}. For a registered model source, this is - * the {@link ModelSourceRegistration.id}. + * the {@link ModelSourceRegistration.id}. A source is registered when + * {@link RootState.modelSourceRegistrations} has an entry with this `id` + * whose `provider` is the agent. */ id: string; /** Human-readable name */ @@ -291,6 +293,8 @@ export interface SessionModelInfo { * The source this model comes from. MUST match a {@link ModelSourceInfo.id} * in the agent's {@link AgentInfo.modelSources}. For a model from a * registered model source, this is the {@link ModelSourceRegistration.id}. + * An agent's own sources use it too, so it doesn't by itself mark a + * registered source. */ modelSourceId?: string; } @@ -327,15 +331,52 @@ export interface ModelSourceRegistrationCapability { /** * Definition formats the agent reads, most preferred first. Format names * are defined by agent implementations and SHOULD be namespaced, for - * example `example.com/model-source@1`. + * example `example.com/model-source@1`. AHP doesn't define, standardize, + * or name any format. */ formats: string[]; + /** + * How long, in milliseconds, the host keeps a disconnected client's + * contributions before it treats the client as having left. + * + * @integer + * @minimum 0 + */ + gracePeriod?: number; + /** + * Whether clients acting for different principals share the registry. + * Absent means `shared`. + */ + principalPolicy?: ModelSourcePrincipalPolicy; } /** - * A model source registered on this host by a client, or by the host itself. - * Its definition is in a format the agent named by `provider` reads. It never - * contains a credential. + * Whether clients acting for different principals share a host's model + * source registry. + * + * @category Root State + * @stability 1.0 + * @nonexhaustive + */ +export const enum ModelSourcePrincipalPolicy { + /** + * Every connected client may change, supply credentials for, and select + * every registration. + */ + Shared = 'shared', + /** + * The host verifies principals, and limits changes, credentials, and + * selection of each registration to clients of the principal that + * registered it. Root state still lists every registration to every + * client. + */ + Isolated = 'isolated', +} + +/** + * A model source registered on this host by one or more clients, or by the + * host itself. Its definition is in a format the agent named by `provider` + * reads. It never contains a credential. * * @category Root State * @stability 1.0 @@ -362,20 +403,23 @@ export interface ModelSourceRegistration { format: string; /** * How to reach the source: endpoint, wire format, models, and so on, in - * `format`. Its shape belongs to the agent that reads it. MUST NOT contain - * a credential. + * `format`. Its shape belongs to the agent that reads it, and AHP doesn't + * define it. MUST NOT contain a credential. */ definition: Record; /** - * The contributing client: the client that most recently registered or - * changed the source. Absent for a source the host registered itself. + * The clients that contribute this registration, in the order they joined. + * The reducer maintains it from {@link RootModelSourceRegistrationSetAction} + * and {@link RootModelSourceContributorRemovedAction}. Absent when no + * client contributes it: a source the host registered itself, or a + * `host`-retained one whose contributors have all left. */ - clientId?: string; - /** What happens when the contributing client leaves. Absent means `contributingClient`. */ + contributingClientIds?: string[]; + /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ retention?: ModelSourceRetentionPolicy; /** * Host-reported status, set with {@link RootModelSourceStateChangedAction}. - * Absent until the host reports one, and after a client replaces the + * Absent until the host reports one, and after a `Set` replaces the * registration until the host reports again. */ state?: ModelSourceState; @@ -409,6 +453,25 @@ export interface ModelSourceRegistration { * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ credentialResource?: ProtectedResourceMetadata; + /** + * Every origin the host sends the credential to, such as + * `https://api.example.com`. Present whenever `credentialResource` is. A + * client checks each one against its own copy of the definition before it + * sends a key. Set with `state`. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + credentialOrigins?: URI[]; + /** + * The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of + * the credential the host most recently accepted. While the state is + * `starting` or `ready`, the host holds it. While it's `authRequired`, the + * `reason` says what happened to it. Absent until the host accepts a + * credential. Set with `state`. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + credentialId?: string; /** * Additional implementation-defined metadata for this registration. * MUST NOT contain a credential. @@ -417,16 +480,18 @@ export interface ModelSourceRegistration { } /** - * How long a registered model source lasts once its contributing client leaves. + * How long a registered model source lasts once its last contributing client + * leaves. When the last contributor withdraws instead, the source goes away + * whatever its retention. * * @category Root State * @stability 1.0 * @nonexhaustive */ export const enum ModelSourceRetentionPolicy { - /** Removed when the contributing client leaves, once running turns finish. */ + /** Removed when the last contributing client leaves, once running turns finish. */ ContributingClient = 'contributingClient', - /** Kept until a client removes it or host policy expires it. */ + /** Kept until it's removed, its last contributor withdraws, or host policy expires it. */ Host = 'host', } @@ -473,6 +538,29 @@ export interface ModelSourceReadyState { kind: ModelSourceStatus.Ready; } +/** + * Why a model source needs a credential. Specific to model sources: the + * shared `AuthRequiredReason` folds rejection and revocation into `expired`. + * + * @category Root State + * @stability 1.0 + * @nonexhaustive + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ +export const enum ModelSourceAuthRequiredReason { + /** The host holds no credential yet. */ + Required = 'required', + /** The credential's lifetime or lease lapsed. A client may renew it. */ + Expired = 'expired', + /** + * The endpoint refused the credential. Clients don't send a credential with + * the same {@link ModelSourceRegistration.credentialId} again. + */ + Rejected = 'rejected', + /** A client revoked the credential. Clients don't send one again without a user's action. */ + Revoked = 'revoked', +} + /** * Why a model source needs a credential before it can be ready. Deliberately * carries no credential. The endpoint the credential is for is the @@ -484,7 +572,7 @@ export interface ModelSourceReadyState { */ export interface ModelSourceAuthRequirement { /** Why a credential is needed. */ - reason: AuthRequiredReason; + reason: ModelSourceAuthRequiredReason; /** * Human-readable hint the host writes, for example "The endpoint rejected * the API key." diff --git a/types/common/actions.ts b/types/common/actions.ts index 3769be11e..321302c21 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -14,6 +14,7 @@ import type { RootTerminalsChangedAction, RootConfigChangedAction, RootModelSourceRegistrationSetAction, + RootModelSourceContributorRemovedAction, RootModelSourceRegistrationRemovedAction, RootModelSourceStateChangedAction, } from '../channels-root/actions.js'; @@ -244,6 +245,7 @@ export const enum ActionType { RootTerminalsChanged = 'root/terminalsChanged', RootConfigChanged = 'root/configChanged', RootModelSourceRegistrationSet = 'root/modelSourceRegistrationSet', + RootModelSourceContributorRemoved = 'root/modelSourceContributorRemoved', RootModelSourceRegistrationRemoved = 'root/modelSourceRegistrationRemoved', RootModelSourceStateChanged = 'root/modelSourceStateChanged', TerminalData = 'terminal/data', @@ -308,6 +310,7 @@ export type StateAction = | RootTerminalsChangedAction | RootConfigChangedAction | RootModelSourceRegistrationSetAction + | RootModelSourceContributorRemovedAction | RootModelSourceRegistrationRemovedAction | RootModelSourceStateChangedAction | SessionReadyAction diff --git a/types/common/commands.ts b/types/common/commands.ts index 13ebcd0bc..f55df03eb 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1500,6 +1500,15 @@ export interface ModelSourceAuthenticateTarget { * (-32011). */ credentialNonce: string; + /** + * A client-chosen, non-secret ID for the credential, such as a hash of + * where the client stores the key. The host publishes it as the + * registration's `ModelSourceRegistration.credentialId`, so a client can + * tell whether the host holds its current key. Clients SHOULD include it + * when delivering a credential, and omit it when revoking one. MUST NOT be + * derived from the secret. + */ + credentialId?: string; } /** diff --git a/types/common/state.ts b/types/common/state.ts index 484ebcc5e..831e08d2b 100644 --- a/types/common/state.ts +++ b/types/common/state.ts @@ -439,7 +439,15 @@ export interface UsageInfo { * @preserveUnknownMembers */ export interface ErrorInfo { - /** Error type identifier */ + /** + * Error type identifier. Well-known values: + * + * - `modelSourceUnavailable`: a registered model source the turn uses + * can't serve it, for example because its credential is missing, + * expired, rejected, or revoked, or the source was removed. The error + * part is resumable. See + * [Model source credentials](/specification/authentication#model-source-credentials). + */ errorType: string; /** Human-readable error message */ message: string; diff --git a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json index 0a537fa31..ed4606058 100644 --- a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json +++ b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceRegistrationSet creates the registry when it is absent", + "description": "root/modelSourceRegistrationSet adds a registration to an absent registry, with the dispatching client as its only contributor", "reducer": "root", "initial": { "agents": [] @@ -15,11 +15,18 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] - }, - "clientId": "client-1" - } + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + } + }, + "clientId": "client-1" } ], "expected": { @@ -33,10 +40,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] } diff --git a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json index db1128831..beb866433 100644 --- a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json +++ b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceRegistrationSet appends a registration with a new id", + "description": "root/modelSourceRegistrationSet appends a registration with a new id after the existing ones", "reducer": "root", "initial": { "agents": [], @@ -12,10 +12,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] }, @@ -30,11 +39,18 @@ "definition": { "baseUrl": "https://apib.example.com/v1", "models": [ - "model-b" - ] - }, - "clientId": "client-1" - } + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + } + }, + "clientId": "client-2" } ], "expected": { @@ -48,10 +64,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] }, { "id": "model-source-b", @@ -61,10 +86,19 @@ "definition": { "baseUrl": "https://apib.example.com/v1", "models": [ - "model-b" - ] + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-2" + ] } ] } diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json new file mode 100644 index 000000000..9df981b7a --- /dev/null +++ b/types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json @@ -0,0 +1,57 @@ +{ + "description": "root/modelSourceRegistrationSet without a clientId, as when the host registers a source itself, adds it with no contributingClientIds", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host" + } + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host" + } + ] + } +} diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json deleted file mode 100644 index 37f19b231..000000000 --- a/types/test-cases/reducers/332-root-modelsourceregistrationset-replaces-by-id.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet replaces the registration with the same id in place. A client's replacement carries no state or credentialNonce, so it clears the reported status until the host reports again, and its clientId becomes the contributing client", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - "model-a" - ] - }, - "clientId": "client-1", - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - "model-b" - ] - }, - "clientId": "client-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a (renamed)", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - "model-a" - ] - }, - "clientId": "client-2" - } - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a (renamed)", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - "model-a" - ] - }, - "clientId": "client-2" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - "model-b" - ] - }, - "clientId": "client-1" - } - ] - } -} diff --git a/types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json b/types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json new file mode 100644 index 000000000..f3df6f964 --- /dev/null +++ b/types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json @@ -0,0 +1,152 @@ +{ + "description": "root/modelSourceRegistrationSet with the same provider, format, and definition, compared as JSON values ignoring key order, joins: it adds the client to contributingClientIds, keeps every host-reported field, and takes displayName from the action", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a (window 2)", + "format": "example.com/model-source@1", + "definition": { + "headers": { + "x-tier": "pro", + "x-region": "eu" + }, + "models": [ + { + "maxContextWindow": 128000, + "id": "model-a" + } + ], + "baseUrl": "https://apia.example.com/v1" + } + }, + "clientId": "client-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a (window 2)", + "format": "example.com/model-source@1", + "definition": { + "headers": { + "x-tier": "pro", + "x-region": "eu" + }, + "models": [ + { + "maxContextWindow": 128000, + "id": "model-a" + } + ], + "baseUrl": "https://apia.example.com/v1" + }, + "contributingClientIds": [ + "client-1", + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + } +} diff --git a/types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json b/types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json new file mode 100644 index 000000000..25477491c --- /dev/null +++ b/types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json @@ -0,0 +1,111 @@ +{ + "description": "root/modelSourceRegistrationSet from a client that already contributes keeps it listed once, keeps the host-reported fields, and takes retention from the action", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1", + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host" + }, + "clientId": "client-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1", + "client-2" + ], + "retention": "host", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + } +} diff --git a/types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json b/types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json new file mode 100644 index 000000000..558b2ca74 --- /dev/null +++ b/types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json @@ -0,0 +1,109 @@ +{ + "description": "root/modelSourceRegistrationSet joins a host-retained registration whose contributors have all left, making the client its only contributor without disturbing its status, nonce, or credential fields", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "expired" + }, + "credentialNonce": "nonce-a-2", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host" + }, + "clientId": "client-3" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-3" + ], + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "expired" + }, + "credentialNonce": "nonce-a-2", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + } +} diff --git a/types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json b/types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json new file mode 100644 index 000000000..c66225c00 --- /dev/null +++ b/types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json @@ -0,0 +1,140 @@ +{ + "description": "root/modelSourceRegistrationSet with a changed definition replaces the registration: the dispatching client becomes its only contributor, and the host-reported fields are cleared until the host reports again", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1", + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v2", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + } + }, + "clientId": "client-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v2", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-2" + ] + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + } +} diff --git a/types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json b/types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json new file mode 100644 index 000000000..99a684a6a --- /dev/null +++ b/types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json @@ -0,0 +1,95 @@ +{ + "description": "root/modelSourceRegistrationSet with the same definition but a different format replaces the registration and clears the host-reported fields", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@2", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + } + }, + "clientId": "client-1" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@2", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + } +} diff --git a/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json b/types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json similarity index 56% rename from types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json rename to types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json index dfff67bb5..1b34fa968 100644 --- a/types/test-cases/reducers/333-root-modelsourceregistrationremoved-removes-by-id.json +++ b/types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceRegistrationRemoved removes the registration with the given id", + "description": "root/modelSourceRegistrationRemoved removes the registration with the given id for every contributor", "reducer": "root", "initial": { "agents": [], @@ -12,10 +12,20 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1", + "client-2" + ] }, { "id": "model-source-b", @@ -25,10 +35,19 @@ "definition": { "baseUrl": "https://apib.example.com/v1", "models": [ - "model-b" - ] + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] }, @@ -49,10 +68,19 @@ "definition": { "baseUrl": "https://apib.example.com/v1", "models": [ - "model-b" - ] + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] } diff --git a/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json similarity index 63% rename from types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json rename to types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json index d50f02309..1c2c088d0 100644 --- a/types/test-cases/reducers/334-root-modelsourceregistrationremoved-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json @@ -12,10 +12,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] }, @@ -36,10 +45,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] } diff --git a/types/test-cases/reducers/335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json similarity index 100% rename from types/test-cases/reducers/335-root-modelsourceregistrationremoved-no-op-when-registry-absent.json rename to types/test-cases/reducers/340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json diff --git a/types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json b/types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json new file mode 100644 index 000000000..2f38b09d8 --- /dev/null +++ b/types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json @@ -0,0 +1,90 @@ +{ + "description": "root/modelSourceContributorRemoved removes only that client from contributingClientIds, keeping the other contributors and the host-reported fields", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1", + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "model-source-a", + "clientId": "client-1" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + } +} diff --git a/types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json b/types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json new file mode 100644 index 000000000..ee299afe9 --- /dev/null +++ b/types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json @@ -0,0 +1,86 @@ +{ + "description": "root/modelSourceContributorRemoved for the last contributor leaves contributingClientIds absent and keeps the registration, which the host removes or retains itself", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "model-source-a", + "clientId": "client-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + } +} diff --git a/types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json b/types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json new file mode 100644 index 000000000..5ce6c1b42 --- /dev/null +++ b/types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json @@ -0,0 +1,89 @@ +{ + "description": "root/modelSourceContributorRemoved is a no-op when the client doesn't contribute the registration", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "model-source-a", + "clientId": "client-9" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" + } + ] + } +} diff --git a/types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json b/types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json new file mode 100644 index 000000000..f6c6f6e64 --- /dev/null +++ b/types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json @@ -0,0 +1,61 @@ +{ + "description": "root/modelSourceContributorRemoved is a no-op for a registration with no contributors, such as one the host registered", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "model-source-a", + "clientId": "client-1" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "retention": "host" + } + ] + } +} diff --git a/types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json new file mode 100644 index 000000000..24b3299b4 --- /dev/null +++ b/types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json @@ -0,0 +1,65 @@ +{ + "description": "root/modelSourceContributorRemoved is a no-op when no registration has the id", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + }, + "actions": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "model-source-missing", + "clientId": "client-1" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } + }, + "contributingClientIds": [ + "client-1" + ] + } + ] + } +} diff --git a/types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json new file mode 100644 index 000000000..4c0f8a0c4 --- /dev/null +++ b/types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json @@ -0,0 +1,17 @@ +{ + "description": "root/modelSourceContributorRemoved is a no-op when the registry is absent", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "model-source-a", + "clientId": "client-1" + } + ], + "expected": { + "agents": [] + } +} diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json similarity index 54% rename from types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json rename to types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json index cbef1af00..90915adf9 100644 --- a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json +++ b/types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceStateChanged sets the matching registration's state, credentialNonce, and credentialResource together, preserving its other fields and the registry order", + "description": "root/modelSourceStateChanged sets the matching registration's state, credentialNonce, credentialResource, credentialOrigins, and credentialId together, adding credential fields the registration didn't have, and preserves its other fields and the registry order", "reducer": "root", "initial": { "agents": [], @@ -12,10 +12,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] }, { "id": "model-source-b", @@ -25,10 +34,19 @@ "definition": { "baseUrl": "https://apib.example.com/v1", "models": [ - "model-b" - ] + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "retention": "host", "state": { "kind": "starting" @@ -43,13 +61,18 @@ "id": "model-source-b", "state": { "kind": "authRequired", - "reason": "required" + "reason": "rejected", + "description": "The endpoint rejected the API key." }, "credentialNonce": "nonce-b-2", "credentialResource": { "resource": "https://apib.example.com/v1", "resource_name": "Source b API key" - } + }, + "credentialOrigins": [ + "https://apib.example.com" + ], + "credentialId": "key-b-1" } ], "expected": { @@ -63,10 +86,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] }, { "id": "model-source-b", @@ -76,20 +108,34 @@ "definition": { "baseUrl": "https://apib.example.com/v1", "models": [ - "model-b" - ] + { + "id": "model-b", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "retention": "host", "state": { "kind": "authRequired", - "reason": "required" + "reason": "rejected", + "description": "The endpoint rejected the API key." }, "credentialNonce": "nonce-b-2", "credentialResource": { "resource": "https://apib.example.com/v1", "resource_name": "Source b API key" - } + }, + "credentialOrigins": [ + "https://apib.example.com" + ], + "credentialId": "key-b-1" } ] } diff --git a/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json b/types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json similarity index 60% rename from types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json rename to types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json index 1314040d1..11fb03c81 100644 --- a/types/test-cases/reducers/339-root-modelsourcestatechanged-clears-credential-resource.json +++ b/types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceStateChanged without credentialResource clears the registration's existing one, for a source that turns out to need no credential", + "description": "root/modelSourceStateChanged without credentialResource, credentialOrigins, or credentialId clears the registration's existing ones, for a source that turns out to need no credential", "reducer": "root", "initial": { "agents": [], @@ -12,19 +12,31 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "state": { - "kind": "authRequired", - "reason": "required" + "kind": "starting" }, "credentialNonce": "nonce-a-1", "credentialResource": { "resource": "https://apia.example.com/v1", "resource_name": "Source a API key" - } + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "credentialId": "key-a-1" } ] }, @@ -49,10 +61,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "state": { "kind": "ready" }, diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json similarity index 66% rename from types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json rename to types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json index f9ede0026..99be677af 100644 --- a/types/test-cases/reducers/337-root-modelsourcestatechanged-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json @@ -12,10 +12,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] }, @@ -40,10 +49,19 @@ "definition": { "baseUrl": "https://apia.example.com/v1", "models": [ - "model-a" - ] + { + "id": "model-a", + "maxContextWindow": 128000 + } + ], + "headers": { + "x-region": "eu", + "x-tier": "pro" + } }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] } ] } diff --git a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-when-registry-absent.json b/types/test-cases/reducers/350-root-modelsourcestatechanged-no-op-when-registry-absent.json similarity index 100% rename from types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-when-registry-absent.json rename to types/test-cases/reducers/350-root-modelsourcestatechanged-no-op-when-registry-absent.json diff --git a/types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json b/types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json new file mode 100644 index 000000000..52fab1ba6 --- /dev/null +++ b/types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json @@ -0,0 +1,79 @@ +{ + "description": "root/modelSourceRegistrationSet compares definition numbers by numeric value, so 4096 and 4096.0, 0.5 and 0.50, and 1e3 and 1000 are the same routing: the client joins, and the host-reported fields are kept", + "reducer": "root", + "initial": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-n", + "provider": "copilot", + "displayName": "Numbers", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://apin.example.com/v1", + "maxOutputTokens": 4096, + "temperature": 0.5, + "limits": { + "rpm": 1e3 + } + }, + "contributingClientIds": [ + "client-1" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-n-1", + "credentialId": "key-n-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegistrationSet", + "registration": { + "id": "model-source-n", + "provider": "copilot", + "displayName": "Numbers", + "format": "example.com/model-source@1", + "definition": { + "limits": { + "rpm": 1000 + }, + "temperature": 0.50, + "maxOutputTokens": 4096.0, + "baseUrl": "https://apin.example.com/v1" + } + }, + "clientId": "client-2" + } + ], + "expected": { + "agents": [], + "modelSourceRegistrations": [ + { + "id": "model-source-n", + "provider": "copilot", + "displayName": "Numbers", + "format": "example.com/model-source@1", + "definition": { + "limits": { + "rpm": 1000 + }, + "temperature": 0.50, + "maxOutputTokens": 4096.0, + "baseUrl": "https://apin.example.com/v1" + }, + "contributingClientIds": [ + "client-1", + "client-2" + ], + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-n-1", + "credentialId": "key-n-1" + } + ] + } +} diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 735675977..6cae8b08a 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot carries model source registrations with no reported state and in each lifecycle state, including an http endpoint and a host-registered source without clientId. Sources that take a credential carry a host-reported credentialResource in every state, including ready. The agent advertises the modelSourceRegistration capability, and its catalog lists the ready registration and the authRequired one whose key expired, since models stay listed after a registration has been ready.", + "description": "A root snapshot carries model source registrations with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a source two clients contribute, a host-retained source whose contributors have all left, and a host-registered source. Sources that take a credential carry a host-reported credentialResource and credentialOrigins in every state, and credentialId once the host has accepted a key. The agent advertises the modelSourceRegistration capability with its formats, contributor grace period, and principal policy, and its catalog lists the ready registration and the authRequired one whose key expired, since models stay listed after a registration has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -17,7 +17,9 @@ "formats": [ "example.com/model-source@1", "example.com/model-source@0" - ] + ], + "gracePeriod": 30000, + "principalPolicy": "shared" } }, "modelSources": [ @@ -64,7 +66,9 @@ } ] }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] }, { "id": "source-starting", @@ -81,7 +85,9 @@ } ] }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "state": { "kind": "starting" }, @@ -102,7 +108,10 @@ } ] }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1", + "client-2" + ], "icons": [ { "src": "https://example.com/openrouter.svg" @@ -117,6 +126,11 @@ "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, + "credentialOrigins": [ + "https://api.example.com", + "https://files.example.com" + ], + "credentialId": "keychain-openrouter-1", "_meta": { "example.com/label": "Laptop" } @@ -136,7 +150,9 @@ } ] }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "retention": "contributingClient", "state": { "kind": "authRequired", @@ -153,7 +169,11 @@ "scopes_supported": [ "https://cognitiveservices.azure.com/.default" ] - } + }, + "credentialOrigins": [ + "https://example.openai.azure.com" + ], + "credentialId": "entra-azure-1" }, { "id": "source-local", @@ -163,7 +183,9 @@ "definition": { "baseUrl": "http://localhost:11434/v1" }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "state": { "kind": "authRequired", "reason": "required" @@ -172,7 +194,86 @@ "credentialResource": { "resource": "http://localhost:11434/v1", "resource_name": "Local server key" - } + }, + "credentialOrigins": [ + "http://localhost:11434" + ] + }, + { + "id": "source-rejected", + "provider": "example", + "displayName": "Rejected key", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "contributingClientIds": [ + "client-2" + ], + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialNonce": "nonce-rejected-2", + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "credentialOrigins": [ + "https://api.example.com", + "https://files.example.com" + ], + "credentialId": "keychain-rejected-1" + }, + { + "id": "source-revoked", + "provider": "example", + "displayName": "Revoked key", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "revoked" + }, + "credentialNonce": "nonce-revoked-3", + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "credentialOrigins": [ + "https://api.example.com", + "https://files.example.com" + ], + "credentialId": "keychain-revoked-1" }, { "id": "source-host", @@ -209,7 +310,9 @@ "formats": [ "example.com/model-source@1", "example.com/model-source@0" - ] + ], + "gracePeriod": 30000, + "principalPolicy": "shared" } }, "modelSources": [ @@ -256,7 +359,9 @@ } ] }, - "clientId": "client-1" + "contributingClientIds": [ + "client-1" + ] }, { "id": "source-starting", @@ -273,7 +378,9 @@ } ] }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "state": { "kind": "starting" }, @@ -294,7 +401,10 @@ } ] }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1", + "client-2" + ], "icons": [ { "src": "https://example.com/openrouter.svg" @@ -309,6 +419,11 @@ "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, + "credentialOrigins": [ + "https://api.example.com", + "https://files.example.com" + ], + "credentialId": "keychain-openrouter-1", "_meta": { "example.com/label": "Laptop" } @@ -328,7 +443,9 @@ } ] }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "retention": "contributingClient", "state": { "kind": "authRequired", @@ -345,7 +462,11 @@ "scopes_supported": [ "https://cognitiveservices.azure.com/.default" ] - } + }, + "credentialOrigins": [ + "https://example.openai.azure.com" + ], + "credentialId": "entra-azure-1" }, { "id": "source-local", @@ -355,7 +476,9 @@ "definition": { "baseUrl": "http://localhost:11434/v1" }, - "clientId": "client-1", + "contributingClientIds": [ + "client-1" + ], "state": { "kind": "authRequired", "reason": "required" @@ -364,7 +487,86 @@ "credentialResource": { "resource": "http://localhost:11434/v1", "resource_name": "Local server key" - } + }, + "credentialOrigins": [ + "http://localhost:11434" + ] + }, + { + "id": "source-rejected", + "provider": "example", + "displayName": "Rejected key", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "contributingClientIds": [ + "client-2" + ], + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialNonce": "nonce-rejected-2", + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "credentialOrigins": [ + "https://api.example.com", + "https://files.example.com" + ], + "credentialId": "keychain-rejected-1" + }, + { + "id": "source-revoked", + "provider": "example", + "displayName": "Revoked key", + "format": "example.com/model-source@1", + "definition": { + "baseUrl": "https://api.example.com/v1", + "wireFormat": "openai-chat", + "models": [ + { + "id": "example-model", + "maxContextWindow": 128000 + } + ] + }, + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "revoked" + }, + "credentialNonce": "nonce-revoked-3", + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "credentialOrigins": [ + "https://api.example.com", + "https://files.example.com" + ], + "credentialId": "keychain-revoked-1" }, { "id": "source-host", diff --git a/types/test-cases/round-trips/104-root-model-source-registration-set.json b/types/test-cases/round-trips/104-root-model-source-registration-set.json index 07158eafe..2fcde6cd8 100644 --- a/types/test-cases/round-trips/104-root-model-source-registration-set.json +++ b/types/test-cases/round-trips/104-root-model-source-registration-set.json @@ -1,7 +1,7 @@ { "name": "root-model-source-registration-set", "group": "A", - "description": "A client registers a model source with root/modelSourceRegistrationSet: its own clientId, requested retention, an open definition, and no state.", + "description": "A client contributes a model source with root/modelSourceRegistrationSet: its own clientId on the action, requested retention, an open definition, and no host-reported fields.", "type": "StateAction", "input": { "type": "root/modelSourceRegistrationSet", @@ -20,9 +20,9 @@ "x-title": "Example" } }, - "clientId": "client-1", "retention": "host" - } + }, + "clientId": "client-1" }, "acceptableOutputs": [ { @@ -42,9 +42,9 @@ "x-title": "Example" } }, - "clientId": "client-1", "retention": "host" - } + }, + "clientId": "client-1" } ] } diff --git a/types/test-cases/round-trips/106-authenticate-model-source-target.json b/types/test-cases/round-trips/106-authenticate-model-source-target.json index c6d87a403..58250789e 100644 --- a/types/test-cases/round-trips/106-authenticate-model-source-target.json +++ b/types/test-cases/round-trips/106-authenticate-model-source-target.json @@ -1,7 +1,7 @@ { "name": "authenticate-model-source-target", "group": "A", - "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target that echoes the registration's credentialNonce. An API key carries no expiresIn or scopes.", + "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target that echoes the registration's credentialNonce and names the key with a non-secret credentialId. An API key carries no expiresIn or scopes.", "type": "AuthenticateParams", "input": { "channel": "ahp-root://", @@ -10,7 +10,8 @@ "target": { "kind": "modelSource", "modelSourceId": "source-new", - "credentialNonce": "nonce-openrouter-1" + "credentialNonce": "nonce-openrouter-1", + "credentialId": "keychain-openrouter-1" } }, "acceptableOutputs": [ @@ -21,7 +22,8 @@ "target": { "kind": "modelSource", "modelSourceId": "source-new", - "credentialNonce": "nonce-openrouter-1" + "credentialNonce": "nonce-openrouter-1", + "credentialId": "keychain-openrouter-1" } } ] diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json index a98c189e8..1b28d7573 100644 --- a/types/test-cases/round-trips/107-root-model-source-state-changed.json +++ b/types/test-cases/round-trips/107-root-model-source-state-changed.json @@ -1,21 +1,25 @@ { "name": "root-model-source-state-changed", "group": "A", - "description": "The host reports a registration's status with root/modelSourceStateChanged, issuing a credential nonce and the credentialResource the key is for, here asking for an API key.", + "description": "The host reports with root/modelSourceStateChanged that the endpoint rejected a key, issuing a new credential nonce and naming the rejected key's credentialId, along with the credentialResource and every origin the key is sent to.", "type": "StateAction", "input": { "type": "root/modelSourceStateChanged", "id": "source-new", "state": { "kind": "authRequired", - "reason": "required", - "description": "The endpoint needs an API key." + "reason": "rejected", + "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-openrouter-1", + "credentialNonce": "nonce-openrouter-2", "credentialResource": { "resource": "https://openrouter.ai/api/v1", "resource_name": "OpenRouter API key" - } + }, + "credentialOrigins": [ + "https://openrouter.ai" + ], + "credentialId": "keychain-openrouter-1" }, "acceptableOutputs": [ { @@ -23,14 +27,18 @@ "id": "source-new", "state": { "kind": "authRequired", - "reason": "required", - "description": "The endpoint needs an API key." + "reason": "rejected", + "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-openrouter-1", + "credentialNonce": "nonce-openrouter-2", "credentialResource": { "resource": "https://openrouter.ai/api/v1", "resource_name": "OpenRouter API key" - } + }, + "credentialOrigins": [ + "https://openrouter.ai" + ], + "credentialId": "keychain-openrouter-1" } ] } diff --git a/types/test-cases/round-trips/108-root-model-source-contributor-removed.json b/types/test-cases/round-trips/108-root-model-source-contributor-removed.json new file mode 100644 index 000000000..97f35ada3 --- /dev/null +++ b/types/test-cases/round-trips/108-root-model-source-contributor-removed.json @@ -0,0 +1,18 @@ +{ + "name": "root-model-source-contributor-removed", + "group": "A", + "description": "A client withdraws its own contribution to a model source with root/modelSourceContributorRemoved.", + "type": "StateAction", + "input": { + "type": "root/modelSourceContributorRemoved", + "id": "source-new", + "clientId": "client-1" + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceContributorRemoved", + "id": "source-new", + "clientId": "client-1" + } + ] +} diff --git a/types/version/registry.ts b/types/version/registry.ts index 15179c526..4a9435826 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -187,6 +187,7 @@ export const ACTION_INTRODUCED_IN: { readonly [K in StateAction['type']]: string [ActionType.RootTerminalsChanged]: '0.1.0', [ActionType.RootConfigChanged]: '0.1.0', [ActionType.RootModelSourceRegistrationSet]: '1.2.0', + [ActionType.RootModelSourceContributorRemoved]: '1.2.0', [ActionType.RootModelSourceRegistrationRemoved]: '1.2.0', [ActionType.RootModelSourceStateChanged]: '1.2.0', [ActionType.TerminalData]: '0.1.0', From a03a5a1bcbfcc85c9b573a9b46906cc95cd0e263 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 14:02:12 -0500 Subject: [PATCH 09/17] models: rename to ModelSource and keep definitions out of state Implement #622's response to review: - Rename `RootState.modelSourceRegistrations` to `modelSources`, `ModelSourceRegistration` to `ModelSource`, and the actions to `root/modelSourceSet` and `root/modelSourceRemoved`. - Drop client IDs from the registry: no `contributingClientIds`, no `clientId` on `Set`, and no `root/modelSourceContributorRemoved`. The host tracks contributing clients from `ActionEnvelope.origin`. - `root/modelSourceSet` carries `{ modelSource, definition }`, and the reducer stores the source without the definition. `ModelSource` gains a required `nonce`. Reducers compare provider, format, and nonce to tell a re-registration from an update, replacing the JSON comparison of definitions in TypeScript and every client. - Replace `credentialId` with `authenticate`'s existing `accountId`, published as `ModelSource.accountId`. - Document recognized `format` values (`openaiCompatible`, `anthropic`, `azureOpenai`, `gemini`) and built-in sources. - Regenerate clients, replace the reducer fixtures with one per branch, and update the round-trip fixtures, specs, naming dictionary, guide, and changelog fragments. Refs #619 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../protocol-naming.instructions.md | 4 +- .../Generated/Actions.generated.cs | 107 +++----- .../Generated/Commands.generated.cs | 25 +- .../JsonSerializerContext.generated.cs | 7 +- .../Generated/State.generated.cs | 116 ++++---- .../Generated/ActionMetadata.generated.cs | 7 +- .../dotnet/src/AgentHostProtocol/Reducers.cs | 130 ++------- clients/go/ahp/reducers.go | 89 ++----- clients/go/ahptypes/actions.generated.go | 112 +++----- clients/go/ahptypes/commands.generated.go | 21 +- clients/go/ahptypes/state.generated.go | 126 ++++----- .../microsoft/agenthostprotocol/Reducers.kt | 73 ++--- .../generated/Actions.generated.kt | 115 +++----- .../generated/Commands.generated.kt | 23 +- .../generated/State.generated.kt | 122 ++++----- clients/rust/crates/ahp-types/src/actions.rs | 131 ++++----- clients/rust/crates/ahp-types/src/commands.rs | 22 +- clients/rust/crates/ahp-types/src/state.rs | 117 ++++---- .../rust/crates/ahp/examples/reducers_demo.rs | 2 +- clients/rust/crates/ahp/src/hosts/runtime.rs | 2 +- clients/rust/crates/ahp/src/lib.rs | 2 +- .../crates/ahp/src/multi_host_state_mirror.rs | 2 +- clients/rust/crates/ahp/src/reducers.rs | 129 +++------ .../ahp/tests/multi_host_state_mirror.rs | 2 +- .../Generated/ActionOrigin.generated.swift | 10 +- .../Generated/Actions.generated.swift | 145 ++++------ .../Generated/Commands.generated.swift | 23 +- .../Generated/State.generated.swift | 145 +++++----- .../AgentHostProtocol/NativeReducer.swift | 78 ++---- .../Sources/AgentHostProtocol/Reducers.swift | 13 +- ...61123-model-source-registry-migration.json | 2 +- .../20261123-model-source-registry.json | 2 +- docs/guide/actions.md | 9 +- docs/guide/state-model.md | 2 +- docs/specification/authentication.md | 48 ++-- docs/specification/root-channel.md | 85 +++--- schema/actions.schema.json | 131 ++++----- schema/commands.schema.json | 145 ++++------ schema/errors.schema.json | 145 ++++------ schema/notifications.schema.json | 58 ++-- schema/state.schema.json | 58 ++-- scripts/generate-csharp.ts | 7 +- scripts/generate-go.ts | 7 +- scripts/generate-kotlin.ts | 7 +- scripts/generate-rust.ts | 9 +- scripts/generate-swift.ts | 7 +- types/action-origin.generated.ts | 20 +- types/channels-root/actions.ts | 99 +++---- types/channels-root/reducer.ts | 88 ++---- types/channels-root/state.ts | 118 +++++---- types/common/actions.ts | 15 +- types/common/commands.ts | 23 +- ...gistrationset-adds-to-absent-registry.json | 59 ----- ...odelsourceset-adds-to-absent-registry.json | 37 +++ ...lsourceregistrationset-appends-new-id.json | 105 -------- ...e-register-keeps-host-reported-fields.json | 102 +++++++ ...t-host-registers-without-contributors.json | 57 ---- ...et-update-clears-host-reported-fields.json | 72 +++++ ...gistrationset-joins-unchanged-routing.json | 152 ----------- ...root-modelsourceremoved-removes-by-id.json | 53 ++++ ...t-existing-contributor-not-duplicated.json | 111 -------- ...delsourceremoved-no-op-for-unknown-id.json | 34 +++ ...ins-registration-without-contributors.json | 109 -------- ...ceremoved-no-op-when-registry-absent.json} | 4 +- ...rationset-replaces-changed-definition.json | 140 ---------- ...echanged-updates-host-reported-fields.json | 82 ++++++ ...gistrationset-replaces-changed-format.json | 95 ------- ...statechanged-clears-credential-fields.json | 54 ++++ ...urceregistrationremoved-removes-by-id.json | 87 ------ ...urcestatechanged-no-op-for-unknown-id.json | 38 +++ ...istrationremoved-no-op-for-unknown-id.json | 64 ----- ...techanged-no-op-when-registry-absent.json} | 0 ...ibutorremoved-removes-one-contributor.json | 90 ------- ...d-last-contributor-keeps-registration.json | 86 ------ ...butorremoved-no-op-for-unknown-client.json | 89 ------- ...torremoved-no-op-without-contributors.json | 61 ----- ...ntributorremoved-no-op-for-unknown-id.json | 65 ----- ...torremoved-no-op-when-registry-absent.json | 17 -- ...echanged-updates-host-reported-fields.json | 142 ---------- ...statechanged-clears-credential-fields.json | 84 ------ ...urcestatechanged-no-op-for-unknown-id.json | 68 ----- ...et-joins-numerically-equal-definition.json | 79 ------ .../103-model-source-registry-snapshot.json | 250 ++++-------------- ...04-root-model-source-registration-set.json | 50 ---- .../104-root-model-source-set.json | 50 ++++ ...oot-model-source-registration-removed.json | 16 -- .../105-root-model-source-removed.json | 16 ++ .../106-authenticate-model-source-target.json | 10 +- .../107-root-model-source-state-changed.json | 6 +- ...root-model-source-contributor-removed.json | 18 -- types/version/registry.ts | 5 +- 91 files changed, 1775 insertions(+), 3867 deletions(-) delete mode 100644 types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json create mode 100644 types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json delete mode 100644 types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json create mode 100644 types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json delete mode 100644 types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json create mode 100644 types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json delete mode 100644 types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json create mode 100644 types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json delete mode 100644 types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json create mode 100644 types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json delete mode 100644 types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json rename types/test-cases/reducers/{340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json => 335-root-modelsourceremoved-no-op-when-registry-absent.json} (51%) delete mode 100644 types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json create mode 100644 types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json delete mode 100644 types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json create mode 100644 types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json delete mode 100644 types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json create mode 100644 types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json delete mode 100644 types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json rename types/test-cases/reducers/{350-root-modelsourcestatechanged-no-op-when-registry-absent.json => 339-root-modelsourcestatechanged-no-op-when-registry-absent.json} (100%) delete mode 100644 types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json delete mode 100644 types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json delete mode 100644 types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json delete mode 100644 types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json delete mode 100644 types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json delete mode 100644 types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json delete mode 100644 types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json delete mode 100644 types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json delete mode 100644 types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json delete mode 100644 types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json delete mode 100644 types/test-cases/round-trips/104-root-model-source-registration-set.json create mode 100644 types/test-cases/round-trips/104-root-model-source-set.json delete mode 100644 types/test-cases/round-trips/105-root-model-source-registration-removed.json create mode 100644 types/test-cases/round-trips/105-root-model-source-removed.json delete mode 100644 types/test-cases/round-trips/108-root-model-source-contributor-removed.json diff --git a/.github/instructions/protocol-naming.instructions.md b/.github/instructions/protocol-naming.instructions.md index 683972e53..2cc90c774 100644 --- a/.github/instructions/protocol-naming.instructions.md +++ b/.github/instructions/protocol-naming.instructions.md @@ -39,8 +39,8 @@ but don't use them as precedent. | **agent provider** (`provider`) | The ID of the agent backing a session or chat (`AgentInfo.provider`, `SessionState.provider`, `ChatState.provider`). Always write "agent provider" in prose. | The **custom agent** (`Message.agent`, `AgentSelection`): a configured persona within an agent provider. The **model vendor** (`SessionModelInfo.vendor`): the company that serves a model. The **model source** (`modelSourceId`): where a model comes from. | | **model** | A model offered by an agent provider (`SessionModelInfo`). It is selected per message (`Message.model`). | | | **model source** (`modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `AgentInfo.modelSources` (`ModelSourceInfo`). Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | -| **registration** (`ModelSourceRegistration`) | A model source a client or the host added to the host's registry in `RootState.modelSourceRegistrations`, with its definition and status. A ready registration joins its agent's catalog as a model source. | The **model source** it becomes in the catalog. | -| **contributing client** | A client that added a client-contributed entry, named by its `clientId`. A model source registration can have several, listed in `contributingClientIds`; each adds and withdraws only its own contribution. | The **action origin**'s `clientId`, which names the client that dispatched one action. | +| **registration** (`ModelSource`) | A model source a client or the host added to the host's registry in `RootState.modelSources`, with its status. A ready registration joins its agent's catalog as a model source, and a registered source is also called a registration. | The **model source** it becomes in the catalog (`ModelSourceInfo`). | +| **contributing client** | A client that added a client-contributed entry. For a model source, it's a client that registered it and hasn't left; the host tracks these itself, from `ActionEnvelope.origin`, and they aren't in state. | The **action origin**'s `clientId`, which names the client that dispatched one action. | | **principal** | The user or account a host has verified a client acts for. AHP doesn't define how a host verifies one (`ModelSourcePrincipalPolicy`). | A **client** (`clientId`), which identifies a connection's client and isn't verified. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | | **pending message** | Input waiting to be consumed. Its `kind` is **steering** (injected into the active turn) or **queued** (starts a later turn). Both kinds live in `ChatState.queuedMessages`. | | diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index feeca37a0..e579eb4e0 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -199,11 +199,9 @@ public ActionType(string value) public static readonly ActionType RootConfigChanged = new ActionType("root/configChanged"); - public static readonly ActionType RootModelSourceRegistrationSet = new ActionType("root/modelSourceRegistrationSet"); + public static readonly ActionType RootModelSourceSet = new ActionType("root/modelSourceSet"); - public static readonly ActionType RootModelSourceContributorRemoved = new ActionType("root/modelSourceContributorRemoved"); - - public static readonly ActionType RootModelSourceRegistrationRemoved = new ActionType("root/modelSourceRegistrationRemoved"); + public static readonly ActionType RootModelSourceRemoved = new ActionType("root/modelSourceRemoved"); public static readonly ActionType RootModelSourceStateChanged = new ActionType("root/modelSourceStateChanged"); @@ -348,104 +346,78 @@ public sealed record RootConfigChangedAction public bool? Replace { get; init; } } -/// Contributes a model source registration for `clientId`. A registration's -/// routing is its `provider`, `format`, and `definition`, with definitions -/// compared as JSON values: object key order is ignored, and numbers compare -/// by numeric value, so `1` equals `1.0`. -/// -/// - **Add.** When no registration has the `id`, appends it, with -/// `contributingClientIds` set to `[clientId]`, or absent without a -/// `clientId`. -/// - **Join.** When one has, and its routing is unchanged, keeps its -/// host-reported fields (`state`, `credentialNonce`, `credentialResource`, -/// `credentialOrigins`, and `credentialId`), adds `clientId` to -/// `contributingClientIds` if it isn't there, and takes the other fields -/// from the action. -/// - **Replace.** When the routing changed, replaces the registration, with -/// `contributingClientIds` set to `[clientId]`, or absent without a -/// `clientId`. Its host-reported fields are absent until the host reports -/// again with {@link RootModelSourceStateChangedAction}. -/// -/// A client dispatches this with its own `clientId`, and without -/// `contributingClientIds` or any host-reported field. +/// Adds a model source, or updates the one with the same `id`. The reducer +/// stores `modelSource` without the definition: /// -/// Stability: 1.0 - Early development. -public sealed record RootModelSourceRegistrationSetAction -{ - public ActionType Type { get; init; } = ActionType.RootModelSourceRegistrationSet; - - /// The registration to contribute, matched by `id`. - public required ModelSourceRegistration Registration { get; init; } - - /// The contributing client. Absent when the host registers the source - /// itself. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? ClientId { get; init; } -} - -/// Withdraws one client's contribution to a model source registration: -/// removes `clientId` from `contributingClientIds`, leaving the field absent -/// when no contributor remains. A no-op when no registration has `id`, or -/// `clientId` doesn't contribute it. It never removes the registration. +/// - **Add.** When no model source has the `id`, appends `modelSource`. +/// - **Re-register.** When one has, with the same `provider`, `format`, and +/// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, +/// `credentialResource`, `credentialOrigins`, and `accountId`) and takes +/// the other fields from the action. +/// - **Update.** When any of the three differs, replaces the source. Its +/// host-reported fields are absent until the host reports again with +/// {@link RootModelSourceStateChangedAction}. /// -/// A client dispatches this with its own `clientId`. The host dispatches it -/// when a contributing client leaves. +/// A client dispatches this without any host-reported field. The host learns +/// which client registered the source from the envelope's `origin`. /// /// Stability: 1.0 - Early development. -public sealed record RootModelSourceContributorRemovedAction +public sealed record RootModelSourceSetAction { - public ActionType Type { get; init; } = ActionType.RootModelSourceContributorRemoved; + public ActionType Type { get; init; } = ActionType.RootModelSourceSet; - /// The registration's `id`. - public required string Id { get; init; } + /// The model source to add or update, matched by `id`, without host-reported fields. + public required ModelSource ModelSource { get; init; } - /// The contributing client to remove. - public required string ClientId { get; init; } + /// How to reach the source, in `modelSource.format`: endpoint, wire format, + /// models, and so on. The host hands it to the agent, and the reducer + /// doesn't store it. MUST NOT contain a credential. + public required Dictionary Definition { get; init; } } -/// Removes the model source registration with the given `id` for every -/// contributor. A no-op when none matches. +/// Removes the model source with the given `id`, for every client. A no-op +/// when none matches. /// /// Stability: 1.0 - Early development. -public sealed record RootModelSourceRegistrationRemovedAction +public sealed record RootModelSourceRemovedAction { - public ActionType Type { get; init; } = ActionType.RootModelSourceRegistrationRemoved; + public ActionType Type { get; init; } = ActionType.RootModelSourceRemoved; - /// The registration's `id`. + /// The model source's `id`. public required string Id { get; init; } } -/// Updates a model source registration's host-reported fields together: -/// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and -/// `credentialId`. A no-op when no registration has `id`. Other fields of the -/// registration are preserved. Only the host dispatches it. +/// Updates a model source's host-reported fields together: `state`, +/// `credentialNonce`, `credentialResource`, `credentialOrigins`, and +/// `accountId`. A no-op when no model source has `id`. Other fields of the +/// source are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceStateChangedAction { public ActionType Type { get; init; } = ActionType.RootModelSourceStateChanged; - /// The registration's `id`. + /// The model source's `id`. public required string Id { get; init; } /// The new status. public required ModelSourceState State { get; init; } - /// The registration's current credential nonce. + /// The model source's current credential nonce. public required string CredentialNonce { get; init; } - /// Replaces the registration's `credentialResource`. Absent clears it, for a + /// Replaces the source's `credentialResource`. Absent clears it, for a /// source that needs no credential. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } - /// Replaces the registration's `credentialOrigins`. Absent clears it. + /// Replaces the source's `credentialOrigins`. Absent clears it. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? CredentialOrigins { get; init; } - /// Replaces the registration's `credentialId`. Absent clears it. + /// Replaces the source's `accountId`. Absent clears it. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? CredentialId { get; init; } + public string? AccountId { get; init; } } /// Session backend initialized successfully. @@ -2966,9 +2938,8 @@ public StateActionConverter() ["root/agentsChanged"] = typeof(RootAgentsChangedAction), ["root/activeSessionsChanged"] = typeof(RootActiveSessionsChangedAction), ["root/configChanged"] = typeof(RootConfigChangedAction), - ["root/modelSourceRegistrationSet"] = typeof(RootModelSourceRegistrationSetAction), - ["root/modelSourceContributorRemoved"] = typeof(RootModelSourceContributorRemovedAction), - ["root/modelSourceRegistrationRemoved"] = typeof(RootModelSourceRegistrationRemovedAction), + ["root/modelSourceSet"] = typeof(RootModelSourceSetAction), + ["root/modelSourceRemoved"] = typeof(RootModelSourceRemovedAction), ["root/modelSourceStateChanged"] = typeof(RootModelSourceStateChangedAction), ["session/ready"] = typeof(SessionReadyAction), ["session/creationFailed"] = typeof(SessionCreationFailedAction), diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 2f2d44139..af9401be7 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1892,22 +1892,13 @@ public sealed record ModelSourceAuthenticateTarget { public AuthenticateTargetKind Kind { get; init; } = AuthenticateTargetKind.ModelSource; - /// The registration's `ModelSourceRegistration.id`. + /// The registration's `ModelSource.id`. public required string ModelSourceId { get; init; } - /// The registration's current `ModelSourceRegistration.credentialNonce`, as + /// The registration's current `ModelSource.credentialNonce`, as /// published in root state. The host rejects a stale one with `Conflict` /// (-32011). public required string CredentialNonce { get; init; } - - /// A client-chosen, non-secret ID for the credential, such as a hash of - /// where the client stores the key. The host publishes it as the - /// registration's `ModelSourceRegistration.credentialId`, so a client can - /// tell whether the host holds its current key. Clients SHOULD include it - /// when delivering a credential, and omit it when revoking one. MUST NOT be - /// derived from the secret. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? CredentialId { get; init; } } /// Pushes a credential for a protected resource. The `resource` field MUST @@ -1916,7 +1907,7 @@ public sealed record ModelSourceAuthenticateTarget /// or discovered dynamically from a live `McpServerAuthRequiredState.resource` /// or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the /// corresponding MCP server or tool call actually challenges for auth), or -/// from a registered model source's `ModelSourceRegistration.credentialResource`. +/// from a registered model source's `ModelSource.credentialResource`. /// Servers MUST accept any `resource` value they have themselves advertised /// through one of these mechanisms, subject to the `target` rules. A /// `modelSource` target takes only the registration's current @@ -1941,7 +1932,7 @@ public sealed record AuthenticateParams /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - /// or `ModelSourceRegistration.credentialResource`. + /// or `ModelSource.credentialResource`. public required string Resource { get; init; } /// Bearer token obtained from the resource's authorization server, or an @@ -2001,7 +1992,13 @@ public sealed record AuthenticateParams /// Optional identifier for the client's selected account, sent alongside the token. /// Hosts can compare `accountId` values to detect when the underlying account has changed. /// Hosts MUST treat `accountId` as an opaque string. - /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. + /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. + /// + /// With a `modelSource` target, clients SHOULD include it when delivering a + /// credential and omit it when revoking one, and the host publishes it as + /// the source's `ModelSource.accountId`. It MUST NOT be derived from the + /// secret. For an API key with no account of its own, a client uses an ID + /// that changes whenever the user replaces the key. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? AccountId { get; init; } } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 25e0fea3e..53449a991 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -298,6 +298,7 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(MessageOrigin))] [JsonSerializable(typeof(MessageResourceAttachment))] [JsonSerializable(typeof(ModelSelection))] +[JsonSerializable(typeof(ModelSource))] [JsonSerializable(typeof(ModelSourceAuthenticateTarget))] [JsonSerializable(typeof(ModelSourceAuthRequiredReason))] [JsonSerializable(typeof(ModelSourceAuthRequiredState))] @@ -306,7 +307,6 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ModelSourceInfo))] [JsonSerializable(typeof(ModelSourcePrincipalPolicy))] [JsonSerializable(typeof(ModelSourceReadyState))] -[JsonSerializable(typeof(ModelSourceRegistration))] [JsonSerializable(typeof(ModelSourceRegistrationCapability))] [JsonSerializable(typeof(ModelSourceRetentionPolicy))] [JsonSerializable(typeof(ModelSourceStartingState))] @@ -372,9 +372,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RootAgentsChangedAction))] [JsonSerializable(typeof(RootConfigChangedAction))] [JsonSerializable(typeof(RootConfigState))] -[JsonSerializable(typeof(RootModelSourceContributorRemovedAction))] -[JsonSerializable(typeof(RootModelSourceRegistrationRemovedAction))] -[JsonSerializable(typeof(RootModelSourceRegistrationSetAction))] +[JsonSerializable(typeof(RootModelSourceRemovedAction))] +[JsonSerializable(typeof(RootModelSourceSetAction))] [JsonSerializable(typeof(RootModelSourceStateChangedAction))] [JsonSerializable(typeof(RootState))] [JsonSerializable(typeof(RootTerminalsChangedAction))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 0148843db..6299602d5 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1470,8 +1470,7 @@ public override void Write(Utf8JsonWriter writer, ModelSourceStatus value, JsonS } /// How long a registered model source lasts once its last contributing client -/// leaves. When the last contributor withdraws instead, the source goes away -/// whatever its retention. +/// leaves. /// /// Stability: 1.0 - Early development. [JsonConverter(typeof(ModelSourceRetentionPolicyConverter))] @@ -1492,7 +1491,7 @@ public ModelSourceRetentionPolicy(string value) /// Removed when the last contributing client leaves, once running turns finish. public static readonly ModelSourceRetentionPolicy ContributingClient = new ModelSourceRetentionPolicy("contributingClient"); - /// Kept until it's removed, its last contributor withdraws, or host policy expires it. + /// Kept until a client removes it, or host policy expires it. public static readonly ModelSourceRetentionPolicy Host = new ModelSourceRetentionPolicy("host"); /// @@ -1552,7 +1551,7 @@ public ModelSourceAuthRequiredReason(string value) public static readonly ModelSourceAuthRequiredReason Expired = new ModelSourceAuthRequiredReason("expired"); /// The endpoint refused the credential. Clients don't send a credential with - /// the same {@link ModelSourceRegistration.credentialId} again. + /// the same {@link ModelSource.accountId} again. public static readonly ModelSourceAuthRequiredReason Rejected = new ModelSourceAuthRequiredReason("rejected"); /// A client revoked the credential. Clients don't send one again without a user's action. @@ -1609,12 +1608,12 @@ public ModelSourcePrincipalPolicy(string value) public string Value => _value ?? string.Empty; /// Every connected client may change, supply credentials for, and select - /// every registration. + /// every model source. public static readonly ModelSourcePrincipalPolicy Shared = new ModelSourcePrincipalPolicy("shared"); /// The host verifies principals, and limits changes, credentials, and - /// selection of each registration to clients of the principal that - /// registered it. Root state still lists every registration to every + /// selection of each model source to clients of the principal that + /// registered it. Root state still lists every model source to every /// client. public static readonly ModelSourcePrincipalPolicy Isolated = new ModelSourcePrincipalPolicy("isolated"); @@ -2298,11 +2297,13 @@ public sealed class RootState [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public RootConfigState? Config { get; set; } - /// Model sources registered on this host, keyed by `id`. + /// Model sources registered on this host, keyed by `id`. When one is + /// ready, it also appears in its agent's {@link AgentInfo.modelSources} + /// catalog. /// /// Stability: 1.0 - Early development. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public List? ModelSourceRegistrations { get; set; } + public List? ModelSources { get; set; } /// Additional implementation-defined metadata about the agent host itself. /// @@ -2474,14 +2475,13 @@ public sealed record MultipleWorkingDirectoriesCapability /// Stability: 1.0 - Early development. public sealed record ModelSourceRegistrationCapability { - /// Definition formats the agent reads, most preferred first. Format names - /// are defined by agent implementations and SHOULD be namespaced, for - /// example `example.com/model-source@1`. AHP doesn't define, standardize, - /// or name any format. + /// Definition formats the agent reads, most preferred first: recognized + /// values of {@link ModelSource.format}, or namespaced names for formats + /// the agent defines itself. public required List Formats { get; init; } - /// How long, in milliseconds, the host keeps a disconnected client's - /// contributions before it treats the client as having left. + /// How long, in milliseconds, the host keeps counting a disconnected client + /// as a contributing client before it treats the client as having left. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public long? GracePeriod { get; init; } @@ -2495,12 +2495,13 @@ public sealed record ModelSourceRegistrationCapability public Dictionary? Extra { get; set; } } -/// A model source registered on this host by one or more clients, or by the -/// host itself. Its definition is in a format the agent named by `provider` -/// reads. It never contains a credential. +/// A model source registered on this host by a client, or by the host itself. +/// The definition that tells the agent named by `provider` how to reach it +/// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing +/// here is a credential. /// /// Stability: 1.0 - Early development. -public sealed record ModelSourceRegistration +public sealed record ModelSource { /// Host-unique ID, chosen by whoever registers the source. Also the /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the @@ -2517,40 +2518,43 @@ public sealed record ModelSourceRegistration [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? Icons { get; init; } - /// Definition format, one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. + /// The definition's format, one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. Recognized values + /// include: + /// + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as + /// OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + /// - `'azureOpenai'`: an Azure OpenAI deployment. + /// - `'gemini'`: Google's Gemini API. + /// + /// AHP doesn't define what a definition contains, even for these. Agents + /// MAY read other formats, named with a namespace such as + /// `example.com/model-source@1` so they don't collide. public required string Format { get; init; } - /// How to reach the source: endpoint, wire format, models, and so on, in - /// `format`. Its shape belongs to the agent that reads it, and AHP doesn't - /// define it. MUST NOT contain a credential. - public required Dictionary Definition { get; init; } - - /// The clients that contribute this registration, in the order they joined. - /// The reducer maintains it from {@link RootModelSourceRegistrationSetAction} - /// and {@link RootModelSourceContributorRemovedAction}. Absent when no - /// client contributes it: a source the host registered itself, or a - /// `host`-retained one whose contributors have all left. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public List? ContributingClientIds { get; init; } + /// Opaque version token for the definition, such as a hash of it, chosen by + /// whoever registers the source. A client compares it with its own copy + /// instead of the definition, and the reducer compares it to tell an update + /// from a re-registration of the same definition. + public required string Nonce { get; init; } /// What happens when the last contributing client leaves. Absent means `contributingClient`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceRetentionPolicy? Retention { get; init; } /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after a `Set` replaces the - /// registration until the host reports again. + /// Absent until the host reports one, and after an update replaces the + /// definition until the host reports again. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceState? State { get; init; } /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential, and that tags every agent operation on the registration. - /// The host issues a new one when the registration is added, when its - /// `provider`, `format`, or `definition` changes, and whenever the - /// credential is installed or dropped. It never reuses one for the same - /// `id`. Set with `state`. + /// the credential, and that tags every agent operation on the source. The + /// host issues a new one when the source is added or updated, and whenever + /// the credential is installed or dropped. It never reuses one for the + /// same `id`. Set with `state`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? CredentialNonce { get; init; } @@ -2571,21 +2575,21 @@ public sealed record ModelSourceRegistration public ProtectedResourceMetadata? CredentialResource { get; init; } /// Every origin the host sends the credential to, such as - /// `https://api.example.com`. Present whenever `credentialResource` is. A - /// client checks each one against its own copy of the definition before it - /// sends a key. Set with `state`. + /// `https://api.example.com`, derived from the definition it holds. Present + /// whenever `credentialResource` is. A client checks each one against its + /// own copy of the definition before it sends a key. Set with `state`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? CredentialOrigins { get; init; } - /// The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of - /// the credential the host most recently accepted. While the state is - /// `starting` or `ready`, the host holds it. While it's `authRequired`, the - /// `reason` says what happened to it. Absent until the host accepts a - /// credential. Set with `state`. + /// The {@link AuthenticateParams.accountId} the client sent with the + /// credential the host most recently accepted. While the state is + /// `starting` or `ready`, the host holds that credential. While it's + /// `authRequired`, the `reason` says what happened to it. Absent until the + /// host accepts a credential sent with an `accountId`. Set with `state`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? CredentialId { get; init; } + public string? AccountId { get; init; } - /// Additional implementation-defined metadata for this registration. + /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. [JsonPropertyName("_meta")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2610,7 +2614,7 @@ public sealed record ModelSourceStartingState } /// The source is usable, and its models are in the catalog of the agent named -/// by the registration's `provider`. They stay listed through later `starting` +/// by the model source's `provider`. They stay listed through later `starting` /// and `authRequired` states. /// /// Stability: 1.0 - Early development. @@ -2625,7 +2629,7 @@ public sealed record ModelSourceReadyState /// Why a model source needs a credential before it can be ready. Deliberately /// carries no credential. The endpoint the credential is for is the -/// registration's {@link ModelSourceRegistration.credentialResource}. +/// model source's {@link ModelSource.credentialResource}. /// /// Stability: 1.0 - Early development. public sealed record ModelSourceAuthRequirement @@ -2644,7 +2648,7 @@ public sealed record ModelSourceAuthRequirement } /// The source needs a credential before it can be used. A client answers with -/// `authenticate`, the registration's `credentialResource.resource`, and a +/// `authenticate`, the model source's `credentialResource.resource`, and a /// {@link ModelSourceAuthenticateTarget}. /// /// Stability: 1.0 - Early development. @@ -2686,8 +2690,8 @@ public sealed record ModelSourceInfo { /// Model source identifier, unique within the agent's /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSourceRegistration.id}. A source is registered when - /// {@link RootState.modelSourceRegistrations} has an entry with this `id` + /// the {@link ModelSource.id}. A source is registered when + /// {@link RootState.modelSources} has an entry with this `id` /// whose `provider` is the agent. public required string Id { get; init; } @@ -2755,7 +2759,7 @@ public sealed record SessionModelInfo /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// registered model source, this is the {@link ModelSource.id}. /// An agent's own sources use it too, so it doesn't by itself mark a /// registered source. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs index 8fedcd680..b8f9555e6 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -211,13 +211,10 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootConfigChangedAction value: actionType = value.Type; return true; - case RootModelSourceContributorRemovedAction value: + case RootModelSourceRemovedAction value: actionType = value.Type; return true; - case RootModelSourceRegistrationRemovedAction value: - actionType = value.Type; - return true; - case RootModelSourceRegistrationSetAction value: + case RootModelSourceSetAction value: actionType = value.Type; return true; case RootModelSourceStateChangedAction value: diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index e009ffa9f..45b483f2e 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -680,25 +680,18 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) state.Config.Values = MergeConfig(state.Config.Values, a.Config, a.Replace); return ReduceOutcome.Applied; - case RootModelSourceRegistrationSetAction a: + case RootModelSourceSetAction a: { - List list = state.ModelSourceRegistrations ??= new List(); - int index = list.FindIndex(r => r.Id == a.Registration.Id); - ModelSourceRegistration? existing = index >= 0 && SameModelSourceRouting(list[index], a.Registration) ? list[index] : null; - var contributors = new List(existing?.ContributingClientIds ?? new List()); - if (a.ClientId is not null && !contributors.Contains(a.ClientId)) + List list = state.ModelSources ??= new List(); + int index = list.FindIndex(s => s.Id == a.ModelSource.Id); + ModelSource? existing = index >= 0 && SameModelSourceVersion(list[index], a.ModelSource) ? list[index] : null; + ModelSource merged = a.ModelSource with { - contributors.Add(a.ClientId); - } - - ModelSourceRegistration merged = a.Registration with - { - ContributingClientIds = contributors.Count > 0 ? contributors : null, State = existing?.State, CredentialNonce = existing?.CredentialNonce, CredentialResource = existing?.CredentialResource, CredentialOrigins = existing?.CredentialOrigins, - CredentialId = existing?.CredentialId, + AccountId = existing?.AccountId, }; if (index < 0) { @@ -711,41 +704,27 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) return ReduceOutcome.Applied; } - case RootModelSourceContributorRemovedAction a: - { - int index = state.ModelSourceRegistrations?.FindIndex(r => r.Id == a.Id) ?? -1; - List? contributors = index < 0 ? null : state.ModelSourceRegistrations![index].ContributingClientIds; - if (contributors is null || !contributors.Contains(a.ClientId)) - { - return ReduceOutcome.NoOp; - } - - List remaining = contributors.FindAll(id => id != a.ClientId); - List list = state.ModelSourceRegistrations!; - list[index] = list[index] with { ContributingClientIds = remaining.Count > 0 ? remaining : null }; - return ReduceOutcome.Applied; - } - case RootModelSourceRegistrationRemovedAction a: + case RootModelSourceRemovedAction a: { - int index = state.ModelSourceRegistrations?.FindIndex(r => r.Id == a.Id) ?? -1; + int index = state.ModelSources?.FindIndex(s => s.Id == a.Id) ?? -1; if (index < 0) { return ReduceOutcome.NoOp; } - state.ModelSourceRegistrations!.RemoveAt(index); + state.ModelSources!.RemoveAt(index); return ReduceOutcome.Applied; } case RootModelSourceStateChangedAction a: { - int index = state.ModelSourceRegistrations?.FindIndex(r => r.Id == a.Id) ?? -1; + int index = state.ModelSources?.FindIndex(s => s.Id == a.Id) ?? -1; if (index < 0) { return ReduceOutcome.NoOp; } - List list = state.ModelSourceRegistrations!; - list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce, CredentialResource = a.CredentialResource, CredentialOrigins = a.CredentialOrigins, CredentialId = a.CredentialId }; + List list = state.ModelSources!; + list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce, CredentialResource = a.CredentialResource, CredentialOrigins = a.CredentialOrigins, AccountId = a.AccountId }; return ReduceOutcome.Applied; } } @@ -753,83 +732,9 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) return ReduceOutcome.OutOfScope; } - // Whether two registrations have the same provider, format, and definition, - // comparing definitions as JSON values. - private static bool SameModelSourceRouting(ModelSourceRegistration a, ModelSourceRegistration b) - { - if (a.Provider != b.Provider || a.Format != b.Format || a.Definition.Count != b.Definition.Count) - { - return false; - } - - foreach (KeyValuePair entry in a.Definition) - { - if (!b.Definition.TryGetValue(entry.Key, out JsonElement other) || !JsonValuesEqual(entry.Value, other)) - { - return false; - } - } - - return true; - } - - // Compares JSON values regardless of object key order, with numbers compared - // by numeric value, so `1` equals `1.0`. - private static bool JsonValuesEqual(JsonElement a, JsonElement b) - { - if (a.ValueKind != b.ValueKind) - { - return false; - } - - switch (a.ValueKind) - { - case JsonValueKind.Object: - { - int count = 0; - foreach (JsonProperty property in a.EnumerateObject()) - { - count++; - if (!b.TryGetProperty(property.Name, out JsonElement other) || !JsonValuesEqual(property.Value, other)) - { - return false; - } - } - - foreach (JsonProperty _ in b.EnumerateObject()) - { - count--; - } - - return count == 0; - } - case JsonValueKind.Array: - { - if (a.GetArrayLength() != b.GetArrayLength()) - { - return false; - } - - using JsonElement.ArrayEnumerator left = a.EnumerateArray(); - using JsonElement.ArrayEnumerator right = b.EnumerateArray(); - while (left.MoveNext() && right.MoveNext()) - { - if (!JsonValuesEqual(left.Current, right.Current)) - { - return false; - } - } - - return true; - } - case JsonValueKind.Number: - return a.GetDouble() == b.GetDouble(); - case JsonValueKind.String: - return a.GetString() == b.GetString(); - default: - return true; - } - } + // Whether two model sources have the same provider, format, and definition nonce. + private static bool SameModelSourceVersion(ModelSource a, ModelSource b) => + a.Provider == b.Provider && a.Format == b.Format && a.Nonce == b.Nonce; // Shared config merge for the root, session, and chat `configChanged` actions: // when `replace` is set (or no values exist yet) start fresh, otherwise @@ -2771,9 +2676,8 @@ public static ReduceOutcome ApplyToAutomationRun( private static readonly string[] s_clientDispatchableActionNames = { "root/configChanged", - "root/modelSourceRegistrationSet", - "root/modelSourceContributorRemoved", - "root/modelSourceRegistrationRemoved", + "root/modelSourceSet", + "root/modelSourceRemoved", // Chat-channel actions (post-#213) "chat/turnStarted", "chat/toolCallConfirmed", diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 1b4ab7a77..974d70439 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -2,7 +2,6 @@ package ahp import ( "encoding/json" - "reflect" "time" "github.com/microsoft/agent-host-protocol/clients/go/ahptypes" @@ -538,66 +537,47 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R state.Config.Values[k] = v } return ReduceOutcomeApplied - case *ahptypes.RootModelSourceRegistrationSetAction: - updated := a.Registration - var contributors []string - idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, updated.Id) - if idx >= 0 && sameModelSourceRouting(state.ModelSourceRegistrations[idx], updated) { - copyModelSourceHostFields(&updated, state.ModelSourceRegistrations[idx]) - contributors = append(contributors, state.ModelSourceRegistrations[idx].ContributingClientIds...) + case *ahptypes.RootModelSourceSetAction: + updated := a.ModelSource + idx := modelSourceIndex(state.ModelSources, updated.Id) + if idx >= 0 && sameModelSourceVersion(state.ModelSources[idx], updated) { + copyModelSourceHostFields(&updated, state.ModelSources[idx]) } else { - copyModelSourceHostFields(&updated, ahptypes.ModelSourceRegistration{}) + copyModelSourceHostFields(&updated, ahptypes.ModelSource{}) } - if a.ClientId != nil && !containsString(contributors, *a.ClientId) { - contributors = append(contributors, *a.ClientId) - } - updated.ContributingClientIds = contributors if idx >= 0 { - state.ModelSourceRegistrations[idx] = updated + state.ModelSources[idx] = updated } else { - state.ModelSourceRegistrations = append(state.ModelSourceRegistrations, updated) - } - return ReduceOutcomeApplied - case *ahptypes.RootModelSourceContributorRemovedAction: - idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, a.Id) - if idx < 0 || !containsString(state.ModelSourceRegistrations[idx].ContributingClientIds, a.ClientId) { - return ReduceOutcomeNoOp - } - var remaining []string - for _, id := range state.ModelSourceRegistrations[idx].ContributingClientIds { - if id != a.ClientId { - remaining = append(remaining, id) - } + state.ModelSources = append(state.ModelSources, updated) } - state.ModelSourceRegistrations[idx].ContributingClientIds = remaining return ReduceOutcomeApplied - case *ahptypes.RootModelSourceRegistrationRemovedAction: - idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, a.Id) + case *ahptypes.RootModelSourceRemovedAction: + idx := modelSourceIndex(state.ModelSources, a.Id) if idx < 0 { return ReduceOutcomeNoOp } - state.ModelSourceRegistrations = append(state.ModelSourceRegistrations[:idx], state.ModelSourceRegistrations[idx+1:]...) + state.ModelSources = append(state.ModelSources[:idx], state.ModelSources[idx+1:]...) return ReduceOutcomeApplied case *ahptypes.RootModelSourceStateChangedAction: - idx := modelSourceRegistrationIndex(state.ModelSourceRegistrations, a.Id) + idx := modelSourceIndex(state.ModelSources, a.Id) if idx < 0 { return ReduceOutcomeNoOp } st := a.State nonce := a.CredentialNonce - copyModelSourceHostFields(&state.ModelSourceRegistrations[idx], ahptypes.ModelSourceRegistration{ + copyModelSourceHostFields(&state.ModelSources[idx], ahptypes.ModelSource{ State: &st, CredentialNonce: &nonce, CredentialResource: a.CredentialResource, CredentialOrigins: a.CredentialOrigins, - CredentialId: a.CredentialId, + AccountId: a.AccountId, }) return ReduceOutcomeApplied } return ReduceOutcomeOutOfScope } -func modelSourceRegistrationIndex(list []ahptypes.ModelSourceRegistration, id string) int { +func modelSourceIndex(list []ahptypes.ModelSource, id string) int { for i := range list { if list[i].Id == id { return i @@ -608,45 +588,18 @@ func modelSourceRegistrationIndex(list []ahptypes.ModelSourceRegistration, id st // copyModelSourceHostFields copies the host-reported fields of from onto to, // clearing the ones from lacks. -func copyModelSourceHostFields(to *ahptypes.ModelSourceRegistration, from ahptypes.ModelSourceRegistration) { +func copyModelSourceHostFields(to *ahptypes.ModelSource, from ahptypes.ModelSource) { to.State = from.State to.CredentialNonce = from.CredentialNonce to.CredentialResource = from.CredentialResource to.CredentialOrigins = from.CredentialOrigins - to.CredentialId = from.CredentialId + to.AccountId = from.AccountId } -// sameModelSourceRouting reports whether two registrations have the same -// provider, format, and definition, comparing definitions as JSON values. -func sameModelSourceRouting(a, b ahptypes.ModelSourceRegistration) bool { - return a.Provider == b.Provider && a.Format == b.Format && jsonValuesEqual(a.Definition, b.Definition) -} - -// jsonValuesEqual compares two values by their JSON meaning, ignoring object -// key order and formatting. -func jsonValuesEqual(a, b any) bool { - return reflect.DeepEqual(normalizeJSON(a), normalizeJSON(b)) -} - -func normalizeJSON(v any) any { - raw, err := json.Marshal(v) - if err != nil { - return nil - } - var out any - if err := json.Unmarshal(raw, &out); err != nil { - return nil - } - return out -} - -func containsString(list []string, value string) bool { - for _, item := range list { - if item == value { - return true - } - } - return false +// sameModelSourceVersion reports whether two model sources have the same +// provider, format, and definition nonce. +func sameModelSourceVersion(a, b ahptypes.ModelSource) bool { + return a.Provider == b.Provider && a.Format == b.Format && a.Nonce == b.Nonce } // ─── Chat Reducer ────────────────────────────────────────────────────── diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 7f72eb368..29d83b5cd 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -106,9 +106,8 @@ const ( ActionTypeAnnotationsEntryRemoved ActionType = "annotations/entryRemoved" ActionTypeRootTerminalsChanged ActionType = "root/terminalsChanged" ActionTypeRootConfigChanged ActionType = "root/configChanged" - ActionTypeRootModelSourceRegistrationSet ActionType = "root/modelSourceRegistrationSet" - ActionTypeRootModelSourceContributorRemoved ActionType = "root/modelSourceContributorRemoved" - ActionTypeRootModelSourceRegistrationRemoved ActionType = "root/modelSourceRegistrationRemoved" + ActionTypeRootModelSourceSet ActionType = "root/modelSourceSet" + ActionTypeRootModelSourceRemoved ActionType = "root/modelSourceRemoved" ActionTypeRootModelSourceStateChanged ActionType = "root/modelSourceStateChanged" ActionTypeTerminalData ActionType = "terminal/data" ActionTypeTerminalInput ActionType = "terminal/input" @@ -180,85 +179,63 @@ type RootConfigChangedAction struct { Replace *bool `json:"replace,omitempty"` } -// Contributes a model source registration for `clientId`. A registration's -// routing is its `provider`, `format`, and `definition`, with definitions -// compared as JSON values: object key order is ignored, and numbers compare -// by numeric value, so `1` equals `1.0`. +// Adds a model source, or updates the one with the same `id`. The reducer +// stores `modelSource` without the definition: // -// - **Add.** When no registration has the `id`, appends it, with -// `contributingClientIds` set to `[clientId]`, or absent without a -// `clientId`. -// - **Join.** When one has, and its routing is unchanged, keeps its -// host-reported fields (`state`, `credentialNonce`, `credentialResource`, -// `credentialOrigins`, and `credentialId`), adds `clientId` to -// `contributingClientIds` if it isn't there, and takes the other fields -// from the action. -// - **Replace.** When the routing changed, replaces the registration, with -// `contributingClientIds` set to `[clientId]`, or absent without a -// `clientId`. Its host-reported fields are absent until the host reports -// again with {@link RootModelSourceStateChangedAction}. +// - **Add.** When no model source has the `id`, appends `modelSource`. +// - **Re-register.** When one has, with the same `provider`, `format`, and +// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, +// `credentialResource`, `credentialOrigins`, and `accountId`) and takes +// the other fields from the action. +// - **Update.** When any of the three differs, replaces the source. Its +// host-reported fields are absent until the host reports again with +// {@link RootModelSourceStateChangedAction}. // -// A client dispatches this with its own `clientId`, and without -// `contributingClientIds` or any host-reported field. +// A client dispatches this without any host-reported field. The host learns +// which client registered the source from the envelope's `origin`. // // Stability: 1.0 - Early development. -type RootModelSourceRegistrationSetAction struct { +type RootModelSourceSetAction struct { Type ActionType `json:"type"` - // The registration to contribute, matched by `id`. - Registration ModelSourceRegistration `json:"registration"` - // The contributing client. Absent when the host registers the source - // itself. - ClientId *string `json:"clientId,omitempty"` + // The model source to add or update, matched by `id`, without host-reported fields. + ModelSource ModelSource `json:"modelSource"` + // How to reach the source, in `modelSource.format`: endpoint, wire format, + // models, and so on. The host hands it to the agent, and the reducer + // doesn't store it. MUST NOT contain a credential. + Definition map[string]json.RawMessage `json:"definition"` } -// Withdraws one client's contribution to a model source registration: -// removes `clientId` from `contributingClientIds`, leaving the field absent -// when no contributor remains. A no-op when no registration has `id`, or -// `clientId` doesn't contribute it. It never removes the registration. -// -// A client dispatches this with its own `clientId`. The host dispatches it -// when a contributing client leaves. -// -// Stability: 1.0 - Early development. -type RootModelSourceContributorRemovedAction struct { - Type ActionType `json:"type"` - // The registration's `id`. - Id string `json:"id"` - // The contributing client to remove. - ClientId string `json:"clientId"` -} - -// Removes the model source registration with the given `id` for every -// contributor. A no-op when none matches. +// Removes the model source with the given `id`, for every client. A no-op +// when none matches. // // Stability: 1.0 - Early development. -type RootModelSourceRegistrationRemovedAction struct { +type RootModelSourceRemovedAction struct { Type ActionType `json:"type"` - // The registration's `id`. + // The model source's `id`. Id string `json:"id"` } -// Updates a model source registration's host-reported fields together: -// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and -// `credentialId`. A no-op when no registration has `id`. Other fields of the -// registration are preserved. Only the host dispatches it. +// Updates a model source's host-reported fields together: `state`, +// `credentialNonce`, `credentialResource`, `credentialOrigins`, and +// `accountId`. A no-op when no model source has `id`. Other fields of the +// source are preserved. Only the host dispatches it. // // Stability: 1.0 - Early development. type RootModelSourceStateChangedAction struct { Type ActionType `json:"type"` - // The registration's `id`. + // The model source's `id`. Id string `json:"id"` // The new status. State ModelSourceState `json:"state"` - // The registration's current credential nonce. + // The model source's current credential nonce. CredentialNonce string `json:"credentialNonce"` - // Replaces the registration's `credentialResource`. Absent clears it, for a + // Replaces the source's `credentialResource`. Absent clears it, for a // source that needs no credential. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` - // Replaces the registration's `credentialOrigins`. Absent clears it. + // Replaces the source's `credentialOrigins`. Absent clears it. CredentialOrigins []URI `json:"credentialOrigins,omitempty"` - // Replaces the registration's `credentialId`. Absent clears it. - CredentialId *string `json:"credentialId,omitempty"` + // Replaces the source's `accountId`. Absent clears it. + AccountId *string `json:"accountId,omitempty"` } // Session backend initialized successfully. @@ -1946,9 +1923,8 @@ type isStateAction interface{ isStateAction() } func (*RootAgentsChangedAction) isStateAction() {} func (*RootActiveSessionsChangedAction) isStateAction() {} func (*RootConfigChangedAction) isStateAction() {} -func (*RootModelSourceRegistrationSetAction) isStateAction() {} -func (*RootModelSourceContributorRemovedAction) isStateAction() {} -func (*RootModelSourceRegistrationRemovedAction) isStateAction() {} +func (*RootModelSourceSetAction) isStateAction() {} +func (*RootModelSourceRemovedAction) isStateAction() {} func (*RootModelSourceStateChangedAction) isStateAction() {} func (*SessionReadyAction) isStateAction() {} func (*SessionCreationFailedAction) isStateAction() {} @@ -2088,20 +2064,14 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value - case "root/modelSourceRegistrationSet": - var value RootModelSourceRegistrationSetAction - if err := json.Unmarshal(data, &value); err != nil { - return err - } - u.Value = &value - case "root/modelSourceContributorRemoved": - var value RootModelSourceContributorRemovedAction + case "root/modelSourceSet": + var value RootModelSourceSetAction if err := json.Unmarshal(data, &value); err != nil { return err } u.Value = &value - case "root/modelSourceRegistrationRemoved": - var value RootModelSourceRegistrationRemovedAction + case "root/modelSourceRemoved": + var value RootModelSourceRemovedAction if err := json.Unmarshal(data, &value); err != nil { return err } diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index ec443791a..799ff1aa5 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1356,19 +1356,12 @@ type McpServerAuthenticateTarget struct { // Stability: 1.0 - Early development. type ModelSourceAuthenticateTarget struct { Kind AuthenticateTargetKind `json:"kind"` - // The registration's `ModelSourceRegistration.id`. + // The registration's `ModelSource.id`. ModelSourceId string `json:"modelSourceId"` - // The registration's current `ModelSourceRegistration.credentialNonce`, as + // The registration's current `ModelSource.credentialNonce`, as // published in root state. The host rejects a stale one with `Conflict` // (-32011). CredentialNonce string `json:"credentialNonce"` - // A client-chosen, non-secret ID for the credential, such as a hash of - // where the client stores the key. The host publishes it as the - // registration's `ModelSourceRegistration.credentialId`, so a client can - // tell whether the host holds its current key. Clients SHOULD include it - // when delivering a credential, and omit it when revoking one. MUST NOT be - // derived from the secret. - CredentialId *string `json:"credentialId,omitempty"` } // Pushes a credential for a protected resource. The `resource` field MUST @@ -1377,7 +1370,7 @@ type ModelSourceAuthenticateTarget struct { // or discovered dynamically from a live `McpServerAuthRequiredState.resource` // or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the // corresponding MCP server or tool call actually challenges for auth), or -// from a registered model source's `ModelSourceRegistration.credentialResource`. +// from a registered model source's `ModelSource.credentialResource`. // Servers MUST accept any `resource` value they have themselves advertised // through one of these mechanisms, subject to the `target` rules. A // `modelSource` target takes only the registration's current @@ -1398,7 +1391,7 @@ type AuthenticateParams struct { // server has advertised — via `ProtectedResourceMetadata` in // `AgentInfo.protectedResources`, or via a live // `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - // or `ModelSourceRegistration.credentialResource`. + // or `ModelSource.credentialResource`. Resource string `json:"resource"` // Bearer token obtained from the resource's authorization server, or an // opaque secret for a model source. An empty string revokes the credential. @@ -1451,6 +1444,12 @@ type AuthenticateParams struct { // Hosts can compare `accountId` values to detect when the underlying account has changed. // Hosts MUST treat `accountId` as an opaque string. // see {@link /specification/authentication#account-selection-hints | Account selection hints}. + // + // With a `modelSource` target, clients SHOULD include it when delivering a + // credential and omit it when revoking one, and the host publishes it as + // the source's `ModelSource.accountId`. It MUST NOT be derived from the + // secret. For an API key with no account of its own, a client uses an ID + // that changes whenever the user replaces the key. AccountId *string `json:"accountId,omitempty"` } diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 9654864e5..660366230 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -453,8 +453,7 @@ const ( ) // How long a registered model source lasts once its last contributing client -// leaves. When the last contributor withdraws instead, the source goes away -// whatever its retention. +// leaves. // // Stability: 1.0 - Early development. type ModelSourceRetentionPolicy string @@ -462,7 +461,7 @@ type ModelSourceRetentionPolicy string const ( // Removed when the last contributing client leaves, once running turns finish. ModelSourceRetentionPolicyContributingClient ModelSourceRetentionPolicy = "contributingClient" - // Kept until it's removed, its last contributor withdraws, or host policy expires it. + // Kept until a client removes it, or host policy expires it. ModelSourceRetentionPolicyHost ModelSourceRetentionPolicy = "host" ) @@ -478,7 +477,7 @@ const ( // The credential's lifetime or lease lapsed. A client may renew it. ModelSourceAuthRequiredReasonExpired ModelSourceAuthRequiredReason = "expired" // The endpoint refused the credential. Clients don't send a credential with - // the same {@link ModelSourceRegistration.credentialId} again. + // the same {@link ModelSource.accountId} again. ModelSourceAuthRequiredReasonRejected ModelSourceAuthRequiredReason = "rejected" // A client revoked the credential. Clients don't send one again without a user's action. ModelSourceAuthRequiredReasonRevoked ModelSourceAuthRequiredReason = "revoked" @@ -492,11 +491,11 @@ type ModelSourcePrincipalPolicy string const ( // Every connected client may change, supply credentials for, and select - // every registration. + // every model source. ModelSourcePrincipalPolicyShared ModelSourcePrincipalPolicy = "shared" // The host verifies principals, and limits changes, credentials, and - // selection of each registration to clients of the principal that - // registered it. Root state still lists every registration to every + // selection of each model source to clients of the principal that + // registered it. Root state still lists every model source to every // client. ModelSourcePrincipalPolicyIsolated ModelSourcePrincipalPolicy = "isolated" ) @@ -847,10 +846,12 @@ type RootState struct { Terminals []TerminalInfo `json:"terminals,omitempty"` // Agent host configuration schema and current values Config *RootConfigState `json:"config,omitempty"` - // Model sources registered on this host, keyed by `id`. + // Model sources registered on this host, keyed by `id`. When one is + // ready, it also appears in its agent's {@link AgentInfo.modelSources} + // catalog. // // Stability: 1.0 - Early development. - ModelSourceRegistrations []ModelSourceRegistration `json:"modelSourceRegistrations,omitempty"` + ModelSources []ModelSource `json:"modelSources,omitempty"` // Additional implementation-defined metadata about the agent host itself. // // Clients MAY look for well-known keys here to provide enhanced UI. @@ -990,13 +991,12 @@ type MultipleWorkingDirectoriesCapability struct { // // Stability: 1.0 - Early development. type ModelSourceRegistrationCapability struct { - // Definition formats the agent reads, most preferred first. Format names - // are defined by agent implementations and SHOULD be namespaced, for - // example `example.com/model-source@1`. AHP doesn't define, standardize, - // or name any format. + // Definition formats the agent reads, most preferred first: recognized + // values of {@link ModelSource.format}, or namespaced names for formats + // the agent defines itself. Formats []string `json:"formats"` - // How long, in milliseconds, the host keeps a disconnected client's - // contributions before it treats the client as having left. + // How long, in milliseconds, the host keeps counting a disconnected client + // as a contributing client before it treats the client as having left. GracePeriod *int64 `json:"gracePeriod,omitempty"` // Whether clients acting for different principals share the registry. // Absent means `shared`. @@ -1015,12 +1015,13 @@ func (v ModelSourceRegistrationCapability) MarshalJSON() ([]byte, error) { return marshalWithExtra(wire(v), v.Extra, "formats", "gracePeriod", "principalPolicy") } -// A model source registered on this host by one or more clients, or by the -// host itself. Its definition is in a format the agent named by `provider` -// reads. It never contains a credential. +// A model source registered on this host by a client, or by the host itself. +// The definition that tells the agent named by `provider` how to reach it +// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing +// here is a credential. // // Stability: 1.0 - Early development. -type ModelSourceRegistration struct { +type ModelSource struct { // Host-unique ID, chosen by whoever registers the source. Also the // source's {@link ModelSourceInfo.id} in the agent's catalog, and the // {@link SessionModelInfo.modelSourceId} of its models. @@ -1031,32 +1032,37 @@ type ModelSourceRegistration struct { DisplayName string `json:"displayName"` // Icons for UI display. Icons []Icon `json:"icons,omitempty"` - // Definition format, one of the agent's - // {@link ModelSourceRegistrationCapability.formats}. + // The definition's format, one of the agent's + // {@link ModelSourceRegistrationCapability.formats}. Recognized values + // include: + // + // - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as + // OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + // - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + // - `'azureOpenai'`: an Azure OpenAI deployment. + // - `'gemini'`: Google's Gemini API. + // + // AHP doesn't define what a definition contains, even for these. Agents + // MAY read other formats, named with a namespace such as + // `example.com/model-source@1` so they don't collide. Format string `json:"format"` - // How to reach the source: endpoint, wire format, models, and so on, in - // `format`. Its shape belongs to the agent that reads it, and AHP doesn't - // define it. MUST NOT contain a credential. - Definition map[string]json.RawMessage `json:"definition"` - // The clients that contribute this registration, in the order they joined. - // The reducer maintains it from {@link RootModelSourceRegistrationSetAction} - // and {@link RootModelSourceContributorRemovedAction}. Absent when no - // client contributes it: a source the host registered itself, or a - // `host`-retained one whose contributors have all left. - ContributingClientIds []string `json:"contributingClientIds,omitempty"` + // Opaque version token for the definition, such as a hash of it, chosen by + // whoever registers the source. A client compares it with its own copy + // instead of the definition, and the reducer compares it to tell an update + // from a re-registration of the same definition. + Nonce string `json:"nonce"` // What happens when the last contributing client leaves. Absent means `contributingClient`. Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` // Host-reported status, set with {@link RootModelSourceStateChangedAction}. - // Absent until the host reports one, and after a `Set` replaces the - // registration until the host reports again. + // Absent until the host reports one, and after an update replaces the + // definition until the host reports again. State *ModelSourceState `json:"state,omitempty"` // Host-issued token that a client echoes in // {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - // the credential, and that tags every agent operation on the registration. - // The host issues a new one when the registration is added, when its - // `provider`, `format`, or `definition` changes, and whenever the - // credential is installed or dropped. It never reuses one for the same - // `id`. Set with `state`. + // the credential, and that tags every agent operation on the source. The + // host issues a new one when the source is added or updated, and whenever + // the credential is installed or dropped. It never reuses one for the + // same `id`. Set with `state`. CredentialNonce *string `json:"credentialNonce,omitempty"` // RFC 9728 metadata for the endpoint the credential is for. Present // whenever the source takes a credential, in every state, so any client @@ -1073,31 +1079,31 @@ type ModelSourceRegistration struct { // takes a user-supplied secret omits them. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` // Every origin the host sends the credential to, such as - // `https://api.example.com`. Present whenever `credentialResource` is. A - // client checks each one against its own copy of the definition before it - // sends a key. Set with `state`. + // `https://api.example.com`, derived from the definition it holds. Present + // whenever `credentialResource` is. A client checks each one against its + // own copy of the definition before it sends a key. Set with `state`. CredentialOrigins []URI `json:"credentialOrigins,omitempty"` - // The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of - // the credential the host most recently accepted. While the state is - // `starting` or `ready`, the host holds it. While it's `authRequired`, the - // `reason` says what happened to it. Absent until the host accepts a - // credential. Set with `state`. - CredentialId *string `json:"credentialId,omitempty"` - // Additional implementation-defined metadata for this registration. + // The {@link AuthenticateParams.accountId} the client sent with the + // credential the host most recently accepted. While the state is + // `starting` or `ready`, the host holds that credential. While it's + // `authRequired`, the `reason` says what happened to it. Absent until the + // host accepts a credential sent with an `accountId`. Set with `state`. + AccountId *string `json:"accountId,omitempty"` + // Additional implementation-defined metadata for this model source. // MUST NOT contain a credential. Meta map[string]json.RawMessage `json:"_meta,omitempty"` // Extra contains unrecognized wire members retained for full-object edits. Extra map[string]json.RawMessage `json:"-"` } -func (v *ModelSourceRegistration) UnmarshalJSON(data []byte) error { - type wire ModelSourceRegistration - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "contributingClientIds", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "credentialId", "_meta") +func (v *ModelSource) UnmarshalJSON(data []byte) error { + type wire ModelSource + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "nonce", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "accountId", "_meta") } -func (v ModelSourceRegistration) MarshalJSON() ([]byte, error) { - type wire ModelSourceRegistration - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "contributingClientIds", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "credentialId", "_meta") +func (v ModelSource) MarshalJSON() ([]byte, error) { + type wire ModelSource + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "nonce", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "accountId", "_meta") } // The agent is reading and validating the definition, or listing the @@ -1121,7 +1127,7 @@ func (v ModelSourceStartingState) MarshalJSON() ([]byte, error) { } // The source is usable, and its models are in the catalog of the agent named -// by the registration's `provider`. They stay listed through later `starting` +// by the model source's `provider`. They stay listed through later `starting` // and `authRequired` states. // // Stability: 1.0 - Early development. @@ -1143,7 +1149,7 @@ func (v ModelSourceReadyState) MarshalJSON() ([]byte, error) { // Why a model source needs a credential before it can be ready. Deliberately // carries no credential. The endpoint the credential is for is the -// registration's {@link ModelSourceRegistration.credentialResource}. +// model source's {@link ModelSource.credentialResource}. // // Stability: 1.0 - Early development. type ModelSourceAuthRequirement struct { @@ -1167,7 +1173,7 @@ func (v ModelSourceAuthRequirement) MarshalJSON() ([]byte, error) { } // The source needs a credential before it can be used. A client answers with -// `authenticate`, the registration's `credentialResource.resource`, and a +// `authenticate`, the model source's `credentialResource.resource`, and a // {@link ModelSourceAuthenticateTarget}. // // Stability: 1.0 - Early development. @@ -1218,8 +1224,8 @@ func (v ModelSourceErrorState) MarshalJSON() ([]byte, error) { type ModelSourceInfo struct { // Model source identifier, unique within the agent's // {@link AgentInfo.modelSources}. For a registered model source, this is - // the {@link ModelSourceRegistration.id}. A source is registered when - // {@link RootState.modelSourceRegistrations} has an entry with this `id` + // the {@link ModelSource.id}. A source is registered when + // {@link RootState.modelSources} has an entry with this `id` // whose `provider` is the agent. Id string `json:"id"` // Human-readable name @@ -1265,7 +1271,7 @@ type SessionModelInfo struct { Vendor *string `json:"vendor,omitempty"` // The source this model comes from. MUST match a {@link ModelSourceInfo.id} // in the agent's {@link AgentInfo.modelSources}. For a model from a - // registered model source, this is the {@link ModelSourceRegistration.id}. + // registered model source, this is the {@link ModelSource.id}. // An agent's own sources use it too, so it doesn't by itself mark a // registered source. ModelSourceId *string `json:"modelSourceId,omitempty"` diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index ae2c45a49..6c1798094 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -10,11 +10,8 @@ package com.microsoft.agenthostprotocol import com.microsoft.agenthostprotocol.generated.* import java.time.Instant import java.time.format.DateTimeFormatterBuilder -import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.doubleOrNull // ─── Reducer Interface ────────────────────────────────────────────────────── @@ -578,53 +575,35 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when } } - is StateActionRootModelSourceRegistrationSet -> { - val registration = action.value.registration - val clientId = action.value.clientId - val list = state.modelSourceRegistrations.orEmpty() - val idx = list.indexOfFirst { it.id == registration.id } - val existing = list.getOrNull(idx)?.takeIf { sameModelSourceRouting(it, registration) } - val contributors = existing?.contributingClientIds.orEmpty().toMutableList() - if (clientId != null && clientId !in contributors) contributors.add(clientId) - val merged = registration.copy( - contributingClientIds = contributors.takeIf { it.isNotEmpty() }, + is StateActionRootModelSourceSet -> { + val source = action.value.modelSource + val list = state.modelSources.orEmpty() + val idx = list.indexOfFirst { it.id == source.id } + val existing = list.getOrNull(idx)?.takeIf { sameModelSourceVersion(it, source) } + val merged = source.copy( state = existing?.state, credentialNonce = existing?.credentialNonce, credentialResource = existing?.credentialResource, credentialOrigins = existing?.credentialOrigins, - credentialId = existing?.credentialId, + accountId = existing?.accountId, ) val updated = list.toMutableList() if (idx < 0) updated.add(merged) else updated[idx] = merged - state.copy(modelSourceRegistrations = updated) + state.copy(modelSources = updated) } - is StateActionRootModelSourceContributorRemoved -> { - val list = state.modelSourceRegistrations - val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 - val contributors = list?.getOrNull(idx)?.contributingClientIds.orEmpty() - if (list == null || action.value.clientId !in contributors) { - state - } else { - val remaining = contributors.filter { it != action.value.clientId } - val updated = list.toMutableList() - updated[idx] = updated[idx].copy(contributingClientIds = remaining.takeIf { it.isNotEmpty() }) - state.copy(modelSourceRegistrations = updated) - } - } - - is StateActionRootModelSourceRegistrationRemoved -> { - val list = state.modelSourceRegistrations + is StateActionRootModelSourceRemoved -> { + val list = state.modelSources val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 if (list == null || idx < 0) { state } else { - state.copy(modelSourceRegistrations = list.toMutableList().apply { removeAt(idx) }) + state.copy(modelSources = list.toMutableList().apply { removeAt(idx) }) } } is StateActionRootModelSourceStateChanged -> { - val list = state.modelSourceRegistrations + val list = state.modelSources val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 if (list == null || idx < 0) { state @@ -635,36 +614,18 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when credentialNonce = action.value.credentialNonce, credentialResource = action.value.credentialResource, credentialOrigins = action.value.credentialOrigins, - credentialId = action.value.credentialId, + accountId = action.value.accountId, ) - state.copy(modelSourceRegistrations = updated) + state.copy(modelSources = updated) } } else -> state } -/** - * Whether two registrations have the same `provider`, `format`, and - * `definition`, comparing definitions as JSON values. - */ -private fun sameModelSourceRouting(a: ModelSourceRegistration, b: ModelSourceRegistration): Boolean = - a.provider == b.provider && a.format == b.format && jsonValuesEqual(JsonObject(a.definition), JsonObject(b.definition)) - -/** - * Compares JSON values regardless of object key order, with numbers compared - * by numeric value, so `1` equals `1.0`. - */ -private fun jsonValuesEqual(a: JsonElement, b: JsonElement): Boolean = when { - a is JsonObject && b is JsonObject -> - a.size == b.size && a.all { (key, value) -> b[key]?.let { jsonValuesEqual(value, it) } == true } - a is JsonArray && b is JsonArray -> - a.size == b.size && a.indices.all { jsonValuesEqual(a[it], b[it]) } - a is JsonPrimitive && b is JsonPrimitive && !a.isString && !b.isString && - a.doubleOrNull != null && b.doubleOrNull != null -> - a.doubleOrNull == b.doubleOrNull - else -> a == b -} +/** Whether two model sources have the same `provider`, `format`, and definition `nonce`. */ +private fun sameModelSourceVersion(a: ModelSource, b: ModelSource): Boolean = + a.provider == b.provider && a.format == b.format && a.nonce == b.nonce // ─── Session Reducer ──────────────────────────────────────────────────────── diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 20609600d..2cc30b6ff 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -116,9 +116,8 @@ value class ActionType(val rawValue: String) { val ANNOTATIONS_ENTRY_REMOVED: ActionType = ActionType("annotations/entryRemoved") val ROOT_TERMINALS_CHANGED: ActionType = ActionType("root/terminalsChanged") val ROOT_CONFIG_CHANGED: ActionType = ActionType("root/configChanged") - val ROOT_MODEL_SOURCE_REGISTRATION_SET: ActionType = ActionType("root/modelSourceRegistrationSet") - val ROOT_MODEL_SOURCE_CONTRIBUTOR_REMOVED: ActionType = ActionType("root/modelSourceContributorRemoved") - val ROOT_MODEL_SOURCE_REGISTRATION_REMOVED: ActionType = ActionType("root/modelSourceRegistrationRemoved") + val ROOT_MODEL_SOURCE_SET: ActionType = ActionType("root/modelSourceSet") + val ROOT_MODEL_SOURCE_REMOVED: ActionType = ActionType("root/modelSourceRemoved") val ROOT_MODEL_SOURCE_STATE_CHANGED: ActionType = ActionType("root/modelSourceStateChanged") val TERMINAL_DATA: ActionType = ActionType("terminal/data") val TERMINAL_INPUT: ActionType = ActionType("terminal/input") @@ -1487,87 +1486,58 @@ data class RootConfigChangedAction( ) /** - * Contributes a model source registration for `clientId`. A registration's - * routing is its `provider`, `format`, and `definition`, with definitions - * compared as JSON values: object key order is ignored, and numbers compare - * by numeric value, so `1` equals `1.0`. + * Adds a model source, or updates the one with the same `id`. The reducer + * stores `modelSource` without the definition: * - * - **Add.** When no registration has the `id`, appends it, with - * `contributingClientIds` set to `[clientId]`, or absent without a - * `clientId`. - * - **Join.** When one has, and its routing is unchanged, keeps its - * host-reported fields (`state`, `credentialNonce`, `credentialResource`, - * `credentialOrigins`, and `credentialId`), adds `clientId` to - * `contributingClientIds` if it isn't there, and takes the other fields - * from the action. - * - **Replace.** When the routing changed, replaces the registration, with - * `contributingClientIds` set to `[clientId]`, or absent without a - * `clientId`. Its host-reported fields are absent until the host reports - * again with {@link RootModelSourceStateChangedAction}. + * - **Add.** When no model source has the `id`, appends `modelSource`. + * - **Re-register.** When one has, with the same `provider`, `format`, and + * `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, + * `credentialResource`, `credentialOrigins`, and `accountId`) and takes + * the other fields from the action. + * - **Update.** When any of the three differs, replaces the source. Its + * host-reported fields are absent until the host reports again with + * {@link RootModelSourceStateChangedAction}. * - * A client dispatches this with its own `clientId`, and without - * `contributingClientIds` or any host-reported field. + * A client dispatches this without any host-reported field. The host learns + * which client registered the source from the envelope's `origin`. * * Stability: 1.0 - Early development. */ @Serializable -data class RootModelSourceRegistrationSetAction( +data class RootModelSourceSetAction( val type: ActionType, /** - * The registration to contribute, matched by `id`. + * The model source to add or update, matched by `id`, without host-reported fields. */ - val registration: ModelSourceRegistration, + val modelSource: ModelSource, /** - * The contributing client. Absent when the host registers the source - * itself. + * How to reach the source, in `modelSource.format`: endpoint, wire format, + * models, and so on. The host hands it to the agent, and the reducer + * doesn't store it. MUST NOT contain a credential. */ - val clientId: String? = null + val definition: Map ) /** - * Withdraws one client's contribution to a model source registration: - * removes `clientId` from `contributingClientIds`, leaving the field absent - * when no contributor remains. A no-op when no registration has `id`, or - * `clientId` doesn't contribute it. It never removes the registration. - * - * A client dispatches this with its own `clientId`. The host dispatches it - * when a contributing client leaves. - * - * Stability: 1.0 - Early development. - */ -@Serializable -data class RootModelSourceContributorRemovedAction( - val type: ActionType, - /** - * The registration's `id`. - */ - val id: String, - /** - * The contributing client to remove. - */ - val clientId: String -) - -/** - * Removes the model source registration with the given `id` for every - * contributor. A no-op when none matches. + * Removes the model source with the given `id`, for every client. A no-op + * when none matches. * * Stability: 1.0 - Early development. */ @Serializable -data class RootModelSourceRegistrationRemovedAction( +data class RootModelSourceRemovedAction( val type: ActionType, /** - * The registration's `id`. + * The model source's `id`. */ val id: String ) /** - * Updates a model source registration's host-reported fields together: - * `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and - * `credentialId`. A no-op when no registration has `id`. Other fields of the - * registration are preserved. Only the host dispatches it. + * Updates a model source's host-reported fields together: `state`, + * `credentialNonce`, `credentialResource`, `credentialOrigins`, and + * `accountId`. A no-op when no model source has `id`. Other fields of the + * source are preserved. Only the host dispatches it. * * Stability: 1.0 - Early development. */ @@ -1575,7 +1545,7 @@ data class RootModelSourceRegistrationRemovedAction( data class RootModelSourceStateChangedAction( val type: ActionType, /** - * The registration's `id`. + * The model source's `id`. */ val id: String, /** @@ -1583,22 +1553,22 @@ data class RootModelSourceStateChangedAction( */ val state: ModelSourceState, /** - * The registration's current credential nonce. + * The model source's current credential nonce. */ val credentialNonce: String, /** - * Replaces the registration's `credentialResource`. Absent clears it, for a + * Replaces the source's `credentialResource`. Absent clears it, for a * source that needs no credential. */ val credentialResource: ProtectedResourceMetadata? = null, /** - * Replaces the registration's `credentialOrigins`. Absent clears it. + * Replaces the source's `credentialOrigins`. Absent clears it. */ val credentialOrigins: List? = null, /** - * Replaces the registration's `credentialId`. Absent clears it. + * Replaces the source's `accountId`. Absent clears it. */ - val credentialId: String? = null + val accountId: String? = null ) @Serializable @@ -1972,9 +1942,8 @@ sealed interface StateAction @JvmInline value class StateActionAnnotationsEntryRemoved(val value: AnnotationsEntryRemovedAction) : StateAction @JvmInline value class StateActionRootTerminalsChanged(val value: RootTerminalsChangedAction) : StateAction @JvmInline value class StateActionRootConfigChanged(val value: RootConfigChangedAction) : StateAction -@JvmInline value class StateActionRootModelSourceRegistrationSet(val value: RootModelSourceRegistrationSetAction) : StateAction -@JvmInline value class StateActionRootModelSourceContributorRemoved(val value: RootModelSourceContributorRemovedAction) : StateAction -@JvmInline value class StateActionRootModelSourceRegistrationRemoved(val value: RootModelSourceRegistrationRemovedAction) : StateAction +@JvmInline value class StateActionRootModelSourceSet(val value: RootModelSourceSetAction) : StateAction +@JvmInline value class StateActionRootModelSourceRemoved(val value: RootModelSourceRemovedAction) : StateAction @JvmInline value class StateActionRootModelSourceStateChanged(val value: RootModelSourceStateChangedAction) : StateAction @JvmInline value class StateActionTerminalData(val value: TerminalDataAction) : StateAction @JvmInline value class StateActionTerminalInput(val value: TerminalInputAction) : StateAction @@ -2099,9 +2068,8 @@ internal object StateActionSerializer : KSerializer { "annotations/entryRemoved" -> StateActionAnnotationsEntryRemoved(input.json.decodeFromJsonElement(AnnotationsEntryRemovedAction.serializer(), element)) "root/terminalsChanged" -> StateActionRootTerminalsChanged(input.json.decodeFromJsonElement(RootTerminalsChangedAction.serializer(), element)) "root/configChanged" -> StateActionRootConfigChanged(input.json.decodeFromJsonElement(RootConfigChangedAction.serializer(), element)) - "root/modelSourceRegistrationSet" -> StateActionRootModelSourceRegistrationSet(input.json.decodeFromJsonElement(RootModelSourceRegistrationSetAction.serializer(), element)) - "root/modelSourceContributorRemoved" -> StateActionRootModelSourceContributorRemoved(input.json.decodeFromJsonElement(RootModelSourceContributorRemovedAction.serializer(), element)) - "root/modelSourceRegistrationRemoved" -> StateActionRootModelSourceRegistrationRemoved(input.json.decodeFromJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), element)) + "root/modelSourceSet" -> StateActionRootModelSourceSet(input.json.decodeFromJsonElement(RootModelSourceSetAction.serializer(), element)) + "root/modelSourceRemoved" -> StateActionRootModelSourceRemoved(input.json.decodeFromJsonElement(RootModelSourceRemovedAction.serializer(), element)) "root/modelSourceStateChanged" -> StateActionRootModelSourceStateChanged(input.json.decodeFromJsonElement(RootModelSourceStateChangedAction.serializer(), element)) "terminal/data" -> StateActionTerminalData(input.json.decodeFromJsonElement(TerminalDataAction.serializer(), element)) "terminal/input" -> StateActionTerminalInput(input.json.decodeFromJsonElement(TerminalInputAction.serializer(), element)) @@ -2219,9 +2187,8 @@ internal object StateActionSerializer : KSerializer { is StateActionAnnotationsEntryRemoved -> output.json.encodeToJsonElement(AnnotationsEntryRemovedAction.serializer(), value.value) is StateActionRootTerminalsChanged -> output.json.encodeToJsonElement(RootTerminalsChangedAction.serializer(), value.value) is StateActionRootConfigChanged -> output.json.encodeToJsonElement(RootConfigChangedAction.serializer(), value.value) - is StateActionRootModelSourceRegistrationSet -> output.json.encodeToJsonElement(RootModelSourceRegistrationSetAction.serializer(), value.value) - is StateActionRootModelSourceContributorRemoved -> output.json.encodeToJsonElement(RootModelSourceContributorRemovedAction.serializer(), value.value) - is StateActionRootModelSourceRegistrationRemoved -> output.json.encodeToJsonElement(RootModelSourceRegistrationRemovedAction.serializer(), value.value) + is StateActionRootModelSourceSet -> output.json.encodeToJsonElement(RootModelSourceSetAction.serializer(), value.value) + is StateActionRootModelSourceRemoved -> output.json.encodeToJsonElement(RootModelSourceRemovedAction.serializer(), value.value) is StateActionRootModelSourceStateChanged -> output.json.encodeToJsonElement(RootModelSourceStateChangedAction.serializer(), value.value) is StateActionTerminalData -> output.json.encodeToJsonElement(TerminalDataAction.serializer(), value.value) is StateActionTerminalInput -> output.json.encodeToJsonElement(TerminalInputAction.serializer(), value.value) diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt index 4b9ed735f..8f6853db2 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 @@ -1626,24 +1626,15 @@ data class McpServerAuthenticateTarget( data class ModelSourceAuthenticateTarget( val kind: AuthenticateTargetKind, /** - * The registration's `ModelSourceRegistration.id`. + * The registration's `ModelSource.id`. */ val modelSourceId: String, /** - * The registration's current `ModelSourceRegistration.credentialNonce`, as + * The registration's current `ModelSource.credentialNonce`, as * published in root state. The host rejects a stale one with `Conflict` * (-32011). */ - val credentialNonce: String, - /** - * A client-chosen, non-secret ID for the credential, such as a hash of - * where the client stores the key. The host publishes it as the - * registration's `ModelSourceRegistration.credentialId`, so a client can - * tell whether the host holds its current key. Clients SHOULD include it - * when delivering a credential, and omit it when revoking one. MUST NOT be - * derived from the secret. - */ - val credentialId: String? = null + val credentialNonce: String ) @Serializable @@ -1663,7 +1654,7 @@ data class AuthenticateParams( * server has advertised — via `ProtectedResourceMetadata` in * `AgentInfo.protectedResources`, or via a live * `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - * or `ModelSourceRegistration.credentialResource`. + * or `ModelSource.credentialResource`. */ val resource: String, /** @@ -1726,6 +1717,12 @@ data class AuthenticateParams( * Hosts can compare `accountId` values to detect when the underlying account has changed. * Hosts MUST treat `accountId` as an opaque string. * see {@link /specification/authentication#account-selection-hints | Account selection hints}. + * + * With a `modelSource` target, clients SHOULD include it when delivering a + * credential and omit it when revoking one, and the host publishes it as + * the source's `ModelSource.accountId`. It MUST NOT be derived from the + * secret. For an API key with no account of its own, a client uses an ID + * that changes whenever the user replaces the key. */ val accountId: String? = null ) 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 d035c48c0..c33e7eca1 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 @@ -961,8 +961,7 @@ internal object ModelSourceStatusSerializer : KSerializer { /** * How long a registered model source lasts once its last contributing client - * leaves. When the last contributor withdraws instead, the source goes away - * whatever its retention. + * leaves. * * Stability: 1.0 - Early development. */ @@ -975,7 +974,7 @@ value class ModelSourceRetentionPolicy(val rawValue: String) { */ val CONTRIBUTING_CLIENT: ModelSourceRetentionPolicy = ModelSourceRetentionPolicy("contributingClient") /** - * Kept until it's removed, its last contributor withdraws, or host policy expires it. + * Kept until a client removes it, or host policy expires it. */ val HOST: ModelSourceRetentionPolicy = ModelSourceRetentionPolicy("host") } @@ -1011,7 +1010,7 @@ value class ModelSourceAuthRequiredReason(val rawValue: String) { val EXPIRED: ModelSourceAuthRequiredReason = ModelSourceAuthRequiredReason("expired") /** * The endpoint refused the credential. Clients don't send a credential with - * the same {@link ModelSourceRegistration.credentialId} again. + * the same {@link ModelSource.accountId} again. */ val REJECTED: ModelSourceAuthRequiredReason = ModelSourceAuthRequiredReason("rejected") /** @@ -1043,13 +1042,13 @@ value class ModelSourcePrincipalPolicy(val rawValue: String) { companion object { /** * Every connected client may change, supply credentials for, and select - * every registration. + * every model source. */ val SHARED: ModelSourcePrincipalPolicy = ModelSourcePrincipalPolicy("shared") /** * The host verifies principals, and limits changes, credentials, and - * selection of each registration to clients of the principal that - * registered it. Root state still lists every registration to every + * selection of each model source to clients of the principal that + * registered it. Root state still lists every model source to every * client. */ val ISOLATED: ModelSourcePrincipalPolicy = ModelSourcePrincipalPolicy("isolated") @@ -1673,11 +1672,13 @@ data class RootState( */ val config: RootConfigState? = null, /** - * Model sources registered on this host, keyed by `id`. + * Model sources registered on this host, keyed by `id`. When one is + * ready, it also appears in its agent's {@link AgentInfo.modelSources} + * catalog. * * Stability: 1.0 - Early development. */ - val modelSourceRegistrations: List? = null, + val modelSources: List? = null, /** * Additional implementation-defined metadata about the agent host itself. * @@ -1853,15 +1854,14 @@ data class MultipleWorkingDirectoriesCapability( @Serializable(with = ModelSourceRegistrationCapabilitySerializer::class) data class ModelSourceRegistrationCapability( /** - * Definition formats the agent reads, most preferred first. Format names - * are defined by agent implementations and SHOULD be namespaced, for - * example `example.com/model-source@1`. AHP doesn't define, standardize, - * or name any format. + * Definition formats the agent reads, most preferred first: recognized + * values of {@link ModelSource.format}, or namespaced names for formats + * the agent defines itself. */ val formats: List, /** - * How long, in milliseconds, the host keeps a disconnected client's - * contributions before it treats the client as having left. + * How long, in milliseconds, the host keeps counting a disconnected client + * as a contributing client before it treats the client as having left. */ val gracePeriod: Long? = null, /** @@ -1880,15 +1880,16 @@ internal object ModelSourceRegistrationCapabilitySerializer : UnknownMembersSeri ) /** - * A model source registered on this host by one or more clients, or by the - * host itself. Its definition is in a format the agent named by `provider` - * reads. It never contains a credential. + * A model source registered on this host by a client, or by the host itself. + * The definition that tells the agent named by `provider` how to reach it + * travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing + * here is a credential. * * Stability: 1.0 - Early development. */ @KeepGeneratedSerializer -@Serializable(with = ModelSourceRegistrationSerializer::class) -data class ModelSourceRegistration( +@Serializable(with = ModelSourceSerializer::class) +data class ModelSource( /** * Host-unique ID, chosen by whoever registers the source. Also the * source's {@link ModelSourceInfo.id} in the agent's catalog, and the @@ -1908,42 +1909,45 @@ data class ModelSourceRegistration( */ val icons: List? = null, /** - * Definition format, one of the agent's - * {@link ModelSourceRegistrationCapability.formats}. + * The definition's format, one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. Recognized values + * include: + * + * - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as + * OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + * - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + * - `'azureOpenai'`: an Azure OpenAI deployment. + * - `'gemini'`: Google's Gemini API. + * + * AHP doesn't define what a definition contains, even for these. Agents + * MAY read other formats, named with a namespace such as + * `example.com/model-source@1` so they don't collide. */ val format: String, /** - * How to reach the source: endpoint, wire format, models, and so on, in - * `format`. Its shape belongs to the agent that reads it, and AHP doesn't - * define it. MUST NOT contain a credential. + * Opaque version token for the definition, such as a hash of it, chosen by + * whoever registers the source. A client compares it with its own copy + * instead of the definition, and the reducer compares it to tell an update + * from a re-registration of the same definition. */ - val definition: Map, - /** - * The clients that contribute this registration, in the order they joined. - * The reducer maintains it from {@link RootModelSourceRegistrationSetAction} - * and {@link RootModelSourceContributorRemovedAction}. Absent when no - * client contributes it: a source the host registered itself, or a - * `host`-retained one whose contributors have all left. - */ - val contributingClientIds: List? = null, + val nonce: String, /** * What happens when the last contributing client leaves. Absent means `contributingClient`. */ val retention: ModelSourceRetentionPolicy? = null, /** * Host-reported status, set with {@link RootModelSourceStateChangedAction}. - * Absent until the host reports one, and after a `Set` replaces the - * registration until the host reports again. + * Absent until the host reports one, and after an update replaces the + * definition until the host reports again. */ val state: ModelSourceState? = null, /** * Host-issued token that a client echoes in * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential, and that tags every agent operation on the registration. - * The host issues a new one when the registration is added, when its - * `provider`, `format`, or `definition` changes, and whenever the - * credential is installed or dropped. It never reuses one for the same - * `id`. Set with `state`. + * the credential, and that tags every agent operation on the source. The + * host issues a new one when the source is added or updated, and whenever + * the credential is installed or dropped. It never reuses one for the + * same `id`. Set with `state`. */ val credentialNonce: String? = null, /** @@ -1964,21 +1968,21 @@ data class ModelSourceRegistration( val credentialResource: ProtectedResourceMetadata? = null, /** * Every origin the host sends the credential to, such as - * `https://api.example.com`. Present whenever `credentialResource` is. A - * client checks each one against its own copy of the definition before it - * sends a key. Set with `state`. + * `https://api.example.com`, derived from the definition it holds. Present + * whenever `credentialResource` is. A client checks each one against its + * own copy of the definition before it sends a key. Set with `state`. */ val credentialOrigins: List? = null, /** - * The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of - * the credential the host most recently accepted. While the state is - * `starting` or `ready`, the host holds it. While it's `authRequired`, the - * `reason` says what happened to it. Absent until the host accepts a - * credential. Set with `state`. + * The {@link AuthenticateParams.accountId} the client sent with the + * credential the host most recently accepted. While the state is + * `starting` or `ready`, the host holds that credential. While it's + * `authRequired`, the `reason` says what happened to it. Absent until the + * host accepts a credential sent with an `accountId`. Set with `state`. */ - val credentialId: String? = null, + val accountId: String? = null, /** - * Additional implementation-defined metadata for this registration. + * Additional implementation-defined metadata for this model source. * MUST NOT contain a credential. */ @SerialName("_meta") @@ -1987,8 +1991,8 @@ data class ModelSourceRegistration( val extra: Map = emptyMap() ) -internal object ModelSourceRegistrationSerializer : UnknownMembersSerializer( - ModelSourceRegistration.generatedSerializer(), +internal object ModelSourceSerializer : UnknownMembersSerializer( + ModelSource.generatedSerializer(), { it.extra }, { value, extra -> value.copy(extra = extra) }, ) @@ -2015,7 +2019,7 @@ internal object ModelSourceStartingStateSerializer : UnknownMembersSerializer serializer.serialize_str("annotations/entryRemoved"), Self::RootTerminalsChanged => serializer.serialize_str("root/terminalsChanged"), Self::RootConfigChanged => serializer.serialize_str("root/configChanged"), - Self::RootModelSourceRegistrationSet => { - serializer.serialize_str("root/modelSourceRegistrationSet") - } - Self::RootModelSourceContributorRemoved => { - serializer.serialize_str("root/modelSourceContributorRemoved") - } - Self::RootModelSourceRegistrationRemoved => { - serializer.serialize_str("root/modelSourceRegistrationRemoved") - } + Self::RootModelSourceSet => serializer.serialize_str("root/modelSourceSet"), + Self::RootModelSourceRemoved => serializer.serialize_str("root/modelSourceRemoved"), Self::RootModelSourceStateChanged => { serializer.serialize_str("root/modelSourceStateChanged") } @@ -437,9 +429,8 @@ impl<'de> serde::Deserialize<'de> for ActionType { "annotations/entryRemoved" => Self::AnnotationsEntryRemoved, "root/terminalsChanged" => Self::RootTerminalsChanged, "root/configChanged" => Self::RootConfigChanged, - "root/modelSourceRegistrationSet" => Self::RootModelSourceRegistrationSet, - "root/modelSourceContributorRemoved" => Self::RootModelSourceContributorRemoved, - "root/modelSourceRegistrationRemoved" => Self::RootModelSourceRegistrationRemoved, + "root/modelSourceSet" => Self::RootModelSourceSet, + "root/modelSourceRemoved" => Self::RootModelSourceRemoved, "root/modelSourceStateChanged" => Self::RootModelSourceStateChanged, "terminal/data" => Self::TerminalData, "terminal/input" => Self::TerminalInput, @@ -529,93 +520,69 @@ pub struct RootConfigChangedAction { pub replace: Option, } -/// Contributes a model source registration for `clientId`. A registration's -/// routing is its `provider`, `format`, and `definition`, with definitions -/// compared as JSON values: object key order is ignored, and numbers compare -/// by numeric value, so `1` equals `1.0`. +/// Adds a model source, or updates the one with the same `id`. The reducer +/// stores `modelSource` without the definition: /// -/// - **Add.** When no registration has the `id`, appends it, with -/// `contributingClientIds` set to `[clientId]`, or absent without a -/// `clientId`. -/// - **Join.** When one has, and its routing is unchanged, keeps its -/// host-reported fields (`state`, `credentialNonce`, `credentialResource`, -/// `credentialOrigins`, and `credentialId`), adds `clientId` to -/// `contributingClientIds` if it isn't there, and takes the other fields -/// from the action. -/// - **Replace.** When the routing changed, replaces the registration, with -/// `contributingClientIds` set to `[clientId]`, or absent without a -/// `clientId`. Its host-reported fields are absent until the host reports -/// again with {@link RootModelSourceStateChangedAction}. +/// - **Add.** When no model source has the `id`, appends `modelSource`. +/// - **Re-register.** When one has, with the same `provider`, `format`, and +/// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, +/// `credentialResource`, `credentialOrigins`, and `accountId`) and takes +/// the other fields from the action. +/// - **Update.** When any of the three differs, replaces the source. Its +/// host-reported fields are absent until the host reports again with +/// {@link RootModelSourceStateChangedAction}. /// -/// A client dispatches this with its own `clientId`, and without -/// `contributingClientIds` or any host-reported field. +/// A client dispatches this without any host-reported field. The host learns +/// which client registered the source from the envelope's `origin`. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RootModelSourceRegistrationSetAction { - /// The registration to contribute, matched by `id`. - pub registration: ModelSourceRegistration, - /// The contributing client. Absent when the host registers the source - /// itself. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub client_id: Option, -} - -/// Withdraws one client's contribution to a model source registration: -/// removes `clientId` from `contributingClientIds`, leaving the field absent -/// when no contributor remains. A no-op when no registration has `id`, or -/// `clientId` doesn't contribute it. It never removes the registration. -/// -/// A client dispatches this with its own `clientId`. The host dispatches it -/// when a contributing client leaves. -/// -/// Stability: 1.0 - Early development. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct RootModelSourceContributorRemovedAction { - /// The registration's `id`. - pub id: String, - /// The contributing client to remove. - pub client_id: String, +pub struct RootModelSourceSetAction { + /// The model source to add or update, matched by `id`, without host-reported fields. + pub model_source: ModelSource, + /// How to reach the source, in `modelSource.format`: endpoint, wire format, + /// models, and so on. The host hands it to the agent, and the reducer + /// doesn't store it. MUST NOT contain a credential. + pub definition: JsonObject, } -/// Removes the model source registration with the given `id` for every -/// contributor. A no-op when none matches. +/// Removes the model source with the given `id`, for every client. A no-op +/// when none matches. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RootModelSourceRegistrationRemovedAction { - /// The registration's `id`. +pub struct RootModelSourceRemovedAction { + /// The model source's `id`. pub id: String, } -/// Updates a model source registration's host-reported fields together: -/// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and -/// `credentialId`. A no-op when no registration has `id`. Other fields of the -/// registration are preserved. Only the host dispatches it. +/// Updates a model source's host-reported fields together: `state`, +/// `credentialNonce`, `credentialResource`, `credentialOrigins`, and +/// `accountId`. A no-op when no model source has `id`. Other fields of the +/// source are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceStateChangedAction { - /// The registration's `id`. + /// The model source's `id`. pub id: String, /// The new status. pub state: ModelSourceState, - /// The registration's current credential nonce. + /// The model source's current credential nonce. pub credential_nonce: String, - /// Replaces the registration's `credentialResource`. Absent clears it, for a + /// Replaces the source's `credentialResource`. Absent clears it, for a /// source that needs no credential. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, - /// Replaces the registration's `credentialOrigins`. Absent clears it. + /// Replaces the source's `credentialOrigins`. Absent clears it. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_origins: Option>, - /// Replaces the registration's `credentialId`. Absent clears it. + /// Replaces the source's `accountId`. Absent clears it. #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_id: Option, + pub account_id: Option, } /// Session backend initialized successfully. @@ -2565,12 +2532,10 @@ pub enum StateAction { RootActiveSessionsChanged(RootActiveSessionsChangedAction), #[serde(rename = "root/configChanged")] RootConfigChanged(RootConfigChangedAction), - #[serde(rename = "root/modelSourceRegistrationSet")] - RootModelSourceRegistrationSet(Box), - #[serde(rename = "root/modelSourceContributorRemoved")] - RootModelSourceContributorRemoved(RootModelSourceContributorRemovedAction), - #[serde(rename = "root/modelSourceRegistrationRemoved")] - RootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction), + #[serde(rename = "root/modelSourceSet")] + RootModelSourceSet(Box), + #[serde(rename = "root/modelSourceRemoved")] + RootModelSourceRemoved(RootModelSourceRemovedAction), #[serde(rename = "root/modelSourceStateChanged")] RootModelSourceStateChanged(RootModelSourceStateChangedAction), #[serde(rename = "session/ready")] diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index d8758c178..e2d2fd951 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1754,20 +1754,12 @@ pub struct McpServerAuthenticateTarget { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceAuthenticateTarget { - /// The registration's `ModelSourceRegistration.id`. + /// The registration's `ModelSource.id`. pub model_source_id: String, - /// The registration's current `ModelSourceRegistration.credentialNonce`, as + /// The registration's current `ModelSource.credentialNonce`, as /// published in root state. The host rejects a stale one with `Conflict` /// (-32011). pub credential_nonce: String, - /// A client-chosen, non-secret ID for the credential, such as a hash of - /// where the client stores the key. The host publishes it as the - /// registration's `ModelSourceRegistration.credentialId`, so a client can - /// tell whether the host holds its current key. Clients SHOULD include it - /// when delivering a credential, and omit it when revoking one. MUST NOT be - /// derived from the secret. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_id: Option, } /// Pushes a credential for a protected resource. The `resource` field MUST @@ -1776,7 +1768,7 @@ pub struct ModelSourceAuthenticateTarget { /// or discovered dynamically from a live `McpServerAuthRequiredState.resource` /// or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the /// corresponding MCP server or tool call actually challenges for auth), or -/// from a registered model source's `ModelSourceRegistration.credentialResource`. +/// from a registered model source's `ModelSource.credentialResource`. /// Servers MUST accept any `resource` value they have themselves advertised /// through one of these mechanisms, subject to the `target` rules. A /// `modelSource` target takes only the registration's current @@ -1800,7 +1792,7 @@ pub struct AuthenticateParams { /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - /// or `ModelSourceRegistration.credentialResource`. + /// or `ModelSource.credentialResource`. pub resource: String, /// Bearer token obtained from the resource's authorization server, or an /// opaque secret for a model source. An empty string revokes the credential. @@ -1856,6 +1848,12 @@ pub struct AuthenticateParams { /// Hosts can compare `accountId` values to detect when the underlying account has changed. /// Hosts MUST treat `accountId` as an opaque string. /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. + /// + /// With a `modelSource` target, clients SHOULD include it when delivering a + /// credential and omit it when revoking one, and the host publishes it as + /// the source's `ModelSource.accountId`. It MUST NOT be derived from the + /// secret. For an API key with no account of its own, a client uses an ID + /// that changes whenever the user replaces the key. #[serde(default, skip_serializing_if = "Option::is_none")] pub account_id: Option, } diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index d2bd8b6c7..42641a6e7 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1214,15 +1214,14 @@ impl<'de> serde::Deserialize<'de> for ModelSourceStatus { } /// How long a registered model source lasts once its last contributing client -/// leaves. When the last contributor withdraws instead, the source goes away -/// whatever its retention. +/// leaves. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ModelSourceRetentionPolicy { /// Removed when the last contributing client leaves, once running turns finish. ContributingClient, - /// Kept until it's removed, its last contributor withdraws, or host policy expires it. + /// Kept until a client removes it, or host policy expires it. Host, /// Unknown raw value from a newer protocol version, preserved verbatim. Unknown(String), @@ -1266,7 +1265,7 @@ pub enum ModelSourceAuthRequiredReason { /// The credential's lifetime or lease lapsed. A client may renew it. Expired, /// The endpoint refused the credential. Clients don't send a credential with - /// the same {@link ModelSourceRegistration.credentialId} again. + /// the same {@link ModelSource.accountId} again. Rejected, /// A client revoked the credential. Clients don't send one again without a user's action. Revoked, @@ -1312,11 +1311,11 @@ impl<'de> serde::Deserialize<'de> for ModelSourceAuthRequiredReason { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ModelSourcePrincipalPolicy { /// Every connected client may change, supply credentials for, and select - /// every registration. + /// every model source. Shared, /// The host verifies principals, and limits changes, credentials, and - /// selection of each registration to clients of the principal that - /// registered it. Root state still lists every registration to every + /// selection of each model source to clients of the principal that + /// registered it. Root state still lists every model source to every /// client. Isolated, /// Unknown raw value from a newer protocol version, preserved verbatim. @@ -2042,11 +2041,13 @@ pub struct RootState { /// Agent host configuration schema and current values #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option, - /// Model sources registered on this host, keyed by `id`. + /// Model sources registered on this host, keyed by `id`. When one is + /// ready, it also appears in its agent's {@link AgentInfo.modelSources} + /// catalog. /// /// Stability: 1.0 - Early development. #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_source_registrations: Option>, + pub model_sources: Option>, /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -2210,13 +2211,12 @@ pub struct MultipleWorkingDirectoriesCapability { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceRegistrationCapability { - /// Definition formats the agent reads, most preferred first. Format names - /// are defined by agent implementations and SHOULD be namespaced, for - /// example `example.com/model-source@1`. AHP doesn't define, standardize, - /// or name any format. + /// Definition formats the agent reads, most preferred first: recognized + /// values of {@link ModelSource.format}, or namespaced names for formats + /// the agent defines itself. pub formats: Vec, - /// How long, in milliseconds, the host keeps a disconnected client's - /// contributions before it treats the client as having left. + /// How long, in milliseconds, the host keeps counting a disconnected client + /// as a contributing client before it treats the client as having left. #[serde(default, skip_serializing_if = "Option::is_none")] pub grace_period: Option, /// Whether clients acting for different principals share the registry. @@ -2228,14 +2228,15 @@ pub struct ModelSourceRegistrationCapability { pub extra: serde_json::Map, } -/// A model source registered on this host by one or more clients, or by the -/// host itself. Its definition is in a format the agent named by `provider` -/// reads. It never contains a credential. +/// A model source registered on this host by a client, or by the host itself. +/// The definition that tells the agent named by `provider` how to reach it +/// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing +/// here is a credential. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ModelSourceRegistration { +pub struct ModelSource { /// Host-unique ID, chosen by whoever registers the source. Also the /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the /// {@link SessionModelInfo.modelSourceId} of its models. @@ -2247,35 +2248,39 @@ pub struct ModelSourceRegistration { /// Icons for UI display. #[serde(default, skip_serializing_if = "Option::is_none")] pub icons: Option>, - /// Definition format, one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. + /// The definition's format, one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. Recognized values + /// include: + /// + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as + /// OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + /// - `'azureOpenai'`: an Azure OpenAI deployment. + /// - `'gemini'`: Google's Gemini API. + /// + /// AHP doesn't define what a definition contains, even for these. Agents + /// MAY read other formats, named with a namespace such as + /// `example.com/model-source@1` so they don't collide. pub format: String, - /// How to reach the source: endpoint, wire format, models, and so on, in - /// `format`. Its shape belongs to the agent that reads it, and AHP doesn't - /// define it. MUST NOT contain a credential. - pub definition: JsonObject, - /// The clients that contribute this registration, in the order they joined. - /// The reducer maintains it from {@link RootModelSourceRegistrationSetAction} - /// and {@link RootModelSourceContributorRemovedAction}. Absent when no - /// client contributes it: a source the host registered itself, or a - /// `host`-retained one whose contributors have all left. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub contributing_client_ids: Option>, + /// Opaque version token for the definition, such as a hash of it, chosen by + /// whoever registers the source. A client compares it with its own copy + /// instead of the definition, and the reducer compares it to tell an update + /// from a re-registration of the same definition. + pub nonce: String, /// What happens when the last contributing client leaves. Absent means `contributingClient`. #[serde(default, skip_serializing_if = "Option::is_none")] pub retention: Option, /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after a `Set` replaces the - /// registration until the host reports again. + /// Absent until the host reports one, and after an update replaces the + /// definition until the host reports again. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential, and that tags every agent operation on the registration. - /// The host issues a new one when the registration is added, when its - /// `provider`, `format`, or `definition` changes, and whenever the - /// credential is installed or dropped. It never reuses one for the same - /// `id`. Set with `state`. + /// the credential, and that tags every agent operation on the source. The + /// host issues a new one when the source is added or updated, and whenever + /// the credential is installed or dropped. It never reuses one for the + /// same `id`. Set with `state`. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_nonce: Option, /// RFC 9728 metadata for the endpoint the credential is for. Present @@ -2294,19 +2299,19 @@ pub struct ModelSourceRegistration { #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, /// Every origin the host sends the credential to, such as - /// `https://api.example.com`. Present whenever `credentialResource` is. A - /// client checks each one against its own copy of the definition before it - /// sends a key. Set with `state`. + /// `https://api.example.com`, derived from the definition it holds. Present + /// whenever `credentialResource` is. A client checks each one against its + /// own copy of the definition before it sends a key. Set with `state`. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_origins: Option>, - /// The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of - /// the credential the host most recently accepted. While the state is - /// `starting` or `ready`, the host holds it. While it's `authRequired`, the - /// `reason` says what happened to it. Absent until the host accepts a - /// credential. Set with `state`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_id: Option, - /// Additional implementation-defined metadata for this registration. + /// The {@link AuthenticateParams.accountId} the client sent with the + /// credential the host most recently accepted. While the state is + /// `starting` or `ready`, the host holds that credential. While it's + /// `authRequired`, the `reason` says what happened to it. Absent until the + /// host accepts a credential sent with an `accountId`. Set with `state`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] pub meta: Option, @@ -2328,7 +2333,7 @@ pub struct ModelSourceStartingState { } /// The source is usable, and its models are in the catalog of the agent named -/// by the registration's `provider`. They stay listed through later `starting` +/// by the model source's `provider`. They stay listed through later `starting` /// and `authRequired` states. /// /// Stability: 1.0 - Early development. @@ -2342,7 +2347,7 @@ pub struct ModelSourceReadyState { /// Why a model source needs a credential before it can be ready. Deliberately /// carries no credential. The endpoint the credential is for is the -/// registration's {@link ModelSourceRegistration.credentialResource}. +/// model source's {@link ModelSource.credentialResource}. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2360,7 +2365,7 @@ pub struct ModelSourceAuthRequirement { } /// The source needs a credential before it can be used. A client answers with -/// `authenticate`, the registration's `credentialResource.resource`, and a +/// `authenticate`, the model source's `credentialResource.resource`, and a /// {@link ModelSourceAuthenticateTarget}. /// /// Stability: 1.0 - Early development. @@ -2398,8 +2403,8 @@ pub struct ModelSourceErrorState { pub struct ModelSourceInfo { /// Model source identifier, unique within the agent's /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSourceRegistration.id}. A source is registered when - /// {@link RootState.modelSourceRegistrations} has an entry with this `id` + /// the {@link ModelSource.id}. A source is registered when + /// {@link RootState.modelSources} has an entry with this `id` /// whose `provider` is the agent. pub id: String, /// Human-readable name @@ -2455,7 +2460,7 @@ pub struct SessionModelInfo { pub vendor: Option, /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// registered model source, this is the {@link ModelSource.id}. /// An agent's own sources use it too, so it doesn't by itself mark a /// registered source. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/clients/rust/crates/ahp/examples/reducers_demo.rs b/clients/rust/crates/ahp/examples/reducers_demo.rs index cb18fc547..33cd386ae 100644 --- a/clients/rust/crates/ahp/examples/reducers_demo.rs +++ b/clients/rust/crates/ahp/examples/reducers_demo.rs @@ -23,7 +23,7 @@ fn main() { active_sessions: None, terminals: None, config: None, - model_source_registrations: None, + model_sources: None, meta: None, }; diff --git a/clients/rust/crates/ahp/src/hosts/runtime.rs b/clients/rust/crates/ahp/src/hosts/runtime.rs index be0cab7bb..271201a75 100644 --- a/clients/rust/crates/ahp/src/hosts/runtime.rs +++ b/clients/rust/crates/ahp/src/hosts/runtime.rs @@ -99,7 +99,7 @@ pub(super) fn spawn( active_sessions: None, terminals: None, config: None, - model_source_registrations: None, + model_sources: None, meta: None, }, subscriptions: config.initial_subscriptions.clone(), diff --git a/clients/rust/crates/ahp/src/lib.rs b/clients/rust/crates/ahp/src/lib.rs index 1396e713a..f98cd9eeb 100644 --- a/clients/rust/crates/ahp/src/lib.rs +++ b/clients/rust/crates/ahp/src/lib.rs @@ -116,7 +116,7 @@ //! active_sessions: None, //! terminals: None, //! config: None, -//! model_source_registrations: None, +//! model_sources: None, //! meta: None, //! }; //! diff --git a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs index e0e980627..3304211bc 100644 --- a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs @@ -193,7 +193,7 @@ impl MultiHostStateMirror { active_sessions: None, terminals: None, config: None, - model_source_registrations: None, + model_sources: None, meta: None, }); apply_action_to_root(root, &envelope.action); diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index 1aa21611a..edff3320d 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -28,7 +28,7 @@ //! active_sessions: None, //! terminals: None, //! config: None, -//! model_source_registrations: None, +//! model_sources: None, //! meta: None, //! }; //! @@ -62,9 +62,9 @@ use ahp_types::state::{ ChangesetOperationStatus, ChangesetState, ChangesetStatus, ChatConfigState, ChatInputRequest, ChatState, ChildCustomization, ConfirmationOption, Customization, CustomizationEnablement, ErrorResponsePart, InputRequestResponsePart, McpServerCustomization, McpServerStartingState, - McpServerState, McpServerStoppedState, ModelSourceRegistration, PendingMessage, - PendingMessageKind, ResourceWatchState, ResponsePart, RootState, SessionInputRequest, - SessionLifecycle, SessionState, SessionStatus, TerminalCommandPart, TerminalContentPart, + McpServerState, McpServerStoppedState, ModelSource, PendingMessage, PendingMessageKind, + ResourceWatchState, ResponsePart, RootState, SessionInputRequest, SessionLifecycle, + SessionState, SessionStatus, TerminalCommandPart, TerminalContentPart, TerminalExitedLifecycleState, TerminalLifecycleState, TerminalState, TerminalUnclassifiedPart, ToolCallAuthRequiredState, ToolCallCancellationReason, ToolCallCancelledState, ToolCallCompletedState, ToolCallConfirmationReason, ToolCallContributor, @@ -720,133 +720,74 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu } ReduceOutcome::Applied } - StateAction::RootModelSourceRegistrationSet(a) => { - let list = state - .model_source_registrations - .get_or_insert_with(Vec::new); - let idx = list.iter().position(|r| r.id == a.registration.id); - let mut updated = a.registration.clone(); - let mut contributors = Vec::new(); + StateAction::RootModelSourceSet(a) => { + let list = state.model_sources.get_or_insert_with(Vec::new); + let idx = list.iter().position(|s| s.id == a.model_source.id); + let mut updated = a.model_source.clone(); match idx .map(|i| &list[i]) - .filter(|existing| same_model_source_routing(existing, &a.registration)) + .filter(|existing| same_model_source_version(existing, &a.model_source)) { - Some(existing) => { - copy_model_source_host_fields(&mut updated, existing); - contributors.extend(existing.contributing_client_ids.iter().flatten().cloned()); - } + Some(existing) => copy_model_source_host_fields(&mut updated, existing), None => clear_model_source_host_fields(&mut updated), } - if let Some(client_id) = &a.client_id { - if !contributors.contains(client_id) { - contributors.push(client_id.clone()); - } - } - updated.contributing_client_ids = (!contributors.is_empty()).then_some(contributors); match idx { Some(i) => list[i] = updated, None => list.push(updated), } ReduceOutcome::Applied } - StateAction::RootModelSourceContributorRemoved(a) => { - let Some(registration) = state - .model_source_registrations - .as_mut() - .and_then(|list| list.iter_mut().find(|r| r.id == a.id)) - else { - return ReduceOutcome::NoOp; - }; - let Some(contributors) = registration.contributing_client_ids.as_mut() else { - return ReduceOutcome::NoOp; - }; - if !contributors.contains(&a.client_id) { - return ReduceOutcome::NoOp; - } - contributors.retain(|c| *c != a.client_id); - if contributors.is_empty() { - registration.contributing_client_ids = None; - } - ReduceOutcome::Applied - } - StateAction::RootModelSourceRegistrationRemoved(a) => { - let Some(list) = state.model_source_registrations.as_mut() else { + StateAction::RootModelSourceRemoved(a) => { + let Some(list) = state.model_sources.as_mut() else { return ReduceOutcome::NoOp; }; - let Some(idx) = list.iter().position(|r| r.id == a.id) else { + let Some(idx) = list.iter().position(|s| s.id == a.id) else { return ReduceOutcome::NoOp; }; list.remove(idx); ReduceOutcome::Applied } StateAction::RootModelSourceStateChanged(a) => { - let Some(registration) = state - .model_source_registrations + let Some(source) = state + .model_sources .as_mut() - .and_then(|list| list.iter_mut().find(|r| r.id == a.id)) + .and_then(|list| list.iter_mut().find(|s| s.id == a.id)) else { return ReduceOutcome::NoOp; }; - registration.state = Some(a.state.clone()); - registration.credential_nonce = Some(a.credential_nonce.clone()); - registration.credential_resource = a.credential_resource.clone(); - registration.credential_origins = a.credential_origins.clone(); - registration.credential_id = a.credential_id.clone(); + source.state = Some(a.state.clone()); + source.credential_nonce = Some(a.credential_nonce.clone()); + source.credential_resource = a.credential_resource.clone(); + source.credential_origins = a.credential_origins.clone(); + source.account_id = a.account_id.clone(); ReduceOutcome::Applied } _ => ReduceOutcome::OutOfScope, } } -/// Whether two registrations have the same `provider`, `format`, and -/// `definition`, comparing definitions as JSON values. -fn same_model_source_routing(a: &ModelSourceRegistration, b: &ModelSourceRegistration) -> bool { - a.provider == b.provider - && a.format == b.format - && a.definition.len() == b.definition.len() - && a.definition.iter().all(|(key, value)| { - b.definition - .get(key) - .is_some_and(|other| json_values_equal(value, other)) - }) -} - -/// Compares JSON values regardless of object key order, with numbers compared -/// by numeric value, so `1` equals `1.0`. -fn json_values_equal(a: &serde_json::Value, b: &serde_json::Value) -> bool { - use serde_json::Value; - match (a, b) { - (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(), - (Value::Array(x), Value::Array(y)) => { - x.len() == y.len() && x.iter().zip(y).all(|(l, r)| json_values_equal(l, r)) - } - (Value::Object(x), Value::Object(y)) => { - x.len() == y.len() - && x.iter().all(|(key, value)| { - y.get(key) - .is_some_and(|other| json_values_equal(value, other)) - }) - } - _ => a == b, - } +/// Whether two model sources have the same `provider`, `format`, and +/// definition `nonce`. +fn same_model_source_version(a: &ModelSource, b: &ModelSource) -> bool { + a.provider == b.provider && a.format == b.format && a.nonce == b.nonce } /// Copies the host-reported fields of `from` onto `to`. -fn copy_model_source_host_fields(to: &mut ModelSourceRegistration, from: &ModelSourceRegistration) { +fn copy_model_source_host_fields(to: &mut ModelSource, from: &ModelSource) { to.state = from.state.clone(); to.credential_nonce = from.credential_nonce.clone(); to.credential_resource = from.credential_resource.clone(); to.credential_origins = from.credential_origins.clone(); - to.credential_id = from.credential_id.clone(); + to.account_id = from.account_id.clone(); } -/// Clears the host-reported fields of `registration`. -fn clear_model_source_host_fields(registration: &mut ModelSourceRegistration) { - registration.state = None; - registration.credential_nonce = None; - registration.credential_resource = None; - registration.credential_origins = None; - registration.credential_id = None; +/// Clears the host-reported fields of `source`. +fn clear_model_source_host_fields(source: &mut ModelSource) { + source.state = None; + source.credential_nonce = None; + source.credential_resource = None; + source.credential_origins = None; + source.account_id = None; } // ─── Session Reducer ────────────────────────────────────────────────── @@ -2730,7 +2671,7 @@ mod tests { active_sessions: None, terminals: None, config: None, - model_source_registrations: None, + model_sources: None, meta: None, }; let a = StateAction::RootActiveSessionsChanged( diff --git a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs index c235adca0..0d7c8ee82 100644 --- a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs @@ -41,7 +41,7 @@ fn root_snapshot(agents: Vec) -> Snapshot { active_sessions: None, terminals: None, config: None, - model_source_registrations: None, + model_sources: None, meta: None, })), from_seq: 0, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift index 313800b15..bdb2dc95a 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift @@ -5,9 +5,8 @@ import Foundation /// Set of action types that clients are allowed to dispatch. public let clientDispatchableActions: Set = [ "root/configChanged", - "root/modelSourceRegistrationSet", - "root/modelSourceContributorRemoved", - "root/modelSourceRegistrationRemoved", + "root/modelSourceSet", + "root/modelSourceRemoved", "session/titleChanged", "session/activeClientSet", "session/activeClientRemoved", @@ -61,9 +60,8 @@ public let clientDispatchableActions: Set = [ public func isClientDispatchable(_ action: StateAction) -> Bool { switch action { case .rootConfigChanged, - .rootModelSourceRegistrationSet, - .rootModelSourceContributorRemoved, - .rootModelSourceRegistrationRemoved, + .rootModelSourceSet, + .rootModelSourceRemoved, .sessionTitleChanged, .sessionActiveClientSet, .sessionActiveClientRemoved, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index e9d2bf078..36081af7d 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -93,9 +93,8 @@ public enum ActionType: Codable, Sendable, Equatable { case annotationsEntryRemoved case rootTerminalsChanged case rootConfigChanged - case rootModelSourceRegistrationSet - case rootModelSourceContributorRemoved - case rootModelSourceRegistrationRemoved + case rootModelSourceSet + case rootModelSourceRemoved case rootModelSourceStateChanged case terminalData case terminalInput @@ -212,9 +211,8 @@ public enum ActionType: Codable, Sendable, Equatable { case "annotations/entryRemoved": self = .annotationsEntryRemoved case "root/terminalsChanged": self = .rootTerminalsChanged case "root/configChanged": self = .rootConfigChanged - case "root/modelSourceRegistrationSet": self = .rootModelSourceRegistrationSet - case "root/modelSourceContributorRemoved": self = .rootModelSourceContributorRemoved - case "root/modelSourceRegistrationRemoved": self = .rootModelSourceRegistrationRemoved + case "root/modelSourceSet": self = .rootModelSourceSet + case "root/modelSourceRemoved": self = .rootModelSourceRemoved case "root/modelSourceStateChanged": self = .rootModelSourceStateChanged case "terminal/data": self = .terminalData case "terminal/input": self = .terminalInput @@ -331,9 +329,8 @@ public enum ActionType: Codable, Sendable, Equatable { case .annotationsEntryRemoved: try container.encode("annotations/entryRemoved") case .rootTerminalsChanged: try container.encode("root/terminalsChanged") case .rootConfigChanged: try container.encode("root/configChanged") - case .rootModelSourceRegistrationSet: try container.encode("root/modelSourceRegistrationSet") - case .rootModelSourceContributorRemoved: try container.encode("root/modelSourceContributorRemoved") - case .rootModelSourceRegistrationRemoved: try container.encode("root/modelSourceRegistrationRemoved") + case .rootModelSourceSet: try container.encode("root/modelSourceSet") + case .rootModelSourceRemoved: try container.encode("root/modelSourceRemoved") case .rootModelSourceStateChanged: try container.encode("root/modelSourceStateChanged") case .terminalData: try container.encode("terminal/data") case .terminalInput: try container.encode("terminal/input") @@ -2293,81 +2290,49 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { } } -/// Contributes a model source registration for `clientId`. A registration's -/// routing is its `provider`, `format`, and `definition`, with definitions -/// compared as JSON values: object key order is ignored, and numbers compare -/// by numeric value, so `1` equals `1.0`. +/// Adds a model source, or updates the one with the same `id`. The reducer +/// stores `modelSource` without the definition: /// -/// - **Add.** When no registration has the `id`, appends it, with -/// `contributingClientIds` set to `[clientId]`, or absent without a -/// `clientId`. -/// - **Join.** When one has, and its routing is unchanged, keeps its -/// host-reported fields (`state`, `credentialNonce`, `credentialResource`, -/// `credentialOrigins`, and `credentialId`), adds `clientId` to -/// `contributingClientIds` if it isn't there, and takes the other fields -/// from the action. -/// - **Replace.** When the routing changed, replaces the registration, with -/// `contributingClientIds` set to `[clientId]`, or absent without a -/// `clientId`. Its host-reported fields are absent until the host reports -/// again with {@link RootModelSourceStateChangedAction}. +/// - **Add.** When no model source has the `id`, appends `modelSource`. +/// - **Re-register.** When one has, with the same `provider`, `format`, and +/// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, +/// `credentialResource`, `credentialOrigins`, and `accountId`) and takes +/// the other fields from the action. +/// - **Update.** When any of the three differs, replaces the source. Its +/// host-reported fields are absent until the host reports again with +/// {@link RootModelSourceStateChangedAction}. /// -/// A client dispatches this with its own `clientId`, and without -/// `contributingClientIds` or any host-reported field. +/// A client dispatches this without any host-reported field. The host learns +/// which client registered the source from the envelope's `origin`. /// /// Stability: 1.0 - Early development. -public struct RootModelSourceRegistrationSetAction: Codable, Sendable, Equatable { +public struct RootModelSourceSetAction: Codable, Sendable, Equatable { public var type: ActionType - /// The registration to contribute, matched by `id`. - public var registration: ModelSourceRegistration - /// The contributing client. Absent when the host registers the source - /// itself. - public var clientId: String? + /// The model source to add or update, matched by `id`, without host-reported fields. + public var modelSource: ModelSource + /// How to reach the source, in `modelSource.format`: endpoint, wire format, + /// models, and so on. The host hands it to the agent, and the reducer + /// doesn't store it. MUST NOT contain a credential. + public var definition: [String: AnyCodable] public init( type: ActionType, - registration: ModelSourceRegistration, - clientId: String? = nil + modelSource: ModelSource, + definition: [String: AnyCodable] ) { self.type = type - self.registration = registration - self.clientId = clientId - } -} - -/// Withdraws one client's contribution to a model source registration: -/// removes `clientId` from `contributingClientIds`, leaving the field absent -/// when no contributor remains. A no-op when no registration has `id`, or -/// `clientId` doesn't contribute it. It never removes the registration. -/// -/// A client dispatches this with its own `clientId`. The host dispatches it -/// when a contributing client leaves. -/// -/// Stability: 1.0 - Early development. -public struct RootModelSourceContributorRemovedAction: Codable, Sendable, Equatable { - public var type: ActionType - /// The registration's `id`. - public var id: String - /// The contributing client to remove. - public var clientId: String - - public init( - type: ActionType, - id: String, - clientId: String - ) { - self.type = type - self.id = id - self.clientId = clientId + self.modelSource = modelSource + self.definition = definition } } -/// Removes the model source registration with the given `id` for every -/// contributor. A no-op when none matches. +/// Removes the model source with the given `id`, for every client. A no-op +/// when none matches. /// /// Stability: 1.0 - Early development. -public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equatable { +public struct RootModelSourceRemovedAction: Codable, Sendable, Equatable { public var type: ActionType - /// The registration's `id`. + /// The model source's `id`. public var id: String public init( @@ -2379,27 +2344,27 @@ public struct RootModelSourceRegistrationRemovedAction: Codable, Sendable, Equat } } -/// Updates a model source registration's host-reported fields together: -/// `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and -/// `credentialId`. A no-op when no registration has `id`. Other fields of the -/// registration are preserved. Only the host dispatches it. +/// Updates a model source's host-reported fields together: `state`, +/// `credentialNonce`, `credentialResource`, `credentialOrigins`, and +/// `accountId`. A no-op when no model source has `id`. Other fields of the +/// source are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { public var type: ActionType - /// The registration's `id`. + /// The model source's `id`. public var id: String /// The new status. public var state: ModelSourceState - /// The registration's current credential nonce. + /// The model source's current credential nonce. public var credentialNonce: String - /// Replaces the registration's `credentialResource`. Absent clears it, for a + /// Replaces the source's `credentialResource`. Absent clears it, for a /// source that needs no credential. public var credentialResource: ProtectedResourceMetadata? - /// Replaces the registration's `credentialOrigins`. Absent clears it. + /// Replaces the source's `credentialOrigins`. Absent clears it. public var credentialOrigins: [String]? - /// Replaces the registration's `credentialId`. Absent clears it. - public var credentialId: String? + /// Replaces the source's `accountId`. Absent clears it. + public var accountId: String? public init( type: ActionType, @@ -2408,7 +2373,7 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { credentialNonce: String, credentialResource: ProtectedResourceMetadata? = nil, credentialOrigins: [String]? = nil, - credentialId: String? = nil + accountId: String? = nil ) { self.type = type self.id = id @@ -2416,7 +2381,7 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { self.credentialNonce = credentialNonce self.credentialResource = credentialResource self.credentialOrigins = credentialOrigins - self.credentialId = credentialId + self.accountId = accountId } } @@ -2889,9 +2854,8 @@ public enum StateAction: Codable, Sendable, Equatable { case annotationsEntryRemoved(AnnotationsEntryRemovedAction) case rootTerminalsChanged(RootTerminalsChangedAction) case rootConfigChanged(RootConfigChangedAction) - case rootModelSourceRegistrationSet(RootModelSourceRegistrationSetAction) - case rootModelSourceContributorRemoved(RootModelSourceContributorRemovedAction) - case rootModelSourceRegistrationRemoved(RootModelSourceRegistrationRemovedAction) + case rootModelSourceSet(RootModelSourceSetAction) + case rootModelSourceRemoved(RootModelSourceRemovedAction) case rootModelSourceStateChanged(RootModelSourceStateChangedAction) case terminalData(TerminalDataAction) case terminalInput(TerminalInputAction) @@ -3100,12 +3064,10 @@ public enum StateAction: Codable, Sendable, Equatable { self = .rootTerminalsChanged(try RootTerminalsChangedAction(from: decoder)) case "root/configChanged": self = .rootConfigChanged(try RootConfigChangedAction(from: decoder)) - case "root/modelSourceRegistrationSet": - self = .rootModelSourceRegistrationSet(try RootModelSourceRegistrationSetAction(from: decoder)) - case "root/modelSourceContributorRemoved": - self = .rootModelSourceContributorRemoved(try RootModelSourceContributorRemovedAction(from: decoder)) - case "root/modelSourceRegistrationRemoved": - self = .rootModelSourceRegistrationRemoved(try RootModelSourceRegistrationRemovedAction(from: decoder)) + case "root/modelSourceSet": + self = .rootModelSourceSet(try RootModelSourceSetAction(from: decoder)) + case "root/modelSourceRemoved": + self = .rootModelSourceRemoved(try RootModelSourceRemovedAction(from: decoder)) case "root/modelSourceStateChanged": self = .rootModelSourceStateChanged(try RootModelSourceStateChangedAction(from: decoder)) case "terminal/data": @@ -3244,9 +3206,8 @@ public enum StateAction: Codable, Sendable, Equatable { case .annotationsEntryRemoved(let v): try v.encode(to: encoder) case .rootTerminalsChanged(let v): try v.encode(to: encoder) case .rootConfigChanged(let v): try v.encode(to: encoder) - case .rootModelSourceRegistrationSet(let v): try v.encode(to: encoder) - case .rootModelSourceContributorRemoved(let v): try v.encode(to: encoder) - case .rootModelSourceRegistrationRemoved(let v): try v.encode(to: encoder) + case .rootModelSourceSet(let v): try v.encode(to: encoder) + case .rootModelSourceRemoved(let v): try v.encode(to: encoder) case .rootModelSourceStateChanged(let v): try v.encode(to: encoder) case .terminalData(let v): try v.encode(to: encoder) case .terminalInput(let v): try v.encode(to: encoder) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 05dc762a5..874e72fd0 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -1975,30 +1975,21 @@ public struct McpServerAuthenticateTarget: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct ModelSourceAuthenticateTarget: Codable, Sendable, Equatable { public var kind: AuthenticateTargetKind - /// The registration's `ModelSourceRegistration.id`. + /// The registration's `ModelSource.id`. public var modelSourceId: String - /// The registration's current `ModelSourceRegistration.credentialNonce`, as + /// The registration's current `ModelSource.credentialNonce`, as /// published in root state. The host rejects a stale one with `Conflict` /// (-32011). public var credentialNonce: String - /// A client-chosen, non-secret ID for the credential, such as a hash of - /// where the client stores the key. The host publishes it as the - /// registration's `ModelSourceRegistration.credentialId`, so a client can - /// tell whether the host holds its current key. Clients SHOULD include it - /// when delivering a credential, and omit it when revoking one. MUST NOT be - /// derived from the secret. - public var credentialId: String? public init( kind: AuthenticateTargetKind, modelSourceId: String, - credentialNonce: String, - credentialId: String? = nil + credentialNonce: String ) { self.kind = kind self.modelSourceId = modelSourceId self.credentialNonce = credentialNonce - self.credentialId = credentialId } } @@ -2012,7 +2003,7 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// server has advertised — via `ProtectedResourceMetadata` in /// `AgentInfo.protectedResources`, or via a live /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - /// or `ModelSourceRegistration.credentialResource`. + /// or `ModelSource.credentialResource`. public var resource: String /// Bearer token obtained from the resource's authorization server, or an /// opaque secret for a model source. An empty string revokes the credential. @@ -2065,6 +2056,12 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// Hosts can compare `accountId` values to detect when the underlying account has changed. /// Hosts MUST treat `accountId` as an opaque string. /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. + /// + /// With a `modelSource` target, clients SHOULD include it when delivering a + /// credential and omit it when revoking one, and the host publishes it as + /// the source's `ModelSource.accountId`. It MUST NOT be derived from the + /// secret. For an API key with no account of its own, a client uses an ID + /// that changes whenever the user replaces the key. public var accountId: String? enum CodingKeys: String, CodingKey { diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 67a7087d0..cf537f7f3 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -940,14 +940,13 @@ public enum ModelSourceStatus: Codable, Sendable, Equatable { } /// How long a registered model source lasts once its last contributing client -/// leaves. When the last contributor withdraws instead, the source goes away -/// whatever its retention. +/// leaves. /// /// Stability: 1.0 - Early development. public enum ModelSourceRetentionPolicy: Codable, Sendable, Equatable { /// Removed when the last contributing client leaves, once running turns finish. case contributingClient - /// Kept until it's removed, its last contributor withdraws, or host policy expires it. + /// Kept until a client removes it, or host policy expires it. case host /// Unknown raw value from a newer protocol version, preserved verbatim. case unknown(String) @@ -982,7 +981,7 @@ public enum ModelSourceAuthRequiredReason: Codable, Sendable, Equatable { /// The credential's lifetime or lease lapsed. A client may renew it. case expired /// The endpoint refused the credential. Clients don't send a credential with - /// the same {@link ModelSourceRegistration.credentialId} again. + /// the same {@link ModelSource.accountId} again. case rejected /// A client revoked the credential. Clients don't send one again without a user's action. case revoked @@ -1019,11 +1018,11 @@ public enum ModelSourceAuthRequiredReason: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public enum ModelSourcePrincipalPolicy: Codable, Sendable, Equatable { /// Every connected client may change, supply credentials for, and select - /// every registration. + /// every model source. case shared /// The host verifies principals, and limits changes, credentials, and - /// selection of each registration to clients of the principal that - /// registered it. Root state still lists every registration to every + /// selection of each model source to clients of the principal that + /// registered it. Root state still lists every model source to every /// client. case isolated /// Unknown raw value from a newer protocol version, preserved verbatim. @@ -1642,10 +1641,12 @@ public struct RootState: Codable, Sendable, Equatable { public var terminals: [TerminalInfo]? /// Agent host configuration schema and current values public var config: RootConfigState? - /// Model sources registered on this host, keyed by `id`. + /// Model sources registered on this host, keyed by `id`. When one is + /// ready, it also appears in its agent's {@link AgentInfo.modelSources} + /// catalog. /// /// Stability: 1.0 - Early development. - public var modelSourceRegistrations: [ModelSourceRegistration]? + public var modelSources: [ModelSource]? /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -1656,7 +1657,7 @@ public struct RootState: Codable, Sendable, Equatable { case activeSessions case terminals case config - case modelSourceRegistrations + case modelSources case meta = "_meta" } @@ -1665,14 +1666,14 @@ public struct RootState: Codable, Sendable, Equatable { activeSessions: Int? = nil, terminals: [TerminalInfo]? = nil, config: RootConfigState? = nil, - modelSourceRegistrations: [ModelSourceRegistration]? = nil, + modelSources: [ModelSource]? = nil, meta: [String: AnyCodable]? = nil ) { self.agents = agents self.activeSessions = activeSessions self.terminals = terminals self.config = config - self.modelSourceRegistrations = modelSourceRegistrations + self.modelSources = modelSources self.meta = meta } } @@ -1853,13 +1854,12 @@ public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable /// /// Stability: 1.0 - Early development. public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { - /// Definition formats the agent reads, most preferred first. Format names - /// are defined by agent implementations and SHOULD be namespaced, for - /// example `example.com/model-source@1`. AHP doesn't define, standardize, - /// or name any format. + /// Definition formats the agent reads, most preferred first: recognized + /// values of {@link ModelSource.format}, or namespaced names for formats + /// the agent defines itself. public var formats: [String] - /// How long, in milliseconds, the host keeps a disconnected client's - /// contributions before it treats the client as having left. + /// How long, in milliseconds, the host keeps counting a disconnected client + /// as a contributing client before it treats the client as having left. public var gracePeriod: Int? /// Whether clients acting for different principals share the registry. /// Absent means `shared`. @@ -1902,12 +1902,13 @@ public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { } } -/// A model source registered on this host by one or more clients, or by the -/// host itself. Its definition is in a format the agent named by `provider` -/// reads. It never contains a credential. +/// A model source registered on this host by a client, or by the host itself. +/// The definition that tells the agent named by `provider` how to reach it +/// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing +/// here is a credential. /// /// Stability: 1.0 - Early development. -public struct ModelSourceRegistration: Codable, Sendable, Equatable { +public struct ModelSource: Codable, Sendable, Equatable { /// Host-unique ID, chosen by whoever registers the source. Also the /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the /// {@link SessionModelInfo.modelSourceId} of its models. @@ -1918,32 +1919,37 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { public var displayName: String /// Icons for UI display. public var icons: [Icon]? - /// Definition format, one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. + /// The definition's format, one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. Recognized values + /// include: + /// + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as + /// OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + /// - `'azureOpenai'`: an Azure OpenAI deployment. + /// - `'gemini'`: Google's Gemini API. + /// + /// AHP doesn't define what a definition contains, even for these. Agents + /// MAY read other formats, named with a namespace such as + /// `example.com/model-source@1` so they don't collide. public var format: String - /// How to reach the source: endpoint, wire format, models, and so on, in - /// `format`. Its shape belongs to the agent that reads it, and AHP doesn't - /// define it. MUST NOT contain a credential. - public var definition: [String: AnyCodable] - /// The clients that contribute this registration, in the order they joined. - /// The reducer maintains it from {@link RootModelSourceRegistrationSetAction} - /// and {@link RootModelSourceContributorRemovedAction}. Absent when no - /// client contributes it: a source the host registered itself, or a - /// `host`-retained one whose contributors have all left. - public var contributingClientIds: [String]? + /// Opaque version token for the definition, such as a hash of it, chosen by + /// whoever registers the source. A client compares it with its own copy + /// instead of the definition, and the reducer compares it to tell an update + /// from a re-registration of the same definition. + public var nonce: String /// What happens when the last contributing client leaves. Absent means `contributingClient`. public var retention: ModelSourceRetentionPolicy? /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after a `Set` replaces the - /// registration until the host reports again. + /// Absent until the host reports one, and after an update replaces the + /// definition until the host reports again. public var state: ModelSourceState? /// Host-issued token that a client echoes in /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential, and that tags every agent operation on the registration. - /// The host issues a new one when the registration is added, when its - /// `provider`, `format`, or `definition` changes, and whenever the - /// credential is installed or dropped. It never reuses one for the same - /// `id`. Set with `state`. + /// the credential, and that tags every agent operation on the source. The + /// host issues a new one when the source is added or updated, and whenever + /// the credential is installed or dropped. It never reuses one for the + /// same `id`. Set with `state`. public var credentialNonce: String? /// RFC 9728 metadata for the endpoint the credential is for. Present /// whenever the source takes a credential, in every state, so any client @@ -1960,17 +1966,17 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { /// takes a user-supplied secret omits them. public var credentialResource: ProtectedResourceMetadata? /// Every origin the host sends the credential to, such as - /// `https://api.example.com`. Present whenever `credentialResource` is. A - /// client checks each one against its own copy of the definition before it - /// sends a key. Set with `state`. + /// `https://api.example.com`, derived from the definition it holds. Present + /// whenever `credentialResource` is. A client checks each one against its + /// own copy of the definition before it sends a key. Set with `state`. public var credentialOrigins: [String]? - /// The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of - /// the credential the host most recently accepted. While the state is - /// `starting` or `ready`, the host holds it. While it's `authRequired`, the - /// `reason` says what happened to it. Absent until the host accepts a - /// credential. Set with `state`. - public var credentialId: String? - /// Additional implementation-defined metadata for this registration. + /// The {@link AuthenticateParams.accountId} the client sent with the + /// credential the host most recently accepted. While the state is + /// `starting` or `ready`, the host holds that credential. While it's + /// `authRequired`, the `reason` says what happened to it. Absent until the + /// host accepts a credential sent with an `accountId`. Set with `state`. + public var accountId: String? + /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. public var meta: [String: AnyCodable]? /// Unrecognized wire members retained for full-object edits. @@ -1982,14 +1988,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { case displayName case icons case format - case definition - case contributingClientIds + case nonce case retention case state case credentialNonce case credentialResource case credentialOrigins - case credentialId + case accountId case meta = "_meta" } @@ -1999,14 +2004,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { displayName: String, icons: [Icon]? = nil, format: String, - definition: [String: AnyCodable], - contributingClientIds: [String]? = nil, + nonce: String, retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, credentialNonce: String? = nil, credentialResource: ProtectedResourceMetadata? = nil, credentialOrigins: [String]? = nil, - credentialId: String? = nil, + accountId: String? = nil, meta: [String: AnyCodable]? = nil, extra: [String: AnyCodable] = [:] ) { @@ -2015,14 +2019,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.displayName = displayName self.icons = icons self.format = format - self.definition = definition - self.contributingClientIds = contributingClientIds + self.nonce = nonce self.retention = retention self.state = state self.credentialNonce = credentialNonce self.credentialResource = credentialResource self.credentialOrigins = credentialOrigins - self.credentialId = credentialId + self.accountId = accountId self.meta = meta self.extra = extra } @@ -2034,14 +2037,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { self.displayName = try container.decode(String.self, forKey: .displayName) self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) self.format = try container.decode(String.self, forKey: .format) - self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) - self.contributingClientIds = try container.decodeIfPresent([String].self, forKey: .contributingClientIds) + self.nonce = try container.decode(String.self, forKey: .nonce) self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) self.credentialNonce = try container.decodeIfPresent(String.self, forKey: .credentialNonce) self.credentialResource = try container.decodeIfPresent(ProtectedResourceMetadata.self, forKey: .credentialResource) self.credentialOrigins = try container.decodeIfPresent([String].self, forKey: .credentialOrigins) - self.credentialId = try container.decodeIfPresent(String.self, forKey: .credentialId) + self.accountId = try container.decodeIfPresent(String.self, forKey: .accountId) self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -2053,14 +2055,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { try container.encode(self.displayName, forKey: .displayName) try container.encodeIfPresent(self.icons, forKey: .icons) try container.encode(self.format, forKey: .format) - try container.encode(self.definition, forKey: .definition) - try container.encodeIfPresent(self.contributingClientIds, forKey: .contributingClientIds) + try container.encode(self.nonce, forKey: .nonce) try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) try container.encodeIfPresent(self.credentialNonce, forKey: .credentialNonce) try container.encodeIfPresent(self.credentialResource, forKey: .credentialResource) try container.encodeIfPresent(self.credentialOrigins, forKey: .credentialOrigins) - try container.encodeIfPresent(self.credentialId, forKey: .credentialId) + try container.encodeIfPresent(self.accountId, forKey: .accountId) try container.encodeIfPresent(self.meta, forKey: .meta) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } @@ -2101,7 +2102,7 @@ public struct ModelSourceStartingState: Codable, Sendable, Equatable { } /// The source is usable, and its models are in the catalog of the agent named -/// by the registration's `provider`. They stay listed through later `starting` +/// by the model source's `provider`. They stay listed through later `starting` /// and `authRequired` states. /// /// Stability: 1.0 - Early development. @@ -2137,7 +2138,7 @@ public struct ModelSourceReadyState: Codable, Sendable, Equatable { /// Why a model source needs a credential before it can be ready. Deliberately /// carries no credential. The endpoint the credential is for is the -/// registration's {@link ModelSourceRegistration.credentialResource}. +/// model source's {@link ModelSource.credentialResource}. /// /// Stability: 1.0 - Early development. public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { @@ -2180,7 +2181,7 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { } /// The source needs a credential before it can be used. A client answers with -/// `authenticate`, the registration's `credentialResource.resource`, and a +/// `authenticate`, the model source's `credentialResource.resource`, and a /// {@link ModelSourceAuthenticateTarget}. /// /// Stability: 1.0 - Early development. @@ -2272,8 +2273,8 @@ public struct ModelSourceErrorState: Codable, Sendable, Equatable { public struct ModelSourceInfo: Codable, Sendable, Equatable { /// Model source identifier, unique within the agent's /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSourceRegistration.id}. A source is registered when - /// {@link RootState.modelSourceRegistrations} has an entry with this `id` + /// the {@link ModelSource.id}. A source is registered when + /// {@link RootState.modelSources} has an entry with this `id` /// whose `provider` is the agent. public var id: String /// Human-readable name @@ -2327,7 +2328,7 @@ public struct SessionModelInfo: Codable, Sendable, Equatable { public var vendor: String? /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSourceRegistration.id}. + /// registered model source, this is the {@link ModelSource.id}. /// An agent's own sources use it too, so it doesn't by itself mark a /// registered source. public var modelSourceId: String? diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index de385d4d8..44f3c57fa 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -103,14 +103,11 @@ public struct AHPRootReducer: Reducer { config.values = a.replace == true ? a.config : config.values.merging(a.config) { _, new in new } state.config = config - case .rootModelSourceRegistrationSet(let a): - applyModelSourceRegistrationSet(&state, a.registration, clientId: a.clientId) + case .rootModelSourceSet(let a): + applyModelSourceSet(&state, a.modelSource) - case .rootModelSourceContributorRemoved(let a): - _ = applyModelSourceContributorRemoved(&state, id: a.id, clientId: a.clientId) - - case .rootModelSourceRegistrationRemoved(let a): - _ = applyModelSourceRegistrationRemoved(&state, id: a.id) + case .rootModelSourceRemoved(let a): + _ = applyModelSourceRemoved(&state, id: a.id) case .rootModelSourceStateChanged(let a): _ = applyModelSourceStateChanged(&state, a) @@ -121,72 +118,53 @@ public struct AHPRootReducer: Reducer { } } -/// Contributes `registration` for `clientId`: adds it, joins an entry with the -/// same `id` and routing (keeping its host-reported fields), or replaces an -/// entry whose routing changed. -func applyModelSourceRegistrationSet(_ state: inout RootState, _ registration: ModelSourceRegistration, clientId: String?) { - var list = state.modelSourceRegistrations ?? [] - let idx = list.firstIndex(where: { $0.id == registration.id }) - let existing = idx.map { list[$0] }.flatMap { sameModelSourceRouting($0, registration) ? $0 : nil } - var merged = registration - var contributors = existing?.contributingClientIds ?? [] - if let clientId, !contributors.contains(clientId) { - contributors.append(clientId) - } - merged.contributingClientIds = contributors.isEmpty ? nil : contributors +/// Adds `source`, re-registers the entry with the same `id`, `provider`, +/// `format`, and `nonce` (keeping its host-reported fields), or updates an +/// entry where any of those differ. +func applyModelSourceSet(_ state: inout RootState, _ source: ModelSource) { + var list = state.modelSources ?? [] + let idx = list.firstIndex(where: { $0.id == source.id }) + let existing = idx.map { list[$0] }.flatMap { sameModelSourceVersion($0, source) ? $0 : nil } + var merged = source merged.state = existing?.state merged.credentialNonce = existing?.credentialNonce merged.credentialResource = existing?.credentialResource merged.credentialOrigins = existing?.credentialOrigins - merged.credentialId = existing?.credentialId + merged.accountId = existing?.accountId if let idx { list[idx] = merged } else { list.append(merged) } - state.modelSourceRegistrations = list -} - -/// Removes `clientId` from the contributors of the registration with `id`. -/// Returns `false` when no registration has `id`, or `clientId` doesn't -/// contribute it. -func applyModelSourceContributorRemoved(_ state: inout RootState, id: String, clientId: String) -> Bool { - guard var list = state.modelSourceRegistrations, - let idx = list.firstIndex(where: { $0.id == id }), - let contributors = list[idx].contributingClientIds, - contributors.contains(clientId) else { return false } - let remaining = contributors.filter { $0 != clientId } - list[idx].contributingClientIds = remaining.isEmpty ? nil : remaining - state.modelSourceRegistrations = list - return true + state.modelSources = list } -/// Whether two registrations have the same `provider`, `format`, and -/// `definition`. `AnyCodable` dictionaries compare regardless of key order. -private func sameModelSourceRouting(_ a: ModelSourceRegistration, _ b: ModelSourceRegistration) -> Bool { - a.provider == b.provider && a.format == b.format && a.definition == b.definition -} - -/// Removes the registration with `id`. Returns `false` when none matches. -func applyModelSourceRegistrationRemoved(_ state: inout RootState, id: String) -> Bool { - guard var list = state.modelSourceRegistrations, +/// Removes the model source with `id`. Returns `false` when none matches. +func applyModelSourceRemoved(_ state: inout RootState, id: String) -> Bool { + guard var list = state.modelSources, let idx = list.firstIndex(where: { $0.id == id }) else { return false } list.remove(at: idx) - state.modelSourceRegistrations = list + state.modelSources = list return true } -/// Updates the host-reported fields of the registration with `action.id`. +/// Whether two model sources have the same `provider`, `format`, and +/// definition `nonce`. +private func sameModelSourceVersion(_ a: ModelSource, _ b: ModelSource) -> Bool { + a.provider == b.provider && a.format == b.format && a.nonce == b.nonce +} + +/// Updates the host-reported fields of the model source with `action.id`. /// Returns `false` when none matches. func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelSourceStateChangedAction) -> Bool { - guard var list = state.modelSourceRegistrations, + guard var list = state.modelSources, let idx = list.firstIndex(where: { $0.id == action.id }) else { return false } list[idx].state = action.state list[idx].credentialNonce = action.credentialNonce list[idx].credentialResource = action.credentialResource list[idx].credentialOrigins = action.credentialOrigins - list[idx].credentialId = action.credentialId - state.modelSourceRegistrations = list + list[idx].accountId = action.accountId + state.modelSources = list return true } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index 13380aea0..7bf84752e 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -122,19 +122,14 @@ public func rootReducer(state: RootState, action: StateAction) -> RootState { next.config = config return next - case .rootModelSourceRegistrationSet(let a): + case .rootModelSourceSet(let a): var next = state - applyModelSourceRegistrationSet(&next, a.registration, clientId: a.clientId) + applyModelSourceSet(&next, a.modelSource) return next - case .rootModelSourceContributorRemoved(let a): + case .rootModelSourceRemoved(let a): var next = state - guard applyModelSourceContributorRemoved(&next, id: a.id, clientId: a.clientId) else { return state } - return next - - case .rootModelSourceRegistrationRemoved(let a): - var next = state - guard applyModelSourceRegistrationRemoved(&next, id: a.id) else { return state } + guard applyModelSourceRemoved(&next, id: a.id) else { return state } return next case .rootModelSourceStateChanged(let a): diff --git a/docs/.changes/20261123-model-source-registry-migration.json b/docs/.changes/20261123-model-source-registry-migration.json index 607e2a110..d9f663e27 100644 --- a/docs/.changes/20261123-model-source-registry-migration.json +++ b/docs/.changes/20261123-model-source-registry-migration.json @@ -1,6 +1,6 @@ { "type": "changed", - "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. `AuthenticateTarget` is now a union, so TypeScript code that reads `target.session` or `target.customizationId` must first narrow on `target.kind`. Direct Rust struct literals for `RootState` must now include `model_source_registrations: None`, and those for `AgentCapabilities` must include `model_source_registration: None`.", + "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. `AuthenticateTarget` is now a union, so TypeScript code that reads `target.session` or `target.customizationId` must first narrow on `target.kind`. Direct Rust struct literals for `RootState` must now include `model_sources: None`, and those for `AgentCapabilities` must include `model_source_registration: None`.", "targets": ["rust", "swift", "kotlin", "typescript"], "issues": [619] } diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index 4a40f38fd..ad86158c2 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can contribute bring-your-own-key model sources to the host through `RootState.modelSourceRegistrations` and the client-dispatchable `root/modelSourceRegistrationSet`, `root/modelSourceContributorRemoved`, and `root/modelSourceRegistrationRemoved` actions. Several clients can contribute one registration, listed in `contributingClientIds`, and a client that joins an unchanged definition keeps its status and credential. Clients deliver each source's credential with a `modelSource` `authenticate` target that echoes the registration's host-issued `credentialNonce` and names the key with a non-secret `credentialId`. The host reports status, `credentialResource`, `credentialOrigins`, and `credentialId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`), and ends turns on an unavailable source with the resumable `modelSourceUnavailable` error. Agents advertise the definition formats they read, the contributor grace period, and the principal policy with `AgentCapabilities.modelSourceRegistration`.", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSources` and the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. `root/modelSourceSet` carries the source's definition, which isn't kept in state, and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. `ModelSource.format` documents recognized values (`openaiCompatible`, `anthropic`, `azureOpenai`, `gemini`). Clients deliver each source's credential with a `modelSource` `authenticate` target that echoes the host-issued `credentialNonce`, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, `credentialOrigins`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`), and ends turns on an unavailable source with the resumable `modelSourceUnavailable` error. Agents advertise the definition formats they read, the contributor grace period, and the principal policy with `AgentCapabilities.modelSourceRegistration`.", "issues": [619] } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 10eb9f699..87bbda2eb 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -23,7 +23,7 @@ Individual action payloads do **not** carry their own `session: URI` or `termina ## Root Actions -These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceRegistrationSet`, `root/modelSourceContributorRemoved`, and `root/modelSourceRegistrationRemoved` are client-dispatchable; the rest are server-originated. +These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceSet`, and `root/modelSourceRemoved` are client-dispatchable; the rest are server-originated. | Type | Client-dispatchable? | When | |---|---|---| @@ -31,10 +31,9 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/activeSessionsChanged` | No | Count of active sessions changed | | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | -| `root/modelSourceRegistrationSet` | **Yes** | A client contributed a [model source registration](/specification/root-channel#model-source-registry): added, joined, or replaced by `id` | -| `root/modelSourceContributorRemoved` | **Yes** | A client withdrew its contribution to a registration, or left | -| `root/modelSourceRegistrationRemoved` | **Yes** | A model source registration was removed by `id` | -| `root/modelSourceStateChanged` | No | The host reported a registration's status and credential fields | +| `root/modelSourceSet` | **Yes** | A [model source](/specification/root-channel#model-source-registry) was added, re-registered, or updated by `id` | +| `root/modelSourceRemoved` | **Yes** | A model source was removed by `id` | +| `root/modelSourceStateChanged` | No | The host reported a model source's status and credential fields | ## Automation Catalogue Actions diff --git a/docs/guide/state-model.md b/docs/guide/state-model.md index bc0105dfa..bad458e7f 100644 --- a/docs/guide/state-model.md +++ b/docs/guide/state-model.md @@ -12,7 +12,7 @@ RootState { activeSessions?: number // count of non-disposed sessions terminals?: TerminalInfo[] // lightweight terminal catalogue config?: RootConfigState // host-level configuration - modelSourceRegistrations?: ModelSourceRegistration[] // registered model sources + modelSources?: ModelSource[] // registered model sources } ``` diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index 976049911..e4203744d 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -87,7 +87,7 @@ Different agents MAY require authentication with different providers. For exampl ## Token Delivery -Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `ModelSourceRegistration.credentialResource.resource`, which stays available while the source is ready for rotation and revocation (see [Model source credentials](#model-source-credentials)): +Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `ModelSource.credentialResource.resource`, which stays available while the source is ready for rotation and revocation (see [Model source credentials](#model-source-credentials)): ```jsonc // Client → Server @@ -150,14 +150,14 @@ If the token is invalid or the resource is unrecognized, the server MUST return ### Model source credentials -A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the registration carries host-reported credential fields in every state: +A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the model source carries host-reported credential fields in every state: - `credentialResource`: RFC 9728 metadata for the endpoint the credential is for; - `credentialOrigins`: every origin the host sends the credential to; -- `credentialNonce`: the registration's current generation; -- `credentialId`: the client-supplied ID of the key the host most recently accepted. +- `credentialNonce`: the source's current generation; +- `accountId`: the `accountId` the client sent with the key the host most recently accepted. -When the source needs a credential, the host also sets the registration's state to `ModelSourceAuthRequiredState`, with a `reason`. A client answers with a `modelSource` target that names the registration, echoes its current `credentialNonce`, and names the key with a non-secret `credentialId`: +When the source needs a credential, the host also sets the source's state to `ModelSourceAuthRequiredState`, with a `reason`. A client answers with a `modelSource` target that names the source and echoes its current `credentialNonce`, and names the key with the existing `accountId` parameter: ```jsonc // Model source credential delivery @@ -169,40 +169,40 @@ When the source needs a credential, the host also sets the registration's state "channel": "ahp-root://", "resource": "https://api.example.com/v1", "token": "", + "accountId": "keychain-5c2a", "target": { "kind": "modelSource", "modelSourceId": "2f6c0e1a-model-source", - "credentialNonce": "9b41d7", - "credentialId": "keychain-5c2a" + "credentialNonce": "9b41d7" } } } ``` -The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the registration's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `scopes`. `credentialResource.resource_name` labels the prompt, for example "OpenRouter API key". +The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the source's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `scopes`. `credentialResource.resource_name` labels the prompt, for example "OpenRouter API key". `credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Where the host actually sends the credential is governed by `credentialOrigins` and the egress rules below. -`credentialId` is chosen by the client, for example a hash of where it stores the key. It MUST NOT be derived from the secret, because every client can read it. Clients SHOULD include it when they deliver a credential, and omit it when they revoke one. It lets a client that reloads, or one on another device, tell whether the host holds its current key. +Clients SHOULD include `accountId` when they deliver a credential, and omit it when they revoke one. The host publishes it as the source's `accountId`, which lets a client that reloads, or one on another device, tell whether the host holds its current key. It's opaque and MUST NOT be derived from the secret, because every client can read it. For an API key that has no account of its own, a client uses an ID that changes whenever the user replaces the key, such as one derived from where it stores the key and when the key last changed. [Host-owned authentication](https://github.com/microsoft/agent-host-protocol/pull/404) may later supersede the `modelSource` target and this use of `accountId`. When `target.kind` is `modelSource`, the host: -- MUST apply the credential only to that registration, never to other registrations, MCP servers, or agent-level resources, even when they share `resource`; -- MUST require `resource` to equal the registration's current `credentialResource.resource`; +- MUST apply the credential only to that model source, never to other model sources, MCP servers, or agent-level resources, even when they share `resource`; +- MUST require `resource` to equal the source's current `credentialResource.resource`; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); -- MUST reject a `credentialNonce` other than the one it most recently issued for that registration with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; -- MUST publish the target's `credentialId` as the registration's `credentialId` when it accepts a credential; +- MUST reject a `credentialNonce` other than the one it most recently issued for that source with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; +- MUST publish the request's `accountId` as the source's `accountId` when it accepts a credential, and clear it when the request has none; - MUST treat an empty `token` as revocation: it stops using the credential at once, drops it, and reports `authRequired` with `reason: revoked`. -Any client may deliver or revoke a registration's credential, as any client may answer an MCP server's challenge. A host whose `principalPolicy` is `isolated` rejects a credential for another principal's registration with `PermissionDenied` (`-32009`). +Any client may deliver or revoke a model source's credential, as any client may answer an MCP server's challenge. A host whose `principalPolicy` is `isolated` rejects a credential for another principal's source with `PermissionDenied` (`-32009`). -`credentialNonce` fences every credential change, and works as the registration's generation. The host issues a new nonce whenever a registration is added, including one registered again under a removed `id`, and whenever its `provider`, `format`, or `definition` changes, whether or not it held a credential. It also issues one whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation. It never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: +`credentialNonce` fences every credential change, and works as the source's generation. The host issues a new nonce whenever a source is added, including one registered again under a removed `id`, and whenever `root/modelSourceSet` updates it, whether or not it held a credential. It also issues one whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation. It never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: - a key meant for an old definition never reaches a new one, even when the endpoint didn't change; - a rotation that crosses a revocation can't undo the revocation; - when two clients answer the same `authRequired`, the first wins, and the second gets `Conflict`, re-reads state, and finds the source ready. -The host tags every agent operation on the registration with the current nonce and discards any result, success or failure, that carries an older one. A late failure can't drop a key that has since replaced it, and a late success can't mark a changed or re-registered source `ready`, even after an edit that changes the definition back. +The host tags every agent operation on the source with the current nonce and discards any result, success or failure, that carries an older one. A late failure can't drop a key that has since replaced it, and a late success can't mark an updated or re-added source `ready`, even after an edit that changes the definition back. #### Reasons @@ -212,34 +212,34 @@ An `authRequired` state's `reason` is a `ModelSourceAuthRequiredReason`, specifi | --- | --- | --- | | `required` | The host holds no credential yet. | Its key. | | `expired` | The credential's lifetime or lease lapsed. | A renewed credential: a fresh token, or the same static key with a new lease. | -| `rejected` | The endpoint refused the credential. `credentialId` still names it. | Only a key whose `credentialId` differs. Otherwise it asks the user for a new one. | +| `rejected` | The endpoint refused the credential. `accountId` still names it. | Only a key whose `accountId` differs. Otherwise it asks the user for a new one. | | `revoked` | A client revoked the credential. | Nothing, until a user asks. | `expiresIn` keeps its meaning for short-lived tokens. With a static key, it's a lease: the host drops the key when the lease elapses and reports `expired`, and a client renews the lease by sending the key again. An API key without a lease omits `expiresIn`. #### Delivering -Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers a credential only in answer to the registration's current state, reading it from its own secure storage or token provider each time: +Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers a credential only in answer to the source's current state, reading it from its own secure storage or token provider each time: - when the state is `authRequired`, as the table above allows; -- when the state is `starting` or `ready`, and the registration's `credentialId` names a key this client has since replaced, for example one it delivered before the user changed it. A client whose key simply differs leaves the host's credential alone, so two devices with different working keys don't replace each other's in turn; +- when the state is `starting` or `ready`, and the source's `accountId` names a key this client has since replaced, for example one it delivered before the user changed it. A client whose key simply differs leaves the host's credential alone, so two devices with different working keys don't replace each other's in turn; - when a lease or token it delivered is about to expire. -Clients SHOULD NOT prompt the user for a key they don't have. A client MUST NOT send a stored secret unless the registration's `provider`, `format`, and `definition` match its own copy, and every origin in `credentialOrigins` is one its own copy of the definition sends the key to. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. +Clients SHOULD NOT prompt the user for a key they don't have. A client MUST NOT send a stored secret unless the source's `provider`, `format`, and `nonce` match its own copy, and every origin in `credentialOrigins` is one its own copy of the definition sends the key to. The host derives `credentialOrigins` from the definition it actually holds, so the origin check doesn't depend on another client choosing `nonce` honestly. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. #### Handling and egress -The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the registration's `definition`, `_meta`, or credential fields, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. +The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the definition, the source's `nonce`, `_meta`, or credential fields, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. -The host attaches the credential only to that source's requests, as its definition specifies, and only to origins in `credentialOrigins`, never to another origin, including on redirect. It drops the credential when the registration is removed, when its `provider`, `format`, or `definition` changes, when it's revoked, when its lease lapses, and when the host restarts. +The host attaches the credential only to that source's requests, as its definition specifies, and only to origins in `credentialOrigins`, never to another origin, including on redirect. It drops the credential when the source is removed, when `root/modelSourceSet` updates it, when it's revoked, when its lease lapses, and when the host restarts. Endpoints in a definition, including loopback and private addresses, are resolved and reached from the host machine: `localhost` in a source registered with a remote host is that host, not the client's machine. Hosts SHOULD apply an egress policy to registered endpoints: deny link-local and cloud metadata addresses, and require `https` for any credentialed endpoint that isn't a loopback address, unless the host has opted in to plain `http`. #### Turns -When a turn can't use its source, because the credential is missing, expired, rejected, or revoked, or because the source was withdrawn or removed, the host ends the turn with `chat/error`. The error part's `error.errorType` is `modelSourceUnavailable`, and `resumable` is `true`. A client tells why from the registration of the turn's model: its `state`, or its absence. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first. The host never switches the turn to a different model. +When a turn can't use its source, because the credential is missing, expired, rejected, or revoked, or because the source was removed, the host ends the turn with `chat/error`. The error part's `error.errorType` is `modelSourceUnavailable`, and `resumable` is `true`. A client tells why from the registered source of the turn's model: its `state`, or its absence. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first. The host never switches the turn to a different model. -When the last contributing client leaves a `contributingClient`-retained source, turns already running on it finish, and no new ones start. When a client's withdrawal leaves a source with no contributors, when any client removes it, or when a client revokes its credential, the host stops using the credential immediately and ends every running turn that uses it with the `modelSourceUnavailable` error. +When the last contributing client leaves a `contributingClient`-retained source, turns already running on it finish, and no new ones start. When any client removes the source, or revokes its credential, the host stops using the credential immediately and ends every running turn that uses it with the `modelSourceUnavailable` error. ### Why keyed by `resource` and optional `target`? diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index b9f512240..d6beda33c 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -22,7 +22,7 @@ RootState { activeSessions?: number terminals?: TerminalInfo[] config?: RootConfigState - modelSourceRegistrations?: ModelSourceRegistration[] + modelSources?: ModelSource[] } ``` @@ -30,7 +30,7 @@ RootState { - `activeSessions` — count of non-disposed sessions. Lightweight badge counter. - `terminals` — lightweight per-terminal metadata for rendering a terminal manager UI without subscribing to every terminal. See [Terminal Channel](/specification/terminal-channel) for the full state. - `config` — host-level configuration schema and current values. -- `modelSourceRegistrations` — model sources clients or the host registered. See [Model source registry](#model-source-registry). +- `modelSources` — model sources clients or the host registered. See [Model source registry](#model-source-registry). The session list is **not** part of root state. Clients fetch it imperatively via [`listSessions`](/reference/root#listsessions) and patch it from `root/*` notifications described below. @@ -63,16 +63,15 @@ A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, ### Model source registry -Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSourceRegistrations`](/reference/root#modelsourceregistration), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads, how long the host keeps a disconnected client's contributions (`gracePeriod`), and whether clients of different principals share the registry (`principalPolicy`). +Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSources`](/reference/root#modelsource), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads, how long the host keeps counting a disconnected client (`gracePeriod`), and whether clients of different principals share the registry (`principalPolicy`). ```json { "id": "2f6c0e1a-model-source", "provider": "example", "displayName": "OpenRouter", - "format": "example.com/model-source@1", - "definition": { "baseUrl": "https://openrouter.ai/api/v1" }, - "contributingClientIds": ["laptop-window-1", "laptop-window-2"], + "format": "openaiCompatible", + "nonce": "sha256-4f1c9a", "retention": "host", "state": { "kind": "ready" }, "credentialNonce": "9b41d7", @@ -81,84 +80,85 @@ Clients can register bring-your-own-key model sources with the host, so its agen "resource_name": "OpenRouter API key" }, "credentialOrigins": ["https://openrouter.ai"], - "credentialId": "keychain-5c2a" + "accountId": "keychain-5c2a" } ``` -`definition` says how to reach the source, in `format`. AHP doesn't define, standardize, or name any definition format: `format` and `definition` are opaque to AHP and belong to the agent that reads them. A definition MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). +A model source's `format` names the format of its definition. AHP recognizes `openaiCompatible`, `anthropic`, `azureOpenai`, and `gemini`, following the pattern of `Changeset.changeKind`, but doesn't define what a definition contains, even for those. Agents MAY read other formats, named with a namespace such as `example.com/model-source@1`. The definition itself is opaque to AHP and belongs to the agent. It travels only on `root/modelSourceSet`, and the reducer stores the source without it. Clients compare `nonce`, an opaque version token for the definition, with their own copy instead. Actions are broadcast and replayed, so the definition is never secret, and it MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). -#### Contributing +#### Registering, updating, and removing -Several clients, such as two windows or two devices, can want the same source. Each one contributes it with `root/modelSourceRegistrationSet` and its own `clientId`, and each one withdraws only its own contribution with `root/modelSourceContributorRemoved`. `root/modelSourceRegistrationRemoved` removes a registration for every contributor. +A client registers a source with `root/modelSourceSet { modelSource, definition }`, and removes it with `root/modelSourceRemoved { id }`. The reducers follow the keyed-collection convention, with one twist so that re-registering the same definition doesn't disturb a working source: -A registration's routing is its `provider`, `format`, and `definition`, with definitions compared as JSON values: object key order is ignored, and numbers compare by numeric value, so `1` equals `1.0`. The reducers apply the actions as follows: +- **Add.** When no model source has the `id`, `Set` appends `modelSource`. +- **Re-register.** When one has, with the same `provider`, `format`, and `nonce`, `Set` keeps its host-reported fields (`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and `accountId`) and takes `displayName`, `icons`, `retention`, and `_meta` from the action. +- **Update.** When any of the three differs, `Set` replaces the source. Its host-reported fields are absent until the host reports again. +- **Remove.** `Removed` deletes the source by `id`, or returns the state unchanged. -- **Add.** When no registration has the `id`, `Set` appends it, with `contributingClientIds` set to `[clientId]`, or absent when there's no `clientId`. -- **Join.** When one has, and its routing is unchanged, `Set` keeps its host-reported fields (`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and `credentialId`), adds `clientId` to `contributingClientIds` if it isn't there, and takes `displayName`, `icons`, `retention`, and `_meta` from the action. Joining doesn't disturb the status, nonce, or credential. -- **Replace.** When the routing changed, `Set` replaces the registration, with `contributingClientIds` set to `[clientId]`. Its host-reported fields are absent until the host reports again. -- **Withdraw.** `root/modelSourceContributorRemoved` removes `clientId` from `contributingClientIds`, leaving the field absent when no contributor remains. It never removes the registration. -- **Remove.** `Removed` deletes the registration by `id`. Both are no-ops when nothing matches. +A client dispatches `Set` with no host-reported fields, when it starts or reconnects with the source configured, and when the user changes the source. Re-registering an unchanged source is how a second window, a reloaded window, or another device with the same source configured becomes a contributing client. When clients disagree on `displayName`, `icons`, `retention`, or `_meta`, the last `Set` wins. A client SHOULD derive `id` from a stable key in its own configuration, and `nonce` from the definition, for example as a hash of it. A client SHOULD NOT update a source whose `nonce` differs from its own copy unless the user changed the source in its configuration, and SHOULD NOT add back a source another client removed except when it starts or reconnects, or two clients with different configurations would replace each other's source indefinitely. -A client dispatches `Set` with its own `clientId`, and without `contributingClientIds` or any host-reported field, when it starts with the source configured and isn't already a contributor. When contributors disagree on `displayName`, `icons`, `retention`, or `_meta`, the last `Set` wins. A client SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one registration. A client SHOULD NOT replace a registration whose routing differs from its own copy unless the user changed the source in its configuration, or two clients with different configurations would replace each other indefinitely. When the user removes a source, the client withdraws its own contribution, and dispatches `Removed` only to remove the source for everyone. +When the user removes the source from a client's configuration, the client dispatches `Removed`. Removal applies to every client. A client that still has the source configured registers it again the next time it starts or reconnects. The host rejects a client's `Set`, through `rejectionReason`, when: - the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; -- `clientId` is absent or isn't the dispatching client's ID; -- the registration includes `contributingClientIds` or any host-reported field; -- `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same registration doesn't count, so a ready registration can still be joined or changed; +- `modelSource` includes any host-reported field; +- its `provider`, `format`, and `nonce` match the existing source's, but `definition` differs from the definition the host holds. A re-registration must not carry a different definition, because reducers keep the credential for it; +- `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same source doesn't count, so a ready source can still be re-registered or updated; - the host won't honor the requested `retention`. The client can register again with `contributingClient` retention; - the host registered the source itself; -- the host's `principalPolicy` is `isolated`, and the registration belongs to another principal. +- the host's `principalPolicy` is `isolated`, and the source belongs to another principal. -The host rejects a client's `root/modelSourceContributorRemoved` whose `clientId` isn't the dispatching client's ID. A host MAY reject a client's `Removed` for a source it registered itself or one that belongs to another principal. +A host MAY reject a client's `Removed` for a source it registered itself or one that belongs to another principal. -When a client's own withdrawal leaves a registration with no contributors, the host removes it with `Removed`, whatever its retention. When a `Set` replaces a registration's routing, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A join, or a change to `displayName`, `icons`, `retention`, or `_meta`, keeps the credential and the nonce. A host may also register sources itself. Those registrations have no contributing clients, and their retention behaves as `host`. +The host tracks contributing clients itself, from each `Set`'s `ActionEnvelope.origin`, and they aren't in state. An add or a re-registration adds the dispatching client. An update makes the dispatching client the only one, because the others registered a different definition. When `Set` updates a source, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A re-registration, or a change to `displayName`, `icons`, `retention`, or `_meta`, keeps the credential and the nonce. A host may also register sources itself. Those sources have no contributing clients, and their retention behaves as `host`. #### Status -The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets the host-reported fields together: the registration's `state` (`starting`, `ready`, `authRequired`, or `error`), its `credentialNonce`, and its `credentialResource`, `credentialOrigins`, and `credentialId`, which an absent value clears. It never reports status by dispatching the registration back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed registration or overwrite a newer definition. +The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets the host-reported fields together: the source's `state` (`starting`, `ready`, `authRequired`, or `error`), its `credentialNonce`, and its `credentialResource`, `credentialOrigins`, and `accountId`, which an absent value clears. It never reports status by dispatching the source back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed source or overwrite a newer one. An `authRequired` state carries a `reason` specific to model sources: `required` (no credential yet), `expired` (its lifetime or lease lapsed), `rejected` (the endpoint refused it), or `revoked` (a client revoked it). See [Model source credentials](/specification/authentication#model-source-credentials) for what clients do with each. -`credentialNonce` is the registration's generation. The host issues a new one when a registration is added, including under a removed `id`, when its routing changes, and whenever it installs or drops a credential. It tags every agent operation on the registration, such as validation, model discovery, and inference, with the current nonce, and discards any result, success or failure, that carries an older one. A slow result from before a change therefore can't mark the current registration `ready`, even when the definition has changed back to the same value. +`credentialNonce` is the source's generation. The host issues a new one when a source is added, including under a removed `id`, when `Set` updates it, and whenever it installs or drops a credential. It tags every agent operation on the source, such as validation, model discovery, and inference, with the current nonce, and discards any result, success or failure, that carries an older one. A slow result from before an update therefore can't mark the current source `ready`, even when the definition has changed back to the same value. -`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for, and `credentialOrigins` lists every origin the host sends the credential to. The host reports both in every state while the source takes a credential, so any client can check, deliver, rotate, or revoke one, and leaves them absent for a source that needs none. `credentialId` names the key the host most recently accepted. +`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for, and `credentialOrigins` lists every origin the host sends the credential to, derived from the definition the host holds. The host reports both in every state while the source takes a credential, so any client can check, deliver, rotate, or revoke one, and leaves them absent for a source that needs none. `accountId` names the key the host most recently accepted. #### Catalog -When a registration is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the registration's `id` and `displayName`, and its models in `models` with `modelSourceId` set to that `id`. `modelSourceId` alone doesn't mark a registered source, because an agent's own sources use it too. A source is registered when `modelSourceRegistrations` has an entry with that `id` whose `provider` is the agent. +When a registered source is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the source's `id` and `displayName`, and its models in `models` with `modelSourceId` set to that `id`. `modelSourceId` alone doesn't mark a registered source, because an agent's own sources use it too. A source is registered when `modelSources` has an entry with that `id` whose `provider` is the agent. -Once the registration has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the registration is removed, when its last contributing client leaves under `contributingClient` retention, when it enters `error`, or when a routing change mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). The host MAY list the `ModelSourceInfo` in any state. +**Built-in sources.** A source the agent provides itself, such as a first-party service that ships with the agent, stays an agent-declared `ModelSourceInfo`. The host lists it and its models in `AgentInfo` directly, and its sign-in uses `AgentInfo.protectedResources` and an untargeted `authenticate`. It isn't a registered source. Clients register sources only for configuration the agent doesn't have. -Any client can select a registered source's models, in any session whose agent is the registration's `provider`. The host checks every selection: the model is listed, the chat is backed by the registration's agent provider, and, under `isolated`, the turn's client acts for the registration's principal. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. A turn that can't use its source ends with the resumable `modelSourceUnavailable` error, as described in [Model source credentials](/specification/authentication#model-source-credentials). +Once a registered source has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the source is removed, when its last contributing client leaves under `contributingClient` retention, when it enters `error`, or when an update mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). The host MAY list the `ModelSourceInfo` in any state. + +Any client can select a registered source's models, in any session whose agent is the source's `provider`. The host checks every selection: the model is listed, the chat is backed by the source's agent provider, and, under `isolated`, the turn's client acts for the source's principal. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. A turn that can't use its source ends with the resumable `modelSourceUnavailable` error, as described in [Model source credentials](/specification/authentication#model-source-credentials). #### Retention -The contributing clients choose what happens when the last of them leaves. Absent means `contributingClient`, the narrower choice. +The client that registers a source chooses what happens when the last contributing client leaves. Absent means `contributingClient`, the narrower choice. -A contributing client leaves when its connection closes and it doesn't reconnect with the same `clientId` within the host's `gracePeriod`. The host then dispatches `root/modelSourceContributorRemoved` for it. While other contributors remain, nothing else changes. When the last contributor leaves: +A contributing client leaves when its connection closes and it doesn't reconnect with the same `clientId` within the host's `gracePeriod`. While other contributing clients remain, nothing changes. When the last one leaves: -- With `contributingClient`, the source goes away, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the registration and drops its credential. -- With `host`, the source stays, like a host-declared MCP server, with its credential in memory and no contributors, until a client removes it, a client that joins later withdraws, or host policy expires it. A restart drops its credential, as described below. +- With `contributingClient`, the source goes away, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the source with `root/modelSourceRemoved` and drops its credential. +- With `host`, the source stays, like a host-declared MCP server, with its credential in memory and no contributing clients, until a client removes it or host policy expires it. A restart drops its credential, as described below. -Explicit withdrawal is different from leaving: when the last contributor withdraws, the source goes away whatever its retention, so `host` retention doesn't leave sources nobody wants. The host MAY expire `host`-retained registrations. +When the user removes the source from their configuration, their client removes it, whatever its retention, so `host` retention doesn't leave sources nobody wants. The host MAY expire `host`-retained sources. -A client that reconnects with the same `clientId` within the grace period is still listed. A client that comes back with a new `clientId` and the same configuration joins with `Set`, which keeps the status, nonce, and credential. After a restart, a host that persists its state SHOULD keep `host`-retained registrations, which come back through `starting`, and reach `authRequired` with `reason: required` only if they need a credential. +A client that reconnects with the same `clientId` within the grace period is still counted. A client that comes back with a new `clientId` and the same configuration re-registers with `Set`, which keeps the status, nonce, and credential. After a restart, a host that persists its state SHOULD keep `host`-retained sources and their definitions, which come back through `starting`, and reach `authRequired` with `reason: required` only if they need a credential. #### Principals -AHP doesn't verify which client is which, so with `principalPolicy` `shared`, or absent, every connected client may change, supply credentials for, and select every registration, as with MCP servers. Where a host can verify principals, it MAY restrict changes, credentials, and use of a registration to clients of the principal that registered it, and advertises `isolated`. Root state still lists every registration to every client, so a definition is never private. A host whose connections carry credentials scoped to one client, such as a relay that forwards each client's own sign-in, SHOULD NOT let one client's registration be used by another: it uses `isolated`, or doesn't advertise `modelSourceRegistration`. +AHP doesn't verify which client is which, so with `principalPolicy` `shared`, or absent, every connected client may change, supply credentials for, and select every model source, as with MCP servers. Where a host can verify principals, it MAY restrict changes, credentials, and use of a model source to clients of the principal that registered it, and advertises `isolated`. Root state still lists every model source to every client, and the action stream carries every definition, so neither is private. A host whose connections carry credentials scoped to one client, such as a relay that forwards each client's own sign-in, SHOULD NOT let one client's model source be used by another: it uses `isolated`, or doesn't advertise `modelSourceRegistration`. #### Reserved model IDs -Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registration, that ID is bound to that registration and its upstream model for as long as the host keeps state, including after the registration is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same registration comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a `definition` change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when a different client made the change. +Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registered source, that ID is bound to that source and its upstream model for as long as the host keeps state, including after the source is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same source comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a definition change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when a different client made the change. -A host SHOULD derive each model's ID deterministically from the registration (its `id`, `provider`, and `format`), the endpoint, and the endpoint's model identifier, for example with a hash. The same model then gets the same ID when its source is registered again or the host restarts, without a stored table, and a moved endpoint gets a new one. +A host SHOULD derive each model's ID deterministically from the source (its `id`, `provider`, and `format`), the endpoint, and the endpoint's model identifier, for example with a hash. The same model then gets the same ID when its source is registered again or the host restarts, without a stored table, and a moved endpoint gets a new one. #### Automations -An automation may name a registered source's model when the registration has `host` retention, or was registered by the host. The host SHOULD reject an automation create or update that names a model from a `contributingClient`-retained registration, because the automation would outlive the source. If the source isn't `ready` when a run starts, the run fails through the automation run lifecycle. +An automation may name a registered source's model when the source has `host` retention, or was registered by the host. The host SHOULD reject an automation create or update that names a model from a `contributingClient`-retained source, because the automation would outlive the source. If the source isn't `ready` when a run starts, the run fails through the automation run lifecycle. ### Paginating the catalogue @@ -211,7 +211,7 @@ target channel instead. | `root/sessionSummaryChanged` | server → client notification | Session catalogue entry mutated. | | `root/progress` | server → client notification | Generic progress for a long-running operation a client opted into (e.g. an SDK download). | | `unsubscribe` | client → server notification | Stop receiving root-channel messages. | -| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceRegistrationSet`, `root/modelSourceContributorRemoved`, or `root/modelSourceRegistrationRemoved`. | +| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceSet`, or `root/modelSourceRemoved`. | `auth/required` may also be emitted on `ahp-root://` when the auth requirement is root-scoped; see [Authentication](/specification/authentication). @@ -226,9 +226,8 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/activeSessionsChanged` | Server | Replaces `activeSessions` | | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | -| `root/modelSourceRegistrationSet` | Server / Client | Adds, joins, or replaces a registration in `modelSourceRegistrations` by `id`, maintaining `contributingClientIds` | -| `root/modelSourceContributorRemoved` | Server / Client | Removes one client from a registration's `contributingClientIds` | -| `root/modelSourceRegistrationRemoved` | Server / Client | Removes a registration by `id` | +| `root/modelSourceSet` | Server / Client | Adds, re-registers, or updates a source in `modelSources` by `id`. The definition isn't stored | +| `root/modelSourceRemoved` | Server / Client | Removes a source by `id` | | `root/modelSourceStateChanged` | Server | Sets a registration's host-reported fields. A no-op for an unknown `id` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index df640d286..db6417b70 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -127,59 +127,39 @@ "config" ] }, - "RootModelSourceRegistrationSetAction": { + "RootModelSourceSetAction": { "type": "object", - "description": "Contributes a model source registration for `clientId`. A registration's\nrouting is its `provider`, `format`, and `definition`, with definitions\ncompared as JSON values: object key order is ignored, and numbers compare\nby numeric value, so `1` equals `1.0`.\n\n- **Add.** When no registration has the `id`, appends it, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`.\n- **Join.** When one has, and its routing is unchanged, keeps its\n host-reported fields (`state`, `credentialNonce`, `credentialResource`,\n `credentialOrigins`, and `credentialId`), adds `clientId` to\n `contributingClientIds` if it isn't there, and takes the other fields\n from the action.\n- **Replace.** When the routing changed, replaces the registration, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`. Its host-reported fields are absent until the host reports\n again with {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this with its own `clientId`, and without\n`contributingClientIds` or any host-reported field.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`. The reducer\nstores `modelSource` without the definition:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialNonce`,\n `credentialResource`, `credentialOrigins`, and `accountId`) and takes\n the other fields from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRegistrationSet" + "const": "root/modelSourceSet" }, - "registration": { - "$ref": "#/$defs/ModelSourceRegistration", - "description": "The registration to contribute, matched by `id`." + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or update, matched by `id`, without host-reported fields." }, - "clientId": { - "type": "string", - "description": "The contributing client. Absent when the host registers the source\nitself." - } - }, - "required": [ - "type", - "registration" - ] - }, - "RootModelSourceContributorRemovedAction": { - "type": "object", - "description": "Withdraws one client's contribution to a model source registration:\nremoves `clientId` from `contributingClientIds`, leaving the field absent\nwhen no contributor remains. A no-op when no registration has `id`, or\n`clientId` doesn't contribute it. It never removes the registration.\n\nA client dispatches this with its own `clientId`. The host dispatches it\nwhen a contributing client leaves.\n\nStability: 1.0 - Early development.", - "properties": { - "type": { - "const": "root/modelSourceContributorRemoved" - }, - "id": { - "type": "string", - "description": "The registration's `id`." - }, - "clientId": { - "type": "string", - "description": "The contributing client to remove." + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `modelSource.format`: endpoint, wire format,\nmodels, and so on. The host hands it to the agent, and the reducer\ndoesn't store it. MUST NOT contain a credential." } }, "required": [ "type", - "id", - "clientId" + "modelSource", + "definition" ] }, - "RootModelSourceRegistrationRemovedAction": { + "RootModelSourceRemovedAction": { "type": "object", - "description": "Removes the model source registration with the given `id` for every\ncontributor. A no-op when none matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `id`, for every client. A no-op\nwhen none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRegistrationRemoved" + "const": "root/modelSourceRemoved" }, "id": { "type": "string", - "description": "The registration's `id`." + "description": "The model source's `id`." } }, "required": [ @@ -189,14 +169,14 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's host-reported fields together:\n`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`credentialId`. A no-op when no registration has `id`. Other fields of the\nregistration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`accountId`. A no-op when no model source has `id`. Other fields of the\nsource are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" }, "id": { "type": "string", - "description": "The registration's `id`." + "description": "The model source's `id`." }, "state": { "$ref": "#/$defs/ModelSourceState", @@ -204,22 +184,22 @@ }, "credentialNonce": { "type": "string", - "description": "The registration's current credential nonce." + "description": "The model source's current credential nonce." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." + "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." }, "credentialOrigins": { "type": "array", "items": { "$ref": "#/$defs/URI" }, - "description": "Replaces the registration's `credentialOrigins`. Absent clears it." + "description": "Replaces the source's `credentialOrigins`. Absent clears it." }, - "credentialId": { + "accountId": { "type": "string", - "description": "Replaces the registration's `credentialId`. Absent clears it." + "description": "Replaces the source's `accountId`. Absent clears it." } }, "required": [ @@ -3383,12 +3363,12 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, - "modelSourceRegistrations": { + "modelSources": { "type": "array", "items": { - "$ref": "#/$defs/ModelSourceRegistration" + "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -3507,7 +3487,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -3569,7 +3549,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -3607,11 +3587,11 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." }, "gracePeriod": { "type": "integer", - "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", "minimum": 0 }, "principalPolicy": { @@ -3623,9 +3603,9 @@ "formats" ] }, - "ModelSourceRegistration": { + "ModelSource": { "type": "object", - "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -3648,19 +3628,11 @@ }, "format": { "type": "string", - "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." + "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." }, - "contributingClientIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." + "nonce": { + "type": "string", + "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -3668,11 +3640,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", @@ -3683,16 +3655,16 @@ "items": { "$ref": "#/$defs/URI" }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." }, - "credentialId": { + "accountId": { "type": "string", - "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." }, "_meta": { "type": "object", "additionalProperties": {}, - "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ @@ -3700,7 +3672,7 @@ "provider", "displayName", "format", - "definition" + "nonce" ] }, "ModelSourceStartingState": { @@ -3717,7 +3689,7 @@ }, "ModelSourceReadyState": { "type": "object", - "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "ready" @@ -3729,7 +3701,7 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -3746,7 +3718,7 @@ }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the model source's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -9230,7 +9202,7 @@ "$ref": "#/$defs/ModelSourceErrorState" } ], - "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, "SessionOrigin": { "$ref": "#/$defs/AutomationSessionOrigin", @@ -9796,13 +9768,10 @@ "$ref": "#/$defs/RootConfigChangedAction" }, { - "$ref": "#/$defs/RootModelSourceRegistrationSetAction" - }, - { - "$ref": "#/$defs/RootModelSourceContributorRemovedAction" + "$ref": "#/$defs/RootModelSourceSetAction" }, { - "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" + "$ref": "#/$defs/RootModelSourceRemovedAction" }, { "$ref": "#/$defs/RootModelSourceStateChangedAction" @@ -10218,7 +10187,7 @@ "host" ], "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." + "description": "How long a registered model source lasts once its last contributing client\nleaves." }, "ModelSourceAuthRequiredReason": { "enum": [ diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 4d0f11411..485f57b31 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1062,15 +1062,11 @@ }, "modelSourceId": { "type": "string", - "description": "The registration's `ModelSourceRegistration.id`." + "description": "The registration's `ModelSource.id`." }, "credentialNonce": { "type": "string", - "description": "The registration's current `ModelSourceRegistration.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." - }, - "credentialId": { - "type": "string", - "description": "A client-chosen, non-secret ID for the credential, such as a hash of\nwhere the client stores the key. The host publishes it as the\nregistration's `ModelSourceRegistration.credentialId`, so a client can\ntell whether the host holds its current key. Clients SHOULD include it\nwhen delivering a credential, and omit it when revoking one. MUST NOT be\nderived from the secret." + "description": "The registration's current `ModelSource.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." } }, "required": [ @@ -1081,7 +1077,7 @@ }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSourceRegistration.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSource.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -1096,7 +1092,7 @@ }, "resource": { "type": "string", - "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceRegistration.credentialResource`." + "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSource.credentialResource`." }, "token": { "type": "string", @@ -1120,7 +1116,7 @@ }, "accountId": { "type": "string", - "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.", + "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.\n\nWith a `modelSource` target, clients SHOULD include it when delivering a\ncredential and omit it when revoking one, and the host publishes it as\nthe source's `ModelSource.accountId`. It MUST NOT be derived from the\nsecret. For an API key with no account of its own, a client uses an ID\nthat changes whenever the user replaces the key.", "minLength": 1 } }, @@ -2674,12 +2670,12 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, - "modelSourceRegistrations": { + "modelSources": { "type": "array", "items": { - "$ref": "#/$defs/ModelSourceRegistration" + "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -2798,7 +2794,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -2860,7 +2856,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -2898,11 +2894,11 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." }, "gracePeriod": { "type": "integer", - "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", "minimum": 0 }, "principalPolicy": { @@ -2914,9 +2910,9 @@ "formats" ] }, - "ModelSourceRegistration": { + "ModelSource": { "type": "object", - "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -2939,19 +2935,11 @@ }, "format": { "type": "string", - "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." + "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." - }, - "contributingClientIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." + "nonce": { + "type": "string", + "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -2959,11 +2947,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", @@ -2974,16 +2962,16 @@ "items": { "$ref": "#/$defs/URI" }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." }, - "credentialId": { + "accountId": { "type": "string", - "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." }, "_meta": { "type": "object", "additionalProperties": {}, - "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ @@ -2991,7 +2979,7 @@ "provider", "displayName", "format", - "definition" + "nonce" ] }, "ModelSourceStartingState": { @@ -3008,7 +2996,7 @@ }, "ModelSourceReadyState": { "type": "object", - "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "ready" @@ -3020,7 +3008,7 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -3037,7 +3025,7 @@ }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the model source's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -8592,59 +8580,39 @@ "config" ] }, - "RootModelSourceRegistrationSetAction": { + "RootModelSourceSetAction": { "type": "object", - "description": "Contributes a model source registration for `clientId`. A registration's\nrouting is its `provider`, `format`, and `definition`, with definitions\ncompared as JSON values: object key order is ignored, and numbers compare\nby numeric value, so `1` equals `1.0`.\n\n- **Add.** When no registration has the `id`, appends it, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`.\n- **Join.** When one has, and its routing is unchanged, keeps its\n host-reported fields (`state`, `credentialNonce`, `credentialResource`,\n `credentialOrigins`, and `credentialId`), adds `clientId` to\n `contributingClientIds` if it isn't there, and takes the other fields\n from the action.\n- **Replace.** When the routing changed, replaces the registration, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`. Its host-reported fields are absent until the host reports\n again with {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this with its own `clientId`, and without\n`contributingClientIds` or any host-reported field.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`. The reducer\nstores `modelSource` without the definition:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialNonce`,\n `credentialResource`, `credentialOrigins`, and `accountId`) and takes\n the other fields from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRegistrationSet" + "const": "root/modelSourceSet" }, - "registration": { - "$ref": "#/$defs/ModelSourceRegistration", - "description": "The registration to contribute, matched by `id`." + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or update, matched by `id`, without host-reported fields." }, - "clientId": { - "type": "string", - "description": "The contributing client. Absent when the host registers the source\nitself." - } - }, - "required": [ - "type", - "registration" - ] - }, - "RootModelSourceContributorRemovedAction": { - "type": "object", - "description": "Withdraws one client's contribution to a model source registration:\nremoves `clientId` from `contributingClientIds`, leaving the field absent\nwhen no contributor remains. A no-op when no registration has `id`, or\n`clientId` doesn't contribute it. It never removes the registration.\n\nA client dispatches this with its own `clientId`. The host dispatches it\nwhen a contributing client leaves.\n\nStability: 1.0 - Early development.", - "properties": { - "type": { - "const": "root/modelSourceContributorRemoved" - }, - "id": { - "type": "string", - "description": "The registration's `id`." - }, - "clientId": { - "type": "string", - "description": "The contributing client to remove." + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `modelSource.format`: endpoint, wire format,\nmodels, and so on. The host hands it to the agent, and the reducer\ndoesn't store it. MUST NOT contain a credential." } }, "required": [ "type", - "id", - "clientId" + "modelSource", + "definition" ] }, - "RootModelSourceRegistrationRemovedAction": { + "RootModelSourceRemovedAction": { "type": "object", - "description": "Removes the model source registration with the given `id` for every\ncontributor. A no-op when none matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `id`, for every client. A no-op\nwhen none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRegistrationRemoved" + "const": "root/modelSourceRemoved" }, "id": { "type": "string", - "description": "The registration's `id`." + "description": "The model source's `id`." } }, "required": [ @@ -8654,14 +8622,14 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's host-reported fields together:\n`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`credentialId`. A no-op when no registration has `id`. Other fields of the\nregistration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`accountId`. A no-op when no model source has `id`. Other fields of the\nsource are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" }, "id": { "type": "string", - "description": "The registration's `id`." + "description": "The model source's `id`." }, "state": { "$ref": "#/$defs/ModelSourceState", @@ -8669,22 +8637,22 @@ }, "credentialNonce": { "type": "string", - "description": "The registration's current credential nonce." + "description": "The model source's current credential nonce." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." + "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." }, "credentialOrigins": { "type": "array", "items": { "$ref": "#/$defs/URI" }, - "description": "Replaces the registration's `credentialOrigins`. Absent clears it." + "description": "Replaces the source's `credentialOrigins`. Absent clears it." }, - "credentialId": { + "accountId": { "type": "string", - "description": "Replaces the registration's `credentialId`. Absent clears it." + "description": "Replaces the source's `accountId`. Absent clears it." } }, "required": [ @@ -11187,13 +11155,10 @@ "$ref": "#/$defs/RootConfigChangedAction" }, { - "$ref": "#/$defs/RootModelSourceRegistrationSetAction" - }, - { - "$ref": "#/$defs/RootModelSourceContributorRemovedAction" + "$ref": "#/$defs/RootModelSourceSetAction" }, { - "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" + "$ref": "#/$defs/RootModelSourceRemovedAction" }, { "$ref": "#/$defs/RootModelSourceStateChangedAction" @@ -11659,7 +11624,7 @@ "host" ], "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." + "description": "How long a registered model source lasts once its last contributing client\nleaves." }, "ModelSourceState": { "oneOf": [ @@ -11676,7 +11641,7 @@ "$ref": "#/$defs/ModelSourceErrorState" } ], - "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, "ModelSourceAuthRequiredReason": { "enum": [ diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 5b28ab34a..67b95ac3d 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -650,12 +650,12 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, - "modelSourceRegistrations": { + "modelSources": { "type": "array", "items": { - "$ref": "#/$defs/ModelSourceRegistration" + "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -774,7 +774,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -836,7 +836,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -874,11 +874,11 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." }, "gracePeriod": { "type": "integer", - "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", "minimum": 0 }, "principalPolicy": { @@ -890,9 +890,9 @@ "formats" ] }, - "ModelSourceRegistration": { + "ModelSource": { "type": "object", - "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -915,19 +915,11 @@ }, "format": { "type": "string", - "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." + "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." }, - "contributingClientIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." + "nonce": { + "type": "string", + "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -935,11 +927,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", @@ -950,16 +942,16 @@ "items": { "$ref": "#/$defs/URI" }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." }, - "credentialId": { + "accountId": { "type": "string", - "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." }, "_meta": { "type": "object", "additionalProperties": {}, - "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ @@ -967,7 +959,7 @@ "provider", "displayName", "format", - "definition" + "nonce" ] }, "ModelSourceStartingState": { @@ -984,7 +976,7 @@ }, "ModelSourceReadyState": { "type": "object", - "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "ready" @@ -996,7 +988,7 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -1013,7 +1005,7 @@ }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the model source's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -7503,15 +7495,11 @@ }, "modelSourceId": { "type": "string", - "description": "The registration's `ModelSourceRegistration.id`." + "description": "The registration's `ModelSource.id`." }, "credentialNonce": { "type": "string", - "description": "The registration's current `ModelSourceRegistration.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." - }, - "credentialId": { - "type": "string", - "description": "A client-chosen, non-secret ID for the credential, such as a hash of\nwhere the client stores the key. The host publishes it as the\nregistration's `ModelSourceRegistration.credentialId`, so a client can\ntell whether the host holds its current key. Clients SHOULD include it\nwhen delivering a credential, and omit it when revoking one. MUST NOT be\nderived from the secret." + "description": "The registration's current `ModelSource.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." } }, "required": [ @@ -7522,7 +7510,7 @@ }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSourceRegistration.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSource.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", "properties": { "channel": { "type": "string", @@ -7537,7 +7525,7 @@ }, "resource": { "type": "string", - "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSourceRegistration.credentialResource`." + "description": "The protected resource identifier. MUST match a `resource` value the\nserver has advertised — via `ProtectedResourceMetadata` in\n`AgentInfo.protectedResources`, or via a live\n`McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`,\nor `ModelSource.credentialResource`." }, "token": { "type": "string", @@ -7561,7 +7549,7 @@ }, "accountId": { "type": "string", - "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.", + "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.\n\nWith a `modelSource` target, clients SHOULD include it when delivering a\ncredential and omit it when revoking one, and the host publishes it as\nthe source's `ModelSource.accountId`. It MUST NOT be derived from the\nsecret. For an API key with no account of its own, a client uses an ID\nthat changes whenever the user replaces the key.", "minLength": 1 } }, @@ -8523,7 +8511,7 @@ "host" ], "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." + "description": "How long a registered model source lasts once its last contributing client\nleaves." }, "ModelSourceState": { "oneOf": [ @@ -8540,7 +8528,7 @@ "$ref": "#/$defs/ModelSourceErrorState" } ], - "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, "ModelSourceAuthRequiredReason": { "enum": [ @@ -9319,13 +9307,10 @@ "$ref": "#/$defs/RootConfigChangedAction" }, { - "$ref": "#/$defs/RootModelSourceRegistrationSetAction" - }, - { - "$ref": "#/$defs/RootModelSourceContributorRemovedAction" + "$ref": "#/$defs/RootModelSourceSetAction" }, { - "$ref": "#/$defs/RootModelSourceRegistrationRemovedAction" + "$ref": "#/$defs/RootModelSourceRemovedAction" }, { "$ref": "#/$defs/RootModelSourceStateChangedAction" @@ -9865,59 +9850,39 @@ "config" ] }, - "RootModelSourceRegistrationSetAction": { + "RootModelSourceSetAction": { "type": "object", - "description": "Contributes a model source registration for `clientId`. A registration's\nrouting is its `provider`, `format`, and `definition`, with definitions\ncompared as JSON values: object key order is ignored, and numbers compare\nby numeric value, so `1` equals `1.0`.\n\n- **Add.** When no registration has the `id`, appends it, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`.\n- **Join.** When one has, and its routing is unchanged, keeps its\n host-reported fields (`state`, `credentialNonce`, `credentialResource`,\n `credentialOrigins`, and `credentialId`), adds `clientId` to\n `contributingClientIds` if it isn't there, and takes the other fields\n from the action.\n- **Replace.** When the routing changed, replaces the registration, with\n `contributingClientIds` set to `[clientId]`, or absent without a\n `clientId`. Its host-reported fields are absent until the host reports\n again with {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this with its own `clientId`, and without\n`contributingClientIds` or any host-reported field.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`. The reducer\nstores `modelSource` without the definition:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialNonce`,\n `credentialResource`, `credentialOrigins`, and `accountId`) and takes\n the other fields from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRegistrationSet" + "const": "root/modelSourceSet" }, - "registration": { - "$ref": "#/$defs/ModelSourceRegistration", - "description": "The registration to contribute, matched by `id`." + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or update, matched by `id`, without host-reported fields." }, - "clientId": { - "type": "string", - "description": "The contributing client. Absent when the host registers the source\nitself." - } - }, - "required": [ - "type", - "registration" - ] - }, - "RootModelSourceContributorRemovedAction": { - "type": "object", - "description": "Withdraws one client's contribution to a model source registration:\nremoves `clientId` from `contributingClientIds`, leaving the field absent\nwhen no contributor remains. A no-op when no registration has `id`, or\n`clientId` doesn't contribute it. It never removes the registration.\n\nA client dispatches this with its own `clientId`. The host dispatches it\nwhen a contributing client leaves.\n\nStability: 1.0 - Early development.", - "properties": { - "type": { - "const": "root/modelSourceContributorRemoved" - }, - "id": { - "type": "string", - "description": "The registration's `id`." - }, - "clientId": { - "type": "string", - "description": "The contributing client to remove." + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `modelSource.format`: endpoint, wire format,\nmodels, and so on. The host hands it to the agent, and the reducer\ndoesn't store it. MUST NOT contain a credential." } }, "required": [ "type", - "id", - "clientId" + "modelSource", + "definition" ] }, - "RootModelSourceRegistrationRemovedAction": { + "RootModelSourceRemovedAction": { "type": "object", - "description": "Removes the model source registration with the given `id` for every\ncontributor. A no-op when none matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `id`, for every client. A no-op\nwhen none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRegistrationRemoved" + "const": "root/modelSourceRemoved" }, "id": { "type": "string", - "description": "The registration's `id`." + "description": "The model source's `id`." } }, "required": [ @@ -9927,14 +9892,14 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source registration's host-reported fields together:\n`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`credentialId`. A no-op when no registration has `id`. Other fields of the\nregistration are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`accountId`. A no-op when no model source has `id`. Other fields of the\nsource are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" }, "id": { "type": "string", - "description": "The registration's `id`." + "description": "The model source's `id`." }, "state": { "$ref": "#/$defs/ModelSourceState", @@ -9942,22 +9907,22 @@ }, "credentialNonce": { "type": "string", - "description": "The registration's current credential nonce." + "description": "The model source's current credential nonce." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "Replaces the registration's `credentialResource`. Absent clears it, for a\nsource that needs no credential." + "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." }, "credentialOrigins": { "type": "array", "items": { "$ref": "#/$defs/URI" }, - "description": "Replaces the registration's `credentialOrigins`. Absent clears it." + "description": "Replaces the source's `credentialOrigins`. Absent clears it." }, - "credentialId": { + "accountId": { "type": "string", - "description": "Replaces the registration's `credentialId`. Absent clears it." + "description": "Replaces the source's `accountId`. Absent clears it." } }, "required": [ diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 4d02e8ad4..c48fc052e 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -952,12 +952,12 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, - "modelSourceRegistrations": { + "modelSources": { "type": "array", "items": { - "$ref": "#/$defs/ModelSourceRegistration" + "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -1076,7 +1076,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -1138,7 +1138,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -1176,11 +1176,11 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." }, "gracePeriod": { "type": "integer", - "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", "minimum": 0 }, "principalPolicy": { @@ -1192,9 +1192,9 @@ "formats" ] }, - "ModelSourceRegistration": { + "ModelSource": { "type": "object", - "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -1217,19 +1217,11 @@ }, "format": { "type": "string", - "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." + "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." }, - "contributingClientIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." + "nonce": { + "type": "string", + "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -1237,11 +1229,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", @@ -1252,16 +1244,16 @@ "items": { "$ref": "#/$defs/URI" }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." }, - "credentialId": { + "accountId": { "type": "string", - "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." }, "_meta": { "type": "object", "additionalProperties": {}, - "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ @@ -1269,7 +1261,7 @@ "provider", "displayName", "format", - "definition" + "nonce" ] }, "ModelSourceStartingState": { @@ -1286,7 +1278,7 @@ }, "ModelSourceReadyState": { "type": "object", - "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "ready" @@ -1298,7 +1290,7 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -1315,7 +1307,7 @@ }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the model source's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -6833,7 +6825,7 @@ "host" ], "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." + "description": "How long a registered model source lasts once its last contributing client\nleaves." }, "ModelSourceState": { "oneOf": [ @@ -6850,7 +6842,7 @@ "$ref": "#/$defs/ModelSourceErrorState" } ], - "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, "ModelSourceAuthRequiredReason": { "enum": [ diff --git a/schema/state.schema.json b/schema/state.schema.json index dcef0b4b8..aec0dd37e 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -561,12 +561,12 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, - "modelSourceRegistrations": { + "modelSources": { "type": "array", "items": { - "$ref": "#/$defs/ModelSourceRegistration" + "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`.\n\nStability: 1.0 - Early development." + "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -685,7 +685,7 @@ "properties": { "id": { "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSourceRegistration.id}. A source is registered when\n{@link RootState.modelSourceRegistrations} has an entry with this `id`\nwhose `provider` is the agent." + "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." }, "displayName": { "type": "string", @@ -747,7 +747,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSourceRegistration.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." } }, "required": [ @@ -785,11 +785,11 @@ "items": { "type": "string" }, - "description": "Definition formats the agent reads, most preferred first. Format names\nare defined by agent implementations and SHOULD be namespaced, for\nexample `example.com/model-source@1`. AHP doesn't define, standardize,\nor name any format." + "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." }, "gracePeriod": { "type": "integer", - "description": "How long, in milliseconds, the host keeps a disconnected client's\ncontributions before it treats the client as having left.", + "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", "minimum": 0 }, "principalPolicy": { @@ -801,9 +801,9 @@ "formats" ] }, - "ModelSourceRegistration": { + "ModelSource": { "type": "object", - "description": "A model source registered on this host by one or more clients, or by the\nhost itself. Its definition is in a format the agent named by `provider`\nreads. It never contains a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -826,19 +826,11 @@ }, "format": { "type": "string", - "description": "Definition format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source: endpoint, wire format, models, and so on, in\n`format`. Its shape belongs to the agent that reads it, and AHP doesn't\ndefine it. MUST NOT contain a credential." + "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." }, - "contributingClientIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The clients that contribute this registration, in the order they joined.\nThe reducer maintains it from {@link RootModelSourceRegistrationSetAction}\nand {@link RootModelSourceContributorRemovedAction}. Absent when no\nclient contributes it: a source the host registered itself, or a\n`host`-retained one whose contributors have all left." + "nonce": { + "type": "string", + "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -846,11 +838,11 @@ }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after a `Set` replaces the\nregistration until the host reports again." + "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, "credentialNonce": { "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the registration.\nThe host issues a new one when the registration is added, when its\n`provider`, `format`, or `definition` changes, and whenever the\ncredential is installed or dropped. It never reuses one for the same\n`id`. Set with `state`." + "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", @@ -861,16 +853,16 @@ "items": { "$ref": "#/$defs/URI" }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`. Present whenever `credentialResource` is. A\nclient checks each one against its own copy of the definition before it\nsends a key. Set with `state`." + "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." }, - "credentialId": { + "accountId": { "type": "string", - "description": "The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of\nthe credential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds it. While it's `authRequired`, the\n`reason` says what happened to it. Absent until the host accepts a\ncredential. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." }, "_meta": { "type": "object", "additionalProperties": {}, - "description": "Additional implementation-defined metadata for this registration.\nMUST NOT contain a credential." + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ @@ -878,7 +870,7 @@ "provider", "displayName", "format", - "definition" + "nonce" ] }, "ModelSourceStartingState": { @@ -895,7 +887,7 @@ }, "ModelSourceReadyState": { "type": "object", - "description": "The source is usable, and its models are in the catalog of the agent named\nby the registration's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "description": "The source is usable, and its models are in the catalog of the agent named\nby the model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "ready" @@ -907,7 +899,7 @@ }, "ModelSourceAuthRequirement": { "type": "object", - "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nregistration's {@link ModelSourceRegistration.credentialResource}.\n\nStability: 1.0 - Early development.", + "description": "Why a model source needs a credential before it can be ready. Deliberately\ncarries no credential. The endpoint the credential is for is the\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -924,7 +916,7 @@ }, "ModelSourceAuthRequiredState": { "type": "object", - "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the registration's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", + "description": "The source needs a credential before it can be used. A client answers with\n`authenticate`, the model source's `credentialResource.resource`, and a\n{@link ModelSourceAuthenticateTarget}.\n\nStability: 1.0 - Early development.", "properties": { "reason": { "$ref": "#/$defs/ModelSourceAuthRequiredReason", @@ -6408,7 +6400,7 @@ "$ref": "#/$defs/ModelSourceErrorState" } ], - "description": "Lifecycle state of a {@link ModelSourceRegistration}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, "SessionOrigin": { "$ref": "#/$defs/AutomationSessionOrigin", @@ -6994,7 +6986,7 @@ "host" ], "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves. When the last contributor withdraws instead, the source goes away\nwhatever its retention." + "description": "How long a registered model source lasts once its last contributing client\nleaves." }, "ModelSourceAuthRequiredReason": { "enum": [ diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index 2f90278db..b9697b2fd 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -796,7 +796,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, - { name: 'ModelSourceRegistration' }, + { name: 'ModelSource' }, { name: 'ModelSourceStartingState' }, { name: 'ModelSourceReadyState' }, { name: 'ModelSourceAuthRequirement' }, @@ -1678,9 +1678,8 @@ const ACTION_VARIANTS: { type: string; variantName: string; tsInterface: string { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, - { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, - { type: 'root/modelSourceContributorRemoved', variantName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, - { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index b98fe8c08..21d9d8c74 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -780,7 +780,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, - { name: 'ModelSourceRegistration' }, + { name: 'ModelSource' }, { name: 'ModelSourceStartingState' }, { name: 'ModelSourceReadyState' }, { name: 'ModelSourceAuthRequirement' }, @@ -1659,9 +1659,8 @@ const ACTION_VARIANTS: { { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, - { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, - { type: 'root/modelSourceContributorRemoved', variantName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, - { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index b16bedda3..a04e51a80 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1029,7 +1029,7 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceRegistrationCapability', 'ModelSourceRegistration', 'ModelSourceStartingState', + 'ModelSourceRegistrationCapability', 'ModelSource', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', @@ -1659,9 +1659,8 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'annotations/entryRemoved', caseName: 'AnnotationsEntryRemoved', tsInterface: 'AnnotationsEntryRemovedAction' }, { type: 'root/terminalsChanged', caseName: 'RootTerminalsChanged', tsInterface: 'RootTerminalsChangedAction' }, { type: 'root/configChanged', caseName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, - { type: 'root/modelSourceRegistrationSet', caseName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, - { type: 'root/modelSourceContributorRemoved', caseName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, - { type: 'root/modelSourceRegistrationRemoved', caseName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceSet', caseName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', caseName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, { type: 'root/modelSourceStateChanged', caseName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'terminal/data', caseName: 'TerminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'TerminalInput', tsInterface: 'TerminalInputAction' }, diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 7f93f7918..4006c115c 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -881,7 +881,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, - { name: 'ModelSourceRegistration' }, + { name: 'ModelSource' }, { name: 'ModelSourceStartingState', omitDiscriminants: true }, { name: 'ModelSourceReadyState', omitDiscriminants: true }, { name: 'ModelSourceAuthRequirement' }, @@ -1651,9 +1651,8 @@ const ACTION_VARIANTS: { { type: 'root/agentsChanged', variantName: 'RootAgentsChanged', tsInterface: 'RootAgentsChangedAction' }, { type: 'root/activeSessionsChanged', variantName: 'RootActiveSessionsChanged', tsInterface: 'RootActiveSessionsChangedAction' }, { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, - { type: 'root/modelSourceRegistrationSet', variantName: 'RootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction', boxed: true }, - { type: 'root/modelSourceContributorRemoved', variantName: 'RootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, - { type: 'root/modelSourceRegistrationRemoved', variantName: 'RootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction', boxed: true }, + { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, @@ -1837,7 +1836,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSourceRegistration, ModelSourceState, ProtectedResourceMetadata, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ModelSource, ModelSourceState, ProtectedResourceMetadata, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 25fe1bc33..a04afaa0d 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -752,7 +752,7 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceRegistrationCapability', 'ModelSourceRegistration', 'ModelSourceStartingState', + 'ModelSourceRegistrationCapability', 'ModelSource', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', @@ -1569,9 +1569,8 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'annotations/entryRemoved', caseName: 'annotationsEntryRemoved', tsInterface: 'AnnotationsEntryRemovedAction' }, { type: 'root/terminalsChanged', caseName: 'rootTerminalsChanged', tsInterface: 'RootTerminalsChangedAction' }, { type: 'root/configChanged', caseName: 'rootConfigChanged', tsInterface: 'RootConfigChangedAction' }, - { type: 'root/modelSourceRegistrationSet', caseName: 'rootModelSourceRegistrationSet', tsInterface: 'RootModelSourceRegistrationSetAction' }, - { type: 'root/modelSourceContributorRemoved', caseName: 'rootModelSourceContributorRemoved', tsInterface: 'RootModelSourceContributorRemovedAction' }, - { type: 'root/modelSourceRegistrationRemoved', caseName: 'rootModelSourceRegistrationRemoved', tsInterface: 'RootModelSourceRegistrationRemovedAction' }, + { type: 'root/modelSourceSet', caseName: 'rootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', caseName: 'rootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, { type: 'root/modelSourceStateChanged', caseName: 'rootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, { type: 'terminal/data', caseName: 'terminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'terminalInput', tsInterface: 'TerminalInputAction' }, diff --git a/types/action-origin.generated.ts b/types/action-origin.generated.ts index 95b98ac1d..d92ebccfe 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -7,9 +7,8 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, - RootModelSourceRegistrationSetAction, - RootModelSourceContributorRemovedAction, - RootModelSourceRegistrationRemovedAction, + RootModelSourceSetAction, + RootModelSourceRemovedAction, RootModelSourceStateChangedAction, SessionReadyAction, SessionCreationFailedAction, @@ -127,18 +126,16 @@ export type RootAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction - | RootModelSourceRegistrationSetAction - | RootModelSourceContributorRemovedAction - | RootModelSourceRegistrationRemovedAction + | RootModelSourceSetAction + | RootModelSourceRemovedAction | RootModelSourceStateChangedAction ; /** Union of root actions that clients may dispatch. */ export type ClientRootAction = | RootConfigChangedAction - | RootModelSourceRegistrationSetAction - | RootModelSourceContributorRemovedAction - | RootModelSourceRegistrationRemovedAction + | RootModelSourceSetAction + | RootModelSourceRemovedAction ; /** Union of root actions that only the server may produce. */ @@ -479,9 +476,8 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.RootActiveSessionsChanged]: false, [ActionType.RootTerminalsChanged]: false, [ActionType.RootConfigChanged]: true, - [ActionType.RootModelSourceRegistrationSet]: true, - [ActionType.RootModelSourceContributorRemoved]: true, - [ActionType.RootModelSourceRegistrationRemoved]: true, + [ActionType.RootModelSourceSet]: true, + [ActionType.RootModelSourceRemoved]: true, [ActionType.RootModelSourceStateChanged]: false, [ActionType.SessionReady]: false, [ActionType.SessionCreationFailed]: false, diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 32f9003f2..7cc17735b 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -4,7 +4,7 @@ * @module channels-root/actions */ -import type { AgentInfo, ModelSourceRegistration, ModelSourceState } from './state.js'; +import type { AgentInfo, ModelSource, ModelSourceState } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import type { ProtectedResourceMetadata, URI } from '../common/state.js'; import { ActionType } from '../common/actions.js'; @@ -69,85 +69,58 @@ export interface RootConfigChangedAction { } /** - * Contributes a model source registration for `clientId`. A registration's - * routing is its `provider`, `format`, and `definition`, with definitions - * compared as JSON values: object key order is ignored, and numbers compare - * by numeric value, so `1` equals `1.0`. + * Adds a model source, or updates the one with the same `id`. The reducer + * stores `modelSource` without the definition: * - * - **Add.** When no registration has the `id`, appends it, with - * `contributingClientIds` set to `[clientId]`, or absent without a - * `clientId`. - * - **Join.** When one has, and its routing is unchanged, keeps its - * host-reported fields (`state`, `credentialNonce`, `credentialResource`, - * `credentialOrigins`, and `credentialId`), adds `clientId` to - * `contributingClientIds` if it isn't there, and takes the other fields - * from the action. - * - **Replace.** When the routing changed, replaces the registration, with - * `contributingClientIds` set to `[clientId]`, or absent without a - * `clientId`. Its host-reported fields are absent until the host reports - * again with {@link RootModelSourceStateChangedAction}. + * - **Add.** When no model source has the `id`, appends `modelSource`. + * - **Re-register.** When one has, with the same `provider`, `format`, and + * `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, + * `credentialResource`, `credentialOrigins`, and `accountId`) and takes + * the other fields from the action. + * - **Update.** When any of the three differs, replaces the source. Its + * host-reported fields are absent until the host reports again with + * {@link RootModelSourceStateChangedAction}. * - * A client dispatches this with its own `clientId`, and without - * `contributingClientIds` or any host-reported field. + * A client dispatches this without any host-reported field. The host learns + * which client registered the source from the envelope's `origin`. * * @category Root Actions * @stability 1.0 * @clientDispatchable * @see {@link /specification/root-channel#model-source-registry | Model source registry} */ -export interface RootModelSourceRegistrationSetAction { - type: ActionType.RootModelSourceRegistrationSet; - /** The registration to contribute, matched by `id`. */ - registration: ModelSourceRegistration; +export interface RootModelSourceSetAction { + type: ActionType.RootModelSourceSet; + /** The model source to add or update, matched by `id`, without host-reported fields. */ + modelSource: ModelSource; /** - * The contributing client. Absent when the host registers the source - * itself. + * How to reach the source, in `modelSource.format`: endpoint, wire format, + * models, and so on. The host hands it to the agent, and the reducer + * doesn't store it. MUST NOT contain a credential. */ - clientId?: string; + definition: Record; } /** - * Withdraws one client's contribution to a model source registration: - * removes `clientId` from `contributingClientIds`, leaving the field absent - * when no contributor remains. A no-op when no registration has `id`, or - * `clientId` doesn't contribute it. It never removes the registration. - * - * A client dispatches this with its own `clientId`. The host dispatches it - * when a contributing client leaves. - * - * @category Root Actions - * @stability 1.0 - * @clientDispatchable - * @see {@link /specification/root-channel#model-source-registry | Model source registry} - */ -export interface RootModelSourceContributorRemovedAction { - type: ActionType.RootModelSourceContributorRemoved; - /** The registration's `id`. */ - id: string; - /** The contributing client to remove. */ - clientId: string; -} - -/** - * Removes the model source registration with the given `id` for every - * contributor. A no-op when none matches. + * Removes the model source with the given `id`, for every client. A no-op + * when none matches. * * @category Root Actions * @stability 1.0 * @clientDispatchable * @see {@link /specification/root-channel#model-source-registry | Model source registry} */ -export interface RootModelSourceRegistrationRemovedAction { - type: ActionType.RootModelSourceRegistrationRemoved; - /** The registration's `id`. */ +export interface RootModelSourceRemovedAction { + type: ActionType.RootModelSourceRemoved; + /** The model source's `id`. */ id: string; } /** - * Updates a model source registration's host-reported fields together: - * `state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and - * `credentialId`. A no-op when no registration has `id`. Other fields of the - * registration are preserved. Only the host dispatches it. + * Updates a model source's host-reported fields together: `state`, + * `credentialNonce`, `credentialResource`, `credentialOrigins`, and + * `accountId`. A no-op when no model source has `id`. Other fields of the + * source are preserved. Only the host dispatches it. * * @category Root Actions * @stability 1.0 @@ -155,19 +128,19 @@ export interface RootModelSourceRegistrationRemovedAction { */ export interface RootModelSourceStateChangedAction { type: ActionType.RootModelSourceStateChanged; - /** The registration's `id`. */ + /** The model source's `id`. */ id: string; /** The new status. */ state: ModelSourceState; - /** The registration's current credential nonce. */ + /** The model source's current credential nonce. */ credentialNonce: string; /** - * Replaces the registration's `credentialResource`. Absent clears it, for a + * Replaces the source's `credentialResource`. Absent clears it, for a * source that needs no credential. */ credentialResource?: ProtectedResourceMetadata; - /** Replaces the registration's `credentialOrigins`. Absent clears it. */ + /** Replaces the source's `credentialOrigins`. Absent clears it. */ credentialOrigins?: URI[]; - /** Replaces the registration's `credentialId`. Absent clears it. */ - credentialId?: string; + /** Replaces the source's `accountId`. Absent clears it. */ + accountId?: string; } diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index ccbb79a50..08da4e508 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -5,7 +5,7 @@ */ import { ActionType } from '../common/actions.js'; -import type { ModelSourceRegistration, RootState } from './state.js'; +import type { ModelSource, RootState } from './state.js'; import type { RootAction } from '../action-origin.generated.js'; import { softAssertNever } from '../common/reducer-helpers.js'; @@ -35,67 +35,41 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st }, }; - case ActionType.RootModelSourceRegistrationSet: { - const list = state.modelSourceRegistrations ?? []; - const idx = list.findIndex(r => r.id === action.registration.id); + case ActionType.RootModelSourceSet: { + const list = state.modelSources ?? []; + const idx = list.findIndex(source => source.id === action.modelSource.id); const existing = idx < 0 ? undefined : list[idx]; - const joining = existing !== undefined && sameRouting(existing, action.registration); - const updated: ModelSourceRegistration = { ...action.registration }; - copyHostReported(updated, joining ? existing : {}); - const contributors = joining ? [...(existing.contributingClientIds ?? [])] : []; - if (action.clientId !== undefined && !contributors.includes(action.clientId)) { - contributors.push(action.clientId); - } - setContributors(updated, contributors); + const updated: ModelSource = { ...action.modelSource }; + copyHostReported(updated, existing && sameVersion(existing, updated) ? existing : {}); const next = list.slice(); if (idx < 0) { next.push(updated); } else { next[idx] = updated; } - return { ...state, modelSourceRegistrations: next }; + return { ...state, modelSources: next }; } - case ActionType.RootModelSourceContributorRemoved: { - const list = state.modelSourceRegistrations; + case ActionType.RootModelSourceRemoved: { + const list = state.modelSources; if (!list) { return state; } - const idx = list.findIndex(r => r.id === action.id); - if (idx < 0) { - return state; - } - const contributors = list[idx].contributingClientIds ?? []; - if (!contributors.includes(action.clientId)) { - return state; - } - const updated = { ...list[idx] }; - setContributors(updated, contributors.filter(id => id !== action.clientId)); - const next = list.slice(); - next[idx] = updated; - return { ...state, modelSourceRegistrations: next }; - } - - case ActionType.RootModelSourceRegistrationRemoved: { - const list = state.modelSourceRegistrations; - if (!list) { - return state; - } - const idx = list.findIndex(r => r.id === action.id); + const idx = list.findIndex(source => source.id === action.id); if (idx < 0) { return state; } const next = list.slice(); next.splice(idx, 1); - return { ...state, modelSourceRegistrations: next }; + return { ...state, modelSources: next }; } case ActionType.RootModelSourceStateChanged: { - const list = state.modelSourceRegistrations; + const list = state.modelSources; if (!list) { return state; } - const idx = list.findIndex(r => r.id === action.id); + const idx = list.findIndex(source => source.id === action.id); if (idx < 0) { return state; } @@ -103,7 +77,7 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st copyHostReported(updated, action); const next = list.slice(); next[idx] = updated; - return { ...state, modelSourceRegistrations: next }; + return { ...state, modelSources: next }; } default: @@ -114,12 +88,12 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st // ─── Model source registry helpers ─────────────────────────────────────────── -const HOST_REPORTED_FIELDS = ['state', 'credentialNonce', 'credentialResource', 'credentialOrigins', 'credentialId'] as const; +const HOST_REPORTED_FIELDS = ['state', 'credentialNonce', 'credentialResource', 'credentialOrigins', 'accountId'] as const; -type HostReportedFields = Partial>; +type HostReportedFields = Partial>; /** Copies each host-reported field from `from` onto `to`, removing the ones `from` lacks. */ -function copyHostReported(to: ModelSourceRegistration, from: HostReportedFields): void { +function copyHostReported(to: ModelSource, from: HostReportedFields): void { for (const field of HOST_REPORTED_FIELDS) { if (from[field] === undefined) { delete to[field]; @@ -129,29 +103,7 @@ function copyHostReported(to: ModelSourceRegistration, from: HostReportedFields) } } -/** Sets `contributingClientIds`, leaving it absent when there are none. */ -function setContributors(registration: ModelSourceRegistration, contributors: string[]): void { - if (contributors.length > 0) { - registration.contributingClientIds = contributors; - } else { - delete registration.contributingClientIds; - } -} - -/** Whether two registrations have the same `provider`, `format`, and `definition`. */ -function sameRouting(a: ModelSourceRegistration, b: ModelSourceRegistration): boolean { - return a.provider === b.provider - && a.format === b.format - && JSON.stringify(canonicalJson(a.definition)) === JSON.stringify(canonicalJson(b.definition)); -} - -/** Returns `value` with every object's keys sorted, so equal JSON values serialize identically. */ -function canonicalJson(value: unknown): unknown { - if (Array.isArray(value)) { - return value.map(canonicalJson); - } - if (value !== null && typeof value === 'object') { - return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)).map(([key, entry]) => [key, canonicalJson(entry)])); - } - return value; +/** Whether two model sources have the same `provider`, `format`, and definition `nonce`. */ +function sameVersion(a: ModelSource, b: ModelSource): boolean { + return a.provider === b.provider && a.format === b.format && a.nonce === b.nonce; } diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 386d75c70..8fa05ffbf 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -46,12 +46,14 @@ export interface RootState { /** Agent host configuration schema and current values */ config?: RootConfigState; /** - * Model sources registered on this host, keyed by `id`. + * Model sources registered on this host, keyed by `id`. When one is + * ready, it also appears in its agent's {@link AgentInfo.modelSources} + * catalog. * * @stability 1.0 * @see {@link /specification/root-channel#model-source-registry | Model source registry} */ - modelSourceRegistrations?: ModelSourceRegistration[]; + modelSources?: ModelSource[]; /** * Additional implementation-defined metadata about the agent host itself. * @@ -230,8 +232,8 @@ export interface ModelSourceInfo { /** * Model source identifier, unique within the agent's * {@link AgentInfo.modelSources}. For a registered model source, this is - * the {@link ModelSourceRegistration.id}. A source is registered when - * {@link RootState.modelSourceRegistrations} has an entry with this `id` + * the {@link ModelSource.id}. A source is registered when + * {@link RootState.modelSources} has an entry with this `id` * whose `provider` is the agent. */ id: string; @@ -292,7 +294,7 @@ export interface SessionModelInfo { /** * The source this model comes from. MUST match a {@link ModelSourceInfo.id} * in the agent's {@link AgentInfo.modelSources}. For a model from a - * registered model source, this is the {@link ModelSourceRegistration.id}. + * registered model source, this is the {@link ModelSource.id}. * An agent's own sources use it too, so it doesn't by itself mark a * registered source. */ @@ -329,15 +331,14 @@ export interface ModelSelection { */ export interface ModelSourceRegistrationCapability { /** - * Definition formats the agent reads, most preferred first. Format names - * are defined by agent implementations and SHOULD be namespaced, for - * example `example.com/model-source@1`. AHP doesn't define, standardize, - * or name any format. + * Definition formats the agent reads, most preferred first: recognized + * values of {@link ModelSource.format}, or namespaced names for formats + * the agent defines itself. */ formats: string[]; /** - * How long, in milliseconds, the host keeps a disconnected client's - * contributions before it treats the client as having left. + * How long, in milliseconds, the host keeps counting a disconnected client + * as a contributing client before it treats the client as having left. * * @integer * @minimum 0 @@ -361,29 +362,30 @@ export interface ModelSourceRegistrationCapability { export const enum ModelSourcePrincipalPolicy { /** * Every connected client may change, supply credentials for, and select - * every registration. + * every model source. */ Shared = 'shared', /** * The host verifies principals, and limits changes, credentials, and - * selection of each registration to clients of the principal that - * registered it. Root state still lists every registration to every + * selection of each model source to clients of the principal that + * registered it. Root state still lists every model source to every * client. */ Isolated = 'isolated', } /** - * A model source registered on this host by one or more clients, or by the - * host itself. Its definition is in a format the agent named by `provider` - * reads. It never contains a credential. + * A model source registered on this host by a client, or by the host itself. + * The definition that tells the agent named by `provider` how to reach it + * travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing + * here is a credential. * * @category Root State * @stability 1.0 * @preserveUnknownMembers * @see {@link /specification/root-channel#model-source-registry | Model source registry} */ -export interface ModelSourceRegistration { +export interface ModelSource { /** * Host-unique ID, chosen by whoever registers the source. Also the * source's {@link ModelSourceInfo.id} in the agent's catalog, and the @@ -397,40 +399,43 @@ export interface ModelSourceRegistration { /** Icons for UI display. */ icons?: Icon[]; /** - * Definition format, one of the agent's - * {@link ModelSourceRegistrationCapability.formats}. + * The definition's format, one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. Recognized values + * include: + * + * - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as + * OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + * - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + * - `'azureOpenai'`: an Azure OpenAI deployment. + * - `'gemini'`: Google's Gemini API. + * + * AHP doesn't define what a definition contains, even for these. Agents + * MAY read other formats, named with a namespace such as + * `example.com/model-source@1` so they don't collide. */ format: string; /** - * How to reach the source: endpoint, wire format, models, and so on, in - * `format`. Its shape belongs to the agent that reads it, and AHP doesn't - * define it. MUST NOT contain a credential. + * Opaque version token for the definition, such as a hash of it, chosen by + * whoever registers the source. A client compares it with its own copy + * instead of the definition, and the reducer compares it to tell an update + * from a re-registration of the same definition. */ - definition: Record; - /** - * The clients that contribute this registration, in the order they joined. - * The reducer maintains it from {@link RootModelSourceRegistrationSetAction} - * and {@link RootModelSourceContributorRemovedAction}. Absent when no - * client contributes it: a source the host registered itself, or a - * `host`-retained one whose contributors have all left. - */ - contributingClientIds?: string[]; + nonce: string; /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ retention?: ModelSourceRetentionPolicy; /** * Host-reported status, set with {@link RootModelSourceStateChangedAction}. - * Absent until the host reports one, and after a `Set` replaces the - * registration until the host reports again. + * Absent until the host reports one, and after an update replaces the + * definition until the host reports again. */ state?: ModelSourceState; /** * Host-issued token that a client echoes in * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential, and that tags every agent operation on the registration. - * The host issues a new one when the registration is added, when its - * `provider`, `format`, or `definition` changes, and whenever the - * credential is installed or dropped. It never reuses one for the same - * `id`. Set with `state`. + * the credential, and that tags every agent operation on the source. The + * host issues a new one when the source is added or updated, and whenever + * the credential is installed or dropped. It never reuses one for the + * same `id`. Set with `state`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ @@ -455,25 +460,25 @@ export interface ModelSourceRegistration { credentialResource?: ProtectedResourceMetadata; /** * Every origin the host sends the credential to, such as - * `https://api.example.com`. Present whenever `credentialResource` is. A - * client checks each one against its own copy of the definition before it - * sends a key. Set with `state`. + * `https://api.example.com`, derived from the definition it holds. Present + * whenever `credentialResource` is. A client checks each one against its + * own copy of the definition before it sends a key. Set with `state`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ credentialOrigins?: URI[]; /** - * The client-supplied {@link ModelSourceAuthenticateTarget.credentialId} of - * the credential the host most recently accepted. While the state is - * `starting` or `ready`, the host holds it. While it's `authRequired`, the - * `reason` says what happened to it. Absent until the host accepts a - * credential. Set with `state`. + * The {@link AuthenticateParams.accountId} the client sent with the + * credential the host most recently accepted. While the state is + * `starting` or `ready`, the host holds that credential. While it's + * `authRequired`, the `reason` says what happened to it. Absent until the + * host accepts a credential sent with an `accountId`. Set with `state`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ - credentialId?: string; + accountId?: string; /** - * Additional implementation-defined metadata for this registration. + * Additional implementation-defined metadata for this model source. * MUST NOT contain a credential. */ _meta?: Record; @@ -481,8 +486,7 @@ export interface ModelSourceRegistration { /** * How long a registered model source lasts once its last contributing client - * leaves. When the last contributor withdraws instead, the source goes away - * whatever its retention. + * leaves. * * @category Root State * @stability 1.0 @@ -491,7 +495,7 @@ export interface ModelSourceRegistration { export const enum ModelSourceRetentionPolicy { /** Removed when the last contributing client leaves, once running turns finish. */ ContributingClient = 'contributingClient', - /** Kept until it's removed, its last contributor withdraws, or host policy expires it. */ + /** Kept until a client removes it, or host policy expires it. */ Host = 'host', } @@ -527,7 +531,7 @@ export interface ModelSourceStartingState { /** * The source is usable, and its models are in the catalog of the agent named - * by the registration's `provider`. They stay listed through later `starting` + * by the model source's `provider`. They stay listed through later `starting` * and `authRequired` states. * * @category Root State @@ -554,7 +558,7 @@ export const enum ModelSourceAuthRequiredReason { Expired = 'expired', /** * The endpoint refused the credential. Clients don't send a credential with - * the same {@link ModelSourceRegistration.credentialId} again. + * the same {@link ModelSource.accountId} again. */ Rejected = 'rejected', /** A client revoked the credential. Clients don't send one again without a user's action. */ @@ -564,7 +568,7 @@ export const enum ModelSourceAuthRequiredReason { /** * Why a model source needs a credential before it can be ready. Deliberately * carries no credential. The endpoint the credential is for is the - * registration's {@link ModelSourceRegistration.credentialResource}. + * model source's {@link ModelSource.credentialResource}. * * @category Root State * @stability 1.0 @@ -582,7 +586,7 @@ export interface ModelSourceAuthRequirement { /** * The source needs a credential before it can be used. A client answers with - * `authenticate`, the registration's `credentialResource.resource`, and a + * `authenticate`, the model source's `credentialResource.resource`, and a * {@link ModelSourceAuthenticateTarget}. * * @category Root State @@ -608,7 +612,7 @@ export interface ModelSourceErrorState { } /** - * Lifecycle state of a {@link ModelSourceRegistration}, discriminated by + * Lifecycle state of a {@link ModelSource}, discriminated by * `kind` (a {@link ModelSourceStatus} value). * * @category Root State diff --git a/types/common/actions.ts b/types/common/actions.ts index 321302c21..94a275a6d 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -13,9 +13,8 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, - RootModelSourceRegistrationSetAction, - RootModelSourceContributorRemovedAction, - RootModelSourceRegistrationRemovedAction, + RootModelSourceSetAction, + RootModelSourceRemovedAction, RootModelSourceStateChangedAction, } from '../channels-root/actions.js'; @@ -244,9 +243,8 @@ export const enum ActionType { AnnotationsEntryRemoved = 'annotations/entryRemoved', RootTerminalsChanged = 'root/terminalsChanged', RootConfigChanged = 'root/configChanged', - RootModelSourceRegistrationSet = 'root/modelSourceRegistrationSet', - RootModelSourceContributorRemoved = 'root/modelSourceContributorRemoved', - RootModelSourceRegistrationRemoved = 'root/modelSourceRegistrationRemoved', + RootModelSourceSet = 'root/modelSourceSet', + RootModelSourceRemoved = 'root/modelSourceRemoved', RootModelSourceStateChanged = 'root/modelSourceStateChanged', TerminalData = 'terminal/data', TerminalInput = 'terminal/input', @@ -309,9 +307,8 @@ export type StateAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction - | RootModelSourceRegistrationSetAction - | RootModelSourceContributorRemovedAction - | RootModelSourceRegistrationRemovedAction + | RootModelSourceSetAction + | RootModelSourceRemovedAction | RootModelSourceStateChangedAction | SessionReadyAction | SessionCreationFailedAction diff --git a/types/common/commands.ts b/types/common/commands.ts index f55df03eb..5bb3c4099 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1492,23 +1492,14 @@ export interface McpServerAuthenticateTarget { */ export interface ModelSourceAuthenticateTarget { kind: AuthenticateTargetKind.ModelSource; - /** The registration's `ModelSourceRegistration.id`. */ + /** The registration's `ModelSource.id`. */ modelSourceId: string; /** - * The registration's current `ModelSourceRegistration.credentialNonce`, as + * The registration's current `ModelSource.credentialNonce`, as * published in root state. The host rejects a stale one with `Conflict` * (-32011). */ credentialNonce: string; - /** - * A client-chosen, non-secret ID for the credential, such as a hash of - * where the client stores the key. The host publishes it as the - * registration's `ModelSourceRegistration.credentialId`, so a client can - * tell whether the host holds its current key. Clients SHOULD include it - * when delivering a credential, and omit it when revoking one. MUST NOT be - * derived from the secret. - */ - credentialId?: string; } /** @@ -1528,7 +1519,7 @@ export type AuthenticateTarget = * or discovered dynamically from a live `McpServerAuthRequiredState.resource` * or `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the * corresponding MCP server or tool call actually challenges for auth), or - * from a registered model source's `ModelSourceRegistration.credentialResource`. + * from a registered model source's `ModelSource.credentialResource`. * Servers MUST accept any `resource` value they have themselves advertised * through one of these mechanisms, subject to the `target` rules. A * `modelSource` target takes only the registration's current @@ -1567,7 +1558,7 @@ export interface AuthenticateParams extends BaseParams { * server has advertised — via `ProtectedResourceMetadata` in * `AgentInfo.protectedResources`, or via a live * `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, - * or `ModelSourceRegistration.credentialResource`. + * or `ModelSource.credentialResource`. */ resource: string; /** @@ -1634,6 +1625,12 @@ export interface AuthenticateParams extends BaseParams { * Hosts MUST treat `accountId` as an opaque string. * see {@link /specification/authentication#account-selection-hints | Account selection hints}. * + * With a `modelSource` target, clients SHOULD include it when delivering a + * credential and omit it when revoking one, and the host publishes it as + * the source's `ModelSource.accountId`. It MUST NOT be derived from the + * secret. For an API key with no account of its own, a client uses an ID + * that changes whenever the user replaces the key. + * * @minLength 1 */ accountId?: string; diff --git a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json deleted file mode 100644 index ed4606058..000000000 --- a/types/test-cases/reducers/330-root-modelsourceregistrationset-adds-to-absent-registry.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet adds a registration to an absent registry, with the dispatching client as its only contributor", - "reducer": "root", - "initial": { - "agents": [] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - } - }, - "clientId": "client-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json new file mode 100644 index 000000000..f7630119d --- /dev/null +++ b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json @@ -0,0 +1,37 @@ +{ + "description": "root/modelSourceSet adds a model source to an absent registry, storing it without the definition", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + }, + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + } + ] + } +} diff --git a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json b/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json deleted file mode 100644 index beb866433..000000000 --- a/types/test-cases/reducers/331-root-modelsourceregistrationset-appends-new-id.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet appends a registration with a new id after the existing ones", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - } - }, - "clientId": "client-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-2" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json b/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json new file mode 100644 index 000000000..ce41cc0bd --- /dev/null +++ b/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json @@ -0,0 +1,102 @@ +{ + "description": "root/modelSourceSet with the same provider, format, and nonce re-registers: it keeps every host-reported field and takes displayName, icons, retention, and _meta from the action", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "accountId": "account-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a (renamed)", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "icons": [ + { + "src": "https://apia.example.com/icon.png" + } + ], + "retention": "host", + "_meta": { + "example.com/window": "2" + } + }, + "definition": { + "baseUrl": "https://apia.example.com/v1", + "models": [ + "model-a" + ] + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a (renamed)", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "icons": [ + { + "src": "https://apia.example.com/icon.png" + } + ], + "retention": "host", + "_meta": { + "example.com/window": "2" + }, + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "accountId": "account-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1" + } + ] + } +} diff --git a/types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json b/types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json deleted file mode 100644 index 9df981b7a..000000000 --- a/types/test-cases/reducers/332-root-modelsourceregistrationset-host-registers-without-contributors.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet without a clientId, as when the host registers a source itself, adds it with no contributingClientIds", - "reducer": "root", - "initial": { - "agents": [] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host" - } - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host" - } - ] - } -} diff --git a/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json b/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json new file mode 100644 index 000000000..5b3666b77 --- /dev/null +++ b/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json @@ -0,0 +1,72 @@ +{ + "description": "root/modelSourceSet with a different nonce updates the model source: it replaces the source and clears the host-reported fields until the host reports again", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "accountId": "account-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v2" + }, + "definition": { + "baseUrl": "https://apia.example.com/v2", + "models": [ + "model-a" + ] + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v2" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1" + } + ] + } +} diff --git a/types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json b/types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json deleted file mode 100644 index f3df6f964..000000000 --- a/types/test-cases/reducers/333-root-modelsourceregistrationset-joins-unchanged-routing.json +++ /dev/null @@ -1,152 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet with the same provider, format, and definition, compared as JSON values ignoring key order, joins: it adds the client to contributingClientIds, keeps every host-reported field, and takes displayName from the action", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a (window 2)", - "format": "example.com/model-source@1", - "definition": { - "headers": { - "x-tier": "pro", - "x-region": "eu" - }, - "models": [ - { - "maxContextWindow": 128000, - "id": "model-a" - } - ], - "baseUrl": "https://apia.example.com/v1" - } - }, - "clientId": "client-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a (window 2)", - "format": "example.com/model-source@1", - "definition": { - "headers": { - "x-tier": "pro", - "x-region": "eu" - }, - "models": [ - { - "maxContextWindow": 128000, - "id": "model-a" - } - ], - "baseUrl": "https://apia.example.com/v1" - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json new file mode 100644 index 000000000..7bbc6f59c --- /dev/null +++ b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json @@ -0,0 +1,53 @@ +{ + "description": "root/modelSourceRemoved removes the model source with the given id", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "accountId": "account-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRemoved", + "id": "model-source-a" + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1" + } + ] + } +} diff --git a/types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json b/types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json deleted file mode 100644 index 25477491c..000000000 --- a/types/test-cases/reducers/334-root-modelsourceregistrationset-existing-contributor-not-duplicated.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet from a client that already contributes keeps it listed once, keeps the host-reported fields, and takes retention from the action", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host" - }, - "clientId": "client-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], - "retention": "host", - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - } -} diff --git a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json new file mode 100644 index 000000000..be004d473 --- /dev/null +++ b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json @@ -0,0 +1,34 @@ +{ + "description": "root/modelSourceRemoved is a no-op when no model source has the id", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRemoved", + "id": "model-source-missing" + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + } + ] + } +} diff --git a/types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json b/types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json deleted file mode 100644 index 558b2ca74..000000000 --- a/types/test-cases/reducers/335-root-modelsourceregistrationset-joins-registration-without-contributors.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet joins a host-retained registration whose contributors have all left, making the client its only contributor without disturbing its status, nonce, or credential fields", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host", - "state": { - "kind": "authRequired", - "reason": "expired" - }, - "credentialNonce": "nonce-a-2", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host" - }, - "clientId": "client-3" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-3" - ], - "retention": "host", - "state": { - "kind": "authRequired", - "reason": "expired" - }, - "credentialNonce": "nonce-a-2", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - } -} diff --git a/types/test-cases/reducers/340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json similarity index 51% rename from types/test-cases/reducers/340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json rename to types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json index 7e1273658..975bb553e 100644 --- a/types/test-cases/reducers/340-root-modelsourceregistrationremoved-no-op-when-registry-absent.json +++ b/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json @@ -1,12 +1,12 @@ { - "description": "root/modelSourceRegistrationRemoved is a no-op when the registry is absent", + "description": "root/modelSourceRemoved is a no-op when the registry is absent", "reducer": "root", "initial": { "agents": [] }, "actions": [ { - "type": "root/modelSourceRegistrationRemoved", + "type": "root/modelSourceRemoved", "id": "model-source-a" } ], diff --git a/types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json b/types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json deleted file mode 100644 index c66225c00..000000000 --- a/types/test-cases/reducers/336-root-modelsourceregistrationset-replaces-changed-definition.json +++ /dev/null @@ -1,140 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet with a changed definition replaces the registration: the dispatching client becomes its only contributor, and the host-reported fields are cleared until the host reports again", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v2", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - } - }, - "clientId": "client-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v2", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-2" - ] - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json new file mode 100644 index 000000000..40258dac8 --- /dev/null +++ b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json @@ -0,0 +1,82 @@ +{ + "description": "root/modelSourceStateChanged sets the matching model source's state, credentialNonce, credentialResource, credentialOrigins, and accountId together, adding credential fields it didn't have, and preserves its other fields and the registry order", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1", + "retention": "host", + "state": { + "kind": "starting" + }, + "credentialNonce": "nonce-b-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-b", + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialNonce": "nonce-b-2", + "credentialResource": { + "resource": "https://apib.example.com/v1", + "resource_name": "Source b API key" + }, + "credentialOrigins": [ + "https://apib.example.com" + ], + "accountId": "account-b-1" + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "format": "openaiCompatible", + "nonce": "definition-b-v1", + "retention": "host", + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialNonce": "nonce-b-2", + "credentialResource": { + "resource": "https://apib.example.com/v1", + "resource_name": "Source b API key" + }, + "credentialOrigins": [ + "https://apib.example.com" + ], + "accountId": "account-b-1" + } + ] + } +} diff --git a/types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json b/types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json deleted file mode 100644 index 99a684a6a..000000000 --- a/types/test-cases/reducers/337-root-modelsourceregistrationset-replaces-changed-format.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet with the same definition but a different format replaces the registration and clears the host-reported fields", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@2", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - } - }, - "clientId": "client-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@2", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json new file mode 100644 index 000000000..2bfad4a7f --- /dev/null +++ b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json @@ -0,0 +1,54 @@ +{ + "description": "root/modelSourceStateChanged without credentialResource, credentialOrigins, or accountId clears the model source's existing ones, for a source that turns out to need no credential", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "state": { + "kind": "starting" + }, + "credentialNonce": "nonce-a-1", + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "credentialOrigins": [ + "https://apia.example.com" + ], + "accountId": "account-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-a", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-2" + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-a-2" + } + ] + } +} diff --git a/types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json b/types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json deleted file mode 100644 index 1b34fa968..000000000 --- a/types/test-cases/reducers/338-root-modelsourceregistrationremoved-removes-by-id.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "description": "root/modelSourceRegistrationRemoved removes the registration with the given id for every contributor", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1", - "client-2" - ] - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationRemoved", - "id": "model-source-a" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json new file mode 100644 index 000000000..d230814f4 --- /dev/null +++ b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json @@ -0,0 +1,38 @@ +{ + "description": "root/modelSourceStateChanged is a no-op when no model source has the id, so a late status report can't bring back a removed source", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceStateChanged", + "id": "model-source-removed", + "state": { + "kind": "ready" + }, + "credentialNonce": "nonce-removed-1" + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "format": "openaiCompatible", + "nonce": "definition-a-v1" + } + ] + } +} diff --git a/types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json deleted file mode 100644 index 1c2c088d0..000000000 --- a/types/test-cases/reducers/339-root-modelsourceregistrationremoved-no-op-for-unknown-id.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "description": "root/modelSourceRegistrationRemoved is a no-op when no registration has the id", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationRemoved", - "id": "model-source-missing" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/350-root-modelsourcestatechanged-no-op-when-registry-absent.json b/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json similarity index 100% rename from types/test-cases/reducers/350-root-modelsourcestatechanged-no-op-when-registry-absent.json rename to types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json diff --git a/types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json b/types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json deleted file mode 100644 index 2f38b09d8..000000000 --- a/types/test-cases/reducers/341-root-modelsourcecontributorremoved-removes-one-contributor.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "description": "root/modelSourceContributorRemoved removes only that client from contributingClientIds, keeping the other contributors and the host-reported fields", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "model-source-a", - "clientId": "client-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - } -} diff --git a/types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json b/types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json deleted file mode 100644 index ee299afe9..000000000 --- a/types/test-cases/reducers/342-root-modelsourcecontributorremoved-last-contributor-keeps-registration.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "description": "root/modelSourceContributorRemoved for the last contributor leaves contributingClientIds absent and keeps the registration, which the host removes or retains itself", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "model-source-a", - "clientId": "client-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - } -} diff --git a/types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json b/types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json deleted file mode 100644 index 5ce6c1b42..000000000 --- a/types/test-cases/reducers/343-root-modelsourcecontributorremoved-no-op-for-unknown-client.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "description": "root/modelSourceContributorRemoved is a no-op when the client doesn't contribute the registration", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "model-source-a", - "clientId": "client-9" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - } -} diff --git a/types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json b/types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json deleted file mode 100644 index f6c6f6e64..000000000 --- a/types/test-cases/reducers/344-root-modelsourcecontributorremoved-no-op-without-contributors.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "description": "root/modelSourceContributorRemoved is a no-op for a registration with no contributors, such as one the host registered", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "model-source-a", - "clientId": "client-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "retention": "host" - } - ] - } -} diff --git a/types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json deleted file mode 100644 index 24b3299b4..000000000 --- a/types/test-cases/reducers/345-root-modelsourcecontributorremoved-no-op-for-unknown-id.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "description": "root/modelSourceContributorRemoved is a no-op when no registration has the id", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "model-source-missing", - "clientId": "client-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json deleted file mode 100644 index 4c0f8a0c4..000000000 --- a/types/test-cases/reducers/346-root-modelsourcecontributorremoved-no-op-when-registry-absent.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "description": "root/modelSourceContributorRemoved is a no-op when the registry is absent", - "reducer": "root", - "initial": { - "agents": [] - }, - "actions": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "model-source-a", - "clientId": "client-1" - } - ], - "expected": { - "agents": [] - } -} diff --git a/types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json deleted file mode 100644 index 90915adf9..000000000 --- a/types/test-cases/reducers/347-root-modelsourcestatechanged-updates-host-reported-fields.json +++ /dev/null @@ -1,142 +0,0 @@ -{ - "description": "root/modelSourceStateChanged sets the matching registration's state, credentialNonce, credentialResource, credentialOrigins, and credentialId together, adding credential fields the registration didn't have, and preserves its other fields and the registry order", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ], - "retention": "host", - "state": { - "kind": "starting" - }, - "credentialNonce": "nonce-b-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "id": "model-source-b", - "state": { - "kind": "authRequired", - "reason": "rejected", - "description": "The endpoint rejected the API key." - }, - "credentialNonce": "nonce-b-2", - "credentialResource": { - "resource": "https://apib.example.com/v1", - "resource_name": "Source b API key" - }, - "credentialOrigins": [ - "https://apib.example.com" - ], - "credentialId": "key-b-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ], - "retention": "host", - "state": { - "kind": "authRequired", - "reason": "rejected", - "description": "The endpoint rejected the API key." - }, - "credentialNonce": "nonce-b-2", - "credentialResource": { - "resource": "https://apib.example.com/v1", - "resource_name": "Source b API key" - }, - "credentialOrigins": [ - "https://apib.example.com" - ], - "credentialId": "key-b-1" - } - ] - } -} diff --git a/types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json b/types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json deleted file mode 100644 index 11fb03c81..000000000 --- a/types/test-cases/reducers/348-root-modelsourcestatechanged-clears-credential-fields.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "description": "root/modelSourceStateChanged without credentialResource, credentialOrigins, or credentialId clears the registration's existing ones, for a source that turns out to need no credential", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ], - "state": { - "kind": "starting" - }, - "credentialNonce": "nonce-a-1", - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "credentialOrigins": [ - "https://apia.example.com" - ], - "credentialId": "key-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "id": "model-source-a", - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-a-2" - } - ] - } -} diff --git a/types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json deleted file mode 100644 index 99be677af..000000000 --- a/types/test-cases/reducers/349-root-modelsourcestatechanged-no-op-for-unknown-id.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "description": "root/modelSourceStateChanged is a no-op when no registration has the id, so a late status report can't bring back a removed registration", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "id": "model-source-removed", - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-removed-1" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a", - "maxContextWindow": 128000 - } - ], - "headers": { - "x-region": "eu", - "x-tier": "pro" - } - }, - "contributingClientIds": [ - "client-1" - ] - } - ] - } -} diff --git a/types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json b/types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json deleted file mode 100644 index 52fab1ba6..000000000 --- a/types/test-cases/reducers/351-root-modelsourceregistrationset-joins-numerically-equal-definition.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "description": "root/modelSourceRegistrationSet compares definition numbers by numeric value, so 4096 and 4096.0, 0.5 and 0.50, and 1e3 and 1000 are the same routing: the client joins, and the host-reported fields are kept", - "reducer": "root", - "initial": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-n", - "provider": "copilot", - "displayName": "Numbers", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://apin.example.com/v1", - "maxOutputTokens": 4096, - "temperature": 0.5, - "limits": { - "rpm": 1e3 - } - }, - "contributingClientIds": [ - "client-1" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-n-1", - "credentialId": "key-n-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "model-source-n", - "provider": "copilot", - "displayName": "Numbers", - "format": "example.com/model-source@1", - "definition": { - "limits": { - "rpm": 1000 - }, - "temperature": 0.50, - "maxOutputTokens": 4096.0, - "baseUrl": "https://apin.example.com/v1" - } - }, - "clientId": "client-2" - } - ], - "expected": { - "agents": [], - "modelSourceRegistrations": [ - { - "id": "model-source-n", - "provider": "copilot", - "displayName": "Numbers", - "format": "example.com/model-source@1", - "definition": { - "limits": { - "rpm": 1000 - }, - "temperature": 0.50, - "maxOutputTokens": 4096.0, - "baseUrl": "https://apin.example.com/v1" - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], - "state": { - "kind": "ready" - }, - "credentialNonce": "nonce-n-1", - "credentialId": "key-n-1" - } - ] - } -} diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 6cae8b08a..60cfb4b26 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot carries model source registrations with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a source two clients contribute, a host-retained source whose contributors have all left, and a host-registered source. Sources that take a credential carry a host-reported credentialResource and credentialOrigins in every state, and credentialId once the host has accepted a key. The agent advertises the modelSourceRegistration capability with its formats, contributor grace period, and principal policy, and its catalog lists the ready registration and the authRequired one whose key expired, since models stay listed after a registration has been ready.", + "description": "A root snapshot carries registered model sources with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each source carries a nonce for its definition, which isn't kept in state. Sources that take a credential carry a host-reported credentialResource and credentialOrigins in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with the recognized formats it reads and a namespaced one, its contributor grace period, and its principal policy, and its catalog lists the ready source and the authRequired one whose key expired, since models stay listed after a source has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -15,8 +15,11 @@ "capabilities": { "modelSourceRegistration": { "formats": [ - "example.com/model-source@1", - "example.com/model-source@0" + "openaiCompatible", + "anthropic", + "azureOpenai", + "gemini", + "example.com/model-source@1" ], "gracePeriod": 30000, "principalPolicy": "shared" @@ -50,44 +53,20 @@ ] } ], - "modelSourceRegistrations": [ + "modelSources": [ { "id": "source-unreported", "provider": "example", "displayName": "Unreported", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1" - ] + "format": "anthropic", + "nonce": "sha256-unreported-1" }, { "id": "source-starting", "provider": "example", "displayName": "Starting", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1" - ], + "format": "gemini", + "nonce": "sha256-starting-1", "state": { "kind": "starting" }, @@ -97,21 +76,8 @@ "id": "source-ready", "provider": "example", "displayName": "OpenRouter", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], + "format": "openaiCompatible", + "nonce": "sha256-ready-1", "icons": [ { "src": "https://example.com/openrouter.svg" @@ -130,7 +96,7 @@ "https://api.example.com", "https://files.example.com" ], - "credentialId": "keychain-openrouter-1", + "accountId": "keychain-openrouter-1", "_meta": { "example.com/label": "Laptop" } @@ -139,20 +105,8 @@ "id": "source-auth", "provider": "example", "displayName": "Azure endpoint", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://example.openai.azure.com/openai/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1" - ], + "format": "azureOpenai", + "nonce": "sha256-auth-1", "retention": "contributingClient", "state": { "kind": "authRequired", @@ -173,19 +127,14 @@ "credentialOrigins": [ "https://example.openai.azure.com" ], - "credentialId": "entra-azure-1" + "accountId": "entra-azure-1" }, { "id": "source-local", "provider": "example", "displayName": "Local server", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "http://localhost:11434/v1" - }, - "contributingClientIds": [ - "client-1" - ], + "format": "openaiCompatible", + "nonce": "sha256-local-1", "state": { "kind": "authRequired", "reason": "required" @@ -203,20 +152,8 @@ "id": "source-rejected", "provider": "example", "displayName": "Rejected key", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-2" - ], + "format": "openaiCompatible", + "nonce": "sha256-rejected-1", "icons": [ { "src": "https://example.com/openrouter.svg" @@ -237,23 +174,14 @@ "https://api.example.com", "https://files.example.com" ], - "credentialId": "keychain-rejected-1" + "accountId": "keychain-rejected-1" }, { "id": "source-revoked", "provider": "example", "displayName": "Revoked key", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, + "format": "openaiCompatible", + "nonce": "sha256-revoked-1", "icons": [ { "src": "https://example.com/openrouter.svg" @@ -273,16 +201,14 @@ "https://api.example.com", "https://files.example.com" ], - "credentialId": "keychain-revoked-1" + "accountId": "keychain-revoked-1" }, { "id": "source-host", "provider": "example", "displayName": "Host-configured", "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://models.internal.example/v1" - }, + "nonce": "sha256-host-1", "state": { "kind": "error", "error": { @@ -308,8 +234,11 @@ "capabilities": { "modelSourceRegistration": { "formats": [ - "example.com/model-source@1", - "example.com/model-source@0" + "openaiCompatible", + "anthropic", + "azureOpenai", + "gemini", + "example.com/model-source@1" ], "gracePeriod": 30000, "principalPolicy": "shared" @@ -343,44 +272,20 @@ ] } ], - "modelSourceRegistrations": [ + "modelSources": [ { "id": "source-unreported", "provider": "example", "displayName": "Unreported", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1" - ] + "format": "anthropic", + "nonce": "sha256-unreported-1" }, { "id": "source-starting", "provider": "example", "displayName": "Starting", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1" - ], + "format": "gemini", + "nonce": "sha256-starting-1", "state": { "kind": "starting" }, @@ -390,21 +295,8 @@ "id": "source-ready", "provider": "example", "displayName": "OpenRouter", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1", - "client-2" - ], + "format": "openaiCompatible", + "nonce": "sha256-ready-1", "icons": [ { "src": "https://example.com/openrouter.svg" @@ -423,7 +315,7 @@ "https://api.example.com", "https://files.example.com" ], - "credentialId": "keychain-openrouter-1", + "accountId": "keychain-openrouter-1", "_meta": { "example.com/label": "Laptop" } @@ -432,20 +324,8 @@ "id": "source-auth", "provider": "example", "displayName": "Azure endpoint", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://example.openai.azure.com/openai/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-1" - ], + "format": "azureOpenai", + "nonce": "sha256-auth-1", "retention": "contributingClient", "state": { "kind": "authRequired", @@ -466,19 +346,14 @@ "credentialOrigins": [ "https://example.openai.azure.com" ], - "credentialId": "entra-azure-1" + "accountId": "entra-azure-1" }, { "id": "source-local", "provider": "example", "displayName": "Local server", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "http://localhost:11434/v1" - }, - "contributingClientIds": [ - "client-1" - ], + "format": "openaiCompatible", + "nonce": "sha256-local-1", "state": { "kind": "authRequired", "reason": "required" @@ -496,20 +371,8 @@ "id": "source-rejected", "provider": "example", "displayName": "Rejected key", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, - "contributingClientIds": [ - "client-2" - ], + "format": "openaiCompatible", + "nonce": "sha256-rejected-1", "icons": [ { "src": "https://example.com/openrouter.svg" @@ -530,23 +393,14 @@ "https://api.example.com", "https://files.example.com" ], - "credentialId": "keychain-rejected-1" + "accountId": "keychain-rejected-1" }, { "id": "source-revoked", "provider": "example", "displayName": "Revoked key", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://api.example.com/v1", - "wireFormat": "openai-chat", - "models": [ - { - "id": "example-model", - "maxContextWindow": 128000 - } - ] - }, + "format": "openaiCompatible", + "nonce": "sha256-revoked-1", "icons": [ { "src": "https://example.com/openrouter.svg" @@ -566,16 +420,14 @@ "https://api.example.com", "https://files.example.com" ], - "credentialId": "keychain-revoked-1" + "accountId": "keychain-revoked-1" }, { "id": "source-host", "provider": "example", "displayName": "Host-configured", "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://models.internal.example/v1" - }, + "nonce": "sha256-host-1", "state": { "kind": "error", "error": { diff --git a/types/test-cases/round-trips/104-root-model-source-registration-set.json b/types/test-cases/round-trips/104-root-model-source-registration-set.json deleted file mode 100644 index 2fcde6cd8..000000000 --- a/types/test-cases/round-trips/104-root-model-source-registration-set.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "root-model-source-registration-set", - "group": "A", - "description": "A client contributes a model source with root/modelSourceRegistrationSet: its own clientId on the action, requested retention, an open definition, and no host-reported fields.", - "type": "StateAction", - "input": { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "source-new", - "provider": "example", - "displayName": "OpenRouter", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://openrouter.ai/api/v1", - "models": [ - "vendor/model-a", - "vendor/model-b" - ], - "headers": { - "x-title": "Example" - } - }, - "retention": "host" - }, - "clientId": "client-1" - }, - "acceptableOutputs": [ - { - "type": "root/modelSourceRegistrationSet", - "registration": { - "id": "source-new", - "provider": "example", - "displayName": "OpenRouter", - "format": "example.com/model-source@1", - "definition": { - "baseUrl": "https://openrouter.ai/api/v1", - "models": [ - "vendor/model-a", - "vendor/model-b" - ], - "headers": { - "x-title": "Example" - } - }, - "retention": "host" - }, - "clientId": "client-1" - } - ] -} diff --git a/types/test-cases/round-trips/104-root-model-source-set.json b/types/test-cases/round-trips/104-root-model-source-set.json new file mode 100644 index 000000000..4482df08d --- /dev/null +++ b/types/test-cases/round-trips/104-root-model-source-set.json @@ -0,0 +1,50 @@ +{ + "name": "root-model-source-set", + "group": "A", + "description": "A client registers a model source with root/modelSourceSet: the source with a nonce for its definition and requested retention, no host-reported fields, and an open definition alongside it that the reducer doesn't store.", + "type": "StateAction", + "input": { + "type": "root/modelSourceSet", + "modelSource": { + "id": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "format": "openaiCompatible", + "nonce": "sha256-new-1", + "retention": "host" + }, + "definition": { + "baseUrl": "https://openrouter.ai/api/v1", + "models": [ + "vendor/model-a", + "vendor/model-b" + ], + "headers": { + "x-title": "Example" + } + } + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "format": "openaiCompatible", + "nonce": "sha256-new-1", + "retention": "host" + }, + "definition": { + "baseUrl": "https://openrouter.ai/api/v1", + "models": [ + "vendor/model-a", + "vendor/model-b" + ], + "headers": { + "x-title": "Example" + } + } + } + ] +} diff --git a/types/test-cases/round-trips/105-root-model-source-registration-removed.json b/types/test-cases/round-trips/105-root-model-source-registration-removed.json deleted file mode 100644 index 0d6aa7316..000000000 --- a/types/test-cases/round-trips/105-root-model-source-registration-removed.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "root-model-source-registration-removed", - "group": "A", - "description": "A client removes a model source registration by id with root/modelSourceRegistrationRemoved.", - "type": "StateAction", - "input": { - "type": "root/modelSourceRegistrationRemoved", - "id": "source-new" - }, - "acceptableOutputs": [ - { - "type": "root/modelSourceRegistrationRemoved", - "id": "source-new" - } - ] -} diff --git a/types/test-cases/round-trips/105-root-model-source-removed.json b/types/test-cases/round-trips/105-root-model-source-removed.json new file mode 100644 index 000000000..cbb4b9edd --- /dev/null +++ b/types/test-cases/round-trips/105-root-model-source-removed.json @@ -0,0 +1,16 @@ +{ + "name": "root-model-source-removed", + "group": "A", + "description": "A client removes a model source by id, for every client, with root/modelSourceRemoved.", + "type": "StateAction", + "input": { + "type": "root/modelSourceRemoved", + "id": "source-new" + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceRemoved", + "id": "source-new" + } + ] +} diff --git a/types/test-cases/round-trips/106-authenticate-model-source-target.json b/types/test-cases/round-trips/106-authenticate-model-source-target.json index 58250789e..665663e80 100644 --- a/types/test-cases/round-trips/106-authenticate-model-source-target.json +++ b/types/test-cases/round-trips/106-authenticate-model-source-target.json @@ -1,17 +1,17 @@ { "name": "authenticate-model-source-target", "group": "A", - "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target that echoes the registration's credentialNonce and names the key with a non-secret credentialId. An API key carries no expiresIn or scopes.", + "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target that echoes the source's credentialNonce, and names the key with the existing accountId parameter. An API key carries no expiresIn or scopes.", "type": "AuthenticateParams", "input": { "channel": "ahp-root://", "resource": "https://openrouter.ai/api/v1", "token": "test-api-key", + "accountId": "keychain-openrouter-1", "target": { "kind": "modelSource", "modelSourceId": "source-new", - "credentialNonce": "nonce-openrouter-1", - "credentialId": "keychain-openrouter-1" + "credentialNonce": "nonce-openrouter-1" } }, "acceptableOutputs": [ @@ -19,11 +19,11 @@ "channel": "ahp-root://", "resource": "https://openrouter.ai/api/v1", "token": "test-api-key", + "accountId": "keychain-openrouter-1", "target": { "kind": "modelSource", "modelSourceId": "source-new", - "credentialNonce": "nonce-openrouter-1", - "credentialId": "keychain-openrouter-1" + "credentialNonce": "nonce-openrouter-1" } } ] diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json index 1b28d7573..1f5bcc0d8 100644 --- a/types/test-cases/round-trips/107-root-model-source-state-changed.json +++ b/types/test-cases/round-trips/107-root-model-source-state-changed.json @@ -1,7 +1,7 @@ { "name": "root-model-source-state-changed", "group": "A", - "description": "The host reports with root/modelSourceStateChanged that the endpoint rejected a key, issuing a new credential nonce and naming the rejected key's credentialId, along with the credentialResource and every origin the key is sent to.", + "description": "The host reports with root/modelSourceStateChanged that the endpoint rejected a key, issuing a new credential nonce and naming the rejected key's accountId, along with the credentialResource and every origin the key is sent to.", "type": "StateAction", "input": { "type": "root/modelSourceStateChanged", @@ -19,7 +19,7 @@ "credentialOrigins": [ "https://openrouter.ai" ], - "credentialId": "keychain-openrouter-1" + "accountId": "keychain-openrouter-1" }, "acceptableOutputs": [ { @@ -38,7 +38,7 @@ "credentialOrigins": [ "https://openrouter.ai" ], - "credentialId": "keychain-openrouter-1" + "accountId": "keychain-openrouter-1" } ] } diff --git a/types/test-cases/round-trips/108-root-model-source-contributor-removed.json b/types/test-cases/round-trips/108-root-model-source-contributor-removed.json deleted file mode 100644 index 97f35ada3..000000000 --- a/types/test-cases/round-trips/108-root-model-source-contributor-removed.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "root-model-source-contributor-removed", - "group": "A", - "description": "A client withdraws its own contribution to a model source with root/modelSourceContributorRemoved.", - "type": "StateAction", - "input": { - "type": "root/modelSourceContributorRemoved", - "id": "source-new", - "clientId": "client-1" - }, - "acceptableOutputs": [ - { - "type": "root/modelSourceContributorRemoved", - "id": "source-new", - "clientId": "client-1" - } - ] -} diff --git a/types/version/registry.ts b/types/version/registry.ts index 4a9435826..5429ac83c 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -186,9 +186,8 @@ export const ACTION_INTRODUCED_IN: { readonly [K in StateAction['type']]: string [ActionType.AnnotationsEntryRemoved]: '0.4.0', [ActionType.RootTerminalsChanged]: '0.1.0', [ActionType.RootConfigChanged]: '0.1.0', - [ActionType.RootModelSourceRegistrationSet]: '1.2.0', - [ActionType.RootModelSourceContributorRemoved]: '1.2.0', - [ActionType.RootModelSourceRegistrationRemoved]: '1.2.0', + [ActionType.RootModelSourceSet]: '1.2.0', + [ActionType.RootModelSourceRemoved]: '1.2.0', [ActionType.RootModelSourceStateChanged]: '1.2.0', [ActionType.TerminalData]: '0.1.0', [ActionType.TerminalInput]: '0.1.0', From d4f0aac27176808ea75a0af345837a537fc98427 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Tue, 24 Nov 2026 15:57:59 -0500 Subject: [PATCH 10/17] models: keep source definitions in state and trim host policy fields Implements #622 at f30b11a3: - `ModelSource.definition` is back in state, with suggested shapes for the recognized formats documented on it. `root/modelSourceSet` carries only `modelSource`. Reducers still compare `provider`, `format`, and `nonce`. - Remove `credentialNonce` and `credentialOrigins` from `ModelSource`, `root/modelSourceStateChanged`, and the `modelSource` authenticate target. - `ModelSourceRegistrationCapability.formats` lists `ModelSourceFormatInfo` objects. Remove `gracePeriod`, `principalPolicy`, and `ModelSourcePrincipalPolicy`, which are now host policy. Updates the generators, client reducers, fixtures, specs, naming dictionary, and changelog fragment to match. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../protocol-naming.instructions.md | 2 +- .../Generated/Actions.generated.cs | 28 +-- .../Generated/Commands.generated.cs | 8 +- .../JsonSerializerContext.generated.cs | 2 +- .../Generated/State.generated.cs | 139 +++-------- .../dotnet/src/AgentHostProtocol/Reducers.cs | 4 +- clients/go/ahp/reducers.go | 5 - clients/go/ahptypes/actions.generated.go | 24 +- clients/go/ahptypes/commands.generated.go | 7 +- clients/go/ahptypes/state.generated.go | 106 ++++---- .../microsoft/agenthostprotocol/Reducers.kt | 4 - .../generated/Actions.generated.kt | 32 +-- .../generated/Commands.generated.kt | 11 +- .../generated/State.generated.kt | 128 ++++------ clients/rust/crates/ahp-types/src/actions.rs | 25 +- clients/rust/crates/ahp-types/src/commands.rs | 7 +- clients/rust/crates/ahp-types/src/state.rs | 123 ++++----- clients/rust/crates/ahp/src/reducers.rs | 6 - .../Generated/Actions.generated.swift | 32 +-- .../Generated/Commands.generated.swift | 11 +- .../Generated/State.generated.swift | 160 ++++++------ .../AgentHostProtocol/NativeReducer.swift | 4 - .../20261123-model-source-registry.json | 2 +- docs/specification/authentication.md | 24 +- docs/specification/root-channel.md | 50 ++-- schema/actions.schema.json | 85 +++---- schema/commands.schema.json | 94 +++---- schema/errors.schema.json | 94 +++---- schema/notifications.schema.json | 57 ++--- schema/state.schema.json | 57 ++--- scripts/generate-csharp.ts | 3 +- scripts/generate-go.ts | 3 +- scripts/generate-kotlin.ts | 4 +- scripts/generate-rust.ts | 3 +- scripts/generate-swift.ts | 4 +- types/channels-root/actions.ts | 28 +-- types/channels-root/reducer.ts | 2 +- types/channels-root/state.ts | 100 +++----- types/common/commands.ts | 9 +- ...odelsourceset-adds-to-absent-registry.json | 24 +- ...e-register-keeps-host-reported-fields.json | 56 +++-- ...et-update-clears-host-reported-fields.json | 52 +++- ...root-modelsourceremoved-removes-by-id.json | 28 ++- ...delsourceremoved-no-op-for-unknown-id.json | 16 ++ ...echanged-updates-host-reported-fields.json | 45 +++- ...statechanged-clears-credential-fields.json | 28 ++- ...urcestatechanged-no-op-for-unknown-id.json | 19 +- ...atechanged-no-op-when-registry-absent.json | 3 +- .../103-model-source-registry-snapshot.json | 234 ++++++++++++------ .../104-root-model-source-set.json | 58 +++-- .../106-authenticate-model-source-target.json | 8 +- .../107-root-model-source-state-changed.json | 10 +- 52 files changed, 960 insertions(+), 1108 deletions(-) diff --git a/.github/instructions/protocol-naming.instructions.md b/.github/instructions/protocol-naming.instructions.md index 2cc90c774..3ef02040b 100644 --- a/.github/instructions/protocol-naming.instructions.md +++ b/.github/instructions/protocol-naming.instructions.md @@ -41,7 +41,7 @@ but don't use them as precedent. | **model source** (`modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `AgentInfo.modelSources` (`ModelSourceInfo`). Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | | **registration** (`ModelSource`) | A model source a client or the host added to the host's registry in `RootState.modelSources`, with its status. A ready registration joins its agent's catalog as a model source, and a registered source is also called a registration. | The **model source** it becomes in the catalog (`ModelSourceInfo`). | | **contributing client** | A client that added a client-contributed entry. For a model source, it's a client that registered it and hasn't left; the host tracks these itself, from `ActionEnvelope.origin`, and they aren't in state. | The **action origin**'s `clientId`, which names the client that dispatched one action. | -| **principal** | The user or account a host has verified a client acts for. AHP doesn't define how a host verifies one (`ModelSourcePrincipalPolicy`). | A **client** (`clientId`), which identifies a connection's client and isn't verified. | +| **principal** | The user or account a host has verified a client acts for. AHP doesn't define how a host verifies one. A host MAY restrict model sources by principal. | A **client** (`clientId`), which identifies a connection's client and isn't verified. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | | **pending message** | Input waiting to be consumed. Its `kind` is **steering** (injected into the active turn) or **queued** (starts a later turn). Both kinds live in `ChatState.queuedMessages`. | | | **working directories** | The session's set of directories. A chat may use a subset. | Don't use "workspace" for a protocol field. | diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index e579eb4e0..1ead12d85 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -346,14 +346,12 @@ public sealed record RootConfigChangedAction public bool? Replace { get; init; } } -/// Adds a model source, or updates the one with the same `id`. The reducer -/// stores `modelSource` without the definition: +/// Adds a model source, or updates the one with the same `id`: /// /// - **Add.** When no model source has the `id`, appends `modelSource`. /// - **Re-register.** When one has, with the same `provider`, `format`, and -/// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, -/// `credentialResource`, `credentialOrigins`, and `accountId`) and takes -/// the other fields from the action. +/// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, +/// and `accountId`) and takes everything else from the action. /// - **Update.** When any of the three differs, replaces the source. Its /// host-reported fields are absent until the host reports again with /// {@link RootModelSourceStateChangedAction}. @@ -366,13 +364,9 @@ public sealed record RootModelSourceSetAction { public ActionType Type { get; init; } = ActionType.RootModelSourceSet; - /// The model source to add or update, matched by `id`, without host-reported fields. + /// The model source to add or update, matched by `id`, including its + /// `definition`, without host-reported fields. public required ModelSource ModelSource { get; init; } - - /// How to reach the source, in `modelSource.format`: endpoint, wire format, - /// models, and so on. The host hands it to the agent, and the reducer - /// doesn't store it. MUST NOT contain a credential. - public required Dictionary Definition { get; init; } } /// Removes the model source with the given `id`, for every client. A no-op @@ -388,9 +382,8 @@ public sealed record RootModelSourceRemovedAction } /// Updates a model source's host-reported fields together: `state`, -/// `credentialNonce`, `credentialResource`, `credentialOrigins`, and -/// `accountId`. A no-op when no model source has `id`. Other fields of the -/// source are preserved. Only the host dispatches it. +/// `credentialResource`, and `accountId`. A no-op when no model source has +/// `id`. Other fields of the source are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceStateChangedAction @@ -403,18 +396,11 @@ public sealed record RootModelSourceStateChangedAction /// The new status. public required ModelSourceState State { get; init; } - /// The model source's current credential nonce. - public required string CredentialNonce { get; init; } - /// Replaces the source's `credentialResource`. Absent clears it, for a /// source that needs no credential. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } - /// Replaces the source's `credentialOrigins`. Absent clears it. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public List? CredentialOrigins { get; init; } - /// Replaces the source's `accountId`. Absent clears it. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? AccountId { get; init; } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index af9401be7..f8ad4a726 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1894,11 +1894,6 @@ public sealed record ModelSourceAuthenticateTarget /// The registration's `ModelSource.id`. public required string ModelSourceId { get; init; } - - /// The registration's current `ModelSource.credentialNonce`, as - /// published in root state. The host rejects a stale one with `Conflict` - /// (-32011). - public required string CredentialNonce { get; init; } } /// Pushes a credential for a protected resource. The `resource` field MUST @@ -1980,7 +1975,8 @@ public sealed record AuthenticateParams /// /// A registered model source takes its credential only through a /// `modelSource` target, and the host rejects an untargeted `resource` that - /// matches only model source challenges with `InvalidParams` (-32602). See + /// matches only model source challenges with `InvalidParams` (-32602). A + /// delivery replaces whatever credential the host holds for the source. See /// [Model source credentials](/specification/authentication#model-source-credentials) /// for its rules. /// diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 53449a991..9ca757528 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -304,8 +304,8 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ModelSourceAuthRequiredState))] [JsonSerializable(typeof(ModelSourceAuthRequirement))] [JsonSerializable(typeof(ModelSourceErrorState))] +[JsonSerializable(typeof(ModelSourceFormatInfo))] [JsonSerializable(typeof(ModelSourceInfo))] -[JsonSerializable(typeof(ModelSourcePrincipalPolicy))] [JsonSerializable(typeof(ModelSourceReadyState))] [JsonSerializable(typeof(ModelSourceRegistrationCapability))] [JsonSerializable(typeof(ModelSourceRetentionPolicy))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 6299602d5..88abb07e9 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1588,66 +1588,6 @@ public override void Write(Utf8JsonWriter writer, ModelSourceAuthRequiredReason => writer.WriteStringValue(value.Value); } -/// Whether clients acting for different principals share a host's model -/// source registry. -/// -/// Stability: 1.0 - Early development. -[JsonConverter(typeof(ModelSourcePrincipalPolicyConverter))] -public readonly struct ModelSourcePrincipalPolicy : IEquatable -{ - private readonly string? _value; - - /// Wraps a raw wire value — including one this build does not recognize. - /// The raw wire string. - public ModelSourcePrincipalPolicy(string value) - { - _value = value; - } - - /// The raw wire value. - public string Value => _value ?? string.Empty; - - /// Every connected client may change, supply credentials for, and select - /// every model source. - public static readonly ModelSourcePrincipalPolicy Shared = new ModelSourcePrincipalPolicy("shared"); - - /// The host verifies principals, and limits changes, credentials, and - /// selection of each model source to clients of the principal that - /// registered it. Root state still lists every model source to every - /// client. - public static readonly ModelSourcePrincipalPolicy Isolated = new ModelSourcePrincipalPolicy("isolated"); - - /// - public bool Equals(ModelSourcePrincipalPolicy other) => string.Equals(Value, other.Value, StringComparison.Ordinal); - - /// - public override bool Equals(object? obj) => obj is ModelSourcePrincipalPolicy other && Equals(other); - - /// - public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); - - /// - public override string ToString() => Value; - - /// Ordinal equality over the raw wire value. - public static bool operator ==(ModelSourcePrincipalPolicy left, ModelSourcePrincipalPolicy right) => left.Equals(right); - - /// Ordinal inequality over the raw wire value. - public static bool operator !=(ModelSourcePrincipalPolicy left, ModelSourcePrincipalPolicy right) => !left.Equals(right); -} - -/// Reads and writes as its raw wire string, preserving unrecognized values. -internal sealed class ModelSourcePrincipalPolicyConverter : JsonConverter -{ - /// - public override ModelSourcePrincipalPolicy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => new ModelSourcePrincipalPolicy(reader.GetString() ?? throw new JsonException("ModelSourcePrincipalPolicy expects a JSON string.")); - - /// - public override void Write(Utf8JsonWriter writer, ModelSourcePrincipalPolicy value, JsonSerializerOptions options) - => writer.WriteStringValue(value.Value); -} - /// Computation lifecycle of a {@link ChangesetState}. [JsonConverter(typeof(ChangesetStatusConverter))] public readonly struct ChangesetStatus : IEquatable @@ -2475,20 +2415,23 @@ public sealed record MultipleWorkingDirectoriesCapability /// Stability: 1.0 - Early development. public sealed record ModelSourceRegistrationCapability { - /// Definition formats the agent reads, most preferred first: recognized - /// values of {@link ModelSource.format}, or namespaced names for formats - /// the agent defines itself. - public required List Formats { get; init; } + /// Definition formats the agent reads, most preferred first. + public required List Formats { get; init; } - /// How long, in milliseconds, the host keeps counting a disconnected client - /// as a contributing client before it treats the client as having left. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public long? GracePeriod { get; init; } + /// Unrecognized wire members retained for full-object edits. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} - /// Whether clients acting for different principals share the registry. - /// Absent means `shared`. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public ModelSourcePrincipalPolicy? PrincipalPolicy { get; init; } +/// A definition format an agent reads. An object so it can grow, for example +/// with a JSON Schema for the format's definitions. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceFormatInfo +{ + /// A recognized {@link ModelSource.format} value, or a namespaced name for + /// a format the agent defines itself. + public required string Format { get; init; } /// Unrecognized wire members retained for full-object edits. [JsonExtensionData] @@ -2496,9 +2439,7 @@ public sealed record ModelSourceRegistrationCapability } /// A model source registered on this host by a client, or by the host itself. -/// The definition that tells the agent named by `provider` how to reach it -/// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing -/// here is a credential. +/// Nothing here is a credential. /// /// Stability: 1.0 - Early development. public sealed record ModelSource @@ -2518,7 +2459,7 @@ public sealed record ModelSource [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? Icons { get; init; } - /// The definition's format, one of the agent's + /// The definition's format: the `format` of one of the agent's /// {@link ModelSourceRegistrationCapability.formats}. Recognized values /// include: /// @@ -2528,15 +2469,33 @@ public sealed record ModelSource /// - `'azureOpenai'`: an Azure OpenAI deployment. /// - `'gemini'`: Google's Gemini API. /// - /// AHP doesn't define what a definition contains, even for these. Agents - /// MAY read other formats, named with a namespace such as + /// Agents MAY read other formats, named with a namespace such as /// `example.com/model-source@1` so they don't collide. public required string Format { get; init; } - /// Opaque version token for the definition, such as a hash of it, chosen by - /// whoever registers the source. A client compares it with its own copy - /// instead of the definition, and the reducer compares it to tell an update - /// from a re-registration of the same definition. + /// How to reach the source, in `format`: endpoint, wire API, models, and so + /// on. The agent reads it, and AHP doesn't validate it. Every client can + /// read it, so it MUST NOT contain a credential. + /// + /// Suggested shapes for the recognized formats. Agents MAY read more + /// members, and MAY discover models when `models` is absent. + /// + /// - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` + /// - `anthropic`: `{ endpoint, models? }` + /// - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each + /// deployment name as a model `id` + /// - `gemini`: `{ endpoint, models? }` + /// + /// `endpoint` is the API's base URI, such as `https://api.example.com/v1`. + /// Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, + /// supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, + /// where `id` is the endpoint's own model identifier. + public required Dictionary Definition { get; init; } + + /// Opaque version token for `definition`, such as a hash of it, chosen by + /// whoever registers the source. Reducers compare it, instead of the + /// definition, to tell an update from a re-registration of the same + /// definition. public required string Nonce { get; init; } /// What happens when the last contributing client leaves. Absent means `contributingClient`. @@ -2549,15 +2508,6 @@ public sealed record ModelSource [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceState? State { get; init; } - /// Host-issued token that a client echoes in - /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential, and that tags every agent operation on the source. The - /// host issues a new one when the source is added or updated, and whenever - /// the credential is installed or dropped. It never reuses one for the - /// same `id`. Set with `state`. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? CredentialNonce { get; init; } - /// RFC 9728 metadata for the endpoint the credential is for. Present /// whenever the source takes a credential, in every state, so any client /// can deliver, rotate, or revoke one. Absent for a source that needs no @@ -2574,13 +2524,6 @@ public sealed record ModelSource [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } - /// Every origin the host sends the credential to, such as - /// `https://api.example.com`, derived from the definition it holds. Present - /// whenever `credentialResource` is. A client checks each one against its - /// own copy of the definition before it sends a key. Set with `state`. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public List? CredentialOrigins { get; init; } - /// The {@link AuthenticateParams.accountId} the client sent with the /// credential the host most recently accepted. While the state is /// `starting` or `ready`, the host holds that credential. While it's diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index 45b483f2e..c046ad153 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -688,9 +688,7 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) ModelSource merged = a.ModelSource with { State = existing?.State, - CredentialNonce = existing?.CredentialNonce, CredentialResource = existing?.CredentialResource, - CredentialOrigins = existing?.CredentialOrigins, AccountId = existing?.AccountId, }; if (index < 0) @@ -724,7 +722,7 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) } List list = state.ModelSources!; - list[index] = list[index] with { State = a.State, CredentialNonce = a.CredentialNonce, CredentialResource = a.CredentialResource, CredentialOrigins = a.CredentialOrigins, AccountId = a.AccountId }; + list[index] = list[index] with { State = a.State, CredentialResource = a.CredentialResource, AccountId = a.AccountId }; return ReduceOutcome.Applied; } } diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 974d70439..0fa2046c7 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -564,12 +564,9 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R return ReduceOutcomeNoOp } st := a.State - nonce := a.CredentialNonce copyModelSourceHostFields(&state.ModelSources[idx], ahptypes.ModelSource{ State: &st, - CredentialNonce: &nonce, CredentialResource: a.CredentialResource, - CredentialOrigins: a.CredentialOrigins, AccountId: a.AccountId, }) return ReduceOutcomeApplied @@ -590,9 +587,7 @@ func modelSourceIndex(list []ahptypes.ModelSource, id string) int { // clearing the ones from lacks. func copyModelSourceHostFields(to *ahptypes.ModelSource, from ahptypes.ModelSource) { to.State = from.State - to.CredentialNonce = from.CredentialNonce to.CredentialResource = from.CredentialResource - to.CredentialOrigins = from.CredentialOrigins to.AccountId = from.AccountId } diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 29d83b5cd..49421927a 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -179,14 +179,12 @@ type RootConfigChangedAction struct { Replace *bool `json:"replace,omitempty"` } -// Adds a model source, or updates the one with the same `id`. The reducer -// stores `modelSource` without the definition: +// Adds a model source, or updates the one with the same `id`: // // - **Add.** When no model source has the `id`, appends `modelSource`. // - **Re-register.** When one has, with the same `provider`, `format`, and -// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, -// `credentialResource`, `credentialOrigins`, and `accountId`) and takes -// the other fields from the action. +// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, +// and `accountId`) and takes everything else from the action. // - **Update.** When any of the three differs, replaces the source. Its // host-reported fields are absent until the host reports again with // {@link RootModelSourceStateChangedAction}. @@ -197,12 +195,9 @@ type RootConfigChangedAction struct { // Stability: 1.0 - Early development. type RootModelSourceSetAction struct { Type ActionType `json:"type"` - // The model source to add or update, matched by `id`, without host-reported fields. + // The model source to add or update, matched by `id`, including its + // `definition`, without host-reported fields. ModelSource ModelSource `json:"modelSource"` - // How to reach the source, in `modelSource.format`: endpoint, wire format, - // models, and so on. The host hands it to the agent, and the reducer - // doesn't store it. MUST NOT contain a credential. - Definition map[string]json.RawMessage `json:"definition"` } // Removes the model source with the given `id`, for every client. A no-op @@ -216,9 +211,8 @@ type RootModelSourceRemovedAction struct { } // Updates a model source's host-reported fields together: `state`, -// `credentialNonce`, `credentialResource`, `credentialOrigins`, and -// `accountId`. A no-op when no model source has `id`. Other fields of the -// source are preserved. Only the host dispatches it. +// `credentialResource`, and `accountId`. A no-op when no model source has +// `id`. Other fields of the source are preserved. Only the host dispatches it. // // Stability: 1.0 - Early development. type RootModelSourceStateChangedAction struct { @@ -227,13 +221,9 @@ type RootModelSourceStateChangedAction struct { Id string `json:"id"` // The new status. State ModelSourceState `json:"state"` - // The model source's current credential nonce. - CredentialNonce string `json:"credentialNonce"` // Replaces the source's `credentialResource`. Absent clears it, for a // source that needs no credential. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` - // Replaces the source's `credentialOrigins`. Absent clears it. - CredentialOrigins []URI `json:"credentialOrigins,omitempty"` // Replaces the source's `accountId`. Absent clears it. AccountId *string `json:"accountId,omitempty"` } diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index 799ff1aa5..678d8d78b 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1358,10 +1358,6 @@ type ModelSourceAuthenticateTarget struct { Kind AuthenticateTargetKind `json:"kind"` // The registration's `ModelSource.id`. ModelSourceId string `json:"modelSourceId"` - // The registration's current `ModelSource.credentialNonce`, as - // published in root state. The host rejects a stale one with `Conflict` - // (-32011). - CredentialNonce string `json:"credentialNonce"` } // Pushes a credential for a protected resource. The `resource` field MUST @@ -1433,7 +1429,8 @@ type AuthenticateParams struct { // // A registered model source takes its credential only through a // `modelSource` target, and the host rejects an untargeted `resource` that - // matches only model source challenges with `InvalidParams` (-32602). See + // matches only model source challenges with `InvalidParams` (-32602). A + // delivery replaces whatever credential the host holds for the source. See // [Model source credentials](/specification/authentication#model-source-credentials) // for its rules. // diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 660366230..ce8f3c65b 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -483,23 +483,6 @@ const ( ModelSourceAuthRequiredReasonRevoked ModelSourceAuthRequiredReason = "revoked" ) -// Whether clients acting for different principals share a host's model -// source registry. -// -// Stability: 1.0 - Early development. -type ModelSourcePrincipalPolicy string - -const ( - // Every connected client may change, supply credentials for, and select - // every model source. - ModelSourcePrincipalPolicyShared ModelSourcePrincipalPolicy = "shared" - // The host verifies principals, and limits changes, credentials, and - // selection of each model source to clients of the principal that - // registered it. Root state still lists every model source to every - // client. - ModelSourcePrincipalPolicyIsolated ModelSourcePrincipalPolicy = "isolated" -) - // Computation lifecycle of a {@link ChangesetState}. type ChangesetStatus string @@ -991,34 +974,46 @@ type MultipleWorkingDirectoriesCapability struct { // // Stability: 1.0 - Early development. type ModelSourceRegistrationCapability struct { - // Definition formats the agent reads, most preferred first: recognized - // values of {@link ModelSource.format}, or namespaced names for formats - // the agent defines itself. - Formats []string `json:"formats"` - // How long, in milliseconds, the host keeps counting a disconnected client - // as a contributing client before it treats the client as having left. - GracePeriod *int64 `json:"gracePeriod,omitempty"` - // Whether clients acting for different principals share the registry. - // Absent means `shared`. - PrincipalPolicy *ModelSourcePrincipalPolicy `json:"principalPolicy,omitempty"` + // Definition formats the agent reads, most preferred first. + Formats []ModelSourceFormatInfo `json:"formats"` // Extra contains unrecognized wire members retained for full-object edits. Extra map[string]json.RawMessage `json:"-"` } func (v *ModelSourceRegistrationCapability) UnmarshalJSON(data []byte) error { type wire ModelSourceRegistrationCapability - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "formats", "gracePeriod", "principalPolicy") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "formats") } func (v ModelSourceRegistrationCapability) MarshalJSON() ([]byte, error) { type wire ModelSourceRegistrationCapability - return marshalWithExtra(wire(v), v.Extra, "formats", "gracePeriod", "principalPolicy") + return marshalWithExtra(wire(v), v.Extra, "formats") +} + +// A definition format an agent reads. An object so it can grow, for example +// with a JSON Schema for the format's definitions. +// +// Stability: 1.0 - Early development. +type ModelSourceFormatInfo struct { + // A recognized {@link ModelSource.format} value, or a namespaced name for + // a format the agent defines itself. + Format string `json:"format"` + // Extra contains unrecognized wire members retained for full-object edits. + Extra map[string]json.RawMessage `json:"-"` +} + +func (v *ModelSourceFormatInfo) UnmarshalJSON(data []byte) error { + type wire ModelSourceFormatInfo + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "format") +} + +func (v ModelSourceFormatInfo) MarshalJSON() ([]byte, error) { + type wire ModelSourceFormatInfo + return marshalWithExtra(wire(v), v.Extra, "format") } // A model source registered on this host by a client, or by the host itself. -// The definition that tells the agent named by `provider` how to reach it -// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing -// here is a credential. +// Nothing here is a credential. // // Stability: 1.0 - Early development. type ModelSource struct { @@ -1032,7 +1027,7 @@ type ModelSource struct { DisplayName string `json:"displayName"` // Icons for UI display. Icons []Icon `json:"icons,omitempty"` - // The definition's format, one of the agent's + // The definition's format: the `format` of one of the agent's // {@link ModelSourceRegistrationCapability.formats}. Recognized values // include: // @@ -1042,14 +1037,31 @@ type ModelSource struct { // - `'azureOpenai'`: an Azure OpenAI deployment. // - `'gemini'`: Google's Gemini API. // - // AHP doesn't define what a definition contains, even for these. Agents - // MAY read other formats, named with a namespace such as + // Agents MAY read other formats, named with a namespace such as // `example.com/model-source@1` so they don't collide. Format string `json:"format"` - // Opaque version token for the definition, such as a hash of it, chosen by - // whoever registers the source. A client compares it with its own copy - // instead of the definition, and the reducer compares it to tell an update - // from a re-registration of the same definition. + // How to reach the source, in `format`: endpoint, wire API, models, and so + // on. The agent reads it, and AHP doesn't validate it. Every client can + // read it, so it MUST NOT contain a credential. + // + // Suggested shapes for the recognized formats. Agents MAY read more + // members, and MAY discover models when `models` is absent. + // + // - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` + // - `anthropic`: `{ endpoint, models? }` + // - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each + // deployment name as a model `id` + // - `gemini`: `{ endpoint, models? }` + // + // `endpoint` is the API's base URI, such as `https://api.example.com/v1`. + // Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, + // supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, + // where `id` is the endpoint's own model identifier. + Definition map[string]json.RawMessage `json:"definition"` + // Opaque version token for `definition`, such as a hash of it, chosen by + // whoever registers the source. Reducers compare it, instead of the + // definition, to tell an update from a re-registration of the same + // definition. Nonce string `json:"nonce"` // What happens when the last contributing client leaves. Absent means `contributingClient`. Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` @@ -1057,13 +1069,6 @@ type ModelSource struct { // Absent until the host reports one, and after an update replaces the // definition until the host reports again. State *ModelSourceState `json:"state,omitempty"` - // Host-issued token that a client echoes in - // {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - // the credential, and that tags every agent operation on the source. The - // host issues a new one when the source is added or updated, and whenever - // the credential is installed or dropped. It never reuses one for the - // same `id`. Set with `state`. - CredentialNonce *string `json:"credentialNonce,omitempty"` // RFC 9728 metadata for the endpoint the credential is for. Present // whenever the source takes a credential, in every state, so any client // can deliver, rotate, or revoke one. Absent for a source that needs no @@ -1078,11 +1083,6 @@ type ModelSource struct { // advertises `authorization_servers` and `scopes_supported`. A source that // takes a user-supplied secret omits them. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` - // Every origin the host sends the credential to, such as - // `https://api.example.com`, derived from the definition it holds. Present - // whenever `credentialResource` is. A client checks each one against its - // own copy of the definition before it sends a key. Set with `state`. - CredentialOrigins []URI `json:"credentialOrigins,omitempty"` // The {@link AuthenticateParams.accountId} the client sent with the // credential the host most recently accepted. While the state is // `starting` or `ready`, the host holds that credential. While it's @@ -1098,12 +1098,12 @@ type ModelSource struct { func (v *ModelSource) UnmarshalJSON(data []byte) error { type wire ModelSource - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "nonce", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "accountId", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "nonce", "retention", "state", "credentialResource", "accountId", "_meta") } func (v ModelSource) MarshalJSON() ([]byte, error) { type wire ModelSource - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "nonce", "retention", "state", "credentialNonce", "credentialResource", "credentialOrigins", "accountId", "_meta") + return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "nonce", "retention", "state", "credentialResource", "accountId", "_meta") } // The agent is reading and validating the definition, or listing the diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index 6c1798094..eedf1687a 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -582,9 +582,7 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when val existing = list.getOrNull(idx)?.takeIf { sameModelSourceVersion(it, source) } val merged = source.copy( state = existing?.state, - credentialNonce = existing?.credentialNonce, credentialResource = existing?.credentialResource, - credentialOrigins = existing?.credentialOrigins, accountId = existing?.accountId, ) val updated = list.toMutableList() @@ -611,9 +609,7 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when val updated = list.toMutableList() updated[idx] = updated[idx].copy( state = action.value.state, - credentialNonce = action.value.credentialNonce, credentialResource = action.value.credentialResource, - credentialOrigins = action.value.credentialOrigins, accountId = action.value.accountId, ) state.copy(modelSources = updated) diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 2cc30b6ff..84e2ba7c0 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -1486,14 +1486,12 @@ data class RootConfigChangedAction( ) /** - * Adds a model source, or updates the one with the same `id`. The reducer - * stores `modelSource` without the definition: + * Adds a model source, or updates the one with the same `id`: * * - **Add.** When no model source has the `id`, appends `modelSource`. * - **Re-register.** When one has, with the same `provider`, `format`, and - * `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, - * `credentialResource`, `credentialOrigins`, and `accountId`) and takes - * the other fields from the action. + * `nonce`, keeps its host-reported fields (`state`, `credentialResource`, + * and `accountId`) and takes everything else from the action. * - **Update.** When any of the three differs, replaces the source. Its * host-reported fields are absent until the host reports again with * {@link RootModelSourceStateChangedAction}. @@ -1507,15 +1505,10 @@ data class RootConfigChangedAction( data class RootModelSourceSetAction( val type: ActionType, /** - * The model source to add or update, matched by `id`, without host-reported fields. + * The model source to add or update, matched by `id`, including its + * `definition`, without host-reported fields. */ - val modelSource: ModelSource, - /** - * How to reach the source, in `modelSource.format`: endpoint, wire format, - * models, and so on. The host hands it to the agent, and the reducer - * doesn't store it. MUST NOT contain a credential. - */ - val definition: Map + val modelSource: ModelSource ) /** @@ -1535,9 +1528,8 @@ data class RootModelSourceRemovedAction( /** * Updates a model source's host-reported fields together: `state`, - * `credentialNonce`, `credentialResource`, `credentialOrigins`, and - * `accountId`. A no-op when no model source has `id`. Other fields of the - * source are preserved. Only the host dispatches it. + * `credentialResource`, and `accountId`. A no-op when no model source has + * `id`. Other fields of the source are preserved. Only the host dispatches it. * * Stability: 1.0 - Early development. */ @@ -1552,19 +1544,11 @@ data class RootModelSourceStateChangedAction( * The new status. */ val state: ModelSourceState, - /** - * The model source's current credential nonce. - */ - val credentialNonce: String, /** * Replaces the source's `credentialResource`. Absent clears it, for a * source that needs no credential. */ val credentialResource: ProtectedResourceMetadata? = null, - /** - * Replaces the source's `credentialOrigins`. Absent clears it. - */ - val credentialOrigins: List? = null, /** * Replaces the source's `accountId`. Absent clears it. */ 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 8f6853db2..1b872d366 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 @@ -1628,13 +1628,7 @@ data class ModelSourceAuthenticateTarget( /** * The registration's `ModelSource.id`. */ - val modelSourceId: String, - /** - * The registration's current `ModelSource.credentialNonce`, as - * published in root state. The host rejects a stale one with `Conflict` - * (-32011). - */ - val credentialNonce: String + val modelSourceId: String ) @Serializable @@ -1704,7 +1698,8 @@ data class AuthenticateParams( * * A registered model source takes its credential only through a * `modelSource` target, and the host rejects an untargeted `resource` that - * matches only model source challenges with `InvalidParams` (-32602). See + * matches only model source challenges with `InvalidParams` (-32602). A + * delivery replaces whatever credential the host holds for the source. See * [Model source credentials](/specification/authentication#model-source-credentials) * for its rules. * 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 c33e7eca1..db5fec17c 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 @@ -1030,41 +1030,6 @@ internal object ModelSourceAuthRequiredReasonSerializer : KSerializer { - override val descriptor: SerialDescriptor = - PrimitiveSerialDescriptor("ModelSourcePrincipalPolicy", PrimitiveKind.STRING) - override fun serialize(encoder: Encoder, value: ModelSourcePrincipalPolicy) { - encoder.encodeString(value.rawValue) - } - override fun deserialize(decoder: Decoder): ModelSourcePrincipalPolicy = - ModelSourcePrincipalPolicy(decoder.decodeString()) -} - /** * Computation lifecycle of a {@link ChangesetState}. */ @@ -1854,21 +1819,9 @@ data class MultipleWorkingDirectoriesCapability( @Serializable(with = ModelSourceRegistrationCapabilitySerializer::class) data class ModelSourceRegistrationCapability( /** - * Definition formats the agent reads, most preferred first: recognized - * values of {@link ModelSource.format}, or namespaced names for formats - * the agent defines itself. + * Definition formats the agent reads, most preferred first. */ - val formats: List, - /** - * How long, in milliseconds, the host keeps counting a disconnected client - * as a contributing client before it treats the client as having left. - */ - val gracePeriod: Long? = null, - /** - * Whether clients acting for different principals share the registry. - * Absent means `shared`. - */ - val principalPolicy: ModelSourcePrincipalPolicy? = null, + val formats: List, @Transient val extra: Map = emptyMap() ) @@ -1879,11 +1832,33 @@ internal object ModelSourceRegistrationCapabilitySerializer : UnknownMembersSeri { value, extra -> value.copy(extra = extra) }, ) +/** + * A definition format an agent reads. An object so it can grow, for example + * with a JSON Schema for the format's definitions. + * + * Stability: 1.0 - Early development. + */ +@KeepGeneratedSerializer +@Serializable(with = ModelSourceFormatInfoSerializer::class) +data class ModelSourceFormatInfo( + /** + * A recognized {@link ModelSource.format} value, or a namespaced name for + * a format the agent defines itself. + */ + val format: String, + @Transient + val extra: Map = emptyMap() +) + +internal object ModelSourceFormatInfoSerializer : UnknownMembersSerializer( + ModelSourceFormatInfo.generatedSerializer(), + { it.extra }, + { value, extra -> value.copy(extra = extra) }, +) + /** * A model source registered on this host by a client, or by the host itself. - * The definition that tells the agent named by `provider` how to reach it - * travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing - * here is a credential. + * Nothing here is a credential. * * Stability: 1.0 - Early development. */ @@ -1909,7 +1884,7 @@ data class ModelSource( */ val icons: List? = null, /** - * The definition's format, one of the agent's + * The definition's format: the `format` of one of the agent's * {@link ModelSourceRegistrationCapability.formats}. Recognized values * include: * @@ -1919,16 +1894,35 @@ data class ModelSource( * - `'azureOpenai'`: an Azure OpenAI deployment. * - `'gemini'`: Google's Gemini API. * - * AHP doesn't define what a definition contains, even for these. Agents - * MAY read other formats, named with a namespace such as + * Agents MAY read other formats, named with a namespace such as * `example.com/model-source@1` so they don't collide. */ val format: String, /** - * Opaque version token for the definition, such as a hash of it, chosen by - * whoever registers the source. A client compares it with its own copy - * instead of the definition, and the reducer compares it to tell an update - * from a re-registration of the same definition. + * How to reach the source, in `format`: endpoint, wire API, models, and so + * on. The agent reads it, and AHP doesn't validate it. Every client can + * read it, so it MUST NOT contain a credential. + * + * Suggested shapes for the recognized formats. Agents MAY read more + * members, and MAY discover models when `models` is absent. + * + * - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` + * - `anthropic`: `{ endpoint, models? }` + * - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each + * deployment name as a model `id` + * - `gemini`: `{ endpoint, models? }` + * + * `endpoint` is the API's base URI, such as `https://api.example.com/v1`. + * Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, + * supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, + * where `id` is the endpoint's own model identifier. + */ + val definition: Map, + /** + * Opaque version token for `definition`, such as a hash of it, chosen by + * whoever registers the source. Reducers compare it, instead of the + * definition, to tell an update from a re-registration of the same + * definition. */ val nonce: String, /** @@ -1941,15 +1935,6 @@ data class ModelSource( * definition until the host reports again. */ val state: ModelSourceState? = null, - /** - * Host-issued token that a client echoes in - * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential, and that tags every agent operation on the source. The - * host issues a new one when the source is added or updated, and whenever - * the credential is installed or dropped. It never reuses one for the - * same `id`. Set with `state`. - */ - val credentialNonce: String? = null, /** * RFC 9728 metadata for the endpoint the credential is for. Present * whenever the source takes a credential, in every state, so any client @@ -1966,13 +1951,6 @@ data class ModelSource( * takes a user-supplied secret omits them. */ val credentialResource: ProtectedResourceMetadata? = null, - /** - * Every origin the host sends the credential to, such as - * `https://api.example.com`, derived from the definition it holds. Present - * whenever `credentialResource` is. A client checks each one against its - * own copy of the definition before it sends a key. Set with `state`. - */ - val credentialOrigins: List? = null, /** * The {@link AuthenticateParams.accountId} the client sent with the * credential the host most recently accepted. While the state is diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 566ef0664..9b830e0ac 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -520,14 +520,12 @@ pub struct RootConfigChangedAction { pub replace: Option, } -/// Adds a model source, or updates the one with the same `id`. The reducer -/// stores `modelSource` without the definition: +/// Adds a model source, or updates the one with the same `id`: /// /// - **Add.** When no model source has the `id`, appends `modelSource`. /// - **Re-register.** When one has, with the same `provider`, `format`, and -/// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, -/// `credentialResource`, `credentialOrigins`, and `accountId`) and takes -/// the other fields from the action. +/// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, +/// and `accountId`) and takes everything else from the action. /// - **Update.** When any of the three differs, replaces the source. Its /// host-reported fields are absent until the host reports again with /// {@link RootModelSourceStateChangedAction}. @@ -539,12 +537,9 @@ pub struct RootConfigChangedAction { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceSetAction { - /// The model source to add or update, matched by `id`, without host-reported fields. + /// The model source to add or update, matched by `id`, including its + /// `definition`, without host-reported fields. pub model_source: ModelSource, - /// How to reach the source, in `modelSource.format`: endpoint, wire format, - /// models, and so on. The host hands it to the agent, and the reducer - /// doesn't store it. MUST NOT contain a credential. - pub definition: JsonObject, } /// Removes the model source with the given `id`, for every client. A no-op @@ -559,9 +554,8 @@ pub struct RootModelSourceRemovedAction { } /// Updates a model source's host-reported fields together: `state`, -/// `credentialNonce`, `credentialResource`, `credentialOrigins`, and -/// `accountId`. A no-op when no model source has `id`. Other fields of the -/// source are preserved. Only the host dispatches it. +/// `credentialResource`, and `accountId`. A no-op when no model source has +/// `id`. Other fields of the source are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -571,15 +565,10 @@ pub struct RootModelSourceStateChangedAction { pub id: String, /// The new status. pub state: ModelSourceState, - /// The model source's current credential nonce. - pub credential_nonce: String, /// Replaces the source's `credentialResource`. Absent clears it, for a /// source that needs no credential. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, - /// Replaces the source's `credentialOrigins`. Absent clears it. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_origins: Option>, /// Replaces the source's `accountId`. Absent clears it. #[serde(default, skip_serializing_if = "Option::is_none")] pub account_id: Option, diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index e2d2fd951..fbe82df1d 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1756,10 +1756,6 @@ pub struct McpServerAuthenticateTarget { pub struct ModelSourceAuthenticateTarget { /// The registration's `ModelSource.id`. pub model_source_id: String, - /// The registration's current `ModelSource.credentialNonce`, as - /// published in root state. The host rejects a stale one with `Conflict` - /// (-32011). - pub credential_nonce: String, } /// Pushes a credential for a protected resource. The `resource` field MUST @@ -1836,7 +1832,8 @@ pub struct AuthenticateParams { /// /// A registered model source takes its credential only through a /// `modelSource` target, and the host rejects an untargeted `resource` that - /// matches only model source challenges with `InvalidParams` (-32602). See + /// matches only model source challenges with `InvalidParams` (-32602). A + /// delivery replaces whatever credential the host holds for the source. See /// [Model source credentials](/specification/authentication#model-source-credentials) /// for its rules. /// diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 42641a6e7..f3df8dd46 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1304,51 +1304,6 @@ impl<'de> serde::Deserialize<'de> for ModelSourceAuthRequiredReason { } } -/// Whether clients acting for different principals share a host's model -/// source registry. -/// -/// Stability: 1.0 - Early development. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub enum ModelSourcePrincipalPolicy { - /// Every connected client may change, supply credentials for, and select - /// every model source. - Shared, - /// The host verifies principals, and limits changes, credentials, and - /// selection of each model source to clients of the principal that - /// registered it. Root state still lists every model source to every - /// client. - Isolated, - /// Unknown raw value from a newer protocol version, preserved verbatim. - Unknown(String), -} - -impl serde::Serialize for ModelSourcePrincipalPolicy { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - match self { - Self::Shared => serializer.serialize_str("shared"), - Self::Isolated => serializer.serialize_str("isolated"), - Self::Unknown(value) => serializer.serialize_str(value), - } - } -} - -impl<'de> serde::Deserialize<'de> for ModelSourcePrincipalPolicy { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let raw = ::deserialize(deserializer)?; - Ok(match raw.as_str() { - "shared" => Self::Shared, - "isolated" => Self::Isolated, - _ => Self::Unknown(raw), - }) - } -} - /// Computation lifecycle of a {@link ChangesetState}. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ChangesetStatus { @@ -2211,27 +2166,30 @@ pub struct MultipleWorkingDirectoriesCapability { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceRegistrationCapability { - /// Definition formats the agent reads, most preferred first: recognized - /// values of {@link ModelSource.format}, or namespaced names for formats - /// the agent defines itself. - pub formats: Vec, - /// How long, in milliseconds, the host keeps counting a disconnected client - /// as a contributing client before it treats the client as having left. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub grace_period: Option, - /// Whether clients acting for different principals share the registry. - /// Absent means `shared`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub principal_policy: Option, + /// Definition formats the agent reads, most preferred first. + pub formats: Vec, + /// Unrecognized wire members retained for full-object edits. + #[serde(flatten)] + pub extra: serde_json::Map, +} + +/// A definition format an agent reads. An object so it can grow, for example +/// with a JSON Schema for the format's definitions. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSourceFormatInfo { + /// A recognized {@link ModelSource.format} value, or a namespaced name for + /// a format the agent defines itself. + pub format: String, /// Unrecognized wire members retained for full-object edits. #[serde(flatten)] pub extra: serde_json::Map, } /// A model source registered on this host by a client, or by the host itself. -/// The definition that tells the agent named by `provider` how to reach it -/// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing -/// here is a credential. +/// Nothing here is a credential. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2248,7 +2206,7 @@ pub struct ModelSource { /// Icons for UI display. #[serde(default, skip_serializing_if = "Option::is_none")] pub icons: Option>, - /// The definition's format, one of the agent's + /// The definition's format: the `format` of one of the agent's /// {@link ModelSourceRegistrationCapability.formats}. Recognized values /// include: /// @@ -2258,14 +2216,31 @@ pub struct ModelSource { /// - `'azureOpenai'`: an Azure OpenAI deployment. /// - `'gemini'`: Google's Gemini API. /// - /// AHP doesn't define what a definition contains, even for these. Agents - /// MAY read other formats, named with a namespace such as + /// Agents MAY read other formats, named with a namespace such as /// `example.com/model-source@1` so they don't collide. pub format: String, - /// Opaque version token for the definition, such as a hash of it, chosen by - /// whoever registers the source. A client compares it with its own copy - /// instead of the definition, and the reducer compares it to tell an update - /// from a re-registration of the same definition. + /// How to reach the source, in `format`: endpoint, wire API, models, and so + /// on. The agent reads it, and AHP doesn't validate it. Every client can + /// read it, so it MUST NOT contain a credential. + /// + /// Suggested shapes for the recognized formats. Agents MAY read more + /// members, and MAY discover models when `models` is absent. + /// + /// - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` + /// - `anthropic`: `{ endpoint, models? }` + /// - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each + /// deployment name as a model `id` + /// - `gemini`: `{ endpoint, models? }` + /// + /// `endpoint` is the API's base URI, such as `https://api.example.com/v1`. + /// Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, + /// supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, + /// where `id` is the endpoint's own model identifier. + pub definition: JsonObject, + /// Opaque version token for `definition`, such as a hash of it, chosen by + /// whoever registers the source. Reducers compare it, instead of the + /// definition, to tell an update from a re-registration of the same + /// definition. pub nonce: String, /// What happens when the last contributing client leaves. Absent means `contributingClient`. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2275,14 +2250,6 @@ pub struct ModelSource { /// definition until the host reports again. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, - /// Host-issued token that a client echoes in - /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential, and that tags every agent operation on the source. The - /// host issues a new one when the source is added or updated, and whenever - /// the credential is installed or dropped. It never reuses one for the - /// same `id`. Set with `state`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_nonce: Option, /// RFC 9728 metadata for the endpoint the credential is for. Present /// whenever the source takes a credential, in every state, so any client /// can deliver, rotate, or revoke one. Absent for a source that needs no @@ -2298,12 +2265,6 @@ pub struct ModelSource { /// takes a user-supplied secret omits them. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, - /// Every origin the host sends the credential to, such as - /// `https://api.example.com`, derived from the definition it holds. Present - /// whenever `credentialResource` is. A client checks each one against its - /// own copy of the definition before it sends a key. Set with `state`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_origins: Option>, /// The {@link AuthenticateParams.accountId} the client sent with the /// credential the host most recently accepted. While the state is /// `starting` or `ready`, the host holds that credential. While it's diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index edff3320d..2a46073c6 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -756,9 +756,7 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu return ReduceOutcome::NoOp; }; source.state = Some(a.state.clone()); - source.credential_nonce = Some(a.credential_nonce.clone()); source.credential_resource = a.credential_resource.clone(); - source.credential_origins = a.credential_origins.clone(); source.account_id = a.account_id.clone(); ReduceOutcome::Applied } @@ -775,18 +773,14 @@ fn same_model_source_version(a: &ModelSource, b: &ModelSource) -> bool { /// Copies the host-reported fields of `from` onto `to`. fn copy_model_source_host_fields(to: &mut ModelSource, from: &ModelSource) { to.state = from.state.clone(); - to.credential_nonce = from.credential_nonce.clone(); to.credential_resource = from.credential_resource.clone(); - to.credential_origins = from.credential_origins.clone(); to.account_id = from.account_id.clone(); } /// Clears the host-reported fields of `source`. fn clear_model_source_host_fields(source: &mut ModelSource) { source.state = None; - source.credential_nonce = None; source.credential_resource = None; - source.credential_origins = None; source.account_id = None; } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index 36081af7d..3cc9d5f4c 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -2290,14 +2290,12 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { } } -/// Adds a model source, or updates the one with the same `id`. The reducer -/// stores `modelSource` without the definition: +/// Adds a model source, or updates the one with the same `id`: /// /// - **Add.** When no model source has the `id`, appends `modelSource`. /// - **Re-register.** When one has, with the same `provider`, `format`, and -/// `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, -/// `credentialResource`, `credentialOrigins`, and `accountId`) and takes -/// the other fields from the action. +/// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, +/// and `accountId`) and takes everything else from the action. /// - **Update.** When any of the three differs, replaces the source. Its /// host-reported fields are absent until the host reports again with /// {@link RootModelSourceStateChangedAction}. @@ -2308,21 +2306,16 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct RootModelSourceSetAction: Codable, Sendable, Equatable { public var type: ActionType - /// The model source to add or update, matched by `id`, without host-reported fields. + /// The model source to add or update, matched by `id`, including its + /// `definition`, without host-reported fields. public var modelSource: ModelSource - /// How to reach the source, in `modelSource.format`: endpoint, wire format, - /// models, and so on. The host hands it to the agent, and the reducer - /// doesn't store it. MUST NOT contain a credential. - public var definition: [String: AnyCodable] public init( type: ActionType, - modelSource: ModelSource, - definition: [String: AnyCodable] + modelSource: ModelSource ) { self.type = type self.modelSource = modelSource - self.definition = definition } } @@ -2345,9 +2338,8 @@ public struct RootModelSourceRemovedAction: Codable, Sendable, Equatable { } /// Updates a model source's host-reported fields together: `state`, -/// `credentialNonce`, `credentialResource`, `credentialOrigins`, and -/// `accountId`. A no-op when no model source has `id`. Other fields of the -/// source are preserved. Only the host dispatches it. +/// `credentialResource`, and `accountId`. A no-op when no model source has +/// `id`. Other fields of the source are preserved. Only the host dispatches it. /// /// Stability: 1.0 - Early development. public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { @@ -2356,13 +2348,9 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { public var id: String /// The new status. public var state: ModelSourceState - /// The model source's current credential nonce. - public var credentialNonce: String /// Replaces the source's `credentialResource`. Absent clears it, for a /// source that needs no credential. public var credentialResource: ProtectedResourceMetadata? - /// Replaces the source's `credentialOrigins`. Absent clears it. - public var credentialOrigins: [String]? /// Replaces the source's `accountId`. Absent clears it. public var accountId: String? @@ -2370,17 +2358,13 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { type: ActionType, id: String, state: ModelSourceState, - credentialNonce: String, credentialResource: ProtectedResourceMetadata? = nil, - credentialOrigins: [String]? = nil, accountId: String? = nil ) { self.type = type self.id = id self.state = state - self.credentialNonce = credentialNonce self.credentialResource = credentialResource - self.credentialOrigins = credentialOrigins self.accountId = accountId } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 874e72fd0..c87b2ce41 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -1977,19 +1977,13 @@ public struct ModelSourceAuthenticateTarget: Codable, Sendable, Equatable { public var kind: AuthenticateTargetKind /// The registration's `ModelSource.id`. public var modelSourceId: String - /// The registration's current `ModelSource.credentialNonce`, as - /// published in root state. The host rejects a stale one with `Conflict` - /// (-32011). - public var credentialNonce: String public init( kind: AuthenticateTargetKind, - modelSourceId: String, - credentialNonce: String + modelSourceId: String ) { self.kind = kind self.modelSourceId = modelSourceId - self.credentialNonce = credentialNonce } } @@ -2045,7 +2039,8 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// /// A registered model source takes its credential only through a /// `modelSource` target, and the host rejects an untargeted `resource` that - /// matches only model source challenges with `InvalidParams` (-32602). See + /// matches only model source challenges with `InvalidParams` (-32602). A + /// delivery replaces whatever credential the host holds for the source. See /// [Model source credentials](/specification/authentication#model-source-credentials) /// for its rules. /// diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index cf537f7f3..f275b7014 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1012,42 +1012,6 @@ public enum ModelSourceAuthRequiredReason: Codable, Sendable, Equatable { } } -/// Whether clients acting for different principals share a host's model -/// source registry. -/// -/// Stability: 1.0 - Early development. -public enum ModelSourcePrincipalPolicy: Codable, Sendable, Equatable { - /// Every connected client may change, supply credentials for, and select - /// every model source. - case shared - /// The host verifies principals, and limits changes, credentials, and - /// selection of each model source to clients of the principal that - /// registered it. Root state still lists every model source to every - /// client. - case isolated - /// Unknown raw value from a newer protocol version, preserved verbatim. - case unknown(String) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - let raw = try container.decode(String.self) - switch raw { - case "shared": self = .shared - case "isolated": self = .isolated - default: self = .unknown(raw) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .shared: try container.encode("shared") - case .isolated: try container.encode("isolated") - case .unknown(let raw): try container.encode(raw) - } - } -} - /// Computation lifecycle of a {@link ChangesetState}. public enum ChangesetStatus: Codable, Sendable, Equatable { /// The server is computing this changeset for the first time. @@ -1854,58 +1818,74 @@ public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable /// /// Stability: 1.0 - Early development. public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { - /// Definition formats the agent reads, most preferred first: recognized - /// values of {@link ModelSource.format}, or namespaced names for formats - /// the agent defines itself. - public var formats: [String] - /// How long, in milliseconds, the host keeps counting a disconnected client - /// as a contributing client before it treats the client as having left. - public var gracePeriod: Int? - /// Whether clients acting for different principals share the registry. - /// Absent means `shared`. - public var principalPolicy: ModelSourcePrincipalPolicy? + /// Definition formats the agent reads, most preferred first. + public var formats: [ModelSourceFormatInfo] /// Unrecognized wire members retained for full-object edits. public var extra: [String: AnyCodable] enum CodingKeys: String, CodingKey, CaseIterable { case formats - case gracePeriod - case principalPolicy } public init( - formats: [String], - gracePeriod: Int? = nil, - principalPolicy: ModelSourcePrincipalPolicy? = nil, + formats: [ModelSourceFormatInfo], extra: [String: AnyCodable] = [:] ) { self.formats = formats - self.gracePeriod = gracePeriod - self.principalPolicy = principalPolicy self.extra = extra } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.formats = try container.decode([String].self, forKey: .formats) - self.gracePeriod = try container.decodeIfPresent(Int.self, forKey: .gracePeriod) - self.principalPolicy = try container.decodeIfPresent(ModelSourcePrincipalPolicy.self, forKey: .principalPolicy) + self.formats = try container.decode([ModelSourceFormatInfo].self, forKey: .formats) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.formats, forKey: .formats) - try container.encodeIfPresent(self.gracePeriod, forKey: .gracePeriod) - try container.encodeIfPresent(self.principalPolicy, forKey: .principalPolicy) + try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } +} + +/// A definition format an agent reads. An object so it can grow, for example +/// with a JSON Schema for the format's definitions. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceFormatInfo: Codable, Sendable, Equatable { + /// A recognized {@link ModelSource.format} value, or a namespaced name for + /// a format the agent defines itself. + public var format: String + /// Unrecognized wire members retained for full-object edits. + public var extra: [String: AnyCodable] + + enum CodingKeys: String, CodingKey, CaseIterable { + case format + } + + public init( + format: String, + extra: [String: AnyCodable] = [:] + ) { + self.format = format + self.extra = extra + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.format = try container.decode(String.self, forKey: .format) + self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.format, forKey: .format) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } /// A model source registered on this host by a client, or by the host itself. -/// The definition that tells the agent named by `provider` how to reach it -/// travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing -/// here is a credential. +/// Nothing here is a credential. /// /// Stability: 1.0 - Early development. public struct ModelSource: Codable, Sendable, Equatable { @@ -1919,7 +1899,7 @@ public struct ModelSource: Codable, Sendable, Equatable { public var displayName: String /// Icons for UI display. public var icons: [Icon]? - /// The definition's format, one of the agent's + /// The definition's format: the `format` of one of the agent's /// {@link ModelSourceRegistrationCapability.formats}. Recognized values /// include: /// @@ -1929,14 +1909,31 @@ public struct ModelSource: Codable, Sendable, Equatable { /// - `'azureOpenai'`: an Azure OpenAI deployment. /// - `'gemini'`: Google's Gemini API. /// - /// AHP doesn't define what a definition contains, even for these. Agents - /// MAY read other formats, named with a namespace such as + /// Agents MAY read other formats, named with a namespace such as /// `example.com/model-source@1` so they don't collide. public var format: String - /// Opaque version token for the definition, such as a hash of it, chosen by - /// whoever registers the source. A client compares it with its own copy - /// instead of the definition, and the reducer compares it to tell an update - /// from a re-registration of the same definition. + /// How to reach the source, in `format`: endpoint, wire API, models, and so + /// on. The agent reads it, and AHP doesn't validate it. Every client can + /// read it, so it MUST NOT contain a credential. + /// + /// Suggested shapes for the recognized formats. Agents MAY read more + /// members, and MAY discover models when `models` is absent. + /// + /// - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` + /// - `anthropic`: `{ endpoint, models? }` + /// - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each + /// deployment name as a model `id` + /// - `gemini`: `{ endpoint, models? }` + /// + /// `endpoint` is the API's base URI, such as `https://api.example.com/v1`. + /// Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, + /// supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, + /// where `id` is the endpoint's own model identifier. + public var definition: [String: AnyCodable] + /// Opaque version token for `definition`, such as a hash of it, chosen by + /// whoever registers the source. Reducers compare it, instead of the + /// definition, to tell an update from a re-registration of the same + /// definition. public var nonce: String /// What happens when the last contributing client leaves. Absent means `contributingClient`. public var retention: ModelSourceRetentionPolicy? @@ -1944,13 +1941,6 @@ public struct ModelSource: Codable, Sendable, Equatable { /// Absent until the host reports one, and after an update replaces the /// definition until the host reports again. public var state: ModelSourceState? - /// Host-issued token that a client echoes in - /// {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - /// the credential, and that tags every agent operation on the source. The - /// host issues a new one when the source is added or updated, and whenever - /// the credential is installed or dropped. It never reuses one for the - /// same `id`. Set with `state`. - public var credentialNonce: String? /// RFC 9728 metadata for the endpoint the credential is for. Present /// whenever the source takes a credential, in every state, so any client /// can deliver, rotate, or revoke one. Absent for a source that needs no @@ -1965,11 +1955,6 @@ public struct ModelSource: Codable, Sendable, Equatable { /// advertises `authorization_servers` and `scopes_supported`. A source that /// takes a user-supplied secret omits them. public var credentialResource: ProtectedResourceMetadata? - /// Every origin the host sends the credential to, such as - /// `https://api.example.com`, derived from the definition it holds. Present - /// whenever `credentialResource` is. A client checks each one against its - /// own copy of the definition before it sends a key. Set with `state`. - public var credentialOrigins: [String]? /// The {@link AuthenticateParams.accountId} the client sent with the /// credential the host most recently accepted. While the state is /// `starting` or `ready`, the host holds that credential. While it's @@ -1988,12 +1973,11 @@ public struct ModelSource: Codable, Sendable, Equatable { case displayName case icons case format + case definition case nonce case retention case state - case credentialNonce case credentialResource - case credentialOrigins case accountId case meta = "_meta" } @@ -2004,12 +1988,11 @@ public struct ModelSource: Codable, Sendable, Equatable { displayName: String, icons: [Icon]? = nil, format: String, + definition: [String: AnyCodable], nonce: String, retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, - credentialNonce: String? = nil, credentialResource: ProtectedResourceMetadata? = nil, - credentialOrigins: [String]? = nil, accountId: String? = nil, meta: [String: AnyCodable]? = nil, extra: [String: AnyCodable] = [:] @@ -2019,12 +2002,11 @@ public struct ModelSource: Codable, Sendable, Equatable { self.displayName = displayName self.icons = icons self.format = format + self.definition = definition self.nonce = nonce self.retention = retention self.state = state - self.credentialNonce = credentialNonce self.credentialResource = credentialResource - self.credentialOrigins = credentialOrigins self.accountId = accountId self.meta = meta self.extra = extra @@ -2037,12 +2019,11 @@ public struct ModelSource: Codable, Sendable, Equatable { self.displayName = try container.decode(String.self, forKey: .displayName) self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) self.format = try container.decode(String.self, forKey: .format) + self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) self.nonce = try container.decode(String.self, forKey: .nonce) self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) - self.credentialNonce = try container.decodeIfPresent(String.self, forKey: .credentialNonce) self.credentialResource = try container.decodeIfPresent(ProtectedResourceMetadata.self, forKey: .credentialResource) - self.credentialOrigins = try container.decodeIfPresent([String].self, forKey: .credentialOrigins) self.accountId = try container.decodeIfPresent(String.self, forKey: .accountId) self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) @@ -2055,12 +2036,11 @@ public struct ModelSource: Codable, Sendable, Equatable { try container.encode(self.displayName, forKey: .displayName) try container.encodeIfPresent(self.icons, forKey: .icons) try container.encode(self.format, forKey: .format) + try container.encode(self.definition, forKey: .definition) try container.encode(self.nonce, forKey: .nonce) try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) - try container.encodeIfPresent(self.credentialNonce, forKey: .credentialNonce) try container.encodeIfPresent(self.credentialResource, forKey: .credentialResource) - try container.encodeIfPresent(self.credentialOrigins, forKey: .credentialOrigins) try container.encodeIfPresent(self.accountId, forKey: .accountId) try container.encodeIfPresent(self.meta, forKey: .meta) try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index 44f3c57fa..79f3d5744 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -127,9 +127,7 @@ func applyModelSourceSet(_ state: inout RootState, _ source: ModelSource) { let existing = idx.map { list[$0] }.flatMap { sameModelSourceVersion($0, source) ? $0 : nil } var merged = source merged.state = existing?.state - merged.credentialNonce = existing?.credentialNonce merged.credentialResource = existing?.credentialResource - merged.credentialOrigins = existing?.credentialOrigins merged.accountId = existing?.accountId if let idx { list[idx] = merged @@ -160,9 +158,7 @@ func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelS guard var list = state.modelSources, let idx = list.firstIndex(where: { $0.id == action.id }) else { return false } list[idx].state = action.state - list[idx].credentialNonce = action.credentialNonce list[idx].credentialResource = action.credentialResource - list[idx].credentialOrigins = action.credentialOrigins list[idx].accountId = action.accountId state.modelSources = list return true diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index ad86158c2..f7e44cd4b 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSources` and the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. `root/modelSourceSet` carries the source's definition, which isn't kept in state, and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. `ModelSource.format` documents recognized values (`openaiCompatible`, `anthropic`, `azureOpenai`, `gemini`). Clients deliver each source's credential with a `modelSource` `authenticate` target that echoes the host-issued `credentialNonce`, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, `credentialOrigins`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`), and ends turns on an unavailable source with the resumable `modelSourceUnavailable` error. Agents advertise the definition formats they read, the contributor grace period, and the principal policy with `AgentCapabilities.modelSourceRegistration`.", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSources` and the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. Each `ModelSource` carries its `definition` and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. `ModelSource.format` documents recognized values (`openaiCompatible`, `anthropic`, `azureOpenai`, `gemini`), and `definition` documents a suggested shape for each. Clients deliver each source's credential with a `modelSource` `authenticate` target, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`), and ends turns on an unavailable source with the resumable `modelSourceUnavailable` error. Agents advertise the definition formats they read as `ModelSourceFormatInfo` entries in `AgentCapabilities.modelSourceRegistration`.", "issues": [619] } diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index e4203744d..f6c8b8c3a 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -153,11 +153,9 @@ If the token is invalid or the resource is unrecognized, the server MUST return A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the model source carries host-reported credential fields in every state: - `credentialResource`: RFC 9728 metadata for the endpoint the credential is for; -- `credentialOrigins`: every origin the host sends the credential to; -- `credentialNonce`: the source's current generation; - `accountId`: the `accountId` the client sent with the key the host most recently accepted. -When the source needs a credential, the host also sets the source's state to `ModelSourceAuthRequiredState`, with a `reason`. A client answers with a `modelSource` target that names the source and echoes its current `credentialNonce`, and names the key with the existing `accountId` parameter: +When the source needs a credential, the host also sets the source's state to `ModelSourceAuthRequiredState`, with a `reason`. A client answers with a `modelSource` target that names the source, and names the key with the existing `accountId` parameter: ```jsonc // Model source credential delivery @@ -172,8 +170,7 @@ When the source needs a credential, the host also sets the source's state to `Mo "accountId": "keychain-5c2a", "target": { "kind": "modelSource", - "modelSourceId": "2f6c0e1a-model-source", - "credentialNonce": "9b41d7" + "modelSourceId": "2f6c0e1a-model-source" } } } @@ -181,7 +178,7 @@ When the source needs a credential, the host also sets the source's state to `Mo The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the source's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `scopes`. `credentialResource.resource_name` labels the prompt, for example "OpenRouter API key". -`credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Where the host actually sends the credential is governed by `credentialOrigins` and the egress rules below. +`credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Where the host actually sends the credential is governed by the source's definition and the egress rules below. Clients SHOULD include `accountId` when they deliver a credential, and omit it when they revoke one. The host publishes it as the source's `accountId`, which lets a client that reloads, or one on another device, tell whether the host holds its current key. It's opaque and MUST NOT be derived from the secret, because every client can read it. For an API key that has no account of its own, a client uses an ID that changes whenever the user replaces the key, such as one derived from where it stores the key and when the key last changed. [Host-owned authentication](https://github.com/microsoft/agent-host-protocol/pull/404) may later supersede the `modelSource` target and this use of `accountId`. @@ -190,19 +187,12 @@ When `target.kind` is `modelSource`, the host: - MUST apply the credential only to that model source, never to other model sources, MCP servers, or agent-level resources, even when they share `resource`; - MUST require `resource` to equal the source's current `credentialResource.resource`; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); -- MUST reject a `credentialNonce` other than the one it most recently issued for that source with `Conflict` (`-32011`). The client re-reads root state and, if the source still needs a credential, sends it again with the current nonce; - MUST publish the request's `accountId` as the source's `accountId` when it accepts a credential, and clear it when the request has none; - MUST treat an empty `token` as revocation: it stops using the credential at once, drops it, and reports `authRequired` with `reason: revoked`. -Any client may deliver or revoke a model source's credential, as any client may answer an MCP server's challenge. A host whose `principalPolicy` is `isolated` rejects a credential for another principal's source with `PermissionDenied` (`-32009`). +Any client may deliver or revoke a model source's credential, as any client may answer an MCP server's challenge. A host that restricts sources by principal rejects a credential for another principal's source with `PermissionDenied` (`-32009`). -`credentialNonce` fences every credential change, and works as the source's generation. The host issues a new nonce whenever a source is added, including one registered again under a removed `id`, and whenever `root/modelSourceSet` updates it, whether or not it held a credential. It also issues one whenever it installs or drops a credential: on delivery, rotation, expiry, rejection, and revocation. It never reuses a nonce for the same `id`. An `authenticate` built before any of those changes is stale, so: - -- a key meant for an old definition never reaches a new one, even when the endpoint didn't change; -- a rotation that crosses a revocation can't undo the revocation; -- when two clients answer the same `authRequired`, the first wins, and the second gets `Conflict`, re-reads state, and finds the source ready. - -The host tags every agent operation on the source with the current nonce and discards any result, success or failure, that carries an older one. A late failure can't drop a key that has since replaced it, and a late success can't mark an updated or re-added source `ready`, even after an edit that changes the definition back. +As with MCP servers, the target names the source but not a version of it. A delivery replaces whatever credential the host holds for the source, so when two clients answer the same `authRequired`, the later one wins. #### Reasons @@ -225,13 +215,13 @@ Clients MUST NOT cache a model source credential they delivered, or replay one, - when the state is `starting` or `ready`, and the source's `accountId` names a key this client has since replaced, for example one it delivered before the user changed it. A client whose key simply differs leaves the host's credential alone, so two devices with different working keys don't replace each other's in turn; - when a lease or token it delivered is about to expire. -Clients SHOULD NOT prompt the user for a key they don't have. A client MUST NOT send a stored secret unless the source's `provider`, `format`, and `nonce` match its own copy, and every origin in `credentialOrigins` is one its own copy of the definition sends the key to. The host derives `credentialOrigins` from the definition it actually holds, so the origin check doesn't depend on another client choosing `nonce` honestly. `credentialNonce` stops a delayed reply, but not a device whose copy of the definition is out of date or a registration another client has changed. +Clients SHOULD NOT prompt the user for a key they don't have. A client MUST NOT send a stored secret unless the source's `provider` and `format` match its own copy, and every endpoint in the source's `definition` that the key would reach is one its own copy sends the key to. It checks the definition itself rather than trusting `nonce`, which another client chooses. #### Handling and egress The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the definition, the source's `nonce`, `_meta`, or credential fields, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. -The host attaches the credential only to that source's requests, as its definition specifies, and only to origins in `credentialOrigins`, never to another origin, including on redirect. It drops the credential when the source is removed, when `root/modelSourceSet` updates it, when it's revoked, when its lease lapses, and when the host restarts. +The host attaches the credential only to that source's requests, as its definition specifies, and only to the endpoints its definition names, never to another origin, including on redirect. It drops the credential when the source is removed, when `root/modelSourceSet` updates it, when it's revoked, when its lease lapses, and when the host restarts. Endpoints in a definition, including loopback and private addresses, are resolved and reached from the host machine: `localhost` in a source registered with a remote host is that host, not the client's machine. Hosts SHOULD apply an egress policy to registered endpoints: deny link-local and cloud metadata addresses, and require `https` for any credentialed endpoint that isn't a loopback address, unless the host has opted in to plain `http`. diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index d6beda33c..2a7ea5fb0 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -63,7 +63,7 @@ A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, ### Model source registry -Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSources`](/reference/root#modelsource), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads, how long the host keeps counting a disconnected client (`gracePeriod`), and whether clients of different principals share the registry (`principalPolicy`). +Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSources`](/reference/root#modelsource), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads, most preferred first, as [`ModelSourceFormatInfo`](/reference/root#modelsourceformatinfo) objects. ```json { @@ -71,30 +71,44 @@ Clients can register bring-your-own-key model sources with the host, so its agen "provider": "example", "displayName": "OpenRouter", "format": "openaiCompatible", + "definition": { + "endpoint": "https://openrouter.ai/api/v1", + "wireApi": "chatCompletions", + "models": [{ "id": "vendor/model-a", "maxContextWindow": 200000 }] + }, "nonce": "sha256-4f1c9a", "retention": "host", "state": { "kind": "ready" }, - "credentialNonce": "9b41d7", "credentialResource": { "resource": "https://openrouter.ai/api/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": ["https://openrouter.ai"], "accountId": "keychain-5c2a" } ``` -A model source's `format` names the format of its definition. AHP recognizes `openaiCompatible`, `anthropic`, `azureOpenai`, and `gemini`, following the pattern of `Changeset.changeKind`, but doesn't define what a definition contains, even for those. Agents MAY read other formats, named with a namespace such as `example.com/model-source@1`. The definition itself is opaque to AHP and belongs to the agent. It travels only on `root/modelSourceSet`, and the reducer stores the source without it. Clients compare `nonce`, an opaque version token for the definition, with their own copy instead. Actions are broadcast and replayed, so the definition is never secret, and it MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). +A model source's `definition` tells the agent how to reach it: endpoint, wire API, models, and so on, in the format `format` names. AHP recognizes `openaiCompatible`, `anthropic`, `azureOpenai`, and `gemini`, following the pattern of `Changeset.changeKind`, and suggests a shape for each: + +- `openaiCompatible`: `{ endpoint, wireApi?, models? }`, where `wireApi` is `chatCompletions` or `responses`; +- `anthropic`: `{ endpoint, models? }`; +- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each deployment name as a model `id`; +- `gemini`: `{ endpoint, models? }`. + +`endpoint` is the API's base URI, such as `https://api.example.com/v1`. Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, named as in `SessionModelInfo`, where `id` is the endpoint's own model identifier. Agents MAY read more members, and MAY discover models when `models` is absent. AHP doesn't validate definitions, even for the recognized formats: `definition` belongs to the agent. Agents MAY read other formats, named with a namespace such as `example.com/model-source@1`. + +Every client can read a source's definition, for example to show which endpoint it uses, or to check it against its own copy before sending a key. Root state is broadcast and replayed, so a definition is never secret, and it MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). `nonce` is an opaque version token for the definition, so reducers compare a string rather than JSON. #### Registering, updating, and removing -A client registers a source with `root/modelSourceSet { modelSource, definition }`, and removes it with `root/modelSourceRemoved { id }`. The reducers follow the keyed-collection convention, with one twist so that re-registering the same definition doesn't disturb a working source: +A client registers a source with `root/modelSourceSet { modelSource }`, including its definition, and removes it with `root/modelSourceRemoved { id }`. The reducers follow the keyed-collection convention, with one twist so that re-registering the same definition doesn't disturb a working source: - **Add.** When no model source has the `id`, `Set` appends `modelSource`. -- **Re-register.** When one has, with the same `provider`, `format`, and `nonce`, `Set` keeps its host-reported fields (`state`, `credentialNonce`, `credentialResource`, `credentialOrigins`, and `accountId`) and takes `displayName`, `icons`, `retention`, and `_meta` from the action. +- **Re-register.** When one has, with the same `provider`, `format`, and `nonce`, `Set` keeps its host-reported fields (`state`, `credentialResource`, and `accountId`) and takes everything else from the action. - **Update.** When any of the three differs, `Set` replaces the source. Its host-reported fields are absent until the host reports again. - **Remove.** `Removed` deletes the source by `id`, or returns the state unchanged. +Comparing three strings keeps every client's reducer in agreement without comparing definitions. + A client dispatches `Set` with no host-reported fields, when it starts or reconnects with the source configured, and when the user changes the source. Re-registering an unchanged source is how a second window, a reloaded window, or another device with the same source configured becomes a contributing client. When clients disagree on `displayName`, `icons`, `retention`, or `_meta`, the last `Set` wins. A client SHOULD derive `id` from a stable key in its own configuration, and `nonce` from the definition, for example as a hash of it. A client SHOULD NOT update a source whose `nonce` differs from its own copy unless the user changed the source in its configuration, and SHOULD NOT add back a source another client removed except when it starts or reconnects, or two clients with different configurations would replace each other's source indefinitely. When the user removes the source from a client's configuration, the client dispatches `Removed`. Removal applies to every client. A client that still has the source configured registers it again the next time it starts or reconnects. @@ -103,25 +117,23 @@ The host rejects a client's `Set`, through `rejectionReason`, when: - the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; - `modelSource` includes any host-reported field; -- its `provider`, `format`, and `nonce` match the existing source's, but `definition` differs from the definition the host holds. A re-registration must not carry a different definition, because reducers keep the credential for it; +- its `provider`, `format`, and `nonce` match the existing source's, but its `definition` differs. A re-registration must not carry a different definition, because reducers keep the credential for it; - `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same source doesn't count, so a ready source can still be re-registered or updated; - the host won't honor the requested `retention`. The client can register again with `contributingClient` retention; - the host registered the source itself; -- the host's `principalPolicy` is `isolated`, and the source belongs to another principal. +- the host restricts sources by principal, and the existing source belongs to another principal. A host MAY reject a client's `Removed` for a source it registered itself or one that belongs to another principal. -The host tracks contributing clients itself, from each `Set`'s `ActionEnvelope.origin`, and they aren't in state. An add or a re-registration adds the dispatching client. An update makes the dispatching client the only one, because the others registered a different definition. When `Set` updates a source, the host drops its credential, issues a new `credentialNonce`, and the source goes back through `starting`. A re-registration, or a change to `displayName`, `icons`, `retention`, or `_meta`, keeps the credential and the nonce. A host may also register sources itself. Those sources have no contributing clients, and their retention behaves as `host`. +The host tracks contributing clients itself, from each `Set`'s `ActionEnvelope.origin`, and they aren't in state. An add or a re-registration adds the dispatching client. An update makes the dispatching client the only one, because the others registered a different definition. When `Set` updates a source, the host drops its credential, and the source goes back through `starting`, so a changed definition never receives a key supplied for a different one. A re-registration, or a change to `displayName`, `icons`, `retention`, or `_meta`, keeps the credential. A host may also register sources itself. Those sources have no contributing clients, and their retention behaves as `host`. #### Status -The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets the host-reported fields together: the source's `state` (`starting`, `ready`, `authRequired`, or `error`), its `credentialNonce`, and its `credentialResource`, `credentialOrigins`, and `accountId`, which an absent value clears. It never reports status by dispatching the source back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed source or overwrite a newer one. +The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets the host-reported fields together: the source's `state` (`starting`, `ready`, `authRequired`, or `error`), and its `credentialResource` and `accountId`, which an absent value clears. It never reports status by dispatching the source back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed source or overwrite a newer one. An `authRequired` state carries a `reason` specific to model sources: `required` (no credential yet), `expired` (its lifetime or lease lapsed), `rejected` (the endpoint refused it), or `revoked` (a client revoked it). See [Model source credentials](/specification/authentication#model-source-credentials) for what clients do with each. -`credentialNonce` is the source's generation. The host issues a new one when a source is added, including under a removed `id`, when `Set` updates it, and whenever it installs or drops a credential. It tags every agent operation on the source, such as validation, model discovery, and inference, with the current nonce, and discards any result, success or failure, that carries an older one. A slow result from before an update therefore can't mark the current source `ready`, even when the definition has changed back to the same value. - -`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for, and `credentialOrigins` lists every origin the host sends the credential to, derived from the definition the host holds. The host reports both in every state while the source takes a credential, so any client can check, deliver, rotate, or revoke one, and leaves them absent for a source that needs none. `accountId` names the key the host most recently accepted. +`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for. The host reports it in every state while the source takes a credential, so any client can deliver, rotate, or revoke one, and leaves it absent for a source that needs none. `accountId` names the key the host most recently accepted. #### Catalog @@ -131,24 +143,26 @@ When a registered source is `ready`, the host adds it to the catalog of the agen Once a registered source has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the source is removed, when its last contributing client leaves under `contributingClient` retention, when it enters `error`, or when an update mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). The host MAY list the `ModelSourceInfo` in any state. -Any client can select a registered source's models, in any session whose agent is the source's `provider`. The host checks every selection: the model is listed, the chat is backed by the source's agent provider, and, under `isolated`, the turn's client acts for the source's principal. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. A turn that can't use its source ends with the resumable `modelSourceUnavailable` error, as described in [Model source credentials](/specification/authentication#model-source-credentials). +Any client can select a registered source's models, in any session whose agent is the source's `provider`. The host checks every selection: the model is listed, the chat is backed by the source's agent provider, and, when the host restricts sources by principal, the turn's client acts for the source's principal. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. A turn that can't use its source ends with the resumable `modelSourceUnavailable` error, as described in [Model source credentials](/specification/authentication#model-source-credentials). #### Retention The client that registers a source chooses what happens when the last contributing client leaves. Absent means `contributingClient`, the narrower choice. -A contributing client leaves when its connection closes and it doesn't reconnect with the same `clientId` within the host's `gracePeriod`. While other contributing clients remain, nothing changes. When the last one leaves: +A contributing client leaves when its connection closes and it doesn't reconnect with the same `clientId` within a grace period the host chooses. While other contributing clients remain, nothing changes. When the last one leaves: - With `contributingClient`, the source goes away, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the source with `root/modelSourceRemoved` and drops its credential. - With `host`, the source stays, like a host-declared MCP server, with its credential in memory and no contributing clients, until a client removes it or host policy expires it. A restart drops its credential, as described below. When the user removes the source from their configuration, their client removes it, whatever its retention, so `host` retention doesn't leave sources nobody wants. The host MAY expire `host`-retained sources. -A client that reconnects with the same `clientId` within the grace period is still counted. A client that comes back with a new `clientId` and the same configuration re-registers with `Set`, which keeps the status, nonce, and credential. After a restart, a host that persists its state SHOULD keep `host`-retained sources and their definitions, which come back through `starting`, and reach `authRequired` with `reason: required` only if they need a credential. +A client that reconnects with the same `clientId` within the grace period is still counted. A client that comes back with a new `clientId` and the same configuration re-registers with `Set`, which keeps the status and credential. After a restart, a host that persists its state SHOULD keep `host`-retained sources and their definitions, which come back through `starting`, and reach `authRequired` with `reason: required` only if they need a credential. #### Principals -AHP doesn't verify which client is which, so with `principalPolicy` `shared`, or absent, every connected client may change, supply credentials for, and select every model source, as with MCP servers. Where a host can verify principals, it MAY restrict changes, credentials, and use of a model source to clients of the principal that registered it, and advertises `isolated`. Root state still lists every model source to every client, and the action stream carries every definition, so neither is private. A host whose connections carry credentials scoped to one client, such as a relay that forwards each client's own sign-in, SHOULD NOT let one client's model source be used by another: it uses `isolated`, or doesn't advertise `modelSourceRegistration`. +AHP doesn't verify which client is which, so every connected client may change, supply credentials for, and select every model source, as with MCP servers. Where a host can verify principals, it MAY restrict changes, credentials, and use of a model source to clients of the principal that registered it, and rejects the rest through the usual failure paths. Root state still lists every model source, with its definition, to every client, so neither is private. A host whose connections carry credentials scoped to one client, such as a relay that forwards each client's own sign-in, SHOULD NOT let one client's model source be used by another: it restricts sources by principal, or doesn't advertise `modelSourceRegistration`. + +The grace period and any restriction by principal are host policy. The capability doesn't advertise them, because a client doesn't change what it does or shows because of them. #### Reserved model IDs @@ -226,7 +240,7 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/activeSessionsChanged` | Server | Replaces `activeSessions` | | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | -| `root/modelSourceSet` | Server / Client | Adds, re-registers, or updates a source in `modelSources` by `id`. The definition isn't stored | +| `root/modelSourceSet` | Server / Client | Adds, re-registers, or updates a source in `modelSources` by `id`, including its definition | | `root/modelSourceRemoved` | Server / Client | Removes a source by `id` | | `root/modelSourceStateChanged` | Server | Sets a registration's host-reported fields. A no-op for an unknown `id` | diff --git a/schema/actions.schema.json b/schema/actions.schema.json index db6417b70..031f9fec2 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -129,25 +129,19 @@ }, "RootModelSourceSetAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`. The reducer\nstores `modelSource` without the definition:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialNonce`,\n `credentialResource`, `credentialOrigins`, and `accountId`) and takes\n the other fields from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceSet" }, "modelSource": { "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`, without host-reported fields." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `modelSource.format`: endpoint, wire format,\nmodels, and so on. The host hands it to the agent, and the reducer\ndoesn't store it. MUST NOT contain a credential." + "description": "The model source to add or update, matched by `id`, including its\n`definition`, without host-reported fields." } }, "required": [ "type", - "modelSource", - "definition" + "modelSource" ] }, "RootModelSourceRemovedAction": { @@ -169,7 +163,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`accountId`. A no-op when no model source has `id`. Other fields of the\nsource are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`id`. Other fields of the source are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -182,21 +176,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "The new status." }, - "credentialNonce": { - "type": "string", - "description": "The model source's current credential nonce." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Replaces the source's `credentialOrigins`. Absent clears it." - }, "accountId": { "type": "string", "description": "Replaces the source's `accountId`. Absent clears it." @@ -205,8 +188,7 @@ "required": [ "type", "id", - "state", - "credentialNonce" + "state" ] }, "SessionReadyAction": { @@ -3585,27 +3567,31 @@ "formats": { "type": "array", "items": { - "type": "string" + "$ref": "#/$defs/ModelSourceFormatInfo" }, - "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." - }, - "gracePeriod": { - "type": "integer", - "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", - "minimum": 0 - }, - "principalPolicy": { - "$ref": "#/$defs/ModelSourcePrincipalPolicy", - "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." + "description": "Definition formats the agent reads, most preferred first." } }, "required": [ "formats" ] }, + "ModelSourceFormatInfo": { + "type": "object", + "description": "A definition format an agent reads. An object so it can grow, for example\nwith a JSON Schema for the format's definitions.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + } + }, + "required": [ + "format" + ] + }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -3628,11 +3614,16 @@ }, "format": { "type": "string", - "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." }, "nonce": { "type": "string", - "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -3642,21 +3633,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, - "credentialNonce": { - "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." - }, "accountId": { "type": "string", "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." @@ -3672,6 +3652,7 @@ "provider", "displayName", "format", + "definition", "nonce" ] }, @@ -10173,14 +10154,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourcePrincipalPolicy": { - "enum": [ - "shared", - "isolated" - ], - "type": "string", - "description": "Whether clients acting for different principals share a host's model\nsource registry." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 485f57b31..cbcd3deab 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1063,16 +1063,11 @@ "modelSourceId": { "type": "string", "description": "The registration's `ModelSource.id`." - }, - "credentialNonce": { - "type": "string", - "description": "The registration's current `ModelSource.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." } }, "required": [ "kind", - "modelSourceId", - "credentialNonce" + "modelSourceId" ] }, "AuthenticateParams": { @@ -1112,7 +1107,7 @@ }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). A\ndelivery replaces whatever credential the host holds for the source. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", @@ -2892,27 +2887,31 @@ "formats": { "type": "array", "items": { - "type": "string" + "$ref": "#/$defs/ModelSourceFormatInfo" }, - "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." - }, - "gracePeriod": { - "type": "integer", - "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", - "minimum": 0 - }, - "principalPolicy": { - "$ref": "#/$defs/ModelSourcePrincipalPolicy", - "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." + "description": "Definition formats the agent reads, most preferred first." } }, "required": [ "formats" ] }, + "ModelSourceFormatInfo": { + "type": "object", + "description": "A definition format an agent reads. An object so it can grow, for example\nwith a JSON Schema for the format's definitions.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + } + }, + "required": [ + "format" + ] + }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -2935,11 +2934,16 @@ }, "format": { "type": "string", - "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." }, "nonce": { "type": "string", - "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -2949,21 +2953,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, - "credentialNonce": { - "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." - }, "accountId": { "type": "string", "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." @@ -2979,6 +2972,7 @@ "provider", "displayName", "format", + "definition", "nonce" ] }, @@ -8582,25 +8576,19 @@ }, "RootModelSourceSetAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`. The reducer\nstores `modelSource` without the definition:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialNonce`,\n `credentialResource`, `credentialOrigins`, and `accountId`) and takes\n the other fields from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceSet" }, "modelSource": { "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`, without host-reported fields." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `modelSource.format`: endpoint, wire format,\nmodels, and so on. The host hands it to the agent, and the reducer\ndoesn't store it. MUST NOT contain a credential." + "description": "The model source to add or update, matched by `id`, including its\n`definition`, without host-reported fields." } }, "required": [ "type", - "modelSource", - "definition" + "modelSource" ] }, "RootModelSourceRemovedAction": { @@ -8622,7 +8610,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`accountId`. A no-op when no model source has `id`. Other fields of the\nsource are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`id`. Other fields of the source are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -8635,21 +8623,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "The new status." }, - "credentialNonce": { - "type": "string", - "description": "The model source's current credential nonce." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Replaces the source's `credentialOrigins`. Absent clears it." - }, "accountId": { "type": "string", "description": "Replaces the source's `accountId`. Absent clears it." @@ -8658,8 +8635,7 @@ "required": [ "type", "id", - "state", - "credentialNonce" + "state" ] }, "SessionReadyAction": { @@ -11610,14 +11586,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourcePrincipalPolicy": { - "enum": [ - "shared", - "isolated" - ], - "type": "string", - "description": "Whether clients acting for different principals share a host's model\nsource registry." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 67b95ac3d..3e31839e2 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -872,27 +872,31 @@ "formats": { "type": "array", "items": { - "type": "string" + "$ref": "#/$defs/ModelSourceFormatInfo" }, - "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." - }, - "gracePeriod": { - "type": "integer", - "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", - "minimum": 0 - }, - "principalPolicy": { - "$ref": "#/$defs/ModelSourcePrincipalPolicy", - "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." + "description": "Definition formats the agent reads, most preferred first." } }, "required": [ "formats" ] }, + "ModelSourceFormatInfo": { + "type": "object", + "description": "A definition format an agent reads. An object so it can grow, for example\nwith a JSON Schema for the format's definitions.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + } + }, + "required": [ + "format" + ] + }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -915,11 +919,16 @@ }, "format": { "type": "string", - "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." }, "nonce": { "type": "string", - "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -929,21 +938,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, - "credentialNonce": { - "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." - }, "accountId": { "type": "string", "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." @@ -959,6 +957,7 @@ "provider", "displayName", "format", + "definition", "nonce" ] }, @@ -7496,16 +7495,11 @@ "modelSourceId": { "type": "string", "description": "The registration's `ModelSource.id`." - }, - "credentialNonce": { - "type": "string", - "description": "The registration's current `ModelSource.credentialNonce`, as\npublished in root state. The host rejects a stale one with `Conflict`\n(-32011)." } }, "required": [ "kind", - "modelSourceId", - "credentialNonce" + "modelSourceId" ] }, "AuthenticateParams": { @@ -7545,7 +7539,7 @@ }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). A\ndelivery replaces whatever credential the host holds for the source. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", @@ -8497,14 +8491,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourcePrincipalPolicy": { - "enum": [ - "shared", - "isolated" - ], - "type": "string", - "description": "Whether clients acting for different principals share a host's model\nsource registry." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", @@ -9852,25 +9838,19 @@ }, "RootModelSourceSetAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`. The reducer\nstores `modelSource` without the definition:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialNonce`,\n `credentialResource`, `credentialOrigins`, and `accountId`) and takes\n the other fields from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceSet" }, "modelSource": { "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`, without host-reported fields." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `modelSource.format`: endpoint, wire format,\nmodels, and so on. The host hands it to the agent, and the reducer\ndoesn't store it. MUST NOT contain a credential." + "description": "The model source to add or update, matched by `id`, including its\n`definition`, without host-reported fields." } }, "required": [ "type", - "modelSource", - "definition" + "modelSource" ] }, "RootModelSourceRemovedAction": { @@ -9892,7 +9872,7 @@ }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialNonce`, `credentialResource`, `credentialOrigins`, and\n`accountId`. A no-op when no model source has `id`. Other fields of the\nsource are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`id`. Other fields of the source are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" @@ -9905,21 +9885,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "The new status." }, - "credentialNonce": { - "type": "string", - "description": "The model source's current credential nonce." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Replaces the source's `credentialOrigins`. Absent clears it." - }, "accountId": { "type": "string", "description": "Replaces the source's `accountId`. Absent clears it." @@ -9928,8 +9897,7 @@ "required": [ "type", "id", - "state", - "credentialNonce" + "state" ] }, "SessionReadyAction": { diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index c48fc052e..fea936cfa 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1174,27 +1174,31 @@ "formats": { "type": "array", "items": { - "type": "string" + "$ref": "#/$defs/ModelSourceFormatInfo" }, - "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." - }, - "gracePeriod": { - "type": "integer", - "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", - "minimum": 0 - }, - "principalPolicy": { - "$ref": "#/$defs/ModelSourcePrincipalPolicy", - "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." + "description": "Definition formats the agent reads, most preferred first." } }, "required": [ "formats" ] }, + "ModelSourceFormatInfo": { + "type": "object", + "description": "A definition format an agent reads. An object so it can grow, for example\nwith a JSON Schema for the format's definitions.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + } + }, + "required": [ + "format" + ] + }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -1217,11 +1221,16 @@ }, "format": { "type": "string", - "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." }, "nonce": { "type": "string", - "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -1231,21 +1240,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, - "credentialNonce": { - "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." - }, "accountId": { "type": "string", "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." @@ -1261,6 +1259,7 @@ "provider", "displayName", "format", + "definition", "nonce" ] }, @@ -6811,14 +6810,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourcePrincipalPolicy": { - "enum": [ - "shared", - "isolated" - ], - "type": "string", - "description": "Whether clients acting for different principals share a host's model\nsource registry." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/schema/state.schema.json b/schema/state.schema.json index aec0dd37e..31f3b5b6b 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -783,27 +783,31 @@ "formats": { "type": "array", "items": { - "type": "string" + "$ref": "#/$defs/ModelSourceFormatInfo" }, - "description": "Definition formats the agent reads, most preferred first: recognized\nvalues of {@link ModelSource.format}, or namespaced names for formats\nthe agent defines itself." - }, - "gracePeriod": { - "type": "integer", - "description": "How long, in milliseconds, the host keeps counting a disconnected client\nas a contributing client before it treats the client as having left.", - "minimum": 0 - }, - "principalPolicy": { - "$ref": "#/$defs/ModelSourcePrincipalPolicy", - "description": "Whether clients acting for different principals share the registry.\nAbsent means `shared`." + "description": "Definition formats the agent reads, most preferred first." } }, "required": [ "formats" ] }, + "ModelSourceFormatInfo": { + "type": "object", + "description": "A definition format an agent reads. An object so it can grow, for example\nwith a JSON Schema for the format's definitions.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + } + }, + "required": [ + "format" + ] + }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nThe definition that tells the agent named by `provider` how to reach it\ntravels on {@link RootModelSourceSetAction} and isn't kept here. Nothing\nhere is a credential.\n\nStability: 1.0 - Early development.", + "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -826,11 +830,16 @@ }, "format": { "type": "string", - "description": "The definition's format, one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAHP doesn't define what a definition contains, even for these. Agents\nMAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." }, "nonce": { "type": "string", - "description": "Opaque version token for the definition, such as a hash of it, chosen by\nwhoever registers the source. A client compares it with its own copy\ninstead of the definition, and the reducer compares it to tell an update\nfrom a re-registration of the same definition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -840,21 +849,10 @@ "$ref": "#/$defs/ModelSourceState", "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." }, - "credentialNonce": { - "type": "string", - "description": "Host-issued token that a client echoes in\n{@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers\nthe credential, and that tags every agent operation on the source. The\nhost issues a new one when the source is added or updated, and whenever\nthe credential is installed or dropped. It never reuses one for the\nsame `id`. Set with `state`." - }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." }, - "credentialOrigins": { - "type": "array", - "items": { - "$ref": "#/$defs/URI" - }, - "description": "Every origin the host sends the credential to, such as\n`https://api.example.com`, derived from the definition it holds. Present\nwhenever `credentialResource` is. A client checks each one against its\nown copy of the definition before it sends a key. Set with `state`." - }, "accountId": { "type": "string", "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." @@ -870,6 +868,7 @@ "provider", "displayName", "format", + "definition", "nonce" ] }, @@ -6972,14 +6971,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourcePrincipalPolicy": { - "enum": [ - "shared", - "isolated" - ], - "type": "string", - "description": "Whether clients acting for different principals share a host's model\nsource registry." - }, "ModelSourceRetentionPolicy": { "enum": [ "contributingClient", diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index b9697b2fd..8851af58a 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -773,7 +773,7 @@ const STATE_ENUMS = [ 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', 'AutomationDisableConditionKind', @@ -796,6 +796,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceFormatInfo' }, { name: 'ModelSource' }, { name: 'ModelSourceStartingState' }, { name: 'ModelSourceReadyState' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index 21d9d8c74..06e2d6159 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -758,7 +758,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -780,6 +780,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceFormatInfo' }, { name: 'ModelSource' }, { name: 'ModelSourceStartingState' }, { name: 'ModelSourceReadyState' }, diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index a04e51a80..e71e00cbc 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1012,7 +1012,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1029,7 +1029,7 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceRegistrationCapability', 'ModelSource', 'ModelSourceStartingState', + 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 4006c115c..c24966460 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -854,7 +854,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -881,6 +881,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceFormatInfo' }, { name: 'ModelSource' }, { name: 'ModelSourceStartingState', omitDiscriminants: true }, { name: 'ModelSourceReadyState', omitDiscriminants: true }, diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index a04afaa0d..a1aa51a39 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -735,7 +735,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', - 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ModelSourcePrincipalPolicy', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -752,7 +752,7 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceRegistrationCapability', 'ModelSource', 'ModelSourceStartingState', + 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 7cc17735b..048a4a4a0 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -6,7 +6,7 @@ import type { AgentInfo, ModelSource, ModelSourceState } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; -import type { ProtectedResourceMetadata, URI } from '../common/state.js'; +import type { ProtectedResourceMetadata } from '../common/state.js'; import { ActionType } from '../common/actions.js'; // ─── Root Actions ──────────────────────────────────────────────────────────── @@ -69,14 +69,12 @@ export interface RootConfigChangedAction { } /** - * Adds a model source, or updates the one with the same `id`. The reducer - * stores `modelSource` without the definition: + * Adds a model source, or updates the one with the same `id`: * * - **Add.** When no model source has the `id`, appends `modelSource`. * - **Re-register.** When one has, with the same `provider`, `format`, and - * `nonce`, keeps its host-reported fields (`state`, `credentialNonce`, - * `credentialResource`, `credentialOrigins`, and `accountId`) and takes - * the other fields from the action. + * `nonce`, keeps its host-reported fields (`state`, `credentialResource`, + * and `accountId`) and takes everything else from the action. * - **Update.** When any of the three differs, replaces the source. Its * host-reported fields are absent until the host reports again with * {@link RootModelSourceStateChangedAction}. @@ -91,14 +89,11 @@ export interface RootConfigChangedAction { */ export interface RootModelSourceSetAction { type: ActionType.RootModelSourceSet; - /** The model source to add or update, matched by `id`, without host-reported fields. */ - modelSource: ModelSource; /** - * How to reach the source, in `modelSource.format`: endpoint, wire format, - * models, and so on. The host hands it to the agent, and the reducer - * doesn't store it. MUST NOT contain a credential. + * The model source to add or update, matched by `id`, including its + * `definition`, without host-reported fields. */ - definition: Record; + modelSource: ModelSource; } /** @@ -118,9 +113,8 @@ export interface RootModelSourceRemovedAction { /** * Updates a model source's host-reported fields together: `state`, - * `credentialNonce`, `credentialResource`, `credentialOrigins`, and - * `accountId`. A no-op when no model source has `id`. Other fields of the - * source are preserved. Only the host dispatches it. + * `credentialResource`, and `accountId`. A no-op when no model source has + * `id`. Other fields of the source are preserved. Only the host dispatches it. * * @category Root Actions * @stability 1.0 @@ -132,15 +126,11 @@ export interface RootModelSourceStateChangedAction { id: string; /** The new status. */ state: ModelSourceState; - /** The model source's current credential nonce. */ - credentialNonce: string; /** * Replaces the source's `credentialResource`. Absent clears it, for a * source that needs no credential. */ credentialResource?: ProtectedResourceMetadata; - /** Replaces the source's `credentialOrigins`. Absent clears it. */ - credentialOrigins?: URI[]; /** Replaces the source's `accountId`. Absent clears it. */ accountId?: string; } diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index 08da4e508..d28401f06 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -88,7 +88,7 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st // ─── Model source registry helpers ─────────────────────────────────────────── -const HOST_REPORTED_FIELDS = ['state', 'credentialNonce', 'credentialResource', 'credentialOrigins', 'accountId'] as const; +const HOST_REPORTED_FIELDS = ['state', 'credentialResource', 'accountId'] as const; type HostReportedFields = Partial>; diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 8fa05ffbf..69453bdb0 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -12,7 +12,6 @@ import type { Icon, JsonPrimitive, ProtectedResourceMetadata, - URI, } from '../common/state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import type { Customization } from '../channels-session/state.js'; @@ -330,55 +329,29 @@ export interface ModelSelection { * @preserveUnknownMembers */ export interface ModelSourceRegistrationCapability { - /** - * Definition formats the agent reads, most preferred first: recognized - * values of {@link ModelSource.format}, or namespaced names for formats - * the agent defines itself. - */ - formats: string[]; - /** - * How long, in milliseconds, the host keeps counting a disconnected client - * as a contributing client before it treats the client as having left. - * - * @integer - * @minimum 0 - */ - gracePeriod?: number; - /** - * Whether clients acting for different principals share the registry. - * Absent means `shared`. - */ - principalPolicy?: ModelSourcePrincipalPolicy; + /** Definition formats the agent reads, most preferred first. */ + formats: ModelSourceFormatInfo[]; } /** - * Whether clients acting for different principals share a host's model - * source registry. + * A definition format an agent reads. An object so it can grow, for example + * with a JSON Schema for the format's definitions. * * @category Root State * @stability 1.0 - * @nonexhaustive + * @preserveUnknownMembers */ -export const enum ModelSourcePrincipalPolicy { - /** - * Every connected client may change, supply credentials for, and select - * every model source. - */ - Shared = 'shared', +export interface ModelSourceFormatInfo { /** - * The host verifies principals, and limits changes, credentials, and - * selection of each model source to clients of the principal that - * registered it. Root state still lists every model source to every - * client. + * A recognized {@link ModelSource.format} value, or a namespaced name for + * a format the agent defines itself. */ - Isolated = 'isolated', + format: string; } /** * A model source registered on this host by a client, or by the host itself. - * The definition that tells the agent named by `provider` how to reach it - * travels on {@link RootModelSourceSetAction} and isn't kept here. Nothing - * here is a credential. + * Nothing here is a credential. * * @category Root State * @stability 1.0 @@ -399,7 +372,7 @@ export interface ModelSource { /** Icons for UI display. */ icons?: Icon[]; /** - * The definition's format, one of the agent's + * The definition's format: the `format` of one of the agent's * {@link ModelSourceRegistrationCapability.formats}. Recognized values * include: * @@ -409,16 +382,35 @@ export interface ModelSource { * - `'azureOpenai'`: an Azure OpenAI deployment. * - `'gemini'`: Google's Gemini API. * - * AHP doesn't define what a definition contains, even for these. Agents - * MAY read other formats, named with a namespace such as + * Agents MAY read other formats, named with a namespace such as * `example.com/model-source@1` so they don't collide. */ format: string; /** - * Opaque version token for the definition, such as a hash of it, chosen by - * whoever registers the source. A client compares it with its own copy - * instead of the definition, and the reducer compares it to tell an update - * from a re-registration of the same definition. + * How to reach the source, in `format`: endpoint, wire API, models, and so + * on. The agent reads it, and AHP doesn't validate it. Every client can + * read it, so it MUST NOT contain a credential. + * + * Suggested shapes for the recognized formats. Agents MAY read more + * members, and MAY discover models when `models` is absent. + * + * - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` + * - `anthropic`: `{ endpoint, models? }` + * - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each + * deployment name as a model `id` + * - `gemini`: `{ endpoint, models? }` + * + * `endpoint` is the API's base URI, such as `https://api.example.com/v1`. + * Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, + * supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, + * where `id` is the endpoint's own model identifier. + */ + definition: Record; + /** + * Opaque version token for `definition`, such as a hash of it, chosen by + * whoever registers the source. Reducers compare it, instead of the + * definition, to tell an update from a re-registration of the same + * definition. */ nonce: string; /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ @@ -429,17 +421,6 @@ export interface ModelSource { * definition until the host reports again. */ state?: ModelSourceState; - /** - * Host-issued token that a client echoes in - * {@link ModelSourceAuthenticateTarget.credentialNonce} when it delivers - * the credential, and that tags every agent operation on the source. The - * host issues a new one when the source is added or updated, and whenever - * the credential is installed or dropped. It never reuses one for the - * same `id`. Set with `state`. - * - * @see {@link /specification/authentication#model-source-credentials | Model source credentials} - */ - credentialNonce?: string; /** * RFC 9728 metadata for the endpoint the credential is for. Present * whenever the source takes a credential, in every state, so any client @@ -458,15 +439,6 @@ export interface ModelSource { * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ credentialResource?: ProtectedResourceMetadata; - /** - * Every origin the host sends the credential to, such as - * `https://api.example.com`, derived from the definition it holds. Present - * whenever `credentialResource` is. A client checks each one against its - * own copy of the definition before it sends a key. Set with `state`. - * - * @see {@link /specification/authentication#model-source-credentials | Model source credentials} - */ - credentialOrigins?: URI[]; /** * The {@link AuthenticateParams.accountId} the client sent with the * credential the host most recently accepted. While the state is diff --git a/types/common/commands.ts b/types/common/commands.ts index 5bb3c4099..5accb197e 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1494,12 +1494,6 @@ export interface ModelSourceAuthenticateTarget { kind: AuthenticateTargetKind.ModelSource; /** The registration's `ModelSource.id`. */ modelSourceId: string; - /** - * The registration's current `ModelSource.credentialNonce`, as - * published in root state. The host rejects a stale one with `Conflict` - * (-32011). - */ - credentialNonce: string; } /** @@ -1611,7 +1605,8 @@ export interface AuthenticateParams extends BaseParams { * * A registered model source takes its credential only through a * `modelSource` target, and the host rejects an untargeted `resource` that - * matches only model source challenges with `InvalidParams` (-32602). See + * matches only model source challenges with `InvalidParams` (-32602). A + * delivery replaces whatever credential the host holds for the source. See * [Model source credentials](/specification/authentication#model-source-credentials) * for its rules. * diff --git a/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json index f7630119d..905293a14 100644 --- a/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json +++ b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceSet adds a model source to an absent registry, storing it without the definition", + "description": "root/modelSourceSet adds a model source, including its definition, to an absent registry", "reducer": "root", "initial": { "agents": [] @@ -12,13 +12,15 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" - }, - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - "model-a" - ] } } ], @@ -30,6 +32,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" } ] diff --git a/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json b/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json index ce41cc0bd..2cda1cb20 100644 --- a/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json +++ b/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceSet with the same provider, format, and nonce re-registers: it keeps every host-reported field and takes displayName, icons, retention, and _meta from the action", + "description": "root/modelSourceSet with the same provider, format, and nonce re-registers: it keeps every host-reported field (state, credentialResource, and accountId) and takes everything else from the action, including displayName, icons, retention, and _meta", "reducer": "root", "initial": { "agents": [], @@ -9,18 +9,22 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "state": { "kind": "ready" }, - "credentialNonce": "nonce-a-1", "credentialResource": { "resource": "https://apia.example.com/v1", "resource_name": "Source a API key" }, - "credentialOrigins": [ - "https://apia.example.com" - ], "accountId": "account-a-1" }, { @@ -28,6 +32,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1" } ] @@ -40,6 +52,14 @@ "provider": "copilot", "displayName": "Source a (renamed)", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "icons": [ { @@ -50,12 +70,6 @@ "_meta": { "example.com/window": "2" } - }, - "definition": { - "baseUrl": "https://apia.example.com/v1", - "models": [ - "model-a" - ] } } ], @@ -67,6 +81,14 @@ "provider": "copilot", "displayName": "Source a (renamed)", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "icons": [ { @@ -80,14 +102,10 @@ "state": { "kind": "ready" }, - "credentialNonce": "nonce-a-1", "credentialResource": { "resource": "https://apia.example.com/v1", "resource_name": "Source a API key" }, - "credentialOrigins": [ - "https://apia.example.com" - ], "accountId": "account-a-1" }, { @@ -95,6 +113,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1" } ] diff --git a/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json b/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json index 5b3666b77..d04ebc6ee 100644 --- a/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json +++ b/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceSet with a different nonce updates the model source: it replaces the source and clears the host-reported fields until the host reports again", + "description": "root/modelSourceSet with a different nonce updates the model source: it replaces the source, including its definition, and clears the host-reported fields until the host reports again", "reducer": "root", "initial": { "agents": [], @@ -9,18 +9,22 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "state": { "kind": "ready" }, - "credentialNonce": "nonce-a-1", "credentialResource": { "resource": "https://apia.example.com/v1", "resource_name": "Source a API key" }, - "credentialOrigins": [ - "https://apia.example.com" - ], "accountId": "account-a-1" }, { @@ -28,6 +32,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1" } ] @@ -40,13 +52,15 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v2", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v2" - }, - "definition": { - "baseUrl": "https://apia.example.com/v2", - "models": [ - "model-a" - ] } } ], @@ -58,6 +72,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v2", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v2" }, { @@ -65,6 +87,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1" } ] diff --git a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json index 7bbc6f59c..300a2c367 100644 --- a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json +++ b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json @@ -9,18 +9,22 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "state": { "kind": "ready" }, - "credentialNonce": "nonce-a-1", "credentialResource": { "resource": "https://apia.example.com/v1", "resource_name": "Source a API key" }, - "credentialOrigins": [ - "https://apia.example.com" - ], "accountId": "account-a-1" }, { @@ -28,6 +32,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1" } ] @@ -46,6 +58,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1" } ] diff --git a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json index be004d473..1c7188c56 100644 --- a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json @@ -9,6 +9,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" } ] @@ -27,6 +35,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" } ] diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json index 40258dac8..374e85630 100644 --- a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json +++ b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceStateChanged sets the matching model source's state, credentialNonce, credentialResource, credentialOrigins, and accountId together, adding credential fields it didn't have, and preserves its other fields and the registry order", + "description": "root/modelSourceStateChanged sets the matching model source's state, credentialResource, and accountId together, adding credential fields it didn't have, and preserves its other fields and the registry order", "reducer": "root", "initial": { "agents": [], @@ -9,6 +9,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" }, { @@ -16,12 +24,19 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1", "retention": "host", "state": { "kind": "starting" - }, - "credentialNonce": "nonce-b-1" + } } ] }, @@ -34,14 +49,10 @@ "reason": "rejected", "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-b-2", "credentialResource": { "resource": "https://apib.example.com/v1", "resource_name": "Source b API key" }, - "credentialOrigins": [ - "https://apib.example.com" - ], "accountId": "account-b-1" } ], @@ -53,6 +64,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" }, { @@ -60,6 +79,14 @@ "provider": "copilot", "displayName": "Source b", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + }, "nonce": "definition-b-v1", "retention": "host", "state": { @@ -67,14 +94,10 @@ "reason": "rejected", "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-b-2", "credentialResource": { "resource": "https://apib.example.com/v1", "resource_name": "Source b API key" }, - "credentialOrigins": [ - "https://apib.example.com" - ], "accountId": "account-b-1" } ] diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json index 2bfad4a7f..df738b847 100644 --- a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json +++ b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceStateChanged without credentialResource, credentialOrigins, or accountId clears the model source's existing ones, for a source that turns out to need no credential", + "description": "root/modelSourceStateChanged without credentialResource or accountId clears the model source's existing ones, for a source that turns out to need no credential", "reducer": "root", "initial": { "agents": [], @@ -9,18 +9,22 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "state": { "kind": "starting" }, - "credentialNonce": "nonce-a-1", "credentialResource": { "resource": "https://apia.example.com/v1", "resource_name": "Source a API key" }, - "credentialOrigins": [ - "https://apia.example.com" - ], "accountId": "account-a-1" } ] @@ -31,8 +35,7 @@ "id": "model-source-a", "state": { "kind": "ready" - }, - "credentialNonce": "nonce-a-2" + } } ], "expected": { @@ -43,11 +46,18 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1", "state": { "kind": "ready" - }, - "credentialNonce": "nonce-a-2" + } } ] } diff --git a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json index d230814f4..095c32da3 100644 --- a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json @@ -9,6 +9,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" } ] @@ -19,8 +27,7 @@ "id": "model-source-removed", "state": { "kind": "ready" - }, - "credentialNonce": "nonce-removed-1" + } } ], "expected": { @@ -31,6 +38,14 @@ "provider": "copilot", "displayName": "Source a", "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + }, "nonce": "definition-a-v1" } ] diff --git a/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json b/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json index 8b7eb8e1a..5e5bedf59 100644 --- a/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json +++ b/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json @@ -10,8 +10,7 @@ "id": "model-source-a", "state": { "kind": "starting" - }, - "credentialNonce": "nonce-a-1" + } } ], "expected": { diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 60cfb4b26..1d08dbc39 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot carries registered model sources with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each source carries a nonce for its definition, which isn't kept in state. Sources that take a credential carry a host-reported credentialResource and credentialOrigins in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with the recognized formats it reads and a namespaced one, its contributor grace period, and its principal policy, and its catalog lists the ready source and the authRequired one whose key expired, since models stay listed after a source has been ready.", + "description": "A root snapshot carries registered model sources with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each source carries its definition, in the suggested shape for its recognized format or an agent's own shape, including members the suggested shapes don't name, and a nonce for it. Sources that take a credential carry a host-reported credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects for the recognized formats it reads and a namespaced one, and its catalog lists the ready source and the authRequired one whose key expired, since models stay listed after a source has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -15,14 +15,22 @@ "capabilities": { "modelSourceRegistration": { "formats": [ - "openaiCompatible", - "anthropic", - "azureOpenai", - "gemini", - "example.com/model-source@1" - ], - "gracePeriod": 30000, - "principalPolicy": "shared" + { + "format": "openaiCompatible" + }, + { + "format": "anthropic" + }, + { + "format": "azureOpenai" + }, + { + "format": "gemini" + }, + { + "format": "example.com/model-source@1" + } + ] } }, "modelSources": [ @@ -59,6 +67,9 @@ "provider": "example", "displayName": "Unreported", "format": "anthropic", + "definition": { + "endpoint": "https://api.anthropic.example.com/v1" + }, "nonce": "sha256-unreported-1" }, { @@ -66,17 +77,39 @@ "provider": "example", "displayName": "Starting", "format": "gemini", + "definition": { + "endpoint": "https://gemini.example.com/v1beta", + "models": [ + { + "id": "gemini-model" + } + ] + }, "nonce": "sha256-starting-1", "state": { "kind": "starting" - }, - "credentialNonce": "nonce-starting-1" + } }, { "id": "source-ready", "provider": "example", "displayName": "OpenRouter", "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "wireApi": "chatCompletions", + "models": [ + { + "id": "vendor/model-a", + "name": "Example model", + "maxContextWindow": 128000, + "maxOutputTokens": 16384, + "supportsVision": true, + "supportsTools": true + } + ], + "fileEndpoint": "https://files.example.com/v1" + }, "nonce": "sha256-ready-1", "icons": [ { @@ -87,15 +120,10 @@ "state": { "kind": "ready" }, - "credentialNonce": "nonce-ready-1", "credentialResource": { "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://api.example.com", - "https://files.example.com" - ], "accountId": "keychain-openrouter-1", "_meta": { "example.com/label": "Laptop" @@ -106,6 +134,15 @@ "provider": "example", "displayName": "Azure endpoint", "format": "azureOpenai", + "definition": { + "endpoint": "https://example.openai.azure.com/openai/v1", + "apiVersion": "2024-10-21", + "models": [ + { + "id": "example-deployment" + } + ] + }, "nonce": "sha256-auth-1", "retention": "contributingClient", "state": { @@ -113,7 +150,6 @@ "reason": "expired", "description": "The access token expired." }, - "credentialNonce": "nonce-auth-1", "credentialResource": { "resource": "https://example.openai.azure.com/openai/v1", "resource_name": "Azure OpenAI", @@ -124,9 +160,6 @@ "https://cognitiveservices.azure.com/.default" ] }, - "credentialOrigins": [ - "https://example.openai.azure.com" - ], "accountId": "entra-azure-1" }, { @@ -134,25 +167,33 @@ "provider": "example", "displayName": "Local server", "format": "openaiCompatible", + "definition": { + "endpoint": "http://localhost:11434/v1", + "wireApi": "responses" + }, "nonce": "sha256-local-1", "state": { "kind": "authRequired", "reason": "required" }, - "credentialNonce": "nonce-local-1", "credentialResource": { "resource": "http://localhost:11434/v1", "resource_name": "Local server key" - }, - "credentialOrigins": [ - "http://localhost:11434" - ] + } }, { "id": "source-rejected", "provider": "example", "displayName": "Rejected key", "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, "nonce": "sha256-rejected-1", "icons": [ { @@ -165,15 +206,10 @@ "reason": "rejected", "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-rejected-2", "credentialResource": { "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://api.example.com", - "https://files.example.com" - ], "accountId": "keychain-rejected-1" }, { @@ -181,6 +217,14 @@ "provider": "example", "displayName": "Revoked key", "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, "nonce": "sha256-revoked-1", "icons": [ { @@ -192,15 +236,10 @@ "kind": "authRequired", "reason": "revoked" }, - "credentialNonce": "nonce-revoked-3", "credentialResource": { "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://api.example.com", - "https://files.example.com" - ], "accountId": "keychain-revoked-1" }, { @@ -208,6 +247,12 @@ "provider": "example", "displayName": "Host-configured", "format": "example.com/model-source@1", + "definition": { + "endpoint": "https://models.internal.example.com", + "routing": { + "region": "example-1" + } + }, "nonce": "sha256-host-1", "state": { "kind": "error", @@ -215,8 +260,7 @@ "errorType": "policy", "message": "The endpoint is not allowed by host policy." } - }, - "credentialNonce": "nonce-host-1" + } } ] } @@ -234,14 +278,22 @@ "capabilities": { "modelSourceRegistration": { "formats": [ - "openaiCompatible", - "anthropic", - "azureOpenai", - "gemini", - "example.com/model-source@1" - ], - "gracePeriod": 30000, - "principalPolicy": "shared" + { + "format": "openaiCompatible" + }, + { + "format": "anthropic" + }, + { + "format": "azureOpenai" + }, + { + "format": "gemini" + }, + { + "format": "example.com/model-source@1" + } + ] } }, "modelSources": [ @@ -278,6 +330,9 @@ "provider": "example", "displayName": "Unreported", "format": "anthropic", + "definition": { + "endpoint": "https://api.anthropic.example.com/v1" + }, "nonce": "sha256-unreported-1" }, { @@ -285,17 +340,39 @@ "provider": "example", "displayName": "Starting", "format": "gemini", + "definition": { + "endpoint": "https://gemini.example.com/v1beta", + "models": [ + { + "id": "gemini-model" + } + ] + }, "nonce": "sha256-starting-1", "state": { "kind": "starting" - }, - "credentialNonce": "nonce-starting-1" + } }, { "id": "source-ready", "provider": "example", "displayName": "OpenRouter", "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "wireApi": "chatCompletions", + "models": [ + { + "id": "vendor/model-a", + "name": "Example model", + "maxContextWindow": 128000, + "maxOutputTokens": 16384, + "supportsVision": true, + "supportsTools": true + } + ], + "fileEndpoint": "https://files.example.com/v1" + }, "nonce": "sha256-ready-1", "icons": [ { @@ -306,15 +383,10 @@ "state": { "kind": "ready" }, - "credentialNonce": "nonce-ready-1", "credentialResource": { "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://api.example.com", - "https://files.example.com" - ], "accountId": "keychain-openrouter-1", "_meta": { "example.com/label": "Laptop" @@ -325,6 +397,15 @@ "provider": "example", "displayName": "Azure endpoint", "format": "azureOpenai", + "definition": { + "endpoint": "https://example.openai.azure.com/openai/v1", + "apiVersion": "2024-10-21", + "models": [ + { + "id": "example-deployment" + } + ] + }, "nonce": "sha256-auth-1", "retention": "contributingClient", "state": { @@ -332,7 +413,6 @@ "reason": "expired", "description": "The access token expired." }, - "credentialNonce": "nonce-auth-1", "credentialResource": { "resource": "https://example.openai.azure.com/openai/v1", "resource_name": "Azure OpenAI", @@ -343,9 +423,6 @@ "https://cognitiveservices.azure.com/.default" ] }, - "credentialOrigins": [ - "https://example.openai.azure.com" - ], "accountId": "entra-azure-1" }, { @@ -353,25 +430,33 @@ "provider": "example", "displayName": "Local server", "format": "openaiCompatible", + "definition": { + "endpoint": "http://localhost:11434/v1", + "wireApi": "responses" + }, "nonce": "sha256-local-1", "state": { "kind": "authRequired", "reason": "required" }, - "credentialNonce": "nonce-local-1", "credentialResource": { "resource": "http://localhost:11434/v1", "resource_name": "Local server key" - }, - "credentialOrigins": [ - "http://localhost:11434" - ] + } }, { "id": "source-rejected", "provider": "example", "displayName": "Rejected key", "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, "nonce": "sha256-rejected-1", "icons": [ { @@ -384,15 +469,10 @@ "reason": "rejected", "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-rejected-2", "credentialResource": { "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://api.example.com", - "https://files.example.com" - ], "accountId": "keychain-rejected-1" }, { @@ -400,6 +480,14 @@ "provider": "example", "displayName": "Revoked key", "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, "nonce": "sha256-revoked-1", "icons": [ { @@ -411,15 +499,10 @@ "kind": "authRequired", "reason": "revoked" }, - "credentialNonce": "nonce-revoked-3", "credentialResource": { "resource": "https://api.example.com/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://api.example.com", - "https://files.example.com" - ], "accountId": "keychain-revoked-1" }, { @@ -427,6 +510,12 @@ "provider": "example", "displayName": "Host-configured", "format": "example.com/model-source@1", + "definition": { + "endpoint": "https://models.internal.example.com", + "routing": { + "region": "example-1" + } + }, "nonce": "sha256-host-1", "state": { "kind": "error", @@ -434,8 +523,7 @@ "errorType": "policy", "message": "The endpoint is not allowed by host policy." } - }, - "credentialNonce": "nonce-host-1" + } } ] } diff --git a/types/test-cases/round-trips/104-root-model-source-set.json b/types/test-cases/round-trips/104-root-model-source-set.json index 4482df08d..39eb820fc 100644 --- a/types/test-cases/round-trips/104-root-model-source-set.json +++ b/types/test-cases/round-trips/104-root-model-source-set.json @@ -1,7 +1,7 @@ { "name": "root-model-source-set", "group": "A", - "description": "A client registers a model source with root/modelSourceSet: the source with a nonce for its definition and requested retention, no host-reported fields, and an open definition alongside it that the reducer doesn't store.", + "description": "A client registers a model source with root/modelSourceSet: the source with its definition, in the suggested openaiCompatible shape plus a member the agent defines, a nonce for it, requested retention, and no host-reported fields.", "type": "StateAction", "input": { "type": "root/modelSourceSet", @@ -10,18 +10,26 @@ "provider": "example", "displayName": "OpenRouter", "format": "openaiCompatible", + "definition": { + "endpoint": "https://openrouter.ai/api/v1", + "wireApi": "chatCompletions", + "models": [ + { + "id": "vendor/model-a", + "name": "Model A", + "maxContextWindow": 200000, + "supportsTools": true + }, + { + "id": "vendor/model-b" + } + ], + "headers": { + "x-title": "Example" + } + }, "nonce": "sha256-new-1", "retention": "host" - }, - "definition": { - "baseUrl": "https://openrouter.ai/api/v1", - "models": [ - "vendor/model-a", - "vendor/model-b" - ], - "headers": { - "x-title": "Example" - } } }, "acceptableOutputs": [ @@ -32,18 +40,26 @@ "provider": "example", "displayName": "OpenRouter", "format": "openaiCompatible", + "definition": { + "endpoint": "https://openrouter.ai/api/v1", + "wireApi": "chatCompletions", + "models": [ + { + "id": "vendor/model-a", + "name": "Model A", + "maxContextWindow": 200000, + "supportsTools": true + }, + { + "id": "vendor/model-b" + } + ], + "headers": { + "x-title": "Example" + } + }, "nonce": "sha256-new-1", "retention": "host" - }, - "definition": { - "baseUrl": "https://openrouter.ai/api/v1", - "models": [ - "vendor/model-a", - "vendor/model-b" - ], - "headers": { - "x-title": "Example" - } } } ] diff --git a/types/test-cases/round-trips/106-authenticate-model-source-target.json b/types/test-cases/round-trips/106-authenticate-model-source-target.json index 665663e80..678e0d511 100644 --- a/types/test-cases/round-trips/106-authenticate-model-source-target.json +++ b/types/test-cases/round-trips/106-authenticate-model-source-target.json @@ -1,7 +1,7 @@ { "name": "authenticate-model-source-target", "group": "A", - "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target that echoes the source's credentialNonce, and names the key with the existing accountId parameter. An API key carries no expiresIn or scopes.", + "description": "authenticate delivers an opaque secret for one registered model source through a modelSource target, and names the key with the existing accountId parameter. An API key carries no expiresIn or scopes.", "type": "AuthenticateParams", "input": { "channel": "ahp-root://", @@ -10,8 +10,7 @@ "accountId": "keychain-openrouter-1", "target": { "kind": "modelSource", - "modelSourceId": "source-new", - "credentialNonce": "nonce-openrouter-1" + "modelSourceId": "source-new" } }, "acceptableOutputs": [ @@ -22,8 +21,7 @@ "accountId": "keychain-openrouter-1", "target": { "kind": "modelSource", - "modelSourceId": "source-new", - "credentialNonce": "nonce-openrouter-1" + "modelSourceId": "source-new" } } ] diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json index 1f5bcc0d8..3a92d9e08 100644 --- a/types/test-cases/round-trips/107-root-model-source-state-changed.json +++ b/types/test-cases/round-trips/107-root-model-source-state-changed.json @@ -1,7 +1,7 @@ { "name": "root-model-source-state-changed", "group": "A", - "description": "The host reports with root/modelSourceStateChanged that the endpoint rejected a key, issuing a new credential nonce and naming the rejected key's accountId, along with the credentialResource and every origin the key is sent to.", + "description": "The host reports with root/modelSourceStateChanged that the endpoint rejected a key, naming the rejected key's accountId, along with the credentialResource the key is for.", "type": "StateAction", "input": { "type": "root/modelSourceStateChanged", @@ -11,14 +11,10 @@ "reason": "rejected", "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-openrouter-2", "credentialResource": { "resource": "https://openrouter.ai/api/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://openrouter.ai" - ], "accountId": "keychain-openrouter-1" }, "acceptableOutputs": [ @@ -30,14 +26,10 @@ "reason": "rejected", "description": "The endpoint rejected the API key." }, - "credentialNonce": "nonce-openrouter-2", "credentialResource": { "resource": "https://openrouter.ai/api/v1", "resource_name": "OpenRouter API key" }, - "credentialOrigins": [ - "https://openrouter.ai" - ], "accountId": "keychain-openrouter-1" } ] From 6a80f578efae7aeac1846be795157e17793aa0ba Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 08:50:49 -0500 Subject: [PATCH 11/17] models: fold ModelSourceInfo into ModelSource and address review - `RootState.modelSources` now lists every model source, including an agent's built-in ones. Remove `ModelSourceInfo` and `AgentInfo.modelSources`; `SessionModelInfo.modelSourceId` names a root source whose `provider` is the model's agent. `format`, `definition`, and `nonce` are optional, present on registered sources. - Add `AhpErrorCodes.ModelSourceUnavailable` (-32013) for requests that select a model whose registered source can't serve it. - Revert model-source wording in the shared `authenticate`, `ProtectedResourceMetadata`, and authentication docs, and drop the new empty-token revocation rules. - Describe format names as conventions some agents may read, not values AHP recognizes. - Keep `@preserveUnknownMembers` only on `ModelSource`, the one new root type clients send. - Cut the root channel and authentication spec sections to their normative rules. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../protocol-naming.instructions.md | 4 +- .../Generated/Actions.generated.cs | 8 +- .../Generated/Commands.generated.cs | 34 +- .../Generated/Errors.generated.cs | 2 + .../JsonSerializerContext.generated.cs | 1 - .../Generated/State.generated.cs | 160 +++------ clients/go/ahp/reducers.go | 11 +- clients/go/ahptypes/actions.generated.go | 8 +- clients/go/ahptypes/commands.generated.go | 32 +- clients/go/ahptypes/errors.generated.go | 2 + clients/go/ahptypes/state.generated.go | 207 +++--------- .../generated/Actions.generated.kt | 8 +- .../generated/Commands.generated.kt | 25 +- .../generated/Errors.generated.kt | 2 + .../generated/State.generated.kt | 219 ++++-------- clients/rust/crates/ahp-types/src/actions.rs | 8 +- clients/rust/crates/ahp-types/src/commands.rs | 32 +- clients/rust/crates/ahp-types/src/errors.rs | 2 + clients/rust/crates/ahp-types/src/state.rs | 164 +++------ .../rust/crates/ahp/examples/reducers_demo.rs | 1 - clients/rust/crates/ahp/tests/hosts.rs | 1 - .../ahp/tests/multi_host_state_mirror.rs | 1 - .../Generated/Actions.generated.swift | 8 +- .../Generated/Commands.generated.swift | 25 +- .../Generated/Errors.generated.swift | 2 + .../Generated/State.generated.swift | 317 ++++-------------- .../20261022-model-source-selection.json | 2 +- .../20261123-model-source-registry.json | 2 +- docs/guide/actions.md | 2 +- docs/guide/state-model.md | 2 +- docs/specification/authentication.md | 56 +--- docs/specification/root-channel.md | 146 ++------ schema/actions.schema.json | 62 +--- schema/commands.schema.json | 78 ++--- schema/errors.schema.json | 78 ++--- schema/notifications.schema.json | 58 +--- schema/state.schema.json | 58 +--- scripts/generate-csharp.ts | 1 - scripts/generate-go.ts | 3 +- scripts/generate-kotlin.ts | 4 +- scripts/generate-rust.ts | 3 +- scripts/generate-swift.ts | 4 +- types/channels-root/actions.ts | 16 +- types/channels-root/state.ts | 140 +++----- types/common/commands.ts | 34 +- types/common/errors.ts | 9 + types/common/state.ts | 10 +- ...ourceset-built-in-source-re-registers.json | 40 +++ .../round-trips/101-model-source-catalog.json | 64 ++-- .../103-model-source-registry-snapshot.json | 40 +-- 50 files changed, 673 insertions(+), 1523 deletions(-) create mode 100644 types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json diff --git a/.github/instructions/protocol-naming.instructions.md b/.github/instructions/protocol-naming.instructions.md index 3ef02040b..e83cdcc19 100644 --- a/.github/instructions/protocol-naming.instructions.md +++ b/.github/instructions/protocol-naming.instructions.md @@ -38,8 +38,8 @@ but don't use them as precedent. | **agent** | An agent implementation that the host exposes, described by `AgentInfo`. | | | **agent provider** (`provider`) | The ID of the agent backing a session or chat (`AgentInfo.provider`, `SessionState.provider`, `ChatState.provider`). Always write "agent provider" in prose. | The **custom agent** (`Message.agent`, `AgentSelection`): a configured persona within an agent provider. The **model vendor** (`SessionModelInfo.vendor`): the company that serves a model. The **model source** (`modelSourceId`): where a model comes from. | | **model** | A model offered by an agent provider (`SessionModelInfo`). It is selected per message (`Message.model`). | | -| **model source** (`modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `AgentInfo.modelSources` (`ModelSourceInfo`). Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | -| **registration** (`ModelSource`) | A model source a client or the host added to the host's registry in `RootState.modelSources`, with its status. A ready registration joins its agent's catalog as a model source, and a registered source is also called a registration. | The **model source** it becomes in the catalog (`ModelSourceInfo`). | +| **model source** (`ModelSource`, `modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `RootState.modelSources` with the agent provider it serves. Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | +| **registered model source** | A model source a client added with `root/modelSourceSet`, or the host added from its own configuration, with a `format`, `definition`, and `nonce`, and a host-reported status. Also called a registration. | An agent's **built-in** sources, which the host lists without a definition. | | **contributing client** | A client that added a client-contributed entry. For a model source, it's a client that registered it and hasn't left; the host tracks these itself, from `ActionEnvelope.origin`, and they aren't in state. | The **action origin**'s `clientId`, which names the client that dispatched one action. | | **principal** | The user or account a host has verified a client acts for. AHP doesn't define how a host verifies one. A host MAY restrict model sources by principal. | A **client** (`clientId`), which identifies a connection's client and isn't verified. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 1ead12d85..c8ca46442 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -356,16 +356,16 @@ public sealed record RootConfigChangedAction /// host-reported fields are absent until the host reports again with /// {@link RootModelSourceStateChangedAction}. /// -/// A client dispatches this without any host-reported field. The host learns -/// which client registered the source from the envelope's `origin`. +/// A client registers a source with its `format`, `definition`, and `nonce`, +/// and without any host-reported field. The host learns which client +/// registered it from the envelope's `origin`. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceSetAction { public ActionType Type { get; init; } = ActionType.RootModelSourceSet; - /// The model source to add or update, matched by `id`, including its - /// `definition`, without host-reported fields. + /// The model source to add or update, matched by `id`. public required ModelSource ModelSource { get; init; } } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index f8ad4a726..40073731a 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs @@ -1885,18 +1885,20 @@ public sealed record McpServerAuthenticateTarget public required string CustomizationId { get; init; } } -/// A registered model source. +/// A registered model source. The host applies the credential only to that +/// source, and publishes the request's `accountId` as the source's +/// `ModelSource.accountId`. /// /// Stability: 1.0 - Early development. public sealed record ModelSourceAuthenticateTarget { public AuthenticateTargetKind Kind { get; init; } = AuthenticateTargetKind.ModelSource; - /// The registration's `ModelSource.id`. + /// The source's `ModelSource.id`. public required string ModelSourceId { get; init; } } -/// Pushes a credential for a protected resource. The `resource` field MUST +/// Pushes a Bearer token for a protected resource. The `resource` field MUST /// match a protected-resource identifier the client has discovered from the /// server — whether declared statically in `AgentInfo.protectedResources`, /// or discovered dynamically from a live `McpServerAuthRequiredState.resource` @@ -1905,14 +1907,13 @@ public sealed record ModelSourceAuthenticateTarget /// from a registered model source's `ModelSource.credentialResource`. /// Servers MUST accept any `resource` value they have themselves advertised /// through one of these mechanisms, subject to the `target` rules. A -/// `modelSource` target takes only the registration's current +/// `modelSource` target takes only the source's current /// `credentialResource.resource`. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the /// authorization server(s) listed in the resource's metadata and pushes it -/// to the server via this command. A model source's token is instead an -/// opaque secret, such as an API key. +/// to the server via this command. public sealed record AuthenticateParams { public required string Channel { get; init; } @@ -1930,8 +1931,7 @@ public sealed record AuthenticateParams /// or `ModelSource.credentialResource`. public required string Resource { get; init; } - /// Bearer token obtained from the resource's authorization server, or an - /// opaque secret for a model source. An empty string revokes the credential. + /// Bearer token obtained from the resource's authorization server public required string Token { get; init; } /// The access token's remaining lifetime, in seconds, when this @@ -1943,8 +1943,6 @@ public sealed record AuthenticateParams /// authorization server did not supply an expiry or the expiry is otherwise /// unknown. When supplied, the value MUST be a positive integer. /// - /// An API key omits this field. - /// /// This field is irrelevant when `token` is empty to revoke authentication /// and SHOULD be omitted in that case. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -1955,7 +1953,7 @@ public sealed record AuthenticateParams /// `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is /// satisfied without decoding the (opaque, server-specific) token itself. /// Omit when the client doesn't track granted scopes separately from the - /// token. Scopes apply to OAuth-issued tokens only. + /// token. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? Scopes { get; init; } @@ -1975,10 +1973,8 @@ public sealed record AuthenticateParams /// /// A registered model source takes its credential only through a /// `modelSource` target, and the host rejects an untargeted `resource` that - /// matches only model source challenges with `InvalidParams` (-32602). A - /// delivery replaces whatever credential the host holds for the source. See - /// [Model source credentials](/specification/authentication#model-source-credentials) - /// for its rules. + /// matches only model source challenges with `InvalidParams` (-32602). See + /// [Model source credentials](/specification/authentication#model-source-credentials). /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -1988,13 +1984,7 @@ public sealed record AuthenticateParams /// Optional identifier for the client's selected account, sent alongside the token. /// Hosts can compare `accountId` values to detect when the underlying account has changed. /// Hosts MUST treat `accountId` as an opaque string. - /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. - /// - /// With a `modelSource` target, clients SHOULD include it when delivering a - /// credential and omit it when revoking one, and the host publishes it as - /// the source's `ModelSource.accountId`. It MUST NOT be derived from the - /// secret. For an API key with no account of its own, a client uses an ID - /// that changes whenever the user replaces the key. + /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? AccountId { get; init; } } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs index 86864276d..7358b5c69 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs @@ -47,6 +47,8 @@ public static class AhpErrorCodes public const int Conflict = -32011; /// The host could not open the requested TCP connection. public const int TcpConnectionOpenFailed = -32012; + /// A request selects a model whose registered model source can't serve it, for example because the source needs a credential or was removed. A turn that fails for this reason ends with an error part whose `errorType` is `modelSourceUnavailable` instead. @see {@link /specification/authentication#model-source-credentials | Model source credentials} + public const int ModelSourceUnavailable = -32013; } /// Detail payload of an AuthRequired (-32007) error. diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index 9ca757528..a16e482ff 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -305,7 +305,6 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ModelSourceAuthRequirement))] [JsonSerializable(typeof(ModelSourceErrorState))] [JsonSerializable(typeof(ModelSourceFormatInfo))] -[JsonSerializable(typeof(ModelSourceInfo))] [JsonSerializable(typeof(ModelSourceReadyState))] [JsonSerializable(typeof(ModelSourceRegistrationCapability))] [JsonSerializable(typeof(ModelSourceRetentionPolicy))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 3b526561a..3a28baa38 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2152,9 +2152,7 @@ public sealed record Icon public sealed record ProtectedResourceMetadata { /// REQUIRED. The protected resource's resource identifier, a URL using the - /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). - /// A registered model source's endpoint may use any scheme the agent - /// supports, because nothing fetches it. + /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). public required string Resource { get; init; } /// OPTIONAL. Human-readable name of the protected resource. @@ -2237,9 +2235,9 @@ public sealed class RootState [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public RootConfigState? Config { get; set; } - /// Model sources registered on this host, keyed by `id`. When one is - /// ready, it also appears in its agent's {@link AgentInfo.modelSources} - /// catalog. + /// Model sources on this host, keyed by `id`: the sources agents offer + /// models from, including ones clients registered. Clients use them to + /// label and group each agent's {@link AgentInfo.models}. /// /// Stability: 1.0 - Early development. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2309,11 +2307,6 @@ public sealed record AgentInfo /// id. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public AgentCapabilities? Capabilities { get; init; } - - /// Sources this agent offers models from. Clients use them to label and - /// group {@link models}. A source may have no models. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public List? ModelSources { get; init; } } /// Static capabilities an {@link AgentInfo} advertises. Modelled after MCP @@ -2417,10 +2410,6 @@ public sealed record ModelSourceRegistrationCapability { /// Definition formats the agent reads, most preferred first. public required List Formats { get; init; } - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } /// A definition format an agent reads. An object so it can grow, for example @@ -2429,74 +2418,66 @@ public sealed record ModelSourceRegistrationCapability /// Stability: 1.0 - Early development. public sealed record ModelSourceFormatInfo { - /// A recognized {@link ModelSource.format} value, or a namespaced name for - /// a format the agent defines itself. + /// A {@link ModelSource.format} value. public required string Format { get; init; } - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } -/// A model source registered on this host by a client, or by the host itself. -/// Nothing here is a credential. +/// A source that an agent provider offers models from, such as a service, +/// subscription, or endpoint. The host lists the sources an agent provides +/// itself, and clients can register more with a definition. Nothing here is +/// a credential. /// /// Stability: 1.0 - Early development. public sealed record ModelSource { /// Host-unique ID, chosen by whoever registers the source. Also the - /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the /// {@link SessionModelInfo.modelSourceId} of its models. public required string Id { get; init; } - /// Agent provider whose agent reads the definition and serves the models. + /// Agent provider whose agent serves the source's models. public required string Provider { get; init; } - /// Human-readable name, published as {@link ModelSourceInfo.displayName}. + /// Human-readable name. public required string DisplayName { get; init; } /// Icons for UI display. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? Icons { get; init; } - /// The definition's format: the `format` of one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. Recognized values - /// include: + /// The format of `definition`: the `format` of one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. Present on a + /// registered source. + /// + /// Agents choose the formats they read. Some may read these common names: /// - /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as - /// OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API. /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. /// - `'azureOpenai'`: an Azure OpenAI deployment. /// - `'gemini'`: Google's Gemini API. /// - /// Agents MAY read other formats, named with a namespace such as - /// `example.com/model-source@1` so they don't collide. - public required string Format { get; init; } + /// Other formats are named with a namespace, such as + /// `example.com/model-source@1`, so they don't collide. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Format { get; init; } /// How to reach the source, in `format`: endpoint, wire API, models, and so - /// on. The agent reads it, and AHP doesn't validate it. Every client can - /// read it, so it MUST NOT contain a credential. + /// on. The agent reads it. Every client can read it, so it MUST NOT contain + /// a credential. Present on a registered source. /// - /// Suggested shapes for the recognized formats. Agents MAY read more - /// members, and MAY discover models when `models` is absent. - /// - /// - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` - /// - `anthropic`: `{ endpoint, models? }` - /// - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each - /// deployment name as a model `id` - /// - `gemini`: `{ endpoint, models? }` - /// - /// `endpoint` is the API's base URI, such as `https://api.example.com/v1`. - /// Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, - /// supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, - /// where `id` is the endpoint's own model identifier. - public required Dictionary Definition { get; init; } + /// An agent that reads one of the common format names might expect a shape + /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + /// the API's base URI and each `models` entry is `{ id, name?, + /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + /// named as in {@link SessionModelInfo}. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public Dictionary? Definition { get; init; } /// Opaque version token for `definition`, such as a hash of it, chosen by - /// whoever registers the source. Reducers compare it, instead of the - /// definition, to tell an update from a re-registration of the same - /// definition. - public required string Nonce { get; init; } + /// whoever registers the source. Present on a registered source. Reducers + /// compare it, instead of the definition, to tell an update from a + /// re-registration of the same definition. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Nonce { get; init; } /// What happens when the last contributing client leaves. Absent means `contributingClient`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2508,27 +2489,19 @@ public sealed record ModelSource [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceState? State { get; init; } - /// RFC 9728 metadata for the endpoint the credential is for. Present - /// whenever the source takes a credential, in every state, so any client - /// can deliver, rotate, or revoke one. Absent for a source that needs no - /// credential. Set with `state`. + /// RFC 9728 metadata for the endpoint a registered source's credential is + /// for. Present whenever the source takes a credential, in every state, so + /// any client can deliver or rotate one. Set with `state`. /// /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example /// `http://localhost:11434/v1`). It's the value a client passes back as - /// `authenticate({ resource })`, and nothing fetches it. - /// `credentialResource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. + /// `authenticate({ resource })`, and nothing fetches it. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } - /// The {@link AuthenticateParams.accountId} the client sent with the - /// credential the host most recently accepted. While the state is - /// `starting` or `ready`, the host holds that credential. While it's - /// `authRequired`, the `reason` says what happened to it. Absent until the - /// host accepts a credential sent with an `accountId`. Set with `state`. + /// The {@link AuthenticateParams.accountId} sent with the credential the + /// host most recently accepted. Set with `state`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? AccountId { get; init; } @@ -2550,10 +2523,6 @@ public sealed record ModelSource public sealed record ModelSourceStartingState { public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Starting; - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } /// The source is usable, and its models are in the catalog of the agent named @@ -2564,10 +2533,6 @@ public sealed record ModelSourceStartingState public sealed record ModelSourceReadyState { public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Ready; - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } /// Why a model source needs a credential before it can be ready. Deliberately @@ -2584,10 +2549,6 @@ public sealed record ModelSourceAuthRequirement /// the API key." [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Description { get; init; } - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } /// The source needs a credential before it can be used. A client answers with @@ -2606,10 +2567,6 @@ public sealed record ModelSourceAuthRequiredState public string? Description { get; init; } public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.AuthRequired; - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } /// The source failed, or the host declined it, for example by policy. @@ -2621,25 +2578,6 @@ public sealed record ModelSourceErrorState /// Error details the host writes. MUST NOT contain the credential. public required ErrorInfo Error { get; init; } - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } -} - -/// A source that an agent provider offers models from, such as a service or -/// subscription. -public sealed record ModelSourceInfo -{ - /// Model source identifier, unique within the agent's - /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSource.id}. A source is registered when - /// {@link RootState.modelSources} has an entry with this `id` - /// whose `provider` is the agent. - public required string Id { get; init; } - - /// Human-readable name - public required string DisplayName { get; init; } } public sealed record SessionModelInfo @@ -2700,11 +2638,9 @@ public sealed record SessionModelInfo [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Vendor { get; init; } - /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} - /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSource.id}. - /// An agent's own sources use it too, so it doesn't by itself mark a - /// registered source. + /// The source this model comes from: the {@link ModelSource.id} of an entry + /// in {@link RootState.modelSources} whose `provider` is this model's + /// {@link provider}. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ModelSourceId { get; init; } } @@ -6786,11 +6722,9 @@ public sealed record ErrorInfo { /// Error type identifier. Well-known values: /// - /// - `modelSourceUnavailable`: a registered model source the turn uses - /// can't serve it, for example because its credential is missing, - /// expired, rejected, or revoked, or the source was removed. The error - /// part is resumable. See - /// [Model source credentials](/specification/authentication#model-source-credentials). + /// - `modelSourceUnavailable`: a turn's registered model source can't serve + /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. + /// See [Model source credentials](/specification/authentication#model-source-credentials). public required string ErrorType { get; init; } /// Human-readable error message diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 0fa2046c7..e90a51458 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -594,7 +594,16 @@ func copyModelSourceHostFields(to *ahptypes.ModelSource, from ahptypes.ModelSour // sameModelSourceVersion reports whether two model sources have the same // provider, format, and definition nonce. func sameModelSourceVersion(a, b ahptypes.ModelSource) bool { - return a.Provider == b.Provider && a.Format == b.Format && a.Nonce == b.Nonce + return a.Provider == b.Provider && sameOptionalString(a.Format, b.Format) && sameOptionalString(a.Nonce, b.Nonce) +} + +// sameOptionalString reports whether two optional strings are both absent, or +// both present and equal. +func sameOptionalString(a, b *string) bool { + if a == nil || b == nil { + return a == b + } + return *a == *b } // ─── Chat Reducer ────────────────────────────────────────────────────── diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 49421927a..b530cdfc1 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -189,14 +189,14 @@ type RootConfigChangedAction struct { // host-reported fields are absent until the host reports again with // {@link RootModelSourceStateChangedAction}. // -// A client dispatches this without any host-reported field. The host learns -// which client registered the source from the envelope's `origin`. +// A client registers a source with its `format`, `definition`, and `nonce`, +// and without any host-reported field. The host learns which client +// registered it from the envelope's `origin`. // // Stability: 1.0 - Early development. type RootModelSourceSetAction struct { Type ActionType `json:"type"` - // The model source to add or update, matched by `id`, including its - // `definition`, without host-reported fields. + // The model source to add or update, matched by `id`. ModelSource ModelSource `json:"modelSource"` } diff --git a/clients/go/ahptypes/commands.generated.go b/clients/go/ahptypes/commands.generated.go index 678d8d78b..32a7db230 100644 --- a/clients/go/ahptypes/commands.generated.go +++ b/clients/go/ahptypes/commands.generated.go @@ -1351,16 +1351,18 @@ type McpServerAuthenticateTarget struct { CustomizationId string `json:"customizationId"` } -// A registered model source. +// A registered model source. The host applies the credential only to that +// source, and publishes the request's `accountId` as the source's +// `ModelSource.accountId`. // // Stability: 1.0 - Early development. type ModelSourceAuthenticateTarget struct { Kind AuthenticateTargetKind `json:"kind"` - // The registration's `ModelSource.id`. + // The source's `ModelSource.id`. ModelSourceId string `json:"modelSourceId"` } -// Pushes a credential for a protected resource. The `resource` field MUST +// Pushes a Bearer token for a protected resource. The `resource` field MUST // match a protected-resource identifier the client has discovered from the // server — whether declared statically in `AgentInfo.protectedResources`, // or discovered dynamically from a live `McpServerAuthRequiredState.resource` @@ -1369,14 +1371,13 @@ type ModelSourceAuthenticateTarget struct { // from a registered model source's `ModelSource.credentialResource`. // Servers MUST accept any `resource` value they have themselves advertised // through one of these mechanisms, subject to the `target` rules. A -// `modelSource` target takes only the registration's current +// `modelSource` target takes only the source's current // `credentialResource.resource`. // // Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) // (Bearer Token Usage) semantics. The client obtains the token from the // authorization server(s) listed in the resource's metadata and pushes it -// to the server via this command. A model source's token is instead an -// opaque secret, such as an API key. +// to the server via this command. type AuthenticateParams struct { // Channel URI this command targets. Channel URI `json:"channel"` @@ -1389,8 +1390,7 @@ type AuthenticateParams struct { // `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, // or `ModelSource.credentialResource`. Resource string `json:"resource"` - // Bearer token obtained from the resource's authorization server, or an - // opaque secret for a model source. An empty string revokes the credential. + // Bearer token obtained from the resource's authorization server Token string `json:"token"` // The access token's remaining lifetime, in seconds, when this // `authenticate` request is sent. This corresponds to `expires_in` in an @@ -1401,8 +1401,6 @@ type AuthenticateParams struct { // authorization server did not supply an expiry or the expiry is otherwise // unknown. When supplied, the value MUST be a positive integer. // - // An API key omits this field. - // // This field is irrelevant when `token` is empty to revoke authentication // and SHOULD be omitted in that case. ExpiresIn *int64 `json:"expiresIn,omitempty"` @@ -1411,7 +1409,7 @@ type AuthenticateParams struct { // `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is // satisfied without decoding the (opaque, server-specific) token itself. // Omit when the client doesn't track granted scopes separately from the - // token. Scopes apply to OAuth-issued tokens only. + // token. Scopes []string `json:"scopes,omitempty"` // Optional consumer of the token. Clients SHOULD include this when answering // a specific MCP server's `McpServerAuthRequiredState` or @@ -1429,10 +1427,8 @@ type AuthenticateParams struct { // // A registered model source takes its credential only through a // `modelSource` target, and the host rejects an untargeted `resource` that - // matches only model source challenges with `InvalidParams` (-32602). A - // delivery replaces whatever credential the host holds for the source. See - // [Model source credentials](/specification/authentication#model-source-credentials) - // for its rules. + // matches only model source challenges with `InvalidParams` (-32602). See + // [Model source credentials](/specification/authentication#model-source-credentials). // // Without a target, resource/scope matching is unchanged; the token may // satisfy every matching pending challenge. Older hosts ignore this field. @@ -1441,12 +1437,6 @@ type AuthenticateParams struct { // Hosts can compare `accountId` values to detect when the underlying account has changed. // Hosts MUST treat `accountId` as an opaque string. // see {@link /specification/authentication#account-selection-hints | Account selection hints}. - // - // With a `modelSource` target, clients SHOULD include it when delivering a - // credential and omit it when revoking one, and the host publishes it as - // the source's `ModelSource.accountId`. It MUST NOT be derived from the - // secret. For an API key with no account of its own, a client uses an ID - // that changes whenever the user replaces the key. AccountId *string `json:"accountId,omitempty"` } diff --git a/clients/go/ahptypes/errors.generated.go b/clients/go/ahptypes/errors.generated.go index cc43b684c..cc23833dd 100644 --- a/clients/go/ahptypes/errors.generated.go +++ b/clients/go/ahptypes/errors.generated.go @@ -38,6 +38,8 @@ const ( ErrorCodeAlreadyExists int32 = -32010 // ErrorCodeTcpConnectionOpenFailed indicates that the host could not open a TCP connection. ErrorCodeTcpConnectionOpenFailed int32 = -32012 + // ErrorCodeModelSourceUnavailable indicates that a request selects a model whose registered model source can't serve it. + ErrorCodeModelSourceUnavailable int32 = -32013 ) // AhpErrorCode is the type alias used by AHP application error codes. diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index bf362bc89..aea89715b 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -774,8 +774,6 @@ func (v Icon) MarshalJSON() ([]byte, error) { type ProtectedResourceMetadata struct { // REQUIRED. The protected resource's resource identifier, a URL using the // `https` scheme with no fragment component (e.g. `"https://api.github.com"`). - // A registered model source's endpoint may use any scheme the agent - // supports, because nothing fetches it. Resource string `json:"resource"` // OPTIONAL. Human-readable name of the protected resource. ResourceName *string `json:"resource_name,omitempty"` @@ -829,9 +827,9 @@ type RootState struct { Terminals []TerminalInfo `json:"terminals,omitempty"` // Agent host configuration schema and current values Config *RootConfigState `json:"config,omitempty"` - // Model sources registered on this host, keyed by `id`. When one is - // ready, it also appears in its agent's {@link AgentInfo.modelSources} - // catalog. + // Model sources on this host, keyed by `id`: the sources agents offer + // models from, including ones clients registered. Clients use them to + // label and group each agent's {@link AgentInfo.models}. // // Stability: 1.0 - Early development. ModelSources []ModelSource `json:"modelSources,omitempty"` @@ -885,9 +883,6 @@ type AgentInfo struct { // to gate features (multi-chat, fork) instead of switching on the provider // id. Capabilities *AgentCapabilities `json:"capabilities,omitempty"` - // Sources this agent offers models from. Clients use them to label and - // group {@link models}. A source may have no models. - ModelSources []ModelSourceInfo `json:"modelSources,omitempty"` } // Static capabilities an {@link AgentInfo} advertises. Modelled after MCP @@ -976,18 +971,6 @@ type MultipleWorkingDirectoriesCapability struct { type ModelSourceRegistrationCapability struct { // Definition formats the agent reads, most preferred first. Formats []ModelSourceFormatInfo `json:"formats"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSourceRegistrationCapability) UnmarshalJSON(data []byte) error { - type wire ModelSourceRegistrationCapability - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "formats") -} - -func (v ModelSourceRegistrationCapability) MarshalJSON() ([]byte, error) { - type wire ModelSourceRegistrationCapability - return marshalWithExtra(wire(v), v.Extra, "formats") } // A definition format an agent reads. An object so it can grow, for example @@ -995,99 +978,72 @@ func (v ModelSourceRegistrationCapability) MarshalJSON() ([]byte, error) { // // Stability: 1.0 - Early development. type ModelSourceFormatInfo struct { - // A recognized {@link ModelSource.format} value, or a namespaced name for - // a format the agent defines itself. + // A {@link ModelSource.format} value. Format string `json:"format"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` } -func (v *ModelSourceFormatInfo) UnmarshalJSON(data []byte) error { - type wire ModelSourceFormatInfo - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "format") -} - -func (v ModelSourceFormatInfo) MarshalJSON() ([]byte, error) { - type wire ModelSourceFormatInfo - return marshalWithExtra(wire(v), v.Extra, "format") -} - -// A model source registered on this host by a client, or by the host itself. -// Nothing here is a credential. +// A source that an agent provider offers models from, such as a service, +// subscription, or endpoint. The host lists the sources an agent provides +// itself, and clients can register more with a definition. Nothing here is +// a credential. // // Stability: 1.0 - Early development. type ModelSource struct { // Host-unique ID, chosen by whoever registers the source. Also the - // source's {@link ModelSourceInfo.id} in the agent's catalog, and the // {@link SessionModelInfo.modelSourceId} of its models. Id string `json:"id"` - // Agent provider whose agent reads the definition and serves the models. + // Agent provider whose agent serves the source's models. Provider string `json:"provider"` - // Human-readable name, published as {@link ModelSourceInfo.displayName}. + // Human-readable name. DisplayName string `json:"displayName"` // Icons for UI display. Icons []Icon `json:"icons,omitempty"` - // The definition's format: the `format` of one of the agent's - // {@link ModelSourceRegistrationCapability.formats}. Recognized values - // include: + // The format of `definition`: the `format` of one of the agent's + // {@link ModelSourceRegistrationCapability.formats}. Present on a + // registered source. + // + // Agents choose the formats they read. Some may read these common names: // - // - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as - // OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + // - `'openaiCompatible'`: an endpoint that implements OpenAI's API. // - `'anthropic'`: an endpoint that implements Anthropic's Messages API. // - `'azureOpenai'`: an Azure OpenAI deployment. // - `'gemini'`: Google's Gemini API. // - // Agents MAY read other formats, named with a namespace such as - // `example.com/model-source@1` so they don't collide. - Format string `json:"format"` + // Other formats are named with a namespace, such as + // `example.com/model-source@1`, so they don't collide. + Format *string `json:"format,omitempty"` // How to reach the source, in `format`: endpoint, wire API, models, and so - // on. The agent reads it, and AHP doesn't validate it. Every client can - // read it, so it MUST NOT contain a credential. - // - // Suggested shapes for the recognized formats. Agents MAY read more - // members, and MAY discover models when `models` is absent. - // - // - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` - // - `anthropic`: `{ endpoint, models? }` - // - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each - // deployment name as a model `id` - // - `gemini`: `{ endpoint, models? }` - // - // `endpoint` is the API's base URI, such as `https://api.example.com/v1`. - // Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, - // supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, - // where `id` is the endpoint's own model identifier. - Definition map[string]json.RawMessage `json:"definition"` + // on. The agent reads it. Every client can read it, so it MUST NOT contain + // a credential. Present on a registered source. + // + // An agent that reads one of the common format names might expect a shape + // like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + // the API's base URI and each `models` entry is `{ id, name?, + // maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + // named as in {@link SessionModelInfo}. + Definition map[string]json.RawMessage `json:"definition,omitempty"` // Opaque version token for `definition`, such as a hash of it, chosen by - // whoever registers the source. Reducers compare it, instead of the - // definition, to tell an update from a re-registration of the same - // definition. - Nonce string `json:"nonce"` + // whoever registers the source. Present on a registered source. Reducers + // compare it, instead of the definition, to tell an update from a + // re-registration of the same definition. + Nonce *string `json:"nonce,omitempty"` // What happens when the last contributing client leaves. Absent means `contributingClient`. Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` // Host-reported status, set with {@link RootModelSourceStateChangedAction}. // Absent until the host reports one, and after an update replaces the // definition until the host reports again. State *ModelSourceState `json:"state,omitempty"` - // RFC 9728 metadata for the endpoint the credential is for. Present - // whenever the source takes a credential, in every state, so any client - // can deliver, rotate, or revoke one. Absent for a source that needs no - // credential. Set with `state`. + // RFC 9728 metadata for the endpoint a registered source's credential is + // for. Present whenever the source takes a credential, in every state, so + // any client can deliver or rotate one. Set with `state`. // // `credentialResource.resource` is the endpoint URL as the definition // names it, in any scheme the agent supports (for example // `http://localhost:11434/v1`). It's the value a client passes back as // `authenticate({ resource })`, and nothing fetches it. - // `credentialResource.resource_name` labels the prompt (for example - // "OpenRouter API key"). A source that accepts OAuth access tokens - // advertises `authorization_servers` and `scopes_supported`. A source that - // takes a user-supplied secret omits them. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` - // The {@link AuthenticateParams.accountId} the client sent with the - // credential the host most recently accepted. While the state is - // `starting` or `ready`, the host holds that credential. While it's - // `authRequired`, the `reason` says what happened to it. Absent until the - // host accepts a credential sent with an `accountId`. Set with `state`. + // The {@link AuthenticateParams.accountId} sent with the credential the + // host most recently accepted. Set with `state`. AccountId *string `json:"accountId,omitempty"` // Additional implementation-defined metadata for this model source. // MUST NOT contain a credential. @@ -1112,18 +1068,6 @@ func (v ModelSource) MarshalJSON() ([]byte, error) { // Stability: 1.0 - Early development. type ModelSourceStartingState struct { Kind ModelSourceStatus `json:"kind"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSourceStartingState) UnmarshalJSON(data []byte) error { - type wire ModelSourceStartingState - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind") -} - -func (v ModelSourceStartingState) MarshalJSON() ([]byte, error) { - type wire ModelSourceStartingState - return marshalWithExtra(wire(v), v.Extra, "kind") } // The source is usable, and its models are in the catalog of the agent named @@ -1133,18 +1077,6 @@ func (v ModelSourceStartingState) MarshalJSON() ([]byte, error) { // Stability: 1.0 - Early development. type ModelSourceReadyState struct { Kind ModelSourceStatus `json:"kind"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSourceReadyState) UnmarshalJSON(data []byte) error { - type wire ModelSourceReadyState - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind") -} - -func (v ModelSourceReadyState) MarshalJSON() ([]byte, error) { - type wire ModelSourceReadyState - return marshalWithExtra(wire(v), v.Extra, "kind") } // Why a model source needs a credential before it can be ready. Deliberately @@ -1158,18 +1090,6 @@ type ModelSourceAuthRequirement struct { // Human-readable hint the host writes, for example "The endpoint rejected // the API key." Description *string `json:"description,omitempty"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSourceAuthRequirement) UnmarshalJSON(data []byte) error { - type wire ModelSourceAuthRequirement - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "description") -} - -func (v ModelSourceAuthRequirement) MarshalJSON() ([]byte, error) { - type wire ModelSourceAuthRequirement - return marshalWithExtra(wire(v), v.Extra, "reason", "description") } // The source needs a credential before it can be used. A client answers with @@ -1184,18 +1104,6 @@ type ModelSourceAuthRequiredState struct { // the API key." Description *string `json:"description,omitempty"` Kind ModelSourceStatus `json:"kind"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSourceAuthRequiredState) UnmarshalJSON(data []byte) error { - type wire ModelSourceAuthRequiredState - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "reason", "description", "kind") -} - -func (v ModelSourceAuthRequiredState) MarshalJSON() ([]byte, error) { - type wire ModelSourceAuthRequiredState - return marshalWithExtra(wire(v), v.Extra, "reason", "description", "kind") } // The source failed, or the host declined it, for example by policy. @@ -1205,31 +1113,6 @@ type ModelSourceErrorState struct { Kind ModelSourceStatus `json:"kind"` // Error details the host writes. MUST NOT contain the credential. Error ErrorInfo `json:"error"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSourceErrorState) UnmarshalJSON(data []byte) error { - type wire ModelSourceErrorState - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "kind", "error") -} - -func (v ModelSourceErrorState) MarshalJSON() ([]byte, error) { - type wire ModelSourceErrorState - return marshalWithExtra(wire(v), v.Extra, "kind", "error") -} - -// A source that an agent provider offers models from, such as a service or -// subscription. -type ModelSourceInfo struct { - // Model source identifier, unique within the agent's - // {@link AgentInfo.modelSources}. For a registered model source, this is - // the {@link ModelSource.id}. A source is registered when - // {@link RootState.modelSources} has an entry with this `id` - // whose `provider` is the agent. - Id string `json:"id"` - // Human-readable name - DisplayName string `json:"displayName"` } type SessionModelInfo struct { @@ -1269,11 +1152,9 @@ type SessionModelInfo struct { // SHOULD fall back to a generic presentation for values they do not // recognize. Vendor *string `json:"vendor,omitempty"` - // The source this model comes from. MUST match a {@link ModelSourceInfo.id} - // in the agent's {@link AgentInfo.modelSources}. For a model from a - // registered model source, this is the {@link ModelSource.id}. - // An agent's own sources use it too, so it doesn't by itself mark a - // registered source. + // The source this model comes from: the {@link ModelSource.id} of an entry + // in {@link RootState.modelSources} whose `provider` is this model's + // {@link provider}. ModelSourceId *string `json:"modelSourceId,omitempty"` } @@ -4608,11 +4489,9 @@ type UsageInfo struct { type ErrorInfo struct { // Error type identifier. Well-known values: // - // - `modelSourceUnavailable`: a registered model source the turn uses - // can't serve it, for example because its credential is missing, - // expired, rejected, or revoked, or the source was removed. The error - // part is resumable. See - // [Model source credentials](/specification/authentication#model-source-credentials). + // - `modelSourceUnavailable`: a turn's registered model source can't serve + // it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. + // See [Model source credentials](/specification/authentication#model-source-credentials). ErrorType string `json:"errorType"` // Human-readable error message Message string `json:"message"` diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 84e2ba7c0..991c67ad3 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -1496,8 +1496,9 @@ data class RootConfigChangedAction( * host-reported fields are absent until the host reports again with * {@link RootModelSourceStateChangedAction}. * - * A client dispatches this without any host-reported field. The host learns - * which client registered the source from the envelope's `origin`. + * A client registers a source with its `format`, `definition`, and `nonce`, + * and without any host-reported field. The host learns which client + * registered it from the envelope's `origin`. * * Stability: 1.0 - Early development. */ @@ -1505,8 +1506,7 @@ data class RootConfigChangedAction( data class RootModelSourceSetAction( val type: ActionType, /** - * The model source to add or update, matched by `id`, including its - * `definition`, without host-reported fields. + * The model source to add or update, matched by `id`. */ val modelSource: ModelSource ) 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 1b872d366..eb32253ca 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 @@ -1618,7 +1618,9 @@ data class McpServerAuthenticateTarget( ) /** - * A registered model source. + * A registered model source. The host applies the credential only to that + * source, and publishes the request's `accountId` as the source's + * `ModelSource.accountId`. * * Stability: 1.0 - Early development. */ @@ -1626,7 +1628,7 @@ data class McpServerAuthenticateTarget( data class ModelSourceAuthenticateTarget( val kind: AuthenticateTargetKind, /** - * The registration's `ModelSource.id`. + * The source's `ModelSource.id`. */ val modelSourceId: String ) @@ -1652,8 +1654,7 @@ data class AuthenticateParams( */ val resource: String, /** - * Bearer token obtained from the resource's authorization server, or an - * opaque secret for a model source. An empty string revokes the credential. + * Bearer token obtained from the resource's authorization server */ val token: String, /** @@ -1666,8 +1667,6 @@ data class AuthenticateParams( * authorization server did not supply an expiry or the expiry is otherwise * unknown. When supplied, the value MUST be a positive integer. * - * An API key omits this field. - * * This field is irrelevant when `token` is empty to revoke authentication * and SHOULD be omitted in that case. */ @@ -1678,7 +1677,7 @@ data class AuthenticateParams( * `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is * satisfied without decoding the (opaque, server-specific) token itself. * Omit when the client doesn't track granted scopes separately from the - * token. Scopes apply to OAuth-issued tokens only. + * token. */ val scopes: List? = null, /** @@ -1698,10 +1697,8 @@ data class AuthenticateParams( * * A registered model source takes its credential only through a * `modelSource` target, and the host rejects an untargeted `resource` that - * matches only model source challenges with `InvalidParams` (-32602). A - * delivery replaces whatever credential the host holds for the source. See - * [Model source credentials](/specification/authentication#model-source-credentials) - * for its rules. + * matches only model source challenges with `InvalidParams` (-32602). See + * [Model source credentials](/specification/authentication#model-source-credentials). * * Without a target, resource/scope matching is unchanged; the token may * satisfy every matching pending challenge. Older hosts ignore this field. @@ -1712,12 +1709,6 @@ data class AuthenticateParams( * Hosts can compare `accountId` values to detect when the underlying account has changed. * Hosts MUST treat `accountId` as an opaque string. * see {@link /specification/authentication#account-selection-hints | Account selection hints}. - * - * With a `modelSource` target, clients SHOULD include it when delivering a - * credential and omit it when revoking one, and the host publishes it as - * the source's `ModelSource.accountId`. It MUST NOT be derived from the - * secret. For an API key with no account of its own, a client uses an ID - * that changes whenever the user replaces the key. */ val accountId: String? = null ) diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt index c1ba5c42b..ad17ef3ae 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt @@ -57,6 +57,8 @@ object AhpErrorCodes { const val PERMISSION_DENIED: Int = -32009 /** The target resource already exists and the operation does not allow overwriting */ const val ALREADY_EXISTS: Int = -32010 + /** A request selects a model whose registered model source can't serve it */ + const val MODEL_SOURCE_UNAVAILABLE: Int = -32013 } // ─── Error Detail Payloads ────────────────────────────────────────────────── 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 e754f5af8..f6cc5f23e 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 @@ -1547,8 +1547,6 @@ data class ProtectedResourceMetadata( /** * REQUIRED. The protected resource's resource identifier, a URL using the * `https` scheme with no fragment component (e.g. `"https://api.github.com"`). - * A registered model source's endpoint may use any scheme the agent - * supports, because nothing fetches it. */ val resource: String, /** @@ -1637,9 +1635,9 @@ data class RootState( */ val config: RootConfigState? = null, /** - * Model sources registered on this host, keyed by `id`. When one is - * ready, it also appears in its agent's {@link AgentInfo.modelSources} - * catalog. + * Model sources on this host, keyed by `id`: the sources agents offer + * models from, including ones clients registered. Clients use them to + * label and group each agent's {@link AgentInfo.models}. * * Stability: 1.0 - Early development. */ @@ -1712,12 +1710,7 @@ data class AgentInfo( * to gate features (multi-chat, fork) instead of switching on the provider * id. */ - val capabilities: AgentCapabilities? = null, - /** - * Sources this agent offers models from. Clients use them to label and - * group {@link models}. A source may have no models. - */ - val modelSources: List? = null + val capabilities: AgentCapabilities? = null ) @Serializable @@ -1815,21 +1808,12 @@ data class MultipleWorkingDirectoriesCapability( * * Stability: 1.0 - Early development. */ -@KeepGeneratedSerializer -@Serializable(with = ModelSourceRegistrationCapabilitySerializer::class) +@Serializable data class ModelSourceRegistrationCapability( /** * Definition formats the agent reads, most preferred first. */ - val formats: List, - @Transient - val extra: Map = emptyMap() -) - -internal object ModelSourceRegistrationCapabilitySerializer : UnknownMembersSerializer( - ModelSourceRegistrationCapability.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val formats: List ) /** @@ -1838,27 +1822,19 @@ internal object ModelSourceRegistrationCapabilitySerializer : UnknownMembersSeri * * Stability: 1.0 - Early development. */ -@KeepGeneratedSerializer -@Serializable(with = ModelSourceFormatInfoSerializer::class) +@Serializable data class ModelSourceFormatInfo( /** - * A recognized {@link ModelSource.format} value, or a namespaced name for - * a format the agent defines itself. + * A {@link ModelSource.format} value. */ - val format: String, - @Transient - val extra: Map = emptyMap() -) - -internal object ModelSourceFormatInfoSerializer : UnknownMembersSerializer( - ModelSourceFormatInfo.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val format: String ) /** - * A model source registered on this host by a client, or by the host itself. - * Nothing here is a credential. + * A source that an agent provider offers models from, such as a service, + * subscription, or endpoint. The host lists the sources an agent provides + * itself, and clients can register more with a definition. Nothing here is + * a credential. * * Stability: 1.0 - Early development. */ @@ -1867,16 +1843,15 @@ internal object ModelSourceFormatInfoSerializer : UnknownMembersSerializer? = null, /** - * The definition's format: the `format` of one of the agent's - * {@link ModelSourceRegistrationCapability.formats}. Recognized values - * include: + * The format of `definition`: the `format` of one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. Present on a + * registered source. + * + * Agents choose the formats they read. Some may read these common names: * - * - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as - * OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + * - `'openaiCompatible'`: an endpoint that implements OpenAI's API. * - `'anthropic'`: an endpoint that implements Anthropic's Messages API. * - `'azureOpenai'`: an Azure OpenAI deployment. * - `'gemini'`: Google's Gemini API. * - * Agents MAY read other formats, named with a namespace such as - * `example.com/model-source@1` so they don't collide. + * Other formats are named with a namespace, such as + * `example.com/model-source@1`, so they don't collide. */ - val format: String, + val format: String? = null, /** * How to reach the source, in `format`: endpoint, wire API, models, and so - * on. The agent reads it, and AHP doesn't validate it. Every client can - * read it, so it MUST NOT contain a credential. - * - * Suggested shapes for the recognized formats. Agents MAY read more - * members, and MAY discover models when `models` is absent. - * - * - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` - * - `anthropic`: `{ endpoint, models? }` - * - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each - * deployment name as a model `id` - * - `gemini`: `{ endpoint, models? }` + * on. The agent reads it. Every client can read it, so it MUST NOT contain + * a credential. Present on a registered source. * - * `endpoint` is the API's base URI, such as `https://api.example.com/v1`. - * Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, - * supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, - * where `id` is the endpoint's own model identifier. + * An agent that reads one of the common format names might expect a shape + * like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + * the API's base URI and each `models` entry is `{ id, name?, + * maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + * named as in {@link SessionModelInfo}. */ - val definition: Map, + val definition: Map? = null, /** * Opaque version token for `definition`, such as a hash of it, chosen by - * whoever registers the source. Reducers compare it, instead of the - * definition, to tell an update from a re-registration of the same - * definition. + * whoever registers the source. Present on a registered source. Reducers + * compare it, instead of the definition, to tell an update from a + * re-registration of the same definition. */ - val nonce: String, + val nonce: String? = null, /** * What happens when the last contributing client leaves. Absent means `contributingClient`. */ @@ -1936,27 +1904,19 @@ data class ModelSource( */ val state: ModelSourceState? = null, /** - * RFC 9728 metadata for the endpoint the credential is for. Present - * whenever the source takes a credential, in every state, so any client - * can deliver, rotate, or revoke one. Absent for a source that needs no - * credential. Set with `state`. + * RFC 9728 metadata for the endpoint a registered source's credential is + * for. Present whenever the source takes a credential, in every state, so + * any client can deliver or rotate one. Set with `state`. * * `credentialResource.resource` is the endpoint URL as the definition * names it, in any scheme the agent supports (for example * `http://localhost:11434/v1`). It's the value a client passes back as * `authenticate({ resource })`, and nothing fetches it. - * `credentialResource.resource_name` labels the prompt (for example - * "OpenRouter API key"). A source that accepts OAuth access tokens - * advertises `authorization_servers` and `scopes_supported`. A source that - * takes a user-supplied secret omits them. */ val credentialResource: ProtectedResourceMetadata? = null, /** - * The {@link AuthenticateParams.accountId} the client sent with the - * credential the host most recently accepted. While the state is - * `starting` or `ready`, the host holds that credential. While it's - * `authRequired`, the `reason` says what happened to it. Absent until the - * host accepts a credential sent with an `accountId`. Set with `state`. + * The {@link AuthenticateParams.accountId} sent with the credential the + * host most recently accepted. Set with `state`. */ val accountId: String? = null, /** @@ -1981,18 +1941,9 @@ internal object ModelSourceSerializer : UnknownMembersSerializer( * * Stability: 1.0 - Early development. */ -@KeepGeneratedSerializer -@Serializable(with = ModelSourceStartingStateSerializer::class) +@Serializable data class ModelSourceStartingState( - val kind: ModelSourceStatus, - @Transient - val extra: Map = emptyMap() -) - -internal object ModelSourceStartingStateSerializer : UnknownMembersSerializer( - ModelSourceStartingState.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val kind: ModelSourceStatus ) /** @@ -2002,18 +1953,9 @@ internal object ModelSourceStartingStateSerializer : UnknownMembersSerializer = emptyMap() -) - -internal object ModelSourceReadyStateSerializer : UnknownMembersSerializer( - ModelSourceReadyState.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val kind: ModelSourceStatus ) /** @@ -2023,8 +1965,7 @@ internal object ModelSourceReadyStateSerializer : UnknownMembersSerializer = emptyMap() -) - -internal object ModelSourceAuthRequirementSerializer : UnknownMembersSerializer( - ModelSourceAuthRequirement.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val description: String? = null ) /** @@ -2052,8 +1985,7 @@ internal object ModelSourceAuthRequirementSerializer : UnknownMembersSerializer< * * Stability: 1.0 - Early development. */ -@KeepGeneratedSerializer -@Serializable(with = ModelSourceAuthRequiredStateSerializer::class) +@Serializable data class ModelSourceAuthRequiredState( /** * Why a credential is needed. @@ -2064,15 +1996,7 @@ data class ModelSourceAuthRequiredState( * the API key." */ val description: String? = null, - val kind: ModelSourceStatus, - @Transient - val extra: Map = emptyMap() -) - -internal object ModelSourceAuthRequiredStateSerializer : UnknownMembersSerializer( - ModelSourceAuthRequiredState.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val kind: ModelSourceStatus ) /** @@ -2080,38 +2004,13 @@ internal object ModelSourceAuthRequiredStateSerializer : UnknownMembersSerialize * * Stability: 1.0 - Early development. */ -@KeepGeneratedSerializer -@Serializable(with = ModelSourceErrorStateSerializer::class) +@Serializable data class ModelSourceErrorState( val kind: ModelSourceStatus, /** * Error details the host writes. MUST NOT contain the credential. */ - val error: ErrorInfo, - @Transient - val extra: Map = emptyMap() -) - -internal object ModelSourceErrorStateSerializer : UnknownMembersSerializer( - ModelSourceErrorState.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, -) - -@Serializable -data class ModelSourceInfo( - /** - * Model source identifier, unique within the agent's - * {@link AgentInfo.modelSources}. For a registered model source, this is - * the {@link ModelSource.id}. A source is registered when - * {@link RootState.modelSources} has an entry with this `id` - * whose `provider` is the agent. - */ - val id: String, - /** - * Human-readable name - */ - val displayName: String + val error: ErrorInfo ) @Serializable @@ -2176,11 +2075,9 @@ data class SessionModelInfo( */ val vendor: String? = null, /** - * The source this model comes from. MUST match a {@link ModelSourceInfo.id} - * in the agent's {@link AgentInfo.modelSources}. For a model from a - * registered model source, this is the {@link ModelSource.id}. - * An agent's own sources use it too, so it doesn't by itself mark a - * registered source. + * The source this model comes from: the {@link ModelSource.id} of an entry + * in {@link RootState.modelSources} whose `provider` is this model's + * {@link provider}. */ val modelSourceId: String? = null ) @@ -6160,11 +6057,9 @@ data class ErrorInfo( /** * Error type identifier. Well-known values: * - * - `modelSourceUnavailable`: a registered model source the turn uses - * can't serve it, for example because its credential is missing, - * expired, rejected, or revoked, or the source was removed. The error - * part is resumable. See - * [Model source credentials](/specification/authentication#model-source-credentials). + * - `modelSourceUnavailable`: a turn's registered model source can't serve + * it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. + * See [Model source credentials](/specification/authentication#model-source-credentials). */ val errorType: String, /** diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 9b830e0ac..e777058b4 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -530,15 +530,15 @@ pub struct RootConfigChangedAction { /// host-reported fields are absent until the host reports again with /// {@link RootModelSourceStateChangedAction}. /// -/// A client dispatches this without any host-reported field. The host learns -/// which client registered the source from the envelope's `origin`. +/// A client registers a source with its `format`, `definition`, and `nonce`, +/// and without any host-reported field. The host learns which client +/// registered it from the envelope's `origin`. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceSetAction { - /// The model source to add or update, matched by `id`, including its - /// `definition`, without host-reported fields. + /// The model source to add or update, matched by `id`. pub model_source: ModelSource, } diff --git a/clients/rust/crates/ahp-types/src/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index fbe82df1d..ed83257bc 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -1748,17 +1748,19 @@ pub struct McpServerAuthenticateTarget { pub customization_id: String, } -/// A registered model source. +/// A registered model source. The host applies the credential only to that +/// source, and publishes the request's `accountId` as the source's +/// `ModelSource.accountId`. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceAuthenticateTarget { - /// The registration's `ModelSource.id`. + /// The source's `ModelSource.id`. pub model_source_id: String, } -/// Pushes a credential for a protected resource. The `resource` field MUST +/// Pushes a Bearer token for a protected resource. The `resource` field MUST /// match a protected-resource identifier the client has discovered from the /// server — whether declared statically in `AgentInfo.protectedResources`, /// or discovered dynamically from a live `McpServerAuthRequiredState.resource` @@ -1767,14 +1769,13 @@ pub struct ModelSourceAuthenticateTarget { /// from a registered model source's `ModelSource.credentialResource`. /// Servers MUST accept any `resource` value they have themselves advertised /// through one of these mechanisms, subject to the `target` rules. A -/// `modelSource` target takes only the registration's current +/// `modelSource` target takes only the source's current /// `credentialResource.resource`. /// /// Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) /// (Bearer Token Usage) semantics. The client obtains the token from the /// authorization server(s) listed in the resource's metadata and pushes it -/// to the server via this command. A model source's token is instead an -/// opaque secret, such as an API key. +/// to the server via this command. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticateParams { @@ -1790,8 +1791,7 @@ pub struct AuthenticateParams { /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, /// or `ModelSource.credentialResource`. pub resource: String, - /// Bearer token obtained from the resource's authorization server, or an - /// opaque secret for a model source. An empty string revokes the credential. + /// Bearer token obtained from the resource's authorization server pub token: String, /// The access token's remaining lifetime, in seconds, when this /// `authenticate` request is sent. This corresponds to `expires_in` in an @@ -1802,8 +1802,6 @@ pub struct AuthenticateParams { /// authorization server did not supply an expiry or the expiry is otherwise /// unknown. When supplied, the value MUST be a positive integer. /// - /// An API key omits this field. - /// /// This field is irrelevant when `token` is empty to revoke authentication /// and SHOULD be omitted in that case. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1813,7 +1811,7 @@ pub struct AuthenticateParams { /// `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is /// satisfied without decoding the (opaque, server-specific) token itself. /// Omit when the client doesn't track granted scopes separately from the - /// token. Scopes apply to OAuth-issued tokens only. + /// token. #[serde(default, skip_serializing_if = "Option::is_none")] pub scopes: Option>, /// Optional consumer of the token. Clients SHOULD include this when answering @@ -1832,10 +1830,8 @@ pub struct AuthenticateParams { /// /// A registered model source takes its credential only through a /// `modelSource` target, and the host rejects an untargeted `resource` that - /// matches only model source challenges with `InvalidParams` (-32602). A - /// delivery replaces whatever credential the host holds for the source. See - /// [Model source credentials](/specification/authentication#model-source-credentials) - /// for its rules. + /// matches only model source challenges with `InvalidParams` (-32602). See + /// [Model source credentials](/specification/authentication#model-source-credentials). /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -1845,12 +1841,6 @@ pub struct AuthenticateParams { /// Hosts can compare `accountId` values to detect when the underlying account has changed. /// Hosts MUST treat `accountId` as an opaque string. /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. - /// - /// With a `modelSource` target, clients SHOULD include it when delivering a - /// credential and omit it when revoking one, and the host publishes it as - /// the source's `ModelSource.accountId`. It MUST NOT be derived from the - /// secret. For an API key with no account of its own, a client uses an ID - /// that changes whenever the user replaces the key. #[serde(default, skip_serializing_if = "Option::is_none")] pub account_id: Option, } diff --git a/clients/rust/crates/ahp-types/src/errors.rs b/clients/rust/crates/ahp-types/src/errors.rs index 6f15b4fbd..ec7268761 100644 --- a/clients/rust/crates/ahp-types/src/errors.rs +++ b/clients/rust/crates/ahp-types/src/errors.rs @@ -57,6 +57,8 @@ pub mod ahp_error_codes { pub const CONFLICT: i32 = -32011; /// The host could not open the requested TCP connection. pub const TCP_CONNECTION_OPEN_FAILED: i32 = -32012; + /// A request selects a model whose registered model source can't serve it. + pub const MODEL_SOURCE_UNAVAILABLE: i32 = -32013; } /// Type alias: AHP application error code. diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 740808f30..cceccab5b 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1759,25 +1759,25 @@ pub enum AutomationRunOriginKind { Trigger, } -fn deserialize_extra_without_kind<'de, D>( +fn deserialize_extra_without_type<'de, D>( deserializer: D, ) -> Result, D::Error> where D: serde::Deserializer<'de>, { let mut extra = serde_json::Map::::deserialize(deserializer)?; - extra.remove("kind"); + extra.remove("type"); Ok(extra) } -fn deserialize_extra_without_type<'de, D>( +fn deserialize_extra_without_kind<'de, D>( deserializer: D, ) -> Result, D::Error> where D: serde::Deserializer<'de>, { let mut extra = serde_json::Map::::deserialize(deserializer)?; - extra.remove("type"); + extra.remove("kind"); Ok(extra) } @@ -1903,8 +1903,6 @@ pub struct Icon { pub struct ProtectedResourceMetadata { /// REQUIRED. The protected resource's resource identifier, a URL using the /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). - /// A registered model source's endpoint may use any scheme the agent - /// supports, because nothing fetches it. pub resource: String, /// OPTIONAL. Human-readable name of the protected resource. #[serde( @@ -1996,9 +1994,9 @@ pub struct RootState { /// Agent host configuration schema and current values #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option, - /// Model sources registered on this host, keyed by `id`. When one is - /// ready, it also appears in its agent's {@link AgentInfo.modelSources} - /// catalog. + /// Model sources on this host, keyed by `id`: the sources agents offer + /// models from, including ones clients registered. Clients use them to + /// label and group each agent's {@link AgentInfo.models}. /// /// Stability: 1.0 - Early development. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2061,10 +2059,6 @@ pub struct AgentInfo { /// id. #[serde(default, skip_serializing_if = "Option::is_none")] pub capabilities: Option, - /// Sources this agent offers models from. Clients use them to label and - /// group {@link models}. A source may have no models. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_sources: Option>, } /// Static capabilities an {@link AgentInfo} advertises. Modelled after MCP @@ -2168,9 +2162,6 @@ pub struct MultipleWorkingDirectoriesCapability { pub struct ModelSourceRegistrationCapability { /// Definition formats the agent reads, most preferred first. pub formats: Vec, - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten)] - pub extra: serde_json::Map, } /// A definition format an agent reads. An object so it can grow, for example @@ -2180,68 +2171,61 @@ pub struct ModelSourceRegistrationCapability { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceFormatInfo { - /// A recognized {@link ModelSource.format} value, or a namespaced name for - /// a format the agent defines itself. + /// A {@link ModelSource.format} value. pub format: String, - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten)] - pub extra: serde_json::Map, } -/// A model source registered on this host by a client, or by the host itself. -/// Nothing here is a credential. +/// A source that an agent provider offers models from, such as a service, +/// subscription, or endpoint. The host lists the sources an agent provides +/// itself, and clients can register more with a definition. Nothing here is +/// a credential. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSource { /// Host-unique ID, chosen by whoever registers the source. Also the - /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the /// {@link SessionModelInfo.modelSourceId} of its models. pub id: String, - /// Agent provider whose agent reads the definition and serves the models. + /// Agent provider whose agent serves the source's models. pub provider: String, - /// Human-readable name, published as {@link ModelSourceInfo.displayName}. + /// Human-readable name. pub display_name: String, /// Icons for UI display. #[serde(default, skip_serializing_if = "Option::is_none")] pub icons: Option>, - /// The definition's format: the `format` of one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. Recognized values - /// include: + /// The format of `definition`: the `format` of one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. Present on a + /// registered source. + /// + /// Agents choose the formats they read. Some may read these common names: /// - /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as - /// OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API. /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. /// - `'azureOpenai'`: an Azure OpenAI deployment. /// - `'gemini'`: Google's Gemini API. /// - /// Agents MAY read other formats, named with a namespace such as - /// `example.com/model-source@1` so they don't collide. - pub format: String, + /// Other formats are named with a namespace, such as + /// `example.com/model-source@1`, so they don't collide. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub format: Option, /// How to reach the source, in `format`: endpoint, wire API, models, and so - /// on. The agent reads it, and AHP doesn't validate it. Every client can - /// read it, so it MUST NOT contain a credential. - /// - /// Suggested shapes for the recognized formats. Agents MAY read more - /// members, and MAY discover models when `models` is absent. - /// - /// - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` - /// - `anthropic`: `{ endpoint, models? }` - /// - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each - /// deployment name as a model `id` - /// - `gemini`: `{ endpoint, models? }` - /// - /// `endpoint` is the API's base URI, such as `https://api.example.com/v1`. - /// Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, - /// supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, - /// where `id` is the endpoint's own model identifier. - pub definition: JsonObject, + /// on. The agent reads it. Every client can read it, so it MUST NOT contain + /// a credential. Present on a registered source. + /// + /// An agent that reads one of the common format names might expect a shape + /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + /// the API's base URI and each `models` entry is `{ id, name?, + /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + /// named as in {@link SessionModelInfo}. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub definition: Option, /// Opaque version token for `definition`, such as a hash of it, chosen by - /// whoever registers the source. Reducers compare it, instead of the - /// definition, to tell an update from a re-registration of the same - /// definition. - pub nonce: String, + /// whoever registers the source. Present on a registered source. Reducers + /// compare it, instead of the definition, to tell an update from a + /// re-registration of the same definition. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub nonce: Option, /// What happens when the last contributing client leaves. Absent means `contributingClient`. #[serde(default, skip_serializing_if = "Option::is_none")] pub retention: Option, @@ -2250,26 +2234,18 @@ pub struct ModelSource { /// definition until the host reports again. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, - /// RFC 9728 metadata for the endpoint the credential is for. Present - /// whenever the source takes a credential, in every state, so any client - /// can deliver, rotate, or revoke one. Absent for a source that needs no - /// credential. Set with `state`. + /// RFC 9728 metadata for the endpoint a registered source's credential is + /// for. Present whenever the source takes a credential, in every state, so + /// any client can deliver or rotate one. Set with `state`. /// /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example /// `http://localhost:11434/v1`). It's the value a client passes back as /// `authenticate({ resource })`, and nothing fetches it. - /// `credentialResource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, - /// The {@link AuthenticateParams.accountId} the client sent with the - /// credential the host most recently accepted. While the state is - /// `starting` or `ready`, the host holds that credential. While it's - /// `authRequired`, the `reason` says what happened to it. Absent until the - /// host accepts a credential sent with an `accountId`. Set with `state`. + /// The {@link AuthenticateParams.accountId} sent with the credential the + /// host most recently accepted. Set with `state`. #[serde(default, skip_serializing_if = "Option::is_none")] pub account_id: Option, /// Additional implementation-defined metadata for this model source. @@ -2287,11 +2263,7 @@ pub struct ModelSource { /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ModelSourceStartingState { - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] - pub extra: serde_json::Map, -} +pub struct ModelSourceStartingState {} /// The source is usable, and its models are in the catalog of the agent named /// by the model source's `provider`. They stay listed through later `starting` @@ -2300,11 +2272,7 @@ pub struct ModelSourceStartingState { /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ModelSourceReadyState { - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] - pub extra: serde_json::Map, -} +pub struct ModelSourceReadyState {} /// Why a model source needs a credential before it can be ready. Deliberately /// carries no credential. The endpoint the credential is for is the @@ -2320,9 +2288,6 @@ pub struct ModelSourceAuthRequirement { /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten)] - pub extra: serde_json::Map, } /// The source needs a credential before it can be used. A client answers with @@ -2339,9 +2304,6 @@ pub struct ModelSourceAuthRequiredState { /// the API key." #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] - pub extra: serde_json::Map, } /// The source failed, or the host declined it, for example by policy. @@ -2352,24 +2314,6 @@ pub struct ModelSourceAuthRequiredState { pub struct ModelSourceErrorState { /// Error details the host writes. MUST NOT contain the credential. pub error: ErrorInfo, - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten, deserialize_with = "deserialize_extra_without_kind")] - pub extra: serde_json::Map, -} - -/// A source that an agent provider offers models from, such as a service or -/// subscription. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ModelSourceInfo { - /// Model source identifier, unique within the agent's - /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSource.id}. A source is registered when - /// {@link RootState.modelSources} has an entry with this `id` - /// whose `provider` is the agent. - pub id: String, - /// Human-readable name - pub display_name: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2419,11 +2363,9 @@ pub struct SessionModelInfo { /// recognize. #[serde(default, skip_serializing_if = "Option::is_none")] pub vendor: Option, - /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} - /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSource.id}. - /// An agent's own sources use it too, so it doesn't by itself mark a - /// registered source. + /// The source this model comes from: the {@link ModelSource.id} of an entry + /// in {@link RootState.modelSources} whose `provider` is this model's + /// {@link provider}. #[serde(default, skip_serializing_if = "Option::is_none")] pub model_source_id: Option, } @@ -6039,11 +5981,9 @@ pub struct UsageInfo { pub struct ErrorInfo { /// Error type identifier. Well-known values: /// - /// - `modelSourceUnavailable`: a registered model source the turn uses - /// can't serve it, for example because its credential is missing, - /// expired, rejected, or revoked, or the source was removed. The error - /// part is resumable. See - /// [Model source credentials](/specification/authentication#model-source-credentials). + /// - `modelSourceUnavailable`: a turn's registered model source can't serve + /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. + /// See [Model source credentials](/specification/authentication#model-source-credentials). pub error_type: String, /// Human-readable error message pub message: String, diff --git a/clients/rust/crates/ahp/examples/reducers_demo.rs b/clients/rust/crates/ahp/examples/reducers_demo.rs index 33cd386ae..e28c0255f 100644 --- a/clients/rust/crates/ahp/examples/reducers_demo.rs +++ b/clients/rust/crates/ahp/examples/reducers_demo.rs @@ -39,7 +39,6 @@ fn main() { protected_resources: None, customizations: None, capabilities: None, - model_sources: None, }], }), server_seq: 1, diff --git a/clients/rust/crates/ahp/tests/hosts.rs b/clients/rust/crates/ahp/tests/hosts.rs index 5d4553e6c..0b9cdc675 100644 --- a/clients/rust/crates/ahp/tests/hosts.rs +++ b/clients/rust/crates/ahp/tests/hosts.rs @@ -243,7 +243,6 @@ async fn single_constructor_yields_connected_handle() { protected_resources: None, customizations: None, capabilities: None, - model_sources: None, }; let state = FakeHostState::new().with_agents(vec![agent.clone()]); let factory = make_basic_factory(state); diff --git a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs index 0d7c8ee82..6f9eec081 100644 --- a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs @@ -29,7 +29,6 @@ fn agent(provider: &str) -> AgentInfo { protected_resources: None, customizations: None, capabilities: None, - model_sources: None, } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index 3cc9d5f4c..0f3702d41 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -2300,14 +2300,14 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { /// host-reported fields are absent until the host reports again with /// {@link RootModelSourceStateChangedAction}. /// -/// A client dispatches this without any host-reported field. The host learns -/// which client registered the source from the envelope's `origin`. +/// A client registers a source with its `format`, `definition`, and `nonce`, +/// and without any host-reported field. The host learns which client +/// registered it from the envelope's `origin`. /// /// Stability: 1.0 - Early development. public struct RootModelSourceSetAction: Codable, Sendable, Equatable { public var type: ActionType - /// The model source to add or update, matched by `id`, including its - /// `definition`, without host-reported fields. + /// The model source to add or update, matched by `id`. public var modelSource: ModelSource public init( diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index c87b2ce41..3262d49af 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift @@ -1970,12 +1970,14 @@ public struct McpServerAuthenticateTarget: Codable, Sendable, Equatable { } } -/// A registered model source. +/// A registered model source. The host applies the credential only to that +/// source, and publishes the request's `accountId` as the source's +/// `ModelSource.accountId`. /// /// Stability: 1.0 - Early development. public struct ModelSourceAuthenticateTarget: Codable, Sendable, Equatable { public var kind: AuthenticateTargetKind - /// The registration's `ModelSource.id`. + /// The source's `ModelSource.id`. public var modelSourceId: String public init( @@ -1999,8 +2001,7 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// `McpServerAuthRequiredState.resource`, `ToolCallAuthRequiredState.auth.resource`, /// or `ModelSource.credentialResource`. public var resource: String - /// Bearer token obtained from the resource's authorization server, or an - /// opaque secret for a model source. An empty string revokes the credential. + /// Bearer token obtained from the resource's authorization server public var token: String /// The access token's remaining lifetime, in seconds, when this /// `authenticate` request is sent. This corresponds to `expires_in` in an @@ -2011,8 +2012,6 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// authorization server did not supply an expiry or the expiry is otherwise /// unknown. When supplied, the value MUST be a positive integer. /// - /// An API key omits this field. - /// /// This field is irrelevant when `token` is empty to revoke authentication /// and SHOULD be omitted in that case. public var expiresIn: Int? @@ -2021,7 +2020,7 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is /// satisfied without decoding the (opaque, server-specific) token itself. /// Omit when the client doesn't track granted scopes separately from the - /// token. Scopes apply to OAuth-issued tokens only. + /// token. public var scopes: [String]? /// Optional consumer of the token. Clients SHOULD include this when answering /// a specific MCP server's `McpServerAuthRequiredState` or @@ -2039,10 +2038,8 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// /// A registered model source takes its credential only through a /// `modelSource` target, and the host rejects an untargeted `resource` that - /// matches only model source challenges with `InvalidParams` (-32602). A - /// delivery replaces whatever credential the host holds for the source. See - /// [Model source credentials](/specification/authentication#model-source-credentials) - /// for its rules. + /// matches only model source challenges with `InvalidParams` (-32602). See + /// [Model source credentials](/specification/authentication#model-source-credentials). /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2051,12 +2048,6 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { /// Hosts can compare `accountId` values to detect when the underlying account has changed. /// Hosts MUST treat `accountId` as an opaque string. /// see {@link /specification/authentication#account-selection-hints | Account selection hints}. - /// - /// With a `modelSource` target, clients SHOULD include it when delivering a - /// credential and omit it when revoking one, and the host publishes it as - /// the source's `ModelSource.accountId`. It MUST NOT be derived from the - /// secret. For an API key with no account of its own, a client uses an ID - /// that changes whenever the user replaces the key. public var accountId: String? enum CodingKeys: String, CodingKey { diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift index 7e52f3395..200725a5a 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift @@ -39,6 +39,8 @@ public enum AhpErrorCodes { public static let permissionDenied = -32009 /// The target resource already exists and the operation does not allow overwriting public static let alreadyExists = -32010 + /// A request selects a model whose registered model source can't serve it + public static let modelSourceUnavailable = -32013 } // MARK: - Error Detail Payloads diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 2291f3ccb..2e77d2962 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1487,8 +1487,6 @@ public struct Icon: Codable, Sendable, Equatable { public struct ProtectedResourceMetadata: Codable, Sendable, Equatable { /// REQUIRED. The protected resource's resource identifier, a URL using the /// `https` scheme with no fragment component (e.g. `"https://api.github.com"`). - /// A registered model source's endpoint may use any scheme the agent - /// supports, because nothing fetches it. public var resource: String /// OPTIONAL. Human-readable name of the protected resource. public var resourceName: String? @@ -1605,9 +1603,9 @@ public struct RootState: Codable, Sendable, Equatable { public var terminals: [TerminalInfo]? /// Agent host configuration schema and current values public var config: RootConfigState? - /// Model sources registered on this host, keyed by `id`. When one is - /// ready, it also appears in its agent's {@link AgentInfo.modelSources} - /// catalog. + /// Model sources on this host, keyed by `id`: the sources agents offer + /// models from, including ones clients registered. Clients use them to + /// label and group each agent's {@link AgentInfo.models}. /// /// Stability: 1.0 - Early development. public var modelSources: [ModelSource]? @@ -1690,9 +1688,6 @@ public struct AgentInfo: Codable, Sendable, Equatable { /// to gate features (multi-chat, fork) instead of switching on the provider /// id. public var capabilities: AgentCapabilities? - /// Sources this agent offers models from. Clients use them to label and - /// group {@link models}. A source may have no models. - public var modelSources: [ModelSourceInfo]? public init( provider: String, @@ -1701,8 +1696,7 @@ public struct AgentInfo: Codable, Sendable, Equatable { models: [SessionModelInfo], protectedResources: [ProtectedResourceMetadata]? = nil, customizations: [Customization]? = nil, - capabilities: AgentCapabilities? = nil, - modelSources: [ModelSourceInfo]? = nil + capabilities: AgentCapabilities? = nil ) { self.provider = provider self.displayName = displayName @@ -1711,7 +1705,6 @@ public struct AgentInfo: Codable, Sendable, Equatable { self.protectedResources = protectedResources self.customizations = customizations self.capabilities = capabilities - self.modelSources = modelSources } } @@ -1820,31 +1813,11 @@ public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { /// Definition formats the agent reads, most preferred first. public var formats: [ModelSourceFormatInfo] - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case formats - } public init( - formats: [ModelSourceFormatInfo], - extra: [String: AnyCodable] = [:] + formats: [ModelSourceFormatInfo] ) { self.formats = formats - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.formats = try container.decode([ModelSourceFormatInfo].self, forKey: .formats) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.formats, forKey: .formats) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } @@ -1853,113 +1826,78 @@ public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { /// /// Stability: 1.0 - Early development. public struct ModelSourceFormatInfo: Codable, Sendable, Equatable { - /// A recognized {@link ModelSource.format} value, or a namespaced name for - /// a format the agent defines itself. + /// A {@link ModelSource.format} value. public var format: String - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case format - } public init( - format: String, - extra: [String: AnyCodable] = [:] + format: String ) { self.format = format - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.format = try container.decode(String.self, forKey: .format) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.format, forKey: .format) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } -/// A model source registered on this host by a client, or by the host itself. -/// Nothing here is a credential. +/// A source that an agent provider offers models from, such as a service, +/// subscription, or endpoint. The host lists the sources an agent provides +/// itself, and clients can register more with a definition. Nothing here is +/// a credential. /// /// Stability: 1.0 - Early development. public struct ModelSource: Codable, Sendable, Equatable { /// Host-unique ID, chosen by whoever registers the source. Also the - /// source's {@link ModelSourceInfo.id} in the agent's catalog, and the /// {@link SessionModelInfo.modelSourceId} of its models. public var id: String - /// Agent provider whose agent reads the definition and serves the models. + /// Agent provider whose agent serves the source's models. public var provider: String - /// Human-readable name, published as {@link ModelSourceInfo.displayName}. + /// Human-readable name. public var displayName: String /// Icons for UI display. public var icons: [Icon]? - /// The definition's format: the `format` of one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. Recognized values - /// include: + /// The format of `definition`: the `format` of one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. Present on a + /// registered source. + /// + /// Agents choose the formats they read. Some may read these common names: /// - /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as - /// OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API. /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. /// - `'azureOpenai'`: an Azure OpenAI deployment. /// - `'gemini'`: Google's Gemini API. /// - /// Agents MAY read other formats, named with a namespace such as - /// `example.com/model-source@1` so they don't collide. - public var format: String + /// Other formats are named with a namespace, such as + /// `example.com/model-source@1`, so they don't collide. + public var format: String? /// How to reach the source, in `format`: endpoint, wire API, models, and so - /// on. The agent reads it, and AHP doesn't validate it. Every client can - /// read it, so it MUST NOT contain a credential. - /// - /// Suggested shapes for the recognized formats. Agents MAY read more - /// members, and MAY discover models when `models` is absent. - /// - /// - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` - /// - `anthropic`: `{ endpoint, models? }` - /// - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each - /// deployment name as a model `id` - /// - `gemini`: `{ endpoint, models? }` - /// - /// `endpoint` is the API's base URI, such as `https://api.example.com/v1`. - /// Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, - /// supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, - /// where `id` is the endpoint's own model identifier. - public var definition: [String: AnyCodable] + /// on. The agent reads it. Every client can read it, so it MUST NOT contain + /// a credential. Present on a registered source. + /// + /// An agent that reads one of the common format names might expect a shape + /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + /// the API's base URI and each `models` entry is `{ id, name?, + /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + /// named as in {@link SessionModelInfo}. + public var definition: [String: AnyCodable]? /// Opaque version token for `definition`, such as a hash of it, chosen by - /// whoever registers the source. Reducers compare it, instead of the - /// definition, to tell an update from a re-registration of the same - /// definition. - public var nonce: String + /// whoever registers the source. Present on a registered source. Reducers + /// compare it, instead of the definition, to tell an update from a + /// re-registration of the same definition. + public var nonce: String? /// What happens when the last contributing client leaves. Absent means `contributingClient`. public var retention: ModelSourceRetentionPolicy? /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. /// Absent until the host reports one, and after an update replaces the /// definition until the host reports again. public var state: ModelSourceState? - /// RFC 9728 metadata for the endpoint the credential is for. Present - /// whenever the source takes a credential, in every state, so any client - /// can deliver, rotate, or revoke one. Absent for a source that needs no - /// credential. Set with `state`. + /// RFC 9728 metadata for the endpoint a registered source's credential is + /// for. Present whenever the source takes a credential, in every state, so + /// any client can deliver or rotate one. Set with `state`. /// /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example /// `http://localhost:11434/v1`). It's the value a client passes back as /// `authenticate({ resource })`, and nothing fetches it. - /// `credentialResource.resource_name` labels the prompt (for example - /// "OpenRouter API key"). A source that accepts OAuth access tokens - /// advertises `authorization_servers` and `scopes_supported`. A source that - /// takes a user-supplied secret omits them. public var credentialResource: ProtectedResourceMetadata? - /// The {@link AuthenticateParams.accountId} the client sent with the - /// credential the host most recently accepted. While the state is - /// `starting` or `ready`, the host holds that credential. While it's - /// `authRequired`, the `reason` says what happened to it. Absent until the - /// host accepts a credential sent with an `accountId`. Set with `state`. + /// The {@link AuthenticateParams.accountId} sent with the credential the + /// host most recently accepted. Set with `state`. public var accountId: String? /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. @@ -1987,9 +1925,9 @@ public struct ModelSource: Codable, Sendable, Equatable { provider: String, displayName: String, icons: [Icon]? = nil, - format: String, - definition: [String: AnyCodable], - nonce: String, + format: String? = nil, + definition: [String: AnyCodable]? = nil, + nonce: String? = nil, retention: ModelSourceRetentionPolicy? = nil, state: ModelSourceState? = nil, credentialResource: ProtectedResourceMetadata? = nil, @@ -2018,9 +1956,9 @@ public struct ModelSource: Codable, Sendable, Equatable { self.provider = try container.decode(String.self, forKey: .provider) self.displayName = try container.decode(String.self, forKey: .displayName) self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) - self.format = try container.decode(String.self, forKey: .format) - self.definition = try container.decode([String: AnyCodable].self, forKey: .definition) - self.nonce = try container.decode(String.self, forKey: .nonce) + self.format = try container.decodeIfPresent(String.self, forKey: .format) + self.definition = try container.decodeIfPresent([String: AnyCodable].self, forKey: .definition) + self.nonce = try container.decodeIfPresent(String.self, forKey: .nonce) self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) self.credentialResource = try container.decodeIfPresent(ProtectedResourceMetadata.self, forKey: .credentialResource) @@ -2035,9 +1973,9 @@ public struct ModelSource: Codable, Sendable, Equatable { try container.encode(self.provider, forKey: .provider) try container.encode(self.displayName, forKey: .displayName) try container.encodeIfPresent(self.icons, forKey: .icons) - try container.encode(self.format, forKey: .format) - try container.encode(self.definition, forKey: .definition) - try container.encode(self.nonce, forKey: .nonce) + try container.encodeIfPresent(self.format, forKey: .format) + try container.encodeIfPresent(self.definition, forKey: .definition) + try container.encodeIfPresent(self.nonce, forKey: .nonce) try container.encodeIfPresent(self.retention, forKey: .retention) try container.encodeIfPresent(self.state, forKey: .state) try container.encodeIfPresent(self.credentialResource, forKey: .credentialResource) @@ -2053,31 +1991,11 @@ public struct ModelSource: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct ModelSourceStartingState: Codable, Sendable, Equatable { public var kind: ModelSourceStatus - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case kind - } public init( - kind: ModelSourceStatus, - extra: [String: AnyCodable] = [:] + kind: ModelSourceStatus ) { self.kind = kind - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.kind, forKey: .kind) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } @@ -2088,31 +2006,11 @@ public struct ModelSourceStartingState: Codable, Sendable, Equatable { /// Stability: 1.0 - Early development. public struct ModelSourceReadyState: Codable, Sendable, Equatable { public var kind: ModelSourceStatus - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case kind - } public init( - kind: ModelSourceStatus, - extra: [String: AnyCodable] = [:] + kind: ModelSourceStatus ) { self.kind = kind - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.kind, forKey: .kind) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } @@ -2127,36 +2025,13 @@ public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { /// Human-readable hint the host writes, for example "The endpoint rejected /// the API key." public var description: String? - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case reason - case description - } public init( reason: ModelSourceAuthRequiredReason, - description: String? = nil, - extra: [String: AnyCodable] = [:] + description: String? = nil ) { self.reason = reason self.description = description - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.reason = try container.decode(ModelSourceAuthRequiredReason.self, forKey: .reason) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.reason, forKey: .reason) - try container.encodeIfPresent(self.description, forKey: .description) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } @@ -2172,41 +2047,15 @@ public struct ModelSourceAuthRequiredState: Codable, Sendable, Equatable { /// the API key." public var description: String? public var kind: ModelSourceStatus - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case reason - case description - case kind - } public init( reason: ModelSourceAuthRequiredReason, description: String? = nil, - kind: ModelSourceStatus, - extra: [String: AnyCodable] = [:] + kind: ModelSourceStatus ) { self.reason = reason self.description = description self.kind = kind - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.reason = try container.decode(ModelSourceAuthRequiredReason.self, forKey: .reason) - self.description = try container.decodeIfPresent(String.self, forKey: .description) - self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.reason, forKey: .reason) - try container.encodeIfPresent(self.description, forKey: .description) - try container.encode(self.kind, forKey: .kind) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } @@ -2217,55 +2066,13 @@ public struct ModelSourceErrorState: Codable, Sendable, Equatable { public var kind: ModelSourceStatus /// Error details the host writes. MUST NOT contain the credential. public var error: ErrorInfo - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - - enum CodingKeys: String, CodingKey, CaseIterable { - case kind - case error - } public init( kind: ModelSourceStatus, - error: ErrorInfo, - extra: [String: AnyCodable] = [:] + error: ErrorInfo ) { self.kind = kind self.error = error - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.kind = try container.decode(ModelSourceStatus.self, forKey: .kind) - self.error = try container.decode(ErrorInfo.self, forKey: .error) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.kind, forKey: .kind) - try container.encode(self.error, forKey: .error) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } -} - -public struct ModelSourceInfo: Codable, Sendable, Equatable { - /// Model source identifier, unique within the agent's - /// {@link AgentInfo.modelSources}. For a registered model source, this is - /// the {@link ModelSource.id}. A source is registered when - /// {@link RootState.modelSources} has an entry with this `id` - /// whose `provider` is the agent. - public var id: String - /// Human-readable name - public var displayName: String - - public init( - id: String, - displayName: String - ) { - self.id = id - self.displayName = displayName } } @@ -2306,11 +2113,9 @@ public struct SessionModelInfo: Codable, Sendable, Equatable { /// SHOULD fall back to a generic presentation for values they do not /// recognize. public var vendor: String? - /// The source this model comes from. MUST match a {@link ModelSourceInfo.id} - /// in the agent's {@link AgentInfo.modelSources}. For a model from a - /// registered model source, this is the {@link ModelSource.id}. - /// An agent's own sources use it too, so it doesn't by itself mark a - /// registered source. + /// The source this model comes from: the {@link ModelSource.id} of an entry + /// in {@link RootState.modelSources} whose `provider` is this model's + /// {@link provider}. public var modelSourceId: String? enum CodingKeys: String, CodingKey { @@ -7790,11 +7595,9 @@ public struct UsageInfo: Codable, Sendable, Equatable { public struct ErrorInfo: Codable, Sendable, Equatable { /// Error type identifier. Well-known values: /// - /// - `modelSourceUnavailable`: a registered model source the turn uses - /// can't serve it, for example because its credential is missing, - /// expired, rejected, or revoked, or the source was removed. The error - /// part is resumable. See - /// [Model source credentials](/specification/authentication#model-source-credentials). + /// - `modelSourceUnavailable`: a turn's registered model source can't serve + /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. + /// See [Model source credentials](/specification/authentication#model-source-credentials). public var errorType: String /// Human-readable error message public var message: String diff --git a/docs/.changes/20261022-model-source-selection.json b/docs/.changes/20261022-model-source-selection.json index 1af988cb1..6c1200fc5 100644 --- a/docs/.changes/20261022-model-source-selection.json +++ b/docs/.changes/20261022-model-source-selection.json @@ -1,4 +1,4 @@ { "type": "added", - "message": "`ModelSourceInfo`, `AgentInfo.modelSources`, and `SessionModelInfo.modelSourceId` let an agent label and group its models by source. Model IDs are unique within an agent and stable across catalog updates." + "message": "`RootState.modelSources` and `SessionModelInfo.modelSourceId` let an agent label and group its models by source. Model IDs are unique within an agent and stable across catalog updates." } diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index f7e44cd4b..9f1f825d1 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through `RootState.modelSources` and the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. Each `ModelSource` carries its `definition` and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. `ModelSource.format` documents recognized values (`openaiCompatible`, `anthropic`, `azureOpenai`, `gemini`), and `definition` documents a suggested shape for each. Clients deliver each source's credential with a `modelSource` `authenticate` target, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`), and ends turns on an unavailable source with the resumable `modelSourceUnavailable` error. Agents advertise the definition formats they read as `ModelSourceFormatInfo` entries in `AgentCapabilities.modelSourceRegistration`.", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. A registered `ModelSource` carries its `format`, its `definition`, and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. Agents advertise the formats they read as `ModelSourceFormatInfo` entries in `AgentCapabilities.modelSourceRegistration`. Clients deliver each source's credential with a `modelSource` `authenticate` target, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`). A turn on an unavailable source ends with the resumable `modelSourceUnavailable` error, and a request that selects one of its models fails with `ModelSourceUnavailable` (`-32013`).", "issues": [619] } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 87bbda2eb..18053c4de 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -31,7 +31,7 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/activeSessionsChanged` | No | Count of active sessions changed | | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | -| `root/modelSourceSet` | **Yes** | A [model source](/specification/root-channel#model-source-registry) was added, re-registered, or updated by `id` | +| `root/modelSourceSet` | **Yes** | A [model source](/specification/root-channel#registering-sources) was added, re-registered, or updated by `id` | | `root/modelSourceRemoved` | **Yes** | A model source was removed by `id` | | `root/modelSourceStateChanged` | No | The host reported a model source's status and credential fields | diff --git a/docs/guide/state-model.md b/docs/guide/state-model.md index bad458e7f..125cc1ead 100644 --- a/docs/guide/state-model.md +++ b/docs/guide/state-model.md @@ -12,7 +12,7 @@ RootState { activeSessions?: number // count of non-disposed sessions terminals?: TerminalInfo[] // lightweight terminal catalogue config?: RootConfigState // host-level configuration - modelSources?: ModelSource[] // registered model sources + modelSources?: ModelSource[] // sources agents offer models from } ``` diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index f6c8b8c3a..1752f6e25 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -1,6 +1,6 @@ # Authentication -AHP uses [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) (OAuth 2.0 Protected Resource Metadata) semantics for authentication discovery, and [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) (Bearer Token Usage) semantics for token delivery. Communication is JSON-RPC, not HTTP, but the vocabulary and flow mirror the HTTP standards. A [registered model source](#model-source-credentials) takes an opaque secret, such as an API key, instead of a Bearer token. +AHP uses [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) (OAuth 2.0 Protected Resource Metadata) semantics for authentication discovery, and [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) (Bearer Token Usage) semantics for token delivery. Communication is JSON-RPC, not HTTP, but the vocabulary and flow mirror the HTTP standards. ## Overview @@ -87,7 +87,7 @@ Different agents MAY require authentication with different providers. For exampl ## Token Delivery -Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `ModelSource.credentialResource.resource`, which stays available while the source is ready for rotation and revocation (see [Model source credentials](#model-source-credentials)): +Clients push Bearer tokens to the server using the [`authenticate`](/reference/common#authenticate) command. The `resource` field MUST match a `resource` value the server has itself advertised — either statically via the agent's `protectedResources` metadata, or dynamically via a live MCP authentication challenge (`McpServerAuthRequiredState.resource` or, for a single blocked tool call, `ToolCallAuthRequiredState.auth.resource` — see [MCP Servers](/guide/mcp#authentication)) or a registered model source's `credentialResource.resource` (see [Model source credentials](#model-source-credentials)): ```jsonc // Client → Server @@ -150,12 +150,7 @@ If the token is invalid or the resource is unrecognized, the server MUST return ### Model source credentials -A client can [register a model source](/specification/root-channel#model-source-registry), such as an endpoint configured with the user's own API key, with the host. While the source takes a credential, the model source carries host-reported credential fields in every state: - -- `credentialResource`: RFC 9728 metadata for the endpoint the credential is for; -- `accountId`: the `accountId` the client sent with the key the host most recently accepted. - -When the source needs a credential, the host also sets the source's state to `ModelSourceAuthRequiredState`, with a `reason`. A client answers with a `modelSource` target that names the source, and names the key with the existing `accountId` parameter: +A [registered model source](/specification/root-channel#registering-sources) that takes a credential carries `credentialResource`, RFC 9728 metadata for the endpoint the credential is for, in every state. When the source needs a credential, its state is `authRequired`, with a `reason`. A client delivers the credential with `authenticate`, the source's `credentialResource.resource`, and a `modelSource` target: ```jsonc // Model source credential delivery @@ -176,60 +171,35 @@ When the source needs a credential, the host also sets the source's state to `Mo } ``` -The `token` is an opaque secret rather than an RFC 6750 Bearer token. The agent applies it as the source's definition specifies, for example as an `Authorization: Bearer` or `x-api-key` header. A source that accepts OAuth access tokens, such as Microsoft Entra ID tokens, advertises `authorization_servers` and `scopes_supported`, and the client sends `expiresIn` with each short-lived token. A source that takes a user-supplied secret omits them, and the client omits `scopes`. `credentialResource.resource_name` labels the prompt, for example "OpenRouter API key". - -`credentialResource.resource` is the endpoint URL as the definition names it, and the value the client passes as `resource`. It may use any scheme the agent supports, such as `http://localhost:11434/v1` for a local server. Unlike other protected resources, it doesn't need to be an `https` URL: the client only echoes it in `authenticate`, and nothing fetches it. Where the host actually sends the credential is governed by the source's definition and the egress rules below. - -Clients SHOULD include `accountId` when they deliver a credential, and omit it when they revoke one. The host publishes it as the source's `accountId`, which lets a client that reloads, or one on another device, tell whether the host holds its current key. It's opaque and MUST NOT be derived from the secret, because every client can read it. For an API key that has no account of its own, a client uses an ID that changes whenever the user replaces the key, such as one derived from where it stores the key and when the key last changed. [Host-owned authentication](https://github.com/microsoft/agent-host-protocol/pull/404) may later supersede the `modelSource` target and this use of `accountId`. - When `target.kind` is `modelSource`, the host: -- MUST apply the credential only to that model source, never to other model sources, MCP servers, or agent-level resources, even when they share `resource`; +- MUST apply the credential only to that source, never to other model sources, MCP servers, or agent-level resources, even when they share `resource`; - MUST require `resource` to equal the source's current `credentialResource.resource`; - MUST reject an unknown `modelSourceId` with `InvalidParams` (`-32602`); -- MUST publish the request's `accountId` as the source's `accountId` when it accepts a credential, and clear it when the request has none; -- MUST treat an empty `token` as revocation: it stops using the credential at once, drops it, and reports `authRequired` with `reason: revoked`. - -Any client may deliver or revoke a model source's credential, as any client may answer an MCP server's challenge. A host that restricts sources by principal rejects a credential for another principal's source with `PermissionDenied` (`-32009`). +- MUST publish the request's `accountId` as the source's `accountId` when it accepts the credential. -As with MCP servers, the target names the source but not a version of it. A delivery replaces whatever credential the host holds for the source, so when two clients answer the same `authRequired`, the later one wins. +A delivery replaces the credential the host holds for the source. `accountId` lets a client that reloads, or one on another device, tell whether the host holds its current key. It MUST NOT be derived from the secret, because every client can read it. #### Reasons -An `authRequired` state's `reason` is a `ModelSourceAuthRequiredReason`, specific to model sources. The shared `AuthRequiredReason` folds rejection and revocation into `expired`, so a client that renews automatically could undo a user's revocation. - | `reason` | Meaning | What a client may send | | --- | --- | --- | | `required` | The host holds no credential yet. | Its key. | -| `expired` | The credential's lifetime or lease lapsed. | A renewed credential: a fresh token, or the same static key with a new lease. | -| `rejected` | The endpoint refused the credential. `accountId` still names it. | Only a key whose `accountId` differs. Otherwise it asks the user for a new one. | +| `expired` | The credential's lifetime, or the lease a client set with `expiresIn`, lapsed. | A renewed credential. | +| `rejected` | The endpoint refused the credential. `accountId` still names it. | Only a key whose `accountId` differs. | | `revoked` | A client revoked the credential. | Nothing, until a user asks. | -`expiresIn` keeps its meaning for short-lived tokens. With a static key, it's a lease: the host drops the key when the lease elapses and reports `expired`, and a client renews the lease by sending the key again. An API key without a lease omits `expiresIn`. +#### Delivering and handling -#### Delivering +Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers one only in answer to the source's current state, and MUST NOT send a stored secret unless the source's `provider` and `format` match its own copy and every endpoint in the source's `definition` that the key would reach is one its own copy sends the key to. -Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers a credential only in answer to the source's current state, reading it from its own secure storage or token provider each time: +The host holds the credential in memory only. It never places it in state, actions, notifications, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. It attaches the credential only to the endpoints the source's definition names, never to another origin, including on redirect, and drops it when the source is removed or updated, when its lease lapses, and when the host restarts. -- when the state is `authRequired`, as the table above allows; -- when the state is `starting` or `ready`, and the source's `accountId` names a key this client has since replaced, for example one it delivered before the user changed it. A client whose key simply differs leaves the host's credential alone, so two devices with different working keys don't replace each other's in turn; -- when a lease or token it delivered is about to expire. - -Clients SHOULD NOT prompt the user for a key they don't have. A client MUST NOT send a stored secret unless the source's `provider` and `format` match its own copy, and every endpoint in the source's `definition` that the key would reach is one its own copy sends the key to. It checks the definition itself rather than trusting `nonce`, which another client chooses. - -#### Handling and egress - -The host holds the credential in memory only and never persists it. It never places the credential in state, actions, notifications, the definition, the source's `nonce`, `_meta`, or credential fields, `ErrorInfo`, environment variables, command lines, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. The host SHOULD also redact it from tool output before storing that output or sending it to the model. That's best effort: the same secret can also live where the agent can read it, such as a `.env` file, and a host can only redact values it knows. The host writes `ModelSourceAuthRequirement.description` and `ErrorInfo` itself, and SHOULD NOT copy upstream response bodies or headers into them: an endpoint's error text can echo part of a key, and every client can read root state. - -The host attaches the credential only to that source's requests, as its definition specifies, and only to the endpoints its definition names, never to another origin, including on redirect. It drops the credential when the source is removed, when `root/modelSourceSet` updates it, when it's revoked, when its lease lapses, and when the host restarts. - -Endpoints in a definition, including loopback and private addresses, are resolved and reached from the host machine: `localhost` in a source registered with a remote host is that host, not the client's machine. Hosts SHOULD apply an egress policy to registered endpoints: deny link-local and cloud metadata addresses, and require `https` for any credentialed endpoint that isn't a loopback address, unless the host has opted in to plain `http`. +Endpoints, including loopback and private addresses, are reached from the host machine. Hosts SHOULD deny link-local and cloud metadata addresses, and require `https` for credentialed endpoints other than loopback. #### Turns -When a turn can't use its source, because the credential is missing, expired, rejected, or revoked, or because the source was removed, the host ends the turn with `chat/error`. The error part's `error.errorType` is `modelSourceUnavailable`, and `resumable` is `true`. A client tells why from the registered source of the turn's model: its `state`, or its absence. Once the source is ready again, a client can continue the turn with `chat/turnResume`, and the host checks the turn's selection again first. The host never switches the turn to a different model. - -When the last contributing client leaves a `contributingClient`-retained source, turns already running on it finish, and no new ones start. When any client removes the source, or revokes its credential, the host stops using the credential immediately and ends every running turn that uses it with the `modelSourceUnavailable` error. +When a turn can't use its source, the host ends the turn with an error part whose `errorType` is `modelSourceUnavailable` and whose `resumable` is `true`. A request that selects such a model fails with `ModelSourceUnavailable` (`-32013`). The host never switches to a different model. When a client removes a source or revokes its credential, the host ends running turns that use it. ### Why keyed by `resource` and optional `target`? diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index e901cbbbb..a8ba481bf 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -30,150 +30,60 @@ RootState { - `activeSessions` — count of non-disposed sessions. Lightweight badge counter. - `terminals` — lightweight per-terminal metadata for rendering a terminal manager UI without subscribing to every terminal. See [Terminal Channel](/specification/terminal-channel) for the full state. - `config` — host-level configuration schema and current values. -- `modelSources` — model sources clients or the host registered. See [Model source registry](#model-source-registry). +- `modelSources` — the sources agents offer models from, including ones clients registered. See [Model sources](#model-sources). The session list is **not** part of root state. Clients fetch it imperatively via [`listSessions`](/reference/root#listsessions) and patch it from `root/*` notifications described below. ### Model sources -An agent provider can offer models from more than one source, such as different services or subscriptions. It lists those sources in [`AgentInfo.modelSources`](/reference/root#agentinfo), and each model names its source in [`SessionModelInfo.modelSourceId`](/reference/root#sessionmodelinfo). Clients use sources to label and group models, for example in a model picker. +An agent provider can offer models from more than one source, such as a service, subscription, or endpoint. Root state lists every source in [`modelSources`](/reference/root#modelsource), each naming its agent `provider`, and each model names its source in [`SessionModelInfo.modelSourceId`](/reference/root#sessionmodelinfo). Clients use sources to label and group models, for example in a model picker. -- Source IDs MUST be unique within the agent's `modelSources`. -- A model's `modelSourceId` MUST match an entry in the same agent's `modelSources`. +- Source IDs MUST be unique within `modelSources`. +- A model's `modelSourceId` MUST match a source whose `provider` is the model's agent provider. - Model IDs MUST be unique within the agent's `models`. When two sources serve the same upstream model, the host gives each entry its own ID and maps that ID to the upstream model. - Model IDs are stable. A host SHOULD keep a model's ID across catalog updates, so saved selections keep working. It MUST NOT reuse an ID for a different source or upstream model, even after the model leaves `models`. A saved selection whose ID is no longer in `models` is unavailable. - A source can have no models. -A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, which also determines the source. +A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, which also determines the source. The host lists the sources an agent provides itself. They have no `format` or `definition`, and their sign-in uses `AgentInfo.protectedResources`. -```json -{ - "provider": "example", - "displayName": "Example agent", - "description": "An agent with two model sources", - "modelSources": [ - { "id": "source-a", "displayName": "Service A" }, - { "id": "source-b", "displayName": "Service B" } - ], - "models": [ - { "id": "shared-model-a", "provider": "example", "name": "Shared model", "modelSourceId": "source-a" }, - { "id": "shared-model-b", "provider": "example", "name": "Shared model", "modelSourceId": "source-b" } - ] -} -``` - -### Model source registry - -Clients can register bring-your-own-key model sources with the host, so its agents can serve those models to every session and to automations. Root state lists them in [`modelSources`](/reference/root#modelsource), keyed by `id`. An agent that accepts registrations advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the definition formats it reads, most preferred first, as [`ModelSourceFormatInfo`](/reference/root#modelsourceformatinfo) objects. - -```json -{ - "id": "2f6c0e1a-model-source", - "provider": "example", - "displayName": "OpenRouter", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://openrouter.ai/api/v1", - "wireApi": "chatCompletions", - "models": [{ "id": "vendor/model-a", "maxContextWindow": 200000 }] - }, - "nonce": "sha256-4f1c9a", - "retention": "host", - "state": { "kind": "ready" }, - "credentialResource": { - "resource": "https://openrouter.ai/api/v1", - "resource_name": "OpenRouter API key" - }, - "accountId": "keychain-5c2a" -} -``` - -A model source's `definition` tells the agent how to reach it: endpoint, wire API, models, and so on, in the format `format` names. AHP recognizes `openaiCompatible`, `anthropic`, `azureOpenai`, and `gemini`, following the pattern of `Changeset.changeKind`, and suggests a shape for each: - -- `openaiCompatible`: `{ endpoint, wireApi?, models? }`, where `wireApi` is `chatCompletions` or `responses`; -- `anthropic`: `{ endpoint, models? }`; -- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each deployment name as a model `id`; -- `gemini`: `{ endpoint, models? }`. - -`endpoint` is the API's base URI, such as `https://api.example.com/v1`. Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, named as in `SessionModelInfo`, where `id` is the endpoint's own model identifier. Agents MAY read more members, and MAY discover models when `models` is absent. AHP doesn't validate definitions, even for the recognized formats: `definition` belongs to the agent. Agents MAY read other formats, named with a namespace such as `example.com/model-source@1`. - -Every client can read a source's definition, for example to show which endpoint it uses, or to check it against its own copy before sending a key. Root state is broadcast and replayed, so a definition is never secret, and it MUST NOT contain a credential. A client delivers the credential separately, with [`authenticate`](/specification/authentication#model-source-credentials). `nonce` is an opaque version token for the definition, so reducers compare a string rather than JSON. - -#### Registering, updating, and removing - -A client registers a source with `root/modelSourceSet { modelSource }`, including its definition, and removes it with `root/modelSourceRemoved { id }`. The reducers follow the keyed-collection convention, with one twist so that re-registering the same definition doesn't disturb a working source: +#### Registering sources -- **Add.** When no model source has the `id`, `Set` appends `modelSource`. -- **Re-register.** When one has, with the same `provider`, `format`, and `nonce`, `Set` keeps its host-reported fields (`state`, `credentialResource`, and `accountId`) and takes everything else from the action. -- **Update.** When any of the three differs, `Set` replaces the source. Its host-reported fields are absent until the host reports again. -- **Remove.** `Removed` deletes the source by `id`, or returns the state unchanged. +An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads. A client registers a source with `root/modelSourceSet`, giving its `format`, a `definition` that tells the agent how to reach it, and a `nonce` that versions the definition, such as a hash of it. Each agent decides which formats it reads. Every client can read a definition, so it MUST NOT contain a credential: a client delivers that separately, with [`authenticate`](/specification/authentication#model-source-credentials). -Comparing three strings keeps every client's reducer in agreement without comparing definitions. +`root/modelSourceSet` adds a source, or updates the one with the same `id`: -A client dispatches `Set` with no host-reported fields, when it starts or reconnects with the source configured, and when the user changes the source. Re-registering an unchanged source is how a second window, a reloaded window, or another device with the same source configured becomes a contributing client. When clients disagree on `displayName`, `icons`, `retention`, or `_meta`, the last `Set` wins. A client SHOULD derive `id` from a stable key in its own configuration, and `nonce` from the definition, for example as a hash of it. A client SHOULD NOT update a source whose `nonce` differs from its own copy unless the user changed the source in its configuration, and SHOULD NOT add back a source another client removed except when it starts or reconnects, or two clients with different configurations would replace each other's source indefinitely. +- **Add.** When no source has the `id`, it appends the source. +- **Re-register.** When one has, with the same `provider`, `format`, and `nonce`, it keeps the host-reported fields (`state`, `credentialResource`, and `accountId`) and takes everything else from the action. +- **Update.** When any of the three differs, it replaces the source, whose host-reported fields are absent until the host reports again. The host drops the source's credential. -When the user removes the source from a client's configuration, the client dispatches `Removed`. Removal applies to every client. A client that still has the source configured registers it again the next time it starts or reconnects. +`root/modelSourceRemoved` removes a source for every client. The host rejects a client's `Set`, through `rejectionReason`, when: -The host rejects a client's `Set`, through `rejectionReason`, when: +- the agent doesn't advertise `modelSourceRegistration` or list `format`, or the source lacks `format`, `definition`, or `nonce`; +- the source includes a host-reported field; +- its `provider`, `format`, and `nonce` match the existing source's, but its `definition` differs; +- it would change a source the host registered itself, including an agent's own; +- the host won't honor the requested `retention`. -- the agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format`; -- `modelSource` includes any host-reported field; -- its `provider`, `format`, and `nonce` match the existing source's, but its `definition` differs. A re-registration must not carry a different definition, because reducers keep the credential for it; -- `id` equals a `ModelSourceInfo.id` that the agent declares itself. The catalog entry the host publishes for this same source doesn't count, so a ready source can still be re-registered or updated; -- the host won't honor the requested `retention`. The client can register again with `contributingClient` retention; -- the host registered the source itself; -- the host restricts sources by principal, and the existing source belongs to another principal. +A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one, and SHOULD NOT update a source whose `nonce` differs from its own copy unless the user changed that source. Re-registering an unchanged source makes the client a contributing client. The host tracks contributing clients itself, from `ActionEnvelope.origin`. -A host MAY reject a client's `Removed` for a source it registered itself or one that belongs to another principal. +Every connected client may change, supply credentials for, and select every source. A host that can verify principals MAY restrict a source to clients of the principal that registered it. -The host tracks contributing clients itself, from each `Set`'s `ActionEnvelope.origin`, and they aren't in state. An add or a re-registration adds the dispatching client. An update makes the dispatching client the only one, because the others registered a different definition. When `Set` updates a source, the host drops its credential, and the source goes back through `starting`, so a changed definition never receives a key supplied for a different one. A re-registration, or a change to `displayName`, `icons`, `retention`, or `_meta`, keeps the credential. A host may also register sources itself. Those sources have no contributing clients, and their retention behaves as `host`. +#### Status and catalog -#### Status +The host reports a registered source's status with `root/modelSourceStateChanged`, which sets `state`, `credentialResource`, and `accountId` together, and ignores an unknown `id`. The state is `starting`, `ready`, `authRequired` with a `reason`, or `error`. -The host reports status with `root/modelSourceStateChanged`, as `session/mcpServerStateChanged` does for MCP servers. It sets the host-reported fields together: the source's `state` (`starting`, `ready`, `authRequired`, or `error`), and its `credentialResource` and `accountId`, which an absent value clears. It never reports status by dispatching the source back with `Set`. The reducer ignores an unknown `id` and changes no other field, so a late report can't bring back a removed source or overwrite a newer one. +Once a registered source has been `ready`, the host keeps its models in the agent's `models` through later `starting` and `authRequired` states, so rotating a key doesn't break a selection. It withdraws them when the source is removed or enters `error`, or when an update changes its endpoint. A host SHOULD derive each model's ID deterministically from the source's `id`, `provider`, and `format`, its endpoint, and the endpoint's own model identifier, so a source registered again gets the same IDs. -An `authRequired` state carries a `reason` specific to model sources: `required` (no credential yet), `expired` (its lifetime or lease lapsed), `rejected` (the endpoint refused it), or `revoked` (a client revoked it). See [Model source credentials](/specification/authentication#model-source-credentials) for what clients do with each. - -`credentialResource` is the RFC 9728 metadata for the endpoint the credential is for. The host reports it in every state while the source takes a credential, so any client can deliver, rotate, or revoke one, and leaves it absent for a source that needs none. `accountId` names the key the host most recently accepted. - -#### Catalog - -When a registered source is `ready`, the host adds it to the catalog of the agent named by `provider`, through `root/agentsChanged`: a `ModelSourceInfo` with the source's `id` and `displayName`, and its models in `models` with `modelSourceId` set to that `id`. `modelSourceId` alone doesn't mark a registered source, because an agent's own sources use it too. A source is registered when `modelSources` has an entry with that `id` whose `provider` is the agent. - -**Built-in sources.** A source the agent provides itself, such as a first-party service that ships with the agent, stays an agent-declared `ModelSourceInfo`. The host lists it and its models in `AgentInfo` directly, and its sign-in uses `AgentInfo.protectedResources` and an untargeted `authenticate`. It isn't a registered source. Clients register sources only for configuration the agent doesn't have. - -Once a registered source has been `ready`, the host keeps its models listed through later `starting` and `authRequired` states, so a key rotation or expiry doesn't change the catalog or break a selection. It withdraws them when the source is removed, when its last contributing client leaves under `contributingClient` retention, when it enters `error`, or when an update mints new model IDs (see [Reserved model IDs](#reserved-model-ids)). The host MAY list the `ModelSourceInfo` in any state. - -Any client can select a registered source's models, in any session whose agent is the source's `provider`. The host checks every selection: the model is listed, the chat is backed by the source's agent provider, and, when the host restricts sources by principal, the turn's client acts for the source's principal. It checks whenever it uses a selection, including when a client continues a turn with `chat/turnResume`. Otherwise it rejects the selection through the existing failure paths: `InvalidParams` for requests, and `rejectionReason` for dispatched actions. The host MUST NOT run the work on a different model. A turn that can't use its source ends with the resumable `modelSourceUnavailable` error, as described in [Model source credentials](/specification/authentication#model-source-credentials). +The host checks a selection whenever it uses one, and never runs the work on a different model. A turn that can't use its source fails as described in [Model source credentials](/specification/authentication#turns). #### Retention -The client that registers a source chooses what happens when the last contributing client leaves. Absent means `contributingClient`, the narrower choice. - -A contributing client leaves when its connection closes and it doesn't reconnect with the same `clientId` within a grace period the host chooses. While other contributing clients remain, nothing changes. When the last one leaves: - -- With `contributingClient`, the source goes away, like a client-published plugin: the host withdraws its models from the catalog, new work that names them fails, turns already running on it finish, and then the host removes the source with `root/modelSourceRemoved` and drops its credential. -- With `host`, the source stays, like a host-declared MCP server, with its credential in memory and no contributing clients, until a client removes it or host policy expires it. A restart drops its credential, as described below. - -When the user removes the source from their configuration, their client removes it, whatever its retention, so `host` retention doesn't leave sources nobody wants. The host MAY expire `host`-retained sources. - -A client that reconnects with the same `clientId` within the grace period is still counted. A client that comes back with a new `clientId` and the same configuration re-registers with `Set`, which keeps the status and credential. After a restart, a host that persists its state SHOULD keep `host`-retained sources and their definitions, which come back through `starting`, and reach `authRequired` with `reason: required` only if they need a credential. - -#### Principals - -AHP doesn't verify which client is which, so every connected client may change, supply credentials for, and select every model source, as with MCP servers. Where a host can verify principals, it MAY restrict changes, credentials, and use of a model source to clients of the principal that registered it, and rejects the rest through the usual failure paths. Root state still lists every model source, with its definition, to every client, so neither is private. A host whose connections carry credentials scoped to one client, such as a relay that forwards each client's own sign-in, SHOULD NOT let one client's model source be used by another: it restricts sources by principal, or doesn't advertise `modelSourceRegistration`. - -The grace period and any restriction by principal are host policy. The capability doesn't advertise them, because a client doesn't change what it does or shows because of them. - -#### Reserved model IDs - -Drafts, pending messages, history, and automation definitions keep a selection after its source goes away, and a chat keeps them when it moves to another session. Once the host publishes a model ID for a registered source, that ID is bound to that source and its upstream model for as long as the host keeps state, including after the source is removed and across a restart. The host MUST NOT resolve the ID to anything else. It MAY publish the ID again only when the same source comes back offering the same upstream model. A model's upstream identity is the endpoint the agent sends its requests to plus that endpoint's model identifier. A change to `provider` or `format`, or a definition change that moves the endpoint, makes it a different upstream model, so the host mints new IDs, even when a different client made the change. - -A host SHOULD derive each model's ID deterministically from the source (its `id`, `provider`, and `format`), the endpoint, and the endpoint's model identifier, for example with a hash. The same model then gets the same ID when its source is registered again or the host restarts, without a stored table, and a moved endpoint gets a new one. +A source's `retention` decides what happens when its last contributing client disconnects and doesn't return within a grace period the host chooses: -#### Automations +- `contributingClient`, the default: the host stops new work on the source, lets running turns finish, and then removes it. +- `host`: the source stays until a client removes it or host policy expires it. -An automation may name a registered source's model when the source has `host` retention, or was registered by the host. The host SHOULD reject an automation create or update that names a model from a `contributingClient`-retained source, because the automation would outlive the source. If the source isn't `ready` when a run starts, the run fails through the automation run lifecycle. +The host SHOULD reject an automation that names a model from a `contributingClient`-retained source, because the automation would outlive the source. ### Paginating the catalogue @@ -243,7 +153,7 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | | `root/modelSourceSet` | Server / Client | Adds, re-registers, or updates a source in `modelSources` by `id`, including its definition | | `root/modelSourceRemoved` | Server / Client | Removes a source by `id` | -| `root/modelSourceStateChanged` | Server | Sets a registration's host-reported fields. A no-op for an unknown `id` | +| `root/modelSourceStateChanged` | Server | Sets a source's host-reported fields. A no-op for an unknown `id` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index c4cc7676c..aedb86c49 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -129,14 +129,14 @@ }, "RootModelSourceSetAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client registers a source with its `format`, `definition`, and `nonce`,\nand without any host-reported field. The host learns which client\nregistered it from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceSet" }, "modelSource": { "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`, including its\n`definition`, without host-reported fields." + "description": "The model source to add or update, matched by `id`." } }, "required": [ @@ -2890,7 +2890,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." }, "resource_name": { "type": "string", @@ -3236,7 +3236,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -3350,7 +3350,7 @@ "items": { "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." + "description": "Model sources on this host, keyed by `id`: the sources agents offer\nmodels from, including ones clients registered. Clients use them to\nlabel and group each agent's {@link AgentInfo.models}.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -3401,13 +3401,6 @@ "capabilities": { "$ref": "#/$defs/AgentCapabilities", "description": "Static capabilities the agent advertises about itself. Clients use these\nto gate features (multi-chat, fork) instead of switching on the provider\nid." - }, - "modelSources": { - "type": "array", - "items": { - "$ref": "#/$defs/ModelSourceInfo" - }, - "description": "Sources this agent offers models from. Clients use them to label and\ngroup {@link models}. A source may have no models." } }, "required": [ @@ -3463,24 +3456,6 @@ } } }, - "ModelSourceInfo": { - "type": "object", - "description": "A source that an agent provider offers models from, such as a service or\nsubscription.", - "properties": { - "id": { - "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -3531,7 +3506,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -3582,7 +3557,7 @@ "properties": { "format": { "type": "string", - "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + "description": "A {@link ModelSource.format} value." } }, "required": [ @@ -3591,19 +3566,19 @@ }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", - "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + "description": "Host-unique ID, chosen by whoever registers the source. Also the\n{@link SessionModelInfo.modelSourceId} of its models." }, "provider": { "type": "string", - "description": "Agent provider whose agent reads the definition and serves the models." + "description": "Agent provider whose agent serves the source's models." }, "displayName": { "type": "string", - "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name." }, "icons": { "type": "array", @@ -3614,16 +3589,16 @@ }, "format": { "type": "string", - "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." }, "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." }, "nonce": { "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -3635,11 +3610,11 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." }, "_meta": { "type": "object", @@ -3650,10 +3625,7 @@ "required": [ "id", "provider", - "displayName", - "format", - "definition", - "nonce" + "displayName" ] }, "ModelSourceStartingState": { diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 6c5a2d851..801d1d7c0 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1055,14 +1055,14 @@ }, "ModelSourceAuthenticateTarget": { "type": "object", - "description": "A registered model source.\n\nStability: 1.0 - Early development.", + "description": "A registered model source. The host applies the credential only to that\nsource, and publishes the request's `accountId` as the source's\n`ModelSource.accountId`.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "modelSource" }, "modelSourceId": { "type": "string", - "description": "The registration's `ModelSource.id`." + "description": "The source's `ModelSource.id`." } }, "required": [ @@ -1072,7 +1072,7 @@ }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSource.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a Bearer token for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSource.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the source's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command.", "properties": { "channel": { "type": "string", @@ -1091,11 +1091,11 @@ }, "token": { "type": "string", - "description": "Bearer token obtained from the resource's authorization server, or an\nopaque secret for a model source. An empty string revokes the credential." + "description": "Bearer token obtained from the resource's authorization server" }, "expiresIn": { "type": "integer", - "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nAn API key omits this field.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", + "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", "minimum": 1 }, "scopes": { @@ -1103,15 +1103,15 @@ "items": { "type": "string" }, - "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken. Scopes apply to OAuth-issued tokens only." + "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken." }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). A\ndelivery replaces whatever credential the host holds for the source. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). See\n[Model source credentials](/specification/authentication#model-source-credentials).\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", - "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.\n\nWith a `modelSource` target, clients SHOULD include it when delivering a\ncredential and omit it when revoking one, and the host publishes it as\nthe source's `ModelSource.accountId`. It MUST NOT be derived from the\nsecret. For an API key with no account of its own, a client uses an ID\nthat changes whenever the user replaces the key.", + "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.", "minLength": 1 } }, @@ -2210,7 +2210,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." }, "resource_name": { "type": "string", @@ -2556,7 +2556,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -2670,7 +2670,7 @@ "items": { "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." + "description": "Model sources on this host, keyed by `id`: the sources agents offer\nmodels from, including ones clients registered. Clients use them to\nlabel and group each agent's {@link AgentInfo.models}.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -2721,13 +2721,6 @@ "capabilities": { "$ref": "#/$defs/AgentCapabilities", "description": "Static capabilities the agent advertises about itself. Clients use these\nto gate features (multi-chat, fork) instead of switching on the provider\nid." - }, - "modelSources": { - "type": "array", - "items": { - "$ref": "#/$defs/ModelSourceInfo" - }, - "description": "Sources this agent offers models from. Clients use them to label and\ngroup {@link models}. A source may have no models." } }, "required": [ @@ -2783,24 +2776,6 @@ } } }, - "ModelSourceInfo": { - "type": "object", - "description": "A source that an agent provider offers models from, such as a service or\nsubscription.", - "properties": { - "id": { - "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -2851,7 +2826,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -2902,7 +2877,7 @@ "properties": { "format": { "type": "string", - "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + "description": "A {@link ModelSource.format} value." } }, "required": [ @@ -2911,19 +2886,19 @@ }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", - "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + "description": "Host-unique ID, chosen by whoever registers the source. Also the\n{@link SessionModelInfo.modelSourceId} of its models." }, "provider": { "type": "string", - "description": "Agent provider whose agent reads the definition and serves the models." + "description": "Agent provider whose agent serves the source's models." }, "displayName": { "type": "string", - "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name." }, "icons": { "type": "array", @@ -2934,16 +2909,16 @@ }, "format": { "type": "string", - "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." }, "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." }, "nonce": { "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -2955,11 +2930,11 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." }, "_meta": { "type": "object", @@ -2970,10 +2945,7 @@ "required": [ "id", "provider", - "displayName", - "format", - "definition", - "nonce" + "displayName" ] }, "ModelSourceStartingState": { @@ -8576,14 +8548,14 @@ }, "RootModelSourceSetAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client registers a source with its `format`, `definition`, and `nonce`,\nand without any host-reported field. The host learns which client\nregistered it from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceSet" }, "modelSource": { "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`, including its\n`definition`, without host-reported fields." + "description": "The model source to add or update, matched by `id`." } }, "required": [ diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 381d72b27..d85ebc8bd 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -195,7 +195,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." }, "resource_name": { "type": "string", @@ -541,7 +541,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -655,7 +655,7 @@ "items": { "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." + "description": "Model sources on this host, keyed by `id`: the sources agents offer\nmodels from, including ones clients registered. Clients use them to\nlabel and group each agent's {@link AgentInfo.models}.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -706,13 +706,6 @@ "capabilities": { "$ref": "#/$defs/AgentCapabilities", "description": "Static capabilities the agent advertises about itself. Clients use these\nto gate features (multi-chat, fork) instead of switching on the provider\nid." - }, - "modelSources": { - "type": "array", - "items": { - "$ref": "#/$defs/ModelSourceInfo" - }, - "description": "Sources this agent offers models from. Clients use them to label and\ngroup {@link models}. A source may have no models." } }, "required": [ @@ -768,24 +761,6 @@ } } }, - "ModelSourceInfo": { - "type": "object", - "description": "A source that an agent provider offers models from, such as a service or\nsubscription.", - "properties": { - "id": { - "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -836,7 +811,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -887,7 +862,7 @@ "properties": { "format": { "type": "string", - "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + "description": "A {@link ModelSource.format} value." } }, "required": [ @@ -896,19 +871,19 @@ }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", - "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + "description": "Host-unique ID, chosen by whoever registers the source. Also the\n{@link SessionModelInfo.modelSourceId} of its models." }, "provider": { "type": "string", - "description": "Agent provider whose agent reads the definition and serves the models." + "description": "Agent provider whose agent serves the source's models." }, "displayName": { "type": "string", - "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name." }, "icons": { "type": "array", @@ -919,16 +894,16 @@ }, "format": { "type": "string", - "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." }, "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." }, "nonce": { "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -940,11 +915,11 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." }, "_meta": { "type": "object", @@ -955,10 +930,7 @@ "required": [ "id", "provider", - "displayName", - "format", - "definition", - "nonce" + "displayName" ] }, "ModelSourceStartingState": { @@ -7487,14 +7459,14 @@ }, "ModelSourceAuthenticateTarget": { "type": "object", - "description": "A registered model source.\n\nStability: 1.0 - Early development.", + "description": "A registered model source. The host applies the credential only to that\nsource, and publishes the request's `accountId` as the source's\n`ModelSource.accountId`.\n\nStability: 1.0 - Early development.", "properties": { "kind": { "const": "modelSource" }, "modelSourceId": { "type": "string", - "description": "The registration's `ModelSource.id`." + "description": "The source's `ModelSource.id`." } }, "required": [ @@ -7504,7 +7476,7 @@ }, "AuthenticateParams": { "type": "object", - "description": "Pushes a credential for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSource.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the registration's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command. A model source's token is instead an\nopaque secret, such as an API key.", + "description": "Pushes a Bearer token for a protected resource. The `resource` field MUST\nmatch a protected-resource identifier the client has discovered from the\nserver — whether declared statically in `AgentInfo.protectedResources`,\nor discovered dynamically from a live `McpServerAuthRequiredState.resource`\nor `ToolCallAuthRequiredState.auth.resource` (each surfaced only once the\ncorresponding MCP server or tool call actually challenges for auth), or\nfrom a registered model source's `ModelSource.credentialResource`.\nServers MUST accept any `resource` value they have themselves advertised\nthrough one of these mechanisms, subject to the `target` rules. A\n`modelSource` target takes only the source's current\n`credentialResource.resource`.\n\nTokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)\n(Bearer Token Usage) semantics. The client obtains the token from the\nauthorization server(s) listed in the resource's metadata and pushes it\nto the server via this command.", "properties": { "channel": { "type": "string", @@ -7523,11 +7495,11 @@ }, "token": { "type": "string", - "description": "Bearer token obtained from the resource's authorization server, or an\nopaque secret for a model source. An empty string revokes the credential." + "description": "Bearer token obtained from the resource's authorization server" }, "expiresIn": { "type": "integer", - "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nAn API key omits this field.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", + "description": "The access token's remaining lifetime, in seconds, when this\n`authenticate` request is sent. This corresponds to `expires_in` in an\nOAuth 2.0 token response (RFC 6749 section 5.1).\n\nIf the client retained the original token response, it MUST subtract the\nelapsed time before forwarding this value. Omit this field when the\nauthorization server did not supply an expiry or the expiry is otherwise\nunknown. When supplied, the value MUST be a positive integer.\n\nThis field is irrelevant when `token` is empty to revoke authentication\nand SHOULD be omitted in that case.", "minimum": 1 }, "scopes": { @@ -7535,15 +7507,15 @@ "items": { "type": "string" }, - "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken. Scopes apply to OAuth-issued tokens only." + "description": "OAuth scopes the token grants, when known. Lets the server determine\nwhether a specific challenge — e.g. the `requiredScopes` on a live\n`McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is\nsatisfied without decoding the (opaque, server-specific) token itself.\nOmit when the client doesn't track granted scopes separately from the\ntoken." }, "target": { "$ref": "#/$defs/AuthenticateTarget", - "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). A\ndelivery replaces whatever credential the host holds for the source. See\n[Model source credentials](/specification/authentication#model-source-credentials)\nfor its rules.\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." + "description": "Optional consumer of the token. Clients SHOULD include this when answering\na specific MCP server's `McpServerAuthRequiredState` or\n`ToolCallAuthRequiredState` challenge, MUST include it when delivering a\nregistered model source's credential, and omit it for provider-level\nresources (`AgentInfo.protectedResources` or `AuthRequired` -32007 data).\n\nFor an `mcpServer` target, the host MUST apply the token only to that MCP\nserver in that session, never to sibling servers, other sessions, or\nagent-level resources, even if they share the resource and scopes.\n`resource` MUST still equal that server's advertised\n`McpAuthRequirement.resource.resource`. The host MUST reject an unknown\nsession or customization, or a customization that is not an MCP server,\nwith `InvalidParams` (-32602).\n\nA registered model source takes its credential only through a\n`modelSource` target, and the host rejects an untargeted `resource` that\nmatches only model source challenges with `InvalidParams` (-32602). See\n[Model source credentials](/specification/authentication#model-source-credentials).\n\nWithout a target, resource/scope matching is unchanged; the token may\nsatisfy every matching pending challenge. Older hosts ignore this field." }, "accountId": { "type": "string", - "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.\n\nWith a `modelSource` target, clients SHOULD include it when delivering a\ncredential and omit it when revoking one, and the host publishes it as\nthe source's `ModelSource.accountId`. It MUST NOT be derived from the\nsecret. For an API key with no account of its own, a client uses an ID\nthat changes whenever the user replaces the key.", + "description": "Optional identifier for the client's selected account, sent alongside the token.\nHosts can compare `accountId` values to detect when the underlying account has changed.\nHosts MUST treat `accountId` as an opaque string.\nsee {@link /specification/authentication#account-selection-hints | Account selection hints}.", "minLength": 1 } }, @@ -9838,14 +9810,14 @@ }, "RootModelSourceSetAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client dispatches this without any host-reported field. The host learns\nwhich client registered the source from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client registers a source with its `format`, `definition`, and `nonce`,\nand without any host-reported field. The host learns which client\nregistered it from the envelope's `origin`.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceSet" }, "modelSource": { "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`, including its\n`definition`, without host-reported fields." + "description": "The model source to add or update, matched by `id`." } }, "required": [ diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 1a39ecada..f24664280 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -497,7 +497,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." }, "resource_name": { "type": "string", @@ -843,7 +843,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -957,7 +957,7 @@ "items": { "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." + "description": "Model sources on this host, keyed by `id`: the sources agents offer\nmodels from, including ones clients registered. Clients use them to\nlabel and group each agent's {@link AgentInfo.models}.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -1008,13 +1008,6 @@ "capabilities": { "$ref": "#/$defs/AgentCapabilities", "description": "Static capabilities the agent advertises about itself. Clients use these\nto gate features (multi-chat, fork) instead of switching on the provider\nid." - }, - "modelSources": { - "type": "array", - "items": { - "$ref": "#/$defs/ModelSourceInfo" - }, - "description": "Sources this agent offers models from. Clients use them to label and\ngroup {@link models}. A source may have no models." } }, "required": [ @@ -1070,24 +1063,6 @@ } } }, - "ModelSourceInfo": { - "type": "object", - "description": "A source that an agent provider offers models from, such as a service or\nsubscription.", - "properties": { - "id": { - "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -1138,7 +1113,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -1189,7 +1164,7 @@ "properties": { "format": { "type": "string", - "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + "description": "A {@link ModelSource.format} value." } }, "required": [ @@ -1198,19 +1173,19 @@ }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", - "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + "description": "Host-unique ID, chosen by whoever registers the source. Also the\n{@link SessionModelInfo.modelSourceId} of its models." }, "provider": { "type": "string", - "description": "Agent provider whose agent reads the definition and serves the models." + "description": "Agent provider whose agent serves the source's models." }, "displayName": { "type": "string", - "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name." }, "icons": { "type": "array", @@ -1221,16 +1196,16 @@ }, "format": { "type": "string", - "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." }, "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." }, "nonce": { "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -1242,11 +1217,11 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." }, "_meta": { "type": "object", @@ -1257,10 +1232,7 @@ "required": [ "id", "provider", - "displayName", - "format", - "definition", - "nonce" + "displayName" ] }, "ModelSourceStartingState": { diff --git a/schema/state.schema.json b/schema/state.schema.json index 38ec3073f..9fed3fdea 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -106,7 +106,7 @@ "properties": { "resource": { "type": "string", - "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`).\nA registered model source's endpoint may use any scheme the agent\nsupports, because nothing fetches it." + "description": "REQUIRED. The protected resource's resource identifier, a URL using the\n`https` scheme with no fragment component (e.g. `\"https://api.github.com\"`)." }, "resource_name": { "type": "string", @@ -452,7 +452,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a registered model source the turn uses\n can't serve it, for example because its credential is missing,\n expired, rejected, or revoked, or the source was removed. The error\n part is resumable. See\n [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." }, "message": { "type": "string", @@ -566,7 +566,7 @@ "items": { "$ref": "#/$defs/ModelSource" }, - "description": "Model sources registered on this host, keyed by `id`. When one is\nready, it also appears in its agent's {@link AgentInfo.modelSources}\ncatalog.\n\nStability: 1.0 - Early development." + "description": "Model sources on this host, keyed by `id`: the sources agents offer\nmodels from, including ones clients registered. Clients use them to\nlabel and group each agent's {@link AgentInfo.models}.\n\nStability: 1.0 - Early development." }, "_meta": { "type": "object", @@ -617,13 +617,6 @@ "capabilities": { "$ref": "#/$defs/AgentCapabilities", "description": "Static capabilities the agent advertises about itself. Clients use these\nto gate features (multi-chat, fork) instead of switching on the provider\nid." - }, - "modelSources": { - "type": "array", - "items": { - "$ref": "#/$defs/ModelSourceInfo" - }, - "description": "Sources this agent offers models from. Clients use them to label and\ngroup {@link models}. A source may have no models." } }, "required": [ @@ -679,24 +672,6 @@ } } }, - "ModelSourceInfo": { - "type": "object", - "description": "A source that an agent provider offers models from, such as a service or\nsubscription.", - "properties": { - "id": { - "type": "string", - "description": "Model source identifier, unique within the agent's\n{@link AgentInfo.modelSources}. For a registered model source, this is\nthe {@link ModelSource.id}. A source is registered when\n{@link RootState.modelSources} has an entry with this `id`\nwhose `provider` is the agent." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -747,7 +722,7 @@ }, "modelSourceId": { "type": "string", - "description": "The source this model comes from. MUST match a {@link ModelSourceInfo.id}\nin the agent's {@link AgentInfo.modelSources}. For a model from a\nregistered model source, this is the {@link ModelSource.id}.\nAn agent's own sources use it too, so it doesn't by itself mark a\nregistered source." + "description": "The source this model comes from: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -798,7 +773,7 @@ "properties": { "format": { "type": "string", - "description": "A recognized {@link ModelSource.format} value, or a namespaced name for\na format the agent defines itself." + "description": "A {@link ModelSource.format} value." } }, "required": [ @@ -807,19 +782,19 @@ }, "ModelSource": { "type": "object", - "description": "A model source registered on this host by a client, or by the host itself.\nNothing here is a credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", - "description": "Host-unique ID, chosen by whoever registers the source. Also the\nsource's {@link ModelSourceInfo.id} in the agent's catalog, and the\n{@link SessionModelInfo.modelSourceId} of its models." + "description": "Host-unique ID, chosen by whoever registers the source. Also the\n{@link SessionModelInfo.modelSourceId} of its models." }, "provider": { "type": "string", - "description": "Agent provider whose agent reads the definition and serves the models." + "description": "Agent provider whose agent serves the source's models." }, "displayName": { "type": "string", - "description": "Human-readable name, published as {@link ModelSourceInfo.displayName}." + "description": "Human-readable name." }, "icons": { "type": "array", @@ -830,16 +805,16 @@ }, "format": { "type": "string", - "description": "The definition's format: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Recognized values\ninclude:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as\n OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nAgents MAY read other formats, named with a namespace such as\n`example.com/model-source@1` so they don't collide." + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." }, "definition": { "type": "object", "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it, and AHP doesn't validate it. Every client can\nread it, so it MUST NOT contain a credential.\n\nSuggested shapes for the recognized formats. Agents MAY read more\nmembers, and MAY discover models when `models` is absent.\n\n- `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }`\n- `anthropic`: `{ endpoint, models? }`\n- `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each\n deployment name as a model `id`\n- `gemini`: `{ endpoint, models? }`\n\n`endpoint` is the API's base URI, such as `https://api.example.com/v1`.\nEach `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?,\nsupportsVision?, supportsTools? }`, named as in {@link SessionModelInfo},\nwhere `id` is the endpoint's own model identifier." + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." }, "nonce": { "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Reducers compare it, instead of the\ndefinition, to tell an update from a re-registration of the same\ndefinition." + "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." }, "retention": { "$ref": "#/$defs/ModelSourceRetentionPolicy", @@ -851,11 +826,11 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint the credential is for. Present\nwhenever the source takes a credential, in every state, so any client\ncan deliver, rotate, or revoke one. Absent for a source that needs no\ncredential. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it.\n`credentialResource.resource_name` labels the prompt (for example\n\"OpenRouter API key\"). A source that accepts OAuth access tokens\nadvertises `authorization_servers` and `scopes_supported`. A source that\ntakes a user-supplied secret omits them." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} the client sent with the\ncredential the host most recently accepted. While the state is\n`starting` or `ready`, the host holds that credential. While it's\n`authRequired`, the `reason` says what happened to it. Absent until the\nhost accepts a credential sent with an `accountId`. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." }, "_meta": { "type": "object", @@ -866,10 +841,7 @@ "required": [ "id", "provider", - "displayName", - "format", - "definition", - "nonce" + "displayName" ] }, "ModelSourceStartingState": { diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index 8851af58a..1a46b8aa2 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -803,7 +803,6 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'ModelSourceAuthRequirement' }, { name: 'ModelSourceAuthRequiredState' }, { name: 'ModelSourceErrorState' }, - { name: 'ModelSourceInfo' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, { name: 'AgentSelection' }, diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index 06e2d6159..69232e100 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -787,7 +787,6 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'ModelSourceAuthRequirement' }, { name: 'ModelSourceAuthRequiredState' }, { name: 'ModelSourceErrorState' }, - { name: 'ModelSourceInfo' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, { name: 'AgentSelection' }, @@ -2283,6 +2282,8 @@ const ( \tErrorCodeAlreadyExists int32 = -32010 \t// ErrorCodeTcpConnectionOpenFailed indicates that the host could not open a TCP connection. \tErrorCodeTcpConnectionOpenFailed int32 = -32012 +\t// ErrorCodeModelSourceUnavailable indicates that a request selects a model whose registered model source can't serve it. +\tErrorCodeModelSourceUnavailable int32 = -32013 ) // AhpErrorCode is the type alias used by AHP application error codes. diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index e71e00cbc..23d217a9a 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1032,7 +1032,7 @@ const STATE_STRUCTS = [ 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', - 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', + 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', 'BackgroundShellWork', 'BackgroundSubagentWork', 'CanvasReference', 'CanvasState', @@ -2276,6 +2276,8 @@ function generateErrorsFile(project: Project): string { lines.push(' const val PERMISSION_DENIED: Int = -32009'); lines.push(' /** The target resource already exists and the operation does not allow overwriting */'); lines.push(' const val ALREADY_EXISTS: Int = -32010'); + lines.push(" /** A request selects a model whose registered model source can't serve it */"); + lines.push(' const val MODEL_SOURCE_UNAVAILABLE: Int = -32013'); lines.push('}'); lines.push(''); diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index c24966460..9e5167c67 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -888,7 +888,6 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'ModelSourceAuthRequirement' }, { name: 'ModelSourceAuthRequiredState', omitDiscriminants: true }, { name: 'ModelSourceErrorState', omitDiscriminants: true }, - { name: 'ModelSourceInfo' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, { name: 'AgentSelection' }, @@ -2330,6 +2329,8 @@ pub mod ahp_error_codes { pub const CONFLICT: i32 = -32011; /// The host could not open the requested TCP connection. pub const TCP_CONNECTION_OPEN_FAILED: i32 = -32012; + /// A request selects a model whose registered model source can't serve it. + pub const MODEL_SOURCE_UNAVAILABLE: i32 = -32013; } /// Type alias: AHP application error code. diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index a1aa51a39..995153bfd 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -755,7 +755,7 @@ const STATE_STRUCTS = [ 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', - 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', + 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', 'BackgroundShellWork', 'BackgroundSubagentWork', 'SessionChatInputRequest', 'SessionToolConfirmationRequest', 'SessionToolClientExecutionRequest', @@ -2248,6 +2248,8 @@ function generateErrorsFile(project: Project): string { lines.push(' public static let permissionDenied = -32009'); lines.push(' /// The target resource already exists and the operation does not allow overwriting'); lines.push(' public static let alreadyExists = -32010'); + lines.push(" /// A request selects a model whose registered model source can't serve it"); + lines.push(' public static let modelSourceUnavailable = -32013'); lines.push('}'); lines.push(''); diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 048a4a4a0..d1e6d77b6 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -79,20 +79,18 @@ export interface RootConfigChangedAction { * host-reported fields are absent until the host reports again with * {@link RootModelSourceStateChangedAction}. * - * A client dispatches this without any host-reported field. The host learns - * which client registered the source from the envelope's `origin`. + * A client registers a source with its `format`, `definition`, and `nonce`, + * and without any host-reported field. The host learns which client + * registered it from the envelope's `origin`. * * @category Root Actions * @stability 1.0 * @clientDispatchable - * @see {@link /specification/root-channel#model-source-registry | Model source registry} + * @see {@link /specification/root-channel#registering-sources | Registering sources} */ export interface RootModelSourceSetAction { type: ActionType.RootModelSourceSet; - /** - * The model source to add or update, matched by `id`, including its - * `definition`, without host-reported fields. - */ + /** The model source to add or update, matched by `id`. */ modelSource: ModelSource; } @@ -103,7 +101,7 @@ export interface RootModelSourceSetAction { * @category Root Actions * @stability 1.0 * @clientDispatchable - * @see {@link /specification/root-channel#model-source-registry | Model source registry} + * @see {@link /specification/root-channel#registering-sources | Registering sources} */ export interface RootModelSourceRemovedAction { type: ActionType.RootModelSourceRemoved; @@ -118,7 +116,7 @@ export interface RootModelSourceRemovedAction { * * @category Root Actions * @stability 1.0 - * @see {@link /specification/root-channel#model-source-registry | Model source registry} + * @see {@link /specification/root-channel#status-and-catalog | Status and catalog} */ export interface RootModelSourceStateChangedAction { type: ActionType.RootModelSourceStateChanged; diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 77512aaff..1db08494e 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -45,12 +45,12 @@ export interface RootState { /** Agent host configuration schema and current values */ config?: RootConfigState; /** - * Model sources registered on this host, keyed by `id`. When one is - * ready, it also appears in its agent's {@link AgentInfo.modelSources} - * catalog. + * Model sources on this host, keyed by `id`: the sources agents offer + * models from, including ones clients registered. Clients use them to + * label and group each agent's {@link AgentInfo.models}. * * @stability 1.0 - * @see {@link /specification/root-channel#model-source-registry | Model source registry} + * @see {@link /specification/root-channel#model-sources | Model sources} */ modelSources?: ModelSource[]; /** @@ -105,13 +105,6 @@ export interface AgentInfo { * id. */ capabilities?: AgentCapabilities; - /** - * Sources this agent offers models from. Clients use them to label and - * group {@link models}. A source may have no models. - * - * @see {@link /specification/root-channel#model-sources | Model sources} - */ - modelSources?: ModelSourceInfo[]; } /** @@ -149,7 +142,7 @@ export interface AgentCapabilities { * definition formats. * * @stability 1.0 - * @see {@link /specification/root-channel#model-source-registry | Model source registry} + * @see {@link /specification/root-channel#registering-sources | Registering sources} */ modelSourceRegistration?: ModelSourceRegistrationCapability; } @@ -221,25 +214,6 @@ export interface MultipleWorkingDirectoriesCapability { primaryReplacement?: boolean; } -/** - * A source that an agent provider offers models from, such as a service or - * subscription. - * - * @category Root State - */ -export interface ModelSourceInfo { - /** - * Model source identifier, unique within the agent's - * {@link AgentInfo.modelSources}. For a registered model source, this is - * the {@link ModelSource.id}. A source is registered when - * {@link RootState.modelSources} has an entry with this `id` - * whose `provider` is the agent. - */ - id: string; - /** Human-readable name */ - displayName: string; -} - /** * @category Root State */ @@ -250,7 +224,7 @@ export interface SessionModelInfo { * each entry its own ID. A host SHOULD keep a model's ID across catalog * updates and MUST NOT reuse an ID for a different source or upstream model. * - * @see {@link /specification/root-channel#reserved-model-ids | Reserved model IDs} + * @see {@link /specification/root-channel#model-sources | Model sources} */ id: string; /** Agent provider that owns this model. Matches {@link AgentInfo.provider}. */ @@ -291,11 +265,9 @@ export interface SessionModelInfo { */ vendor?: string; /** - * The source this model comes from. MUST match a {@link ModelSourceInfo.id} - * in the agent's {@link AgentInfo.modelSources}. For a model from a - * registered model source, this is the {@link ModelSource.id}. - * An agent's own sources use it too, so it doesn't by itself mark a - * registered source. + * The source this model comes from: the {@link ModelSource.id} of an entry + * in {@link RootState.modelSources} whose `provider` is this model's + * {@link provider}. */ modelSourceId?: string; } @@ -319,14 +291,13 @@ export interface ModelSelection { config?: Record; } -// ─── Model Source Registry ─────────────────────────────────────────────────── +// ─── Model Sources ─────────────────────────────────────────────────────────── /** * Options for the {@link AgentCapabilities.modelSourceRegistration} capability. * * @category Root State * @stability 1.0 - * @preserveUnknownMembers */ export interface ModelSourceRegistrationCapability { /** Definition formats the agent reads, most preferred first. */ @@ -339,80 +310,70 @@ export interface ModelSourceRegistrationCapability { * * @category Root State * @stability 1.0 - * @preserveUnknownMembers */ export interface ModelSourceFormatInfo { - /** - * A recognized {@link ModelSource.format} value, or a namespaced name for - * a format the agent defines itself. - */ + /** A {@link ModelSource.format} value. */ format: string; } /** - * A model source registered on this host by a client, or by the host itself. - * Nothing here is a credential. + * A source that an agent provider offers models from, such as a service, + * subscription, or endpoint. The host lists the sources an agent provides + * itself, and clients can register more with a definition. Nothing here is + * a credential. * * @category Root State * @stability 1.0 * @preserveUnknownMembers - * @see {@link /specification/root-channel#model-source-registry | Model source registry} + * @see {@link /specification/root-channel#model-sources | Model sources} */ export interface ModelSource { /** * Host-unique ID, chosen by whoever registers the source. Also the - * source's {@link ModelSourceInfo.id} in the agent's catalog, and the * {@link SessionModelInfo.modelSourceId} of its models. */ id: string; - /** Agent provider whose agent reads the definition and serves the models. */ + /** Agent provider whose agent serves the source's models. */ provider: string; - /** Human-readable name, published as {@link ModelSourceInfo.displayName}. */ + /** Human-readable name. */ displayName: string; /** Icons for UI display. */ icons?: Icon[]; /** - * The definition's format: the `format` of one of the agent's - * {@link ModelSourceRegistrationCapability.formats}. Recognized values - * include: + * The format of `definition`: the `format` of one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. Present on a + * registered source. + * + * Agents choose the formats they read. Some may read these common names: * - * - `'openaiCompatible'`: an endpoint that implements OpenAI's API, such as - * OpenAI, OpenRouter, xAI, or a local server like Ollama or LM Studio. + * - `'openaiCompatible'`: an endpoint that implements OpenAI's API. * - `'anthropic'`: an endpoint that implements Anthropic's Messages API. * - `'azureOpenai'`: an Azure OpenAI deployment. * - `'gemini'`: Google's Gemini API. * - * Agents MAY read other formats, named with a namespace such as - * `example.com/model-source@1` so they don't collide. + * Other formats are named with a namespace, such as + * `example.com/model-source@1`, so they don't collide. */ - format: string; + format?: string; /** * How to reach the source, in `format`: endpoint, wire API, models, and so - * on. The agent reads it, and AHP doesn't validate it. Every client can - * read it, so it MUST NOT contain a credential. - * - * Suggested shapes for the recognized formats. Agents MAY read more - * members, and MAY discover models when `models` is absent. + * on. The agent reads it. Every client can read it, so it MUST NOT contain + * a credential. Present on a registered source. * - * - `openaiCompatible`: `{ endpoint, wireApi?: 'chatCompletions' | 'responses', models? }` - * - `anthropic`: `{ endpoint, models? }` - * - `azureOpenai`: `{ endpoint, apiVersion?, models? }`, with each - * deployment name as a model `id` - * - `gemini`: `{ endpoint, models? }` - * - * `endpoint` is the API's base URI, such as `https://api.example.com/v1`. - * Each `models` entry is `{ id, name?, maxContextWindow?, maxOutputTokens?, - * supportsVision?, supportsTools? }`, named as in {@link SessionModelInfo}, - * where `id` is the endpoint's own model identifier. + * An agent that reads one of the common format names might expect a shape + * like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + * the API's base URI and each `models` entry is `{ id, name?, + * maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + * named as in {@link SessionModelInfo}. */ - definition: Record; + definition?: Record; /** * Opaque version token for `definition`, such as a hash of it, chosen by - * whoever registers the source. Reducers compare it, instead of the - * definition, to tell an update from a re-registration of the same - * definition. + * whoever registers the source. Present on a registered source. Reducers + * compare it, instead of the definition, to tell an update from a + * re-registration of the same definition. */ - nonce: string; + nonce?: string; /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ retention?: ModelSourceRetentionPolicy; /** @@ -422,29 +383,21 @@ export interface ModelSource { */ state?: ModelSourceState; /** - * RFC 9728 metadata for the endpoint the credential is for. Present - * whenever the source takes a credential, in every state, so any client - * can deliver, rotate, or revoke one. Absent for a source that needs no - * credential. Set with `state`. + * RFC 9728 metadata for the endpoint a registered source's credential is + * for. Present whenever the source takes a credential, in every state, so + * any client can deliver or rotate one. Set with `state`. * * `credentialResource.resource` is the endpoint URL as the definition * names it, in any scheme the agent supports (for example * `http://localhost:11434/v1`). It's the value a client passes back as * `authenticate({ resource })`, and nothing fetches it. - * `credentialResource.resource_name` labels the prompt (for example - * "OpenRouter API key"). A source that accepts OAuth access tokens - * advertises `authorization_servers` and `scopes_supported`. A source that - * takes a user-supplied secret omits them. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ credentialResource?: ProtectedResourceMetadata; /** - * The {@link AuthenticateParams.accountId} the client sent with the - * credential the host most recently accepted. While the state is - * `starting` or `ready`, the host holds that credential. While it's - * `authRequired`, the `reason` says what happened to it. Absent until the - * host accepts a credential sent with an `accountId`. Set with `state`. + * The {@link AuthenticateParams.accountId} sent with the credential the + * host most recently accepted. Set with `state`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ @@ -495,7 +448,6 @@ export const enum ModelSourceStatus { * * @category Root State * @stability 1.0 - * @preserveUnknownMembers */ export interface ModelSourceStartingState { kind: ModelSourceStatus.Starting; @@ -508,7 +460,6 @@ export interface ModelSourceStartingState { * * @category Root State * @stability 1.0 - * @preserveUnknownMembers */ export interface ModelSourceReadyState { kind: ModelSourceStatus.Ready; @@ -544,7 +495,6 @@ export const enum ModelSourceAuthRequiredReason { * * @category Root State * @stability 1.0 - * @preserveUnknownMembers */ export interface ModelSourceAuthRequirement { /** Why a credential is needed. */ @@ -563,7 +513,6 @@ export interface ModelSourceAuthRequirement { * * @category Root State * @stability 1.0 - * @preserveUnknownMembers * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ export interface ModelSourceAuthRequiredState extends ModelSourceAuthRequirement { @@ -575,7 +524,6 @@ export interface ModelSourceAuthRequiredState extends ModelSourceAuthRequirement * * @category Root State * @stability 1.0 - * @preserveUnknownMembers */ export interface ModelSourceErrorState { kind: ModelSourceStatus.Error; diff --git a/types/common/commands.ts b/types/common/commands.ts index 5accb197e..587f9ac75 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1484,7 +1484,9 @@ export interface McpServerAuthenticateTarget { } /** - * A registered model source. + * A registered model source. The host applies the credential only to that + * source, and publishes the request's `accountId` as the source's + * `ModelSource.accountId`. * * @category Commands * @stability 1.0 @@ -1492,7 +1494,7 @@ export interface McpServerAuthenticateTarget { */ export interface ModelSourceAuthenticateTarget { kind: AuthenticateTargetKind.ModelSource; - /** The registration's `ModelSource.id`. */ + /** The source's `ModelSource.id`. */ modelSourceId: string; } @@ -1507,7 +1509,7 @@ export type AuthenticateTarget = | ModelSourceAuthenticateTarget; /** - * Pushes a credential for a protected resource. The `resource` field MUST + * Pushes a Bearer token for a protected resource. The `resource` field MUST * match a protected-resource identifier the client has discovered from the * server — whether declared statically in `AgentInfo.protectedResources`, * or discovered dynamically from a live `McpServerAuthRequiredState.resource` @@ -1516,14 +1518,13 @@ export type AuthenticateTarget = * from a registered model source's `ModelSource.credentialResource`. * Servers MUST accept any `resource` value they have themselves advertised * through one of these mechanisms, subject to the `target` rules. A - * `modelSource` target takes only the registration's current + * `modelSource` target takes only the source's current * `credentialResource.resource`. * * Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750) * (Bearer Token Usage) semantics. The client obtains the token from the * authorization server(s) listed in the resource's metadata and pushes it - * to the server via this command. A model source's token is instead an - * opaque secret, such as an API key. + * to the server via this command. * * @category Commands * @method authenticate @@ -1555,10 +1556,7 @@ export interface AuthenticateParams extends BaseParams { * or `ModelSource.credentialResource`. */ resource: string; - /** - * Bearer token obtained from the resource's authorization server, or an - * opaque secret for a model source. An empty string revokes the credential. - */ + /** Bearer token obtained from the resource's authorization server */ token: string; /** * The access token's remaining lifetime, in seconds, when this @@ -1570,8 +1568,6 @@ export interface AuthenticateParams extends BaseParams { * authorization server did not supply an expiry or the expiry is otherwise * unknown. When supplied, the value MUST be a positive integer. * - * An API key omits this field. - * * This field is irrelevant when `token` is empty to revoke authentication * and SHOULD be omitted in that case. * @@ -1585,7 +1581,7 @@ export interface AuthenticateParams extends BaseParams { * `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is * satisfied without decoding the (opaque, server-specific) token itself. * Omit when the client doesn't track granted scopes separately from the - * token. Scopes apply to OAuth-issued tokens only. + * token. */ scopes?: string[]; /** @@ -1605,10 +1601,8 @@ export interface AuthenticateParams extends BaseParams { * * A registered model source takes its credential only through a * `modelSource` target, and the host rejects an untargeted `resource` that - * matches only model source challenges with `InvalidParams` (-32602). A - * delivery replaces whatever credential the host holds for the source. See - * [Model source credentials](/specification/authentication#model-source-credentials) - * for its rules. + * matches only model source challenges with `InvalidParams` (-32602). See + * [Model source credentials](/specification/authentication#model-source-credentials). * * Without a target, resource/scope matching is unchanged; the token may * satisfy every matching pending challenge. Older hosts ignore this field. @@ -1620,12 +1614,6 @@ export interface AuthenticateParams extends BaseParams { * Hosts MUST treat `accountId` as an opaque string. * see {@link /specification/authentication#account-selection-hints | Account selection hints}. * - * With a `modelSource` target, clients SHOULD include it when delivering a - * credential and omit it when revoking one, and the host publishes it as - * the source's `ModelSource.accountId`. It MUST NOT be derived from the - * secret. For an API key with no account of its own, a client uses an ID - * that changes whenever the user replaces the key. - * * @minLength 1 */ accountId?: string; diff --git a/types/common/errors.ts b/types/common/errors.ts index 6283e13ea..8f6b78d2a 100644 --- a/types/common/errors.ts +++ b/types/common/errors.ts @@ -95,6 +95,15 @@ export const AhpErrorCodes = { Conflict: -32011, /** The host could not open the requested TCP connection. */ TcpConnectionOpenFailed: -32012, + /** + * A request selects a model whose registered model source can't serve it, + * for example because the source needs a credential or was removed. A turn + * that fails for this reason ends with an error part whose `errorType` is + * `modelSourceUnavailable` instead. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + ModelSourceUnavailable: -32013, } as const; /** Union type of all AHP application error codes. */ diff --git a/types/common/state.ts b/types/common/state.ts index 831e08d2b..3f3f2b780 100644 --- a/types/common/state.ts +++ b/types/common/state.ts @@ -197,8 +197,6 @@ export interface ProtectedResourceMetadata { /** * REQUIRED. The protected resource's resource identifier, a URL using the * `https` scheme with no fragment component (e.g. `"https://api.github.com"`). - * A registered model source's endpoint may use any scheme the agent - * supports, because nothing fetches it. */ resource: string; @@ -442,11 +440,9 @@ export interface ErrorInfo { /** * Error type identifier. Well-known values: * - * - `modelSourceUnavailable`: a registered model source the turn uses - * can't serve it, for example because its credential is missing, - * expired, rejected, or revoked, or the source was removed. The error - * part is resumable. See - * [Model source credentials](/specification/authentication#model-source-credentials). + * - `modelSourceUnavailable`: a turn's registered model source can't serve + * it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. + * See [Model source credentials](/specification/authentication#model-source-credentials). */ errorType: string; /** Human-readable error message */ diff --git a/types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json b/types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json new file mode 100644 index 000000000..2ec6d00d5 --- /dev/null +++ b/types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json @@ -0,0 +1,40 @@ +{ + "description": "root/modelSourceSet for a built-in source with no format, definition, or nonce re-registers it when provider matches and format and nonce are both absent, keeping its host-reported state", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "source-builtin", + "provider": "copilot", + "displayName": "Example subscription", + "state": { + "kind": "ready" + } + } + ] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "source-builtin", + "provider": "copilot", + "displayName": "Example subscription (renamed)" + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "source-builtin", + "provider": "copilot", + "displayName": "Example subscription (renamed)", + "state": { + "kind": "ready" + } + } + ] + } +} diff --git a/types/test-cases/round-trips/101-model-source-catalog.json b/types/test-cases/round-trips/101-model-source-catalog.json index 0a77f9351..880382389 100644 --- a/types/test-cases/round-trips/101-model-source-catalog.json +++ b/types/test-cases/round-trips/101-model-source-catalog.json @@ -1,7 +1,7 @@ { "name": "model-source-catalog", "group": "A", - "description": "An agent labels and groups its models by model source, including a source with no models. Two sources serving the same upstream model get distinct model IDs. Another agent has no model sources.", + "description": "Root state lists the model sources an agent labels and groups its models by, each naming its agent provider, including a source with no models. Two sources serving the same upstream model get distinct model IDs. Another agent has no model sources.", "type": "InitializeResult", "input": { "protocolVersion": "1.1.0", @@ -16,20 +16,6 @@ "provider": "example", "displayName": "Example", "description": "Groups models by source", - "modelSources": [ - { - "id": "source-a", - "displayName": "Service A" - }, - { - "id": "source-b", - "displayName": "Service B" - }, - { - "id": "source-c", - "displayName": "Service C" - } - ], "models": [ { "id": "shared-model-a", @@ -58,6 +44,23 @@ } ] } + ], + "modelSources": [ + { + "id": "source-a", + "provider": "example", + "displayName": "Service A" + }, + { + "id": "source-b", + "provider": "example", + "displayName": "Service B" + }, + { + "id": "source-c", + "provider": "example", + "displayName": "Service C" + } ] } } @@ -77,20 +80,6 @@ "provider": "example", "displayName": "Example", "description": "Groups models by source", - "modelSources": [ - { - "id": "source-a", - "displayName": "Service A" - }, - { - "id": "source-b", - "displayName": "Service B" - }, - { - "id": "source-c", - "displayName": "Service C" - } - ], "models": [ { "id": "shared-model-a", @@ -119,6 +108,23 @@ } ] } + ], + "modelSources": [ + { + "id": "source-a", + "provider": "example", + "displayName": "Service A" + }, + { + "id": "source-b", + "provider": "example", + "displayName": "Service B" + }, + { + "id": "source-c", + "provider": "example", + "displayName": "Service C" + } ] } } diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 1d08dbc39..f998bb562 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot carries registered model sources with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each source carries its definition, in the suggested shape for its recognized format or an agent's own shape, including members the suggested shapes don't name, and a nonce for it. Sources that take a credential carry a host-reported credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects for the recognized formats it reads and a namespaced one, and its catalog lists the ready source and the authRequired one whose key expired, since models stay listed after a source has been ready.", + "description": "A root snapshot lists an agent's built-in model source, with no format, definition, or nonce, alongside registered model sources with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each registered source carries its definition, including members an agent defines itself, and a nonce for it. Sources that take a credential carry a host-reported credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects, and its catalog lists the built-in source's model, the ready source's, and the authRequired one's whose key expired, since models stay listed after a source has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -33,17 +33,13 @@ ] } }, - "modelSources": [ + "models": [ { - "id": "source-ready", - "displayName": "OpenRouter" + "id": "builtin-model", + "provider": "example", + "name": "Example built-in model", + "modelSourceId": "source-builtin" }, - { - "id": "source-auth", - "displayName": "Azure endpoint" - } - ], - "models": [ { "id": "source-ready.8f3a", "provider": "example", @@ -62,6 +58,11 @@ } ], "modelSources": [ + { + "id": "source-builtin", + "provider": "example", + "displayName": "Example subscription" + }, { "id": "source-unreported", "provider": "example", @@ -296,17 +297,13 @@ ] } }, - "modelSources": [ + "models": [ { - "id": "source-ready", - "displayName": "OpenRouter" + "id": "builtin-model", + "provider": "example", + "name": "Example built-in model", + "modelSourceId": "source-builtin" }, - { - "id": "source-auth", - "displayName": "Azure endpoint" - } - ], - "models": [ { "id": "source-ready.8f3a", "provider": "example", @@ -325,6 +322,11 @@ } ], "modelSources": [ + { + "id": "source-builtin", + "provider": "example", + "displayName": "Example subscription" + }, { "id": "source-unreported", "provider": "example", From 6abefee9922f5e3aa9f76e08691ace354b8ea599 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 09:09:24 -0500 Subject: [PATCH 12/17] docs: shorten the model source sections of the root channel spec Fold the reducer branches, rejection rules, status values, and retention values into short sentences. The type docs and reference pages already list them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/specification/root-channel.md | 33 ++++++------------------------ 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index a8ba481bf..c683def76 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -48,42 +48,21 @@ A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, #### Registering sources -An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads. A client registers a source with `root/modelSourceSet`, giving its `format`, a `definition` that tells the agent how to reach it, and a `nonce` that versions the definition, such as a hash of it. Each agent decides which formats it reads. Every client can read a definition, so it MUST NOT contain a credential: a client delivers that separately, with [`authenticate`](/specification/authentication#model-source-credentials). +An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads. A client registers a source with `root/modelSourceSet`, giving its `format`, a `definition` that tells the agent how to reach it, and a `nonce` that versions the definition. Every client can read a definition, so it MUST NOT contain a credential. Clients deliver credentials with [`authenticate`](/specification/authentication#model-source-credentials). -`root/modelSourceSet` adds a source, or updates the one with the same `id`: +`Set` adds the source, or replaces the one with the same `id`. When `provider`, `format`, and `nonce` are unchanged, it keeps the host-reported fields (`state`, `credentialResource`, and `accountId`), so re-registering doesn't disturb a working source. Otherwise it clears them, and the host drops the source's credential. `root/modelSourceRemoved` removes a source for every client. -- **Add.** When no source has the `id`, it appends the source. -- **Re-register.** When one has, with the same `provider`, `format`, and `nonce`, it keeps the host-reported fields (`state`, `credentialResource`, and `accountId`) and takes everything else from the action. -- **Update.** When any of the three differs, it replaces the source, whose host-reported fields are absent until the host reports again. The host drops the source's credential. +The host rejects a client's `Set` that lacks `format`, `definition`, or `nonce`, uses a format the agent doesn't list, includes a host-reported field, changes `definition` without changing `nonce`, changes a source the host registered itself, or asks for a `retention` the host won't honor. -`root/modelSourceRemoved` removes a source for every client. The host rejects a client's `Set`, through `rejectionReason`, when: - -- the agent doesn't advertise `modelSourceRegistration` or list `format`, or the source lacks `format`, `definition`, or `nonce`; -- the source includes a host-reported field; -- its `provider`, `format`, and `nonce` match the existing source's, but its `definition` differs; -- it would change a source the host registered itself, including an agent's own; -- the host won't honor the requested `retention`. - -A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one, and SHOULD NOT update a source whose `nonce` differs from its own copy unless the user changed that source. Re-registering an unchanged source makes the client a contributing client. The host tracks contributing clients itself, from `ActionEnvelope.origin`. - -Every connected client may change, supply credentials for, and select every source. A host that can verify principals MAY restrict a source to clients of the principal that registered it. +A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its configuration, so every window and device shares one source, and SHOULD NOT replace a source with a different `nonce` unless the user changed it. The host counts each client that registers a source as a contributing client, from `ActionEnvelope.origin`. A host that can verify principals MAY restrict a source to clients of the principal that registered it. #### Status and catalog -The host reports a registered source's status with `root/modelSourceStateChanged`, which sets `state`, `credentialResource`, and `accountId` together, and ignores an unknown `id`. The state is `starting`, `ready`, `authRequired` with a `reason`, or `error`. - -Once a registered source has been `ready`, the host keeps its models in the agent's `models` through later `starting` and `authRequired` states, so rotating a key doesn't break a selection. It withdraws them when the source is removed or enters `error`, or when an update changes its endpoint. A host SHOULD derive each model's ID deterministically from the source's `id`, `provider`, and `format`, its endpoint, and the endpoint's own model identifier, so a source registered again gets the same IDs. - -The host checks a selection whenever it uses one, and never runs the work on a different model. A turn that can't use its source fails as described in [Model source credentials](/specification/authentication#turns). +The host reports a registered source's status with `root/modelSourceStateChanged`, which sets `state`, `credentialResource`, and `accountId` together and ignores an unknown `id`. Once a source has been `ready`, its models stay in the agent's `models` through later `starting` and `authRequired` states. They leave when the source is removed or enters `error`, or when an update changes its endpoint. A host SHOULD derive model IDs deterministically from the source and the endpoint's model identifiers, so a source registered again keeps its IDs. The host never runs work on a model other than the one selected. See [Model source credentials](/specification/authentication#turns) for turns on an unavailable source. #### Retention -A source's `retention` decides what happens when its last contributing client disconnects and doesn't return within a grace period the host chooses: - -- `contributingClient`, the default: the host stops new work on the source, lets running turns finish, and then removes it. -- `host`: the source stays until a client removes it or host policy expires it. - -The host SHOULD reject an automation that names a model from a `contributingClient`-retained source, because the automation would outlive the source. +When a source's last contributing client disconnects and doesn't return within the host's grace period, `contributingClient` retention, the default, removes the source once running turns finish. `host` retention keeps it until a client removes it or host policy expires it. The host SHOULD reject an automation that names a model from a `contributingClient`-retained source. ### Paginating the catalogue From 7d0c3279a2183d83137d21b70a4d77ba52e70d08 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 09:16:56 -0500 Subject: [PATCH 13/17] docs: move model source details into a guide page Follow the MCP split between specification and guide: - Add `guide/model-sources.md`, with registration, status, credentials, retention, and unavailable sources, and list it in the guide sidebar. - Keep the model source rules in the root channel spec, and move the rejection rules into a "Server Validation of Client Actions" table like the session and chat channels have. - Keep the `modelSource` target and credential handling rules in the authentication spec, and move the reasons and client delivery guidance to the guide. - Point the type docs at the guide. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Errors.generated.cs | 2 +- .../Generated/State.generated.cs | 2 +- clients/go/ahptypes/state.generated.go | 2 +- .../generated/State.generated.kt | 2 +- clients/rust/crates/ahp-types/src/state.rs | 2 +- .../Generated/State.generated.swift | 2 +- docs/.vitepress/config.mts | 1 + docs/guide/actions.md | 2 +- docs/guide/model-sources.md | 134 ++++++++++++++++++ docs/specification/authentication.md | 19 +-- docs/specification/root-channel.md | 34 +++-- schema/actions.schema.json | 2 +- schema/commands.schema.json | 2 +- schema/errors.schema.json | 2 +- schema/notifications.schema.json | 2 +- schema/state.schema.json | 2 +- types/channels-root/actions.ts | 6 +- types/channels-root/state.ts | 6 +- types/common/errors.ts | 2 +- types/common/state.ts | 2 +- 20 files changed, 173 insertions(+), 55 deletions(-) create mode 100644 docs/guide/model-sources.md diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs index 7358b5c69..50260d2ad 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs @@ -47,7 +47,7 @@ public static class AhpErrorCodes public const int Conflict = -32011; /// The host could not open the requested TCP connection. public const int TcpConnectionOpenFailed = -32012; - /// A request selects a model whose registered model source can't serve it, for example because the source needs a credential or was removed. A turn that fails for this reason ends with an error part whose `errorType` is `modelSourceUnavailable` instead. @see {@link /specification/authentication#model-source-credentials | Model source credentials} + /// A request selects a model whose registered model source can't serve it, for example because the source needs a credential or was removed. A turn that fails for this reason ends with an error part whose `errorType` is `modelSourceUnavailable` instead. @see {@link /guide/model-sources#unavailable-sources | Model Sources guide} public const int ModelSourceUnavailable = -32013; } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 3a28baa38..cc91d6d78 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -6724,7 +6724,7 @@ public sealed record ErrorInfo /// /// - `modelSourceUnavailable`: a turn's registered model source can't serve /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - /// See [Model source credentials](/specification/authentication#model-source-credentials). + /// See [Unavailable sources](/guide/model-sources#unavailable-sources). public required string ErrorType { get; init; } /// Human-readable error message diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index aea89715b..945fe2d82 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -4491,7 +4491,7 @@ type ErrorInfo struct { // // - `modelSourceUnavailable`: a turn's registered model source can't serve // it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - // See [Model source credentials](/specification/authentication#model-source-credentials). + // See [Unavailable sources](/guide/model-sources#unavailable-sources). ErrorType string `json:"errorType"` // Human-readable error message Message string `json:"message"` 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 f6cc5f23e..7ab522bab 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 @@ -6059,7 +6059,7 @@ data class ErrorInfo( * * - `modelSourceUnavailable`: a turn's registered model source can't serve * it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - * See [Model source credentials](/specification/authentication#model-source-credentials). + * See [Unavailable sources](/guide/model-sources#unavailable-sources). */ val errorType: String, /** diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index cceccab5b..744b56393 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -5983,7 +5983,7 @@ pub struct ErrorInfo { /// /// - `modelSourceUnavailable`: a turn's registered model source can't serve /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - /// See [Model source credentials](/specification/authentication#model-source-credentials). + /// See [Unavailable sources](/guide/model-sources#unavailable-sources). pub error_type: String, /// Human-readable error message pub message: String, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 2e77d2962..1d950843f 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -7597,7 +7597,7 @@ public struct ErrorInfo: Codable, Sendable, Equatable { /// /// - `modelSourceUnavailable`: a turn's registered model source can't serve /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - /// See [Model source credentials](/specification/authentication#model-source-credentials). + /// See [Unavailable sources](/guide/model-sources#unavailable-sources). public var errorType: String /// Human-readable error message public var message: String diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index cdc4a6f4e..aa439c488 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -67,6 +67,7 @@ export default withMermaid(defineConfigWithTheme({ { text: 'Terminals', link: '/guide/terminals' }, { text: 'Customizations', link: '/guide/customizations' }, { text: 'MCP Servers', link: '/guide/mcp' }, + { text: 'Model Sources', link: '/guide/model-sources' }, { text: 'Write-Ahead Reconciliation', link: '/guide/reconciliation' }, ], }, diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 18053c4de..8afad2ff8 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -31,7 +31,7 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/activeSessionsChanged` | No | Count of active sessions changed | | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | -| `root/modelSourceSet` | **Yes** | A [model source](/specification/root-channel#registering-sources) was added, re-registered, or updated by `id` | +| `root/modelSourceSet` | **Yes** | A [model source](/guide/model-sources) was added, re-registered, or updated by `id` | | `root/modelSourceRemoved` | **Yes** | A model source was removed by `id` | | `root/modelSourceStateChanged` | No | The host reported a model source's status and credential fields | diff --git a/docs/guide/model-sources.md b/docs/guide/model-sources.md new file mode 100644 index 000000000..18f77c680 --- /dev/null +++ b/docs/guide/model-sources.md @@ -0,0 +1,134 @@ +# Model Sources + +A model source is where an agent provider's models come from, such as a service, a subscription, or an endpoint the user configured with their own key. Root state lists every source in [`RootState.modelSources`](/reference/root#modelsource), and each model names its source in [`SessionModelInfo.modelSourceId`](/reference/root#sessionmodelinfo). Clients use sources to label and group models, for example in a model picker. + +AHP intentionally does **not** re-spec how an agent reaches a model endpoint. It carries: + +- The list of sources, and which models each one serves. +- A way for clients to register a source the agent doesn't have, with a definition the agent reads. +- Each registered source's status. +- A path for the source's credential. + +Reading the definition, validating endpoints, discovering models, and the wire protocol for inference all belong to the agent. + +## Where model sources appear + +Every source is an entry in `RootState.modelSources`, naming the agent `provider` it serves. There are two kinds: + +1. **Built-in sources** that an agent provides itself, such as a first-party subscription. The host lists them without a `format` or `definition`, and their sign-in uses [`AgentInfo.protectedResources`](/specification/authentication#discovery). +2. **Registered sources** that a client registered, or that the host registered from its own configuration. They carry a `format`, a `definition`, and a `nonce`, and the host reports their status. + +```typescript +const sources = state.modelSources?.filter(s => s.provider === agent.provider) ?? []; +const registered = sources.filter(s => s.definition !== undefined); +``` + +## Shape + +```typescript +ModelSource { + id: string // host-unique; the modelSourceId of its models + provider: string // agent provider that serves its models + displayName: string + icons?: Icon[] + format?: string // registered sources only + definition?: Record // how the agent reaches the source; never a credential + nonce?: string // version token for definition + retention?: 'contributingClient' | 'host' + + // Host-reported, set together by root/modelSourceStateChanged + state?: ModelSourceState // starting | ready | authRequired | error + credentialResource?: ProtectedResourceMetadata + accountId?: string +} +``` + +## Registering a source + +An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads, most preferred first. Each agent decides which formats it reads. `ModelSource.format` notes a few common names that some agents may read, such as `openaiCompatible` and `anthropic`. Other formats are named with a namespace, such as `example.com/model-source@1`. + +A client registers a source with [`root/modelSourceSet`](/reference/root#rootmodelsourcesetaction), giving its `format`, a `definition` that tells the agent how to reach it, and a `nonce` that versions the definition, such as a hash of it. Every client can read a definition, so it MUST NOT contain a credential. + +`Set` adds the source, or replaces the one with the same `id`: + +- **Add.** No source has the `id`. +- **Re-register.** One has, with the same `provider`, `format`, and `nonce`. The source keeps its host-reported fields and takes everything else from the action, so re-registering doesn't disturb a working source. +- **Update.** Any of the three differs. The source is replaced, its host-reported fields stay absent until the host reports again, and the host drops its credential. + +[`root/modelSourceRemoved`](/reference/root#rootmodelsourceremovedaction) removes a source for every client. The host rejects either action when it breaks the rules in [Server Validation of Client Actions](/specification/root-channel#server-validation-of-client-actions). + +A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one. It SHOULD NOT replace a source whose `nonce` differs from its own copy unless the user changed that source; otherwise two clients with different configurations replace each other's source indefinitely. + +Each client that registers a source is a **contributing client**. The host tracks contributing clients itself, from `ActionEnvelope.origin`, so they aren't in state. Every connected client may change, supply credentials for, and select every source. A host that can verify principals MAY restrict a source to clients of the principal that registered it. + +## Status + +The host reports a registered source's status with [`root/modelSourceStateChanged`](/reference/root#rootmodelsourcestatechangedaction), which sets `state`, `credentialResource`, and `accountId` together. The reducer ignores an unknown `id`, so a late report can't bring back a removed source. + +```mermaid +stateDiagram-v2 + [*] --> starting : source registered + + starting --> authRequired : credential needed + starting --> ready : models listed + starting --> error : invalid definition, or declined by policy + + authRequired --> starting : credential accepted + + ready --> authRequired : credential expired, rejected, or revoked + ready --> starting : credential rotated + error --> starting : definition changed +``` + +Once a source has been `ready`, its models stay in the agent's `models` through later `starting` and `authRequired` states, so rotating a key doesn't break a selection. They leave when the source is removed or enters `error`, or when an update changes its endpoint. A host SHOULD derive model IDs deterministically from the source and the endpoint's model identifiers, so a source registered again keeps its IDs. + +## Credentials + +A registered source that takes a credential carries `credentialResource`, RFC 9728 metadata for the endpoint the credential is for, in every state. When the source needs a credential, its state is `authRequired` with a `reason`, and a client answers with [`authenticate`](/reference/common#authenticate) and a `modelSource` target: + +```mermaid +sequenceDiagram + participant C as Client + participant H as Agent Host + + C->>H: root/modelSourceSet (format, definition, nonce) + H-->>C: root/modelSourceStateChanged (authRequired, credentialResource) + + C->>H: authenticate({ resource, token, accountId, target: { kind: 'modelSource', modelSourceId } }) + H-->>C: {} + + H-->>C: root/modelSourceStateChanged (ready, accountId) + H-->>C: root/agentsChanged (the source's models join the agent's models) +``` + +The token is whatever the source's definition calls for, such as an API key. The host publishes the request's `accountId` as the source's `accountId`, so a client that reloads, or one on another device, can tell whether the host holds its current key. A delivery replaces the credential the host holds. [Model source credentials](/specification/authentication#model-source-credentials) lists the host's rules. + +| `reason` | Meaning | What a client may send | +| --- | --- | --- | +| `required` | The host holds no credential yet. | Its key. | +| `expired` | The credential's lifetime, or the lease a client set with `expiresIn`, lapsed. | A renewed credential. | +| `rejected` | The endpoint refused the credential. `accountId` still names it. | Only a key whose `accountId` differs. | +| `revoked` | A client revoked the credential. | Nothing, until a user asks. | + +Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers one only in answer to the source's current state, and MUST NOT send a stored secret unless the source's `provider` and `format` match its own copy and every endpoint in the source's `definition` that the key would reach is one its own copy sends the key to. + +## Retention + +A source's `retention` decides what happens when its last contributing client disconnects and doesn't return within a grace period the host chooses: + +- `contributingClient`, the default: the host stops new work on the source, lets running turns finish, and then removes it. +- `host`: the source stays until a client removes it or host policy expires it. + +The host SHOULD reject an automation that names a model from a `contributingClient`-retained source, because the automation would outlive the source. + +## Unavailable sources + +The host checks a selection whenever it uses one, and never runs work on a model other than the one selected. When a turn can't use its source, the host ends the turn with an error part whose `errorType` is `modelSourceUnavailable` and whose `resumable` is `true`. Once the source is ready again, a client can continue the turn with `chat/turnResume`. A request that selects such a model fails with [`ModelSourceUnavailable`](/reference/error-codes#ahp-application-codes) (`-32013`). + +When a client removes a source or revokes its credential, the host ends running turns that use it. + +## Next steps + +- [Root Channel](/specification/root-channel#model-sources) — the rules every model source follows, and which registrations the host rejects. +- [Authentication](/specification/authentication#model-source-credentials) — the host's rules for model source credentials. +- [Root Reference](/reference/root#modelsource) — full type definitions for `ModelSource`, `ModelSourceState`, and the root actions. diff --git a/docs/specification/authentication.md b/docs/specification/authentication.md index 1752f6e25..50afda939 100644 --- a/docs/specification/authentication.md +++ b/docs/specification/authentication.md @@ -150,7 +150,7 @@ If the token is invalid or the resource is unrecognized, the server MUST return ### Model source credentials -A [registered model source](/specification/root-channel#registering-sources) that takes a credential carries `credentialResource`, RFC 9728 metadata for the endpoint the credential is for, in every state. When the source needs a credential, its state is `authRequired`, with a `reason`. A client delivers the credential with `authenticate`, the source's `credentialResource.resource`, and a `modelSource` target: +A [registered model source](/guide/model-sources#credentials) that takes a credential carries `credentialResource`, RFC 9728 metadata for the endpoint the credential is for, in every state. When the source needs a credential, its state is `authRequired`, with a `reason`. A client delivers the credential with `authenticate`, the source's `credentialResource.resource`, and a `modelSource` target: ```jsonc // Model source credential delivery @@ -180,26 +180,11 @@ When `target.kind` is `modelSource`, the host: A delivery replaces the credential the host holds for the source. `accountId` lets a client that reloads, or one on another device, tell whether the host holds its current key. It MUST NOT be derived from the secret, because every client can read it. -#### Reasons - -| `reason` | Meaning | What a client may send | -| --- | --- | --- | -| `required` | The host holds no credential yet. | Its key. | -| `expired` | The credential's lifetime, or the lease a client set with `expiresIn`, lapsed. | A renewed credential. | -| `rejected` | The endpoint refused the credential. `accountId` still names it. | Only a key whose `accountId` differs. | -| `revoked` | A client revoked the credential. | Nothing, until a user asks. | - -#### Delivering and handling - -Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers one only in answer to the source's current state, and MUST NOT send a stored secret unless the source's `provider` and `format` match its own copy and every endpoint in the source's `definition` that the key would reach is one its own copy sends the key to. - The host holds the credential in memory only. It never places it in state, actions, notifications, logs, telemetry, or error messages, and never exposes it to the model, tools, terminals, or hooks. It attaches the credential only to the endpoints the source's definition names, never to another origin, including on redirect, and drops it when the source is removed or updated, when its lease lapses, and when the host restarts. Endpoints, including loopback and private addresses, are reached from the host machine. Hosts SHOULD deny link-local and cloud metadata addresses, and require `https` for credentialed endpoints other than loopback. -#### Turns - -When a turn can't use its source, the host ends the turn with an error part whose `errorType` is `modelSourceUnavailable` and whose `resumable` is `true`. A request that selects such a model fails with `ModelSourceUnavailable` (`-32013`). The host never switches to a different model. When a client removes a source or revokes its credential, the host ends running turns that use it. +See the [Model Sources guide](/guide/model-sources#credentials) for the `authRequired` reasons and when clients deliver a credential. ### Why keyed by `resource` and optional `target`? diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index c683def76..5d9944866 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -46,23 +46,7 @@ An agent provider can offer models from more than one source, such as a service, A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, which also determines the source. The host lists the sources an agent provides itself. They have no `format` or `definition`, and their sign-in uses `AgentInfo.protectedResources`. -#### Registering sources - -An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads. A client registers a source with `root/modelSourceSet`, giving its `format`, a `definition` that tells the agent how to reach it, and a `nonce` that versions the definition. Every client can read a definition, so it MUST NOT contain a credential. Clients deliver credentials with [`authenticate`](/specification/authentication#model-source-credentials). - -`Set` adds the source, or replaces the one with the same `id`. When `provider`, `format`, and `nonce` are unchanged, it keeps the host-reported fields (`state`, `credentialResource`, and `accountId`), so re-registering doesn't disturb a working source. Otherwise it clears them, and the host drops the source's credential. `root/modelSourceRemoved` removes a source for every client. - -The host rejects a client's `Set` that lacks `format`, `definition`, or `nonce`, uses a format the agent doesn't list, includes a host-reported field, changes `definition` without changing `nonce`, changes a source the host registered itself, or asks for a `retention` the host won't honor. - -A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its configuration, so every window and device shares one source, and SHOULD NOT replace a source with a different `nonce` unless the user changed it. The host counts each client that registers a source as a contributing client, from `ActionEnvelope.origin`. A host that can verify principals MAY restrict a source to clients of the principal that registered it. - -#### Status and catalog - -The host reports a registered source's status with `root/modelSourceStateChanged`, which sets `state`, `credentialResource`, and `accountId` together and ignores an unknown `id`. Once a source has been `ready`, its models stay in the agent's `models` through later `starting` and `authRequired` states. They leave when the source is removed or enters `error`, or when an update changes its endpoint. A host SHOULD derive model IDs deterministically from the source and the endpoint's model identifiers, so a source registered again keeps its IDs. The host never runs work on a model other than the one selected. See [Model source credentials](/specification/authentication#turns) for turns on an unavailable source. - -#### Retention - -When a source's last contributing client disconnects and doesn't return within the host's grace period, `contributingClient` retention, the default, removes the source once running turns finish. `host` retention keeps it until a client removes it or host policy expires it. The host SHOULD reject an automation that names a model from a `contributingClient`-retained source. +Clients and hosts can also register sources the agent doesn't have, each with a definition the agent reads. The host reports each registered source's status, and clients deliver its credential with [`authenticate`](/specification/authentication#model-source-credentials). See the [Model Sources guide](/guide/model-sources). ### Paginating the catalogue @@ -120,6 +104,20 @@ target channel instead. `auth/required` may also be emitted on `ahp-root://` when the auth requirement is root-scoped; see [Authentication](/specification/authentication). +## Server Validation of Client Actions + +When the server receives a client-dispatched action on this channel, it MUST validate it before applying. Invalid actions MUST be echoed back with a `rejectionReason` on the `ActionEnvelope`. The following validation rules apply: + +| Action | Condition | Server Behavior | +| --- | --- | --- | +| `root/modelSourceSet` | The agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format` | Server MUST reject the action | +| `root/modelSourceSet` | `format`, `definition`, or `nonce` is absent, or a host-reported field is present | Server MUST reject the action | +| `root/modelSourceSet` | `provider`, `format`, and `nonce` match the existing source's, but `definition` differs | Server MUST reject the action | +| `root/modelSourceSet` | The existing source with that `id` is one the host registered itself | Server MUST reject the action | +| `root/modelSourceSet` | The host won't honor the requested `retention` | Server MUST reject the action | +| `root/modelSourceRemoved` | The source is one the host registered itself | Server MAY reject the action | +| `root/modelSourceSet`, `root/modelSourceRemoved` | The host restricts sources by principal, and the source belongs to another principal | Server MAY reject the action | + ## Actions Root state is mutated by action envelopes broadcast on this channel. Refer to the [Root Channel Reference](/reference/root#actions) for the full list; the root-scoped actions are: @@ -130,7 +128,7 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/activeSessionsChanged` | Server | Replaces `activeSessions` | | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | -| `root/modelSourceSet` | Server / Client | Adds, re-registers, or updates a source in `modelSources` by `id`, including its definition | +| `root/modelSourceSet` | Server / Client | Adds a source to `modelSources`, or replaces the one with the same `id`. Keeps its host-reported fields when `provider`, `format`, and `nonce` are unchanged | | `root/modelSourceRemoved` | Server / Client | Removes a source by `id` | | `root/modelSourceStateChanged` | Server | Sets a source's host-reported fields. A no-op for an unknown `id` | diff --git a/schema/actions.schema.json b/schema/actions.schema.json index aedb86c49..a992a5acb 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -3236,7 +3236,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." }, "message": { "type": "string", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 801d1d7c0..bb9be89a9 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -2556,7 +2556,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." }, "message": { "type": "string", diff --git a/schema/errors.schema.json b/schema/errors.schema.json index d85ebc8bd..12babd251 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -541,7 +541,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." }, "message": { "type": "string", diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index f24664280..c57c1828a 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -843,7 +843,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." }, "message": { "type": "string", diff --git a/schema/state.schema.json b/schema/state.schema.json index 9fed3fdea..75c656972 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -452,7 +452,7 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Model source credentials](/specification/authentication#model-source-credentials)." + "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." }, "message": { "type": "string", diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index d1e6d77b6..d552e4034 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -86,7 +86,7 @@ export interface RootConfigChangedAction { * @category Root Actions * @stability 1.0 * @clientDispatchable - * @see {@link /specification/root-channel#registering-sources | Registering sources} + * @see {@link /guide/model-sources#registering-a-source | Model Sources guide} */ export interface RootModelSourceSetAction { type: ActionType.RootModelSourceSet; @@ -101,7 +101,7 @@ export interface RootModelSourceSetAction { * @category Root Actions * @stability 1.0 * @clientDispatchable - * @see {@link /specification/root-channel#registering-sources | Registering sources} + * @see {@link /guide/model-sources#registering-a-source | Model Sources guide} */ export interface RootModelSourceRemovedAction { type: ActionType.RootModelSourceRemoved; @@ -116,7 +116,7 @@ export interface RootModelSourceRemovedAction { * * @category Root Actions * @stability 1.0 - * @see {@link /specification/root-channel#status-and-catalog | Status and catalog} + * @see {@link /guide/model-sources#status | Model Sources guide} */ export interface RootModelSourceStateChangedAction { type: ActionType.RootModelSourceStateChanged; diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 1db08494e..e6e27ddb9 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -142,7 +142,7 @@ export interface AgentCapabilities { * definition formats. * * @stability 1.0 - * @see {@link /specification/root-channel#registering-sources | Registering sources} + * @see {@link /guide/model-sources#registering-a-source | Model Sources guide} */ modelSourceRegistration?: ModelSourceRegistrationCapability; } @@ -325,7 +325,7 @@ export interface ModelSourceFormatInfo { * @category Root State * @stability 1.0 * @preserveUnknownMembers - * @see {@link /specification/root-channel#model-sources | Model sources} + * @see {@link /guide/model-sources | Model Sources guide} */ export interface ModelSource { /** @@ -472,7 +472,7 @@ export interface ModelSourceReadyState { * @category Root State * @stability 1.0 * @nonexhaustive - * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + * @see {@link /guide/model-sources#credentials | Model Sources guide} */ export const enum ModelSourceAuthRequiredReason { /** The host holds no credential yet. */ diff --git a/types/common/errors.ts b/types/common/errors.ts index 8f6b78d2a..821607e80 100644 --- a/types/common/errors.ts +++ b/types/common/errors.ts @@ -101,7 +101,7 @@ export const AhpErrorCodes = { * that fails for this reason ends with an error part whose `errorType` is * `modelSourceUnavailable` instead. * - * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + * @see {@link /guide/model-sources#unavailable-sources | Model Sources guide} */ ModelSourceUnavailable: -32013, } as const; diff --git a/types/common/state.ts b/types/common/state.ts index 3f3f2b780..b8fc37561 100644 --- a/types/common/state.ts +++ b/types/common/state.ts @@ -442,7 +442,7 @@ export interface ErrorInfo { * * - `modelSourceUnavailable`: a turn's registered model source can't serve * it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - * See [Model source credentials](/specification/authentication#model-source-credentials). + * See [Unavailable sources](/guide/model-sources#unavailable-sources). */ errorType: string; /** Human-readable error message */ From 281a82af21c42166bf611c45e6eb2676551b7b12 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 14:56:21 -0500 Subject: [PATCH 14/17] models: add ErrorInfo.errorCode and apply review suggestions - Add optional `ErrorInfo.errorCode?: AhpErrorCode`. A turn whose model source can't serve it carries `ModelSourceUnavailable` (-32013) there. Generators map `AhpErrorCode` to their integer type, and the JSON Schema types it as an integer. - Rename `id` to `modelSourceId` on `root/modelSourceRemoved` and `root/modelSourceStateChanged`. - Drop `@preserveUnknownMembers` from `ModelSource`, which clients don't round-trip, and apply the doc suggestions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Actions.generated.cs | 11 ++-- .../Generated/Errors.generated.cs | 2 +- .../Generated/State.generated.cs | 23 ++++--- .../dotnet/src/AgentHostProtocol/Reducers.cs | 4 +- clients/go/ahp/reducers.go | 4 +- clients/go/ahptypes/actions.generated.go | 11 ++-- clients/go/ahptypes/errors.generated.go | 2 +- clients/go/ahptypes/state.generated.go | 33 ++++------ .../microsoft/agenthostprotocol/Reducers.kt | 4 +- .../generated/Actions.generated.kt | 11 ++-- .../generated/Errors.generated.kt | 2 +- .../generated/State.generated.kt | 32 ++++------ clients/rust/crates/ahp-types/src/actions.rs | 11 ++-- clients/rust/crates/ahp-types/src/errors.rs | 2 +- clients/rust/crates/ahp-types/src/state.rs | 21 +++--- clients/rust/crates/ahp/src/reducers.rs | 4 +- .../Generated/Actions.generated.swift | 19 +++--- .../Generated/Errors.generated.swift | 2 +- .../Generated/State.generated.swift | 64 +++++-------------- .../AgentHostProtocol/NativeReducer.swift | 4 +- .../Sources/AgentHostProtocol/Reducers.swift | 2 +- ...61123-model-source-registry-migration.json | 2 +- .../20261123-model-source-registry.json | 2 +- docs/guide/actions.md | 2 +- docs/guide/model-sources.md | 4 +- docs/specification/root-channel.md | 4 +- schema/actions.schema.json | 26 +++++--- schema/commands.schema.json | 26 +++++--- schema/errors.schema.json | 25 +++++--- schema/notifications.schema.json | 14 +++- schema/state.schema.json | 14 +++- scripts/generate-csharp.ts | 1 + scripts/generate-go.ts | 2 +- scripts/generate-json-schema.ts | 8 ++- scripts/generate-kotlin.ts | 3 +- scripts/generate-rust.ts | 3 +- scripts/generate-swift.ts | 3 +- types/channels-root/actions.ts | 11 ++-- types/channels-root/reducer.ts | 4 +- types/channels-root/state.ts | 6 +- types/common/errors.ts | 5 +- types/common/state.ts | 13 ++-- ...root-modelsourceremoved-removes-by-id.json | 2 +- ...delsourceremoved-no-op-for-unknown-id.json | 2 +- ...rceremoved-no-op-when-registry-absent.json | 2 +- ...echanged-updates-host-reported-fields.json | 2 +- ...statechanged-clears-credential-fields.json | 2 +- ...urcestatechanged-no-op-for-unknown-id.json | 2 +- ...atechanged-no-op-when-registry-absent.json | 2 +- .../105-root-model-source-removed.json | 4 +- .../107-root-model-source-state-changed.json | 4 +- .../118-chat-error-part-error-code.json | 36 +++++++++++ 52 files changed, 271 insertions(+), 233 deletions(-) create mode 100644 types/test-cases/round-trips/118-chat-error-part-error-code.json diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 963aeebf7..a599ce0ab 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -377,8 +377,8 @@ public sealed record RootModelSourceSetAction public required ModelSource ModelSource { get; init; } } -/// Removes the model source with the given `id`, for every client. A no-op -/// when none matches. +/// Removes the model source with the given `modelSourceId`, for every client. +/// A no-op when none matches. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceRemovedAction @@ -386,12 +386,13 @@ public sealed record RootModelSourceRemovedAction public ActionType Type { get; init; } = ActionType.RootModelSourceRemoved; /// The model source's `id`. - public required string Id { get; init; } + public required string ModelSourceId { get; init; } } /// Updates a model source's host-reported fields together: `state`, /// `credentialResource`, and `accountId`. A no-op when no model source has -/// `id`. Other fields of the source are preserved. Only the host dispatches it. +/// `modelSourceId`. Other fields of the source are preserved. Only the host +/// dispatches it. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceStateChangedAction @@ -399,7 +400,7 @@ public sealed record RootModelSourceStateChangedAction public ActionType Type { get; init; } = ActionType.RootModelSourceStateChanged; /// The model source's `id`. - public required string Id { get; init; } + public required string ModelSourceId { get; init; } /// The new status. public required ModelSourceState State { get; init; } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs index 50260d2ad..1bde256ca 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs @@ -47,7 +47,7 @@ public static class AhpErrorCodes public const int Conflict = -32011; /// The host could not open the requested TCP connection. public const int TcpConnectionOpenFailed = -32012; - /// A request selects a model whose registered model source can't serve it, for example because the source needs a credential or was removed. A turn that fails for this reason ends with an error part whose `errorType` is `modelSourceUnavailable` instead. @see {@link /guide/model-sources#unavailable-sources | Model Sources guide} + /// A request or turn needs a registered model source that can't serve it, for example because the source needs a credential or was removed. A turn carries it in its error part's `ErrorInfo.errorCode`. @see {@link /guide/model-sources#unavailable-sources | Model Sources guide} public const int ModelSourceUnavailable = -32013; } diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index cf588acfc..af3c19b43 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2659,8 +2659,7 @@ public sealed record ModelSourceFormatInfo /// A source that an agent provider offers models from, such as a service, /// subscription, or endpoint. The host lists the sources an agent provides -/// itself, and clients can register more with a definition. Nothing here is -/// a credential. +/// itself, and clients can register more with a definition. /// /// Stability: 1.0 - Early development. public sealed record ModelSource @@ -2731,7 +2730,7 @@ public sealed record ModelSource /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example /// `http://localhost:11434/v1`). It's the value a client passes back as - /// `authenticate({ resource })`, and nothing fetches it. + /// `authenticate({ resource })`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ProtectedResourceMetadata? CredentialResource { get; init; } @@ -2745,10 +2744,6 @@ public sealed record ModelSource [JsonPropertyName("_meta")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary? Meta { get; init; } - - /// Unrecognized wire members retained for full-object edits. - [JsonExtensionData] - public Dictionary? Extra { get; set; } } /// The agent is reading and validating the definition, or listing the @@ -7006,13 +7001,17 @@ public sealed record UsageInfo public sealed record ErrorInfo { - /// Error type identifier. Well-known values: - /// - /// - `modelSourceUnavailable`: a turn's registered model source can't serve - /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - /// See [Unavailable sources](/guide/model-sources#unavailable-sources). + /// Error type identifier public required string ErrorType { get; init; } + /// The {@link AhpErrorCodes} value for this error, when one applies. For + /// example, a turn whose registered model source can't serve it ends with + /// `ModelSourceUnavailable`. + /// + /// Stability: 1.0 - Early development. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public int? ErrorCode { get; init; } + /// Human-readable error message public required string Message { get; init; } diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index c6ec63d50..871af1580 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -704,7 +704,7 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) } case RootModelSourceRemovedAction a: { - int index = state.ModelSources?.FindIndex(s => s.Id == a.Id) ?? -1; + int index = state.ModelSources?.FindIndex(s => s.Id == a.ModelSourceId) ?? -1; if (index < 0) { return ReduceOutcome.NoOp; @@ -715,7 +715,7 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) } case RootModelSourceStateChangedAction a: { - int index = state.ModelSources?.FindIndex(s => s.Id == a.Id) ?? -1; + int index = state.ModelSources?.FindIndex(s => s.Id == a.ModelSourceId) ?? -1; if (index < 0) { return ReduceOutcome.NoOp; diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index 3411a8f33..dc69c8d7b 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -552,14 +552,14 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R } return ReduceOutcomeApplied case *ahptypes.RootModelSourceRemovedAction: - idx := modelSourceIndex(state.ModelSources, a.Id) + idx := modelSourceIndex(state.ModelSources, a.ModelSourceId) if idx < 0 { return ReduceOutcomeNoOp } state.ModelSources = append(state.ModelSources[:idx], state.ModelSources[idx+1:]...) return ReduceOutcomeApplied case *ahptypes.RootModelSourceStateChangedAction: - idx := modelSourceIndex(state.ModelSources, a.Id) + idx := modelSourceIndex(state.ModelSources, a.ModelSourceId) if idx < 0 { return ReduceOutcomeNoOp } diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 2e47d4d53..0df00edc5 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -204,25 +204,26 @@ type RootModelSourceSetAction struct { ModelSource ModelSource `json:"modelSource"` } -// Removes the model source with the given `id`, for every client. A no-op -// when none matches. +// Removes the model source with the given `modelSourceId`, for every client. +// A no-op when none matches. // // Stability: 1.0 - Early development. type RootModelSourceRemovedAction struct { Type ActionType `json:"type"` // The model source's `id`. - Id string `json:"id"` + ModelSourceId string `json:"modelSourceId"` } // Updates a model source's host-reported fields together: `state`, // `credentialResource`, and `accountId`. A no-op when no model source has -// `id`. Other fields of the source are preserved. Only the host dispatches it. +// `modelSourceId`. Other fields of the source are preserved. Only the host +// dispatches it. // // Stability: 1.0 - Early development. type RootModelSourceStateChangedAction struct { Type ActionType `json:"type"` // The model source's `id`. - Id string `json:"id"` + ModelSourceId string `json:"modelSourceId"` // The new status. State ModelSourceState `json:"state"` // Replaces the source's `credentialResource`. Absent clears it, for a diff --git a/clients/go/ahptypes/errors.generated.go b/clients/go/ahptypes/errors.generated.go index cc23833dd..975dbe941 100644 --- a/clients/go/ahptypes/errors.generated.go +++ b/clients/go/ahptypes/errors.generated.go @@ -38,7 +38,7 @@ const ( ErrorCodeAlreadyExists int32 = -32010 // ErrorCodeTcpConnectionOpenFailed indicates that the host could not open a TCP connection. ErrorCodeTcpConnectionOpenFailed int32 = -32012 - // ErrorCodeModelSourceUnavailable indicates that a request selects a model whose registered model source can't serve it. + // ErrorCodeModelSourceUnavailable indicates that a request or turn needs a registered model source that can't serve it. ErrorCodeModelSourceUnavailable int32 = -32013 ) diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index e69dd246a..e47bb057e 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1041,8 +1041,7 @@ type ModelSourceFormatInfo struct { // A source that an agent provider offers models from, such as a service, // subscription, or endpoint. The host lists the sources an agent provides -// itself, and clients can register more with a definition. Nothing here is -// a credential. +// itself, and clients can register more with a definition. // // Stability: 1.0 - Early development. type ModelSource struct { @@ -1097,7 +1096,7 @@ type ModelSource struct { // `credentialResource.resource` is the endpoint URL as the definition // names it, in any scheme the agent supports (for example // `http://localhost:11434/v1`). It's the value a client passes back as - // `authenticate({ resource })`, and nothing fetches it. + // `authenticate({ resource })`. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` // The {@link AuthenticateParams.accountId} sent with the credential the // host most recently accepted. Set with `state`. @@ -1105,18 +1104,6 @@ type ModelSource struct { // Additional implementation-defined metadata for this model source. // MUST NOT contain a credential. Meta map[string]json.RawMessage `json:"_meta,omitempty"` - // Extra contains unrecognized wire members retained for full-object edits. - Extra map[string]json.RawMessage `json:"-"` -} - -func (v *ModelSource) UnmarshalJSON(data []byte) error { - type wire ModelSource - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "nonce", "retention", "state", "credentialResource", "accountId", "_meta") -} - -func (v ModelSource) MarshalJSON() ([]byte, error) { - type wire ModelSource - return marshalWithExtra(wire(v), v.Extra, "id", "provider", "displayName", "icons", "format", "definition", "nonce", "retention", "state", "credentialResource", "accountId", "_meta") } // The agent is reading and validating the definition, or listing the @@ -4583,12 +4570,14 @@ type UsageInfo struct { } type ErrorInfo struct { - // Error type identifier. Well-known values: - // - // - `modelSourceUnavailable`: a turn's registered model source can't serve - // it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - // See [Unavailable sources](/guide/model-sources#unavailable-sources). + // Error type identifier ErrorType string `json:"errorType"` + // The {@link AhpErrorCodes} value for this error, when one applies. For + // example, a turn whose registered model source can't serve it ends with + // `ModelSourceUnavailable`. + // + // Stability: 1.0 - Early development. + ErrorCode *AhpErrorCode `json:"errorCode,omitempty"` // Human-readable error message Message string `json:"message"` // Stack trace @@ -4603,12 +4592,12 @@ type ErrorInfo struct { func (v *ErrorInfo) UnmarshalJSON(data []byte) error { type wire ErrorInfo - return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "errorType", "message", "stack", "_meta") + return unmarshalWithExtra(data, (*wire)(v), &v.Extra, "errorType", "errorCode", "message", "stack", "_meta") } func (v ErrorInfo) MarshalJSON() ([]byte, error) { type wire ErrorInfo - return marshalWithExtra(wire(v), v.Extra, "errorType", "message", "stack", "_meta") + return marshalWithExtra(wire(v), v.Extra, "errorType", "errorCode", "message", "stack", "_meta") } // A point-in-time snapshot of a subscribed resource's state, returned by diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index 783f1ff5c..9d5e9d4b3 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -598,7 +598,7 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when is StateActionRootModelSourceRemoved -> { val list = state.modelSources - val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 + val idx = list?.indexOfFirst { it.id == action.value.modelSourceId } ?: -1 if (list == null || idx < 0) { state } else { @@ -608,7 +608,7 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when is StateActionRootModelSourceStateChanged -> { val list = state.modelSources - val idx = list?.indexOfFirst { it.id == action.value.id } ?: -1 + val idx = list?.indexOfFirst { it.id == action.value.modelSourceId } ?: -1 if (list == null || idx < 0) { state } else { diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 424829922..eb53efcb7 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -1552,8 +1552,8 @@ data class RootModelSourceSetAction( ) /** - * Removes the model source with the given `id`, for every client. A no-op - * when none matches. + * Removes the model source with the given `modelSourceId`, for every client. + * A no-op when none matches. * * Stability: 1.0 - Early development. */ @@ -1563,13 +1563,14 @@ data class RootModelSourceRemovedAction( /** * The model source's `id`. */ - val id: String + val modelSourceId: String ) /** * Updates a model source's host-reported fields together: `state`, * `credentialResource`, and `accountId`. A no-op when no model source has - * `id`. Other fields of the source are preserved. Only the host dispatches it. + * `modelSourceId`. Other fields of the source are preserved. Only the host + * dispatches it. * * Stability: 1.0 - Early development. */ @@ -1579,7 +1580,7 @@ data class RootModelSourceStateChangedAction( /** * The model source's `id`. */ - val id: String, + val modelSourceId: String, /** * The new status. */ diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt index ad17ef3ae..37df971e1 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt @@ -57,7 +57,7 @@ object AhpErrorCodes { const val PERMISSION_DENIED: Int = -32009 /** The target resource already exists and the operation does not allow overwriting */ const val ALREADY_EXISTS: Int = -32010 - /** A request selects a model whose registered model source can't serve it */ + /** A request or turn needs a registered model source that can't serve it */ const val MODEL_SOURCE_UNAVAILABLE: Int = -32013 } 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 31c02e632..275d99b02 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 @@ -1966,13 +1966,11 @@ data class ModelSourceFormatInfo( /** * A source that an agent provider offers models from, such as a service, * subscription, or endpoint. The host lists the sources an agent provides - * itself, and clients can register more with a definition. Nothing here is - * a credential. + * itself, and clients can register more with a definition. * * Stability: 1.0 - Early development. */ -@KeepGeneratedSerializer -@Serializable(with = ModelSourceSerializer::class) +@Serializable data class ModelSource( /** * Host-unique ID, chosen by whoever registers the source. Also the @@ -2044,7 +2042,7 @@ data class ModelSource( * `credentialResource.resource` is the endpoint URL as the definition * names it, in any scheme the agent supports (for example * `http://localhost:11434/v1`). It's the value a client passes back as - * `authenticate({ resource })`, and nothing fetches it. + * `authenticate({ resource })`. */ val credentialResource: ProtectedResourceMetadata? = null, /** @@ -2057,15 +2055,7 @@ data class ModelSource( * MUST NOT contain a credential. */ @SerialName("_meta") - val meta: Map? = null, - @Transient - val extra: Map = emptyMap() -) - -internal object ModelSourceSerializer : UnknownMembersSerializer( - ModelSource.generatedSerializer(), - { it.extra }, - { value, extra -> value.copy(extra = extra) }, + val meta: Map? = null ) /** @@ -6242,13 +6232,17 @@ data class UsageInfo( @Serializable(with = ErrorInfoSerializer::class) data class ErrorInfo( /** - * Error type identifier. Well-known values: - * - * - `modelSourceUnavailable`: a turn's registered model source can't serve - * it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - * See [Unavailable sources](/guide/model-sources#unavailable-sources). + * Error type identifier */ val errorType: String, + /** + * The {@link AhpErrorCodes} value for this error, when one applies. For + * example, a turn whose registered model source can't serve it ends with + * `ModelSourceUnavailable`. + * + * Stability: 1.0 - Early development. + */ + val errorCode: Int? = null, /** * Human-readable error message */ diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 2749f1835..4ffd363db 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -555,27 +555,28 @@ pub struct RootModelSourceSetAction { pub model_source: ModelSource, } -/// Removes the model source with the given `id`, for every client. A no-op -/// when none matches. +/// Removes the model source with the given `modelSourceId`, for every client. +/// A no-op when none matches. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceRemovedAction { /// The model source's `id`. - pub id: String, + pub model_source_id: String, } /// Updates a model source's host-reported fields together: `state`, /// `credentialResource`, and `accountId`. A no-op when no model source has -/// `id`. Other fields of the source are preserved. Only the host dispatches it. +/// `modelSourceId`. Other fields of the source are preserved. Only the host +/// dispatches it. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceStateChangedAction { /// The model source's `id`. - pub id: String, + pub model_source_id: String, /// The new status. pub state: ModelSourceState, /// Replaces the source's `credentialResource`. Absent clears it, for a diff --git a/clients/rust/crates/ahp-types/src/errors.rs b/clients/rust/crates/ahp-types/src/errors.rs index ec7268761..23ee79114 100644 --- a/clients/rust/crates/ahp-types/src/errors.rs +++ b/clients/rust/crates/ahp-types/src/errors.rs @@ -57,7 +57,7 @@ pub mod ahp_error_codes { pub const CONFLICT: i32 = -32011; /// The host could not open the requested TCP connection. pub const TCP_CONNECTION_OPEN_FAILED: i32 = -32012; - /// A request selects a model whose registered model source can't serve it. + /// A request or turn needs a registered model source that can't serve it. pub const MODEL_SOURCE_UNAVAILABLE: i32 = -32013; } diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 331be7a92..2d2ab05fe 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2358,8 +2358,7 @@ pub struct ModelSourceFormatInfo { /// A source that an agent provider offers models from, such as a service, /// subscription, or endpoint. The host lists the sources an agent provides -/// itself, and clients can register more with a definition. Nothing here is -/// a credential. +/// itself, and clients can register more with a definition. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2422,7 +2421,7 @@ pub struct ModelSource { /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example /// `http://localhost:11434/v1`). It's the value a client passes back as - /// `authenticate({ resource })`, and nothing fetches it. + /// `authenticate({ resource })`. #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, /// The {@link AuthenticateParams.accountId} sent with the credential the @@ -2433,9 +2432,6 @@ pub struct ModelSource { /// MUST NOT contain a credential. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] pub meta: Option, - /// Unrecognized wire members retained for full-object edits. - #[serde(flatten)] - pub extra: serde_json::Map, } /// The agent is reading and validating the definition, or listing the @@ -6204,12 +6200,15 @@ pub struct UsageInfo { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorInfo { - /// Error type identifier. Well-known values: - /// - /// - `modelSourceUnavailable`: a turn's registered model source can't serve - /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - /// See [Unavailable sources](/guide/model-sources#unavailable-sources). + /// Error type identifier pub error_type: String, + /// The {@link AhpErrorCodes} value for this error, when one applies. For + /// example, a turn whose registered model source can't serve it ends with + /// `ModelSourceUnavailable`. + /// + /// Stability: 1.0 - Early development. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error_code: Option, /// Human-readable error message pub message: String, /// Stack trace diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index d24790c03..a6a2fdbc9 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -742,7 +742,7 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu let Some(list) = state.model_sources.as_mut() else { return ReduceOutcome::NoOp; }; - let Some(idx) = list.iter().position(|s| s.id == a.id) else { + let Some(idx) = list.iter().position(|s| s.id == a.model_source_id) else { return ReduceOutcome::NoOp; }; list.remove(idx); @@ -752,7 +752,7 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu let Some(source) = state .model_sources .as_mut() - .and_then(|list| list.iter_mut().find(|s| s.id == a.id)) + .and_then(|list| list.iter_mut().find(|s| s.id == a.model_source_id)) else { return ReduceOutcome::NoOp; }; diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index 0eb0e34e2..782a6ddd7 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -2368,33 +2368,34 @@ public struct RootModelSourceSetAction: Codable, Sendable, Equatable { } } -/// Removes the model source with the given `id`, for every client. A no-op -/// when none matches. +/// Removes the model source with the given `modelSourceId`, for every client. +/// A no-op when none matches. /// /// Stability: 1.0 - Early development. public struct RootModelSourceRemovedAction: Codable, Sendable, Equatable { public var type: ActionType /// The model source's `id`. - public var id: String + public var modelSourceId: String public init( type: ActionType, - id: String + modelSourceId: String ) { self.type = type - self.id = id + self.modelSourceId = modelSourceId } } /// Updates a model source's host-reported fields together: `state`, /// `credentialResource`, and `accountId`. A no-op when no model source has -/// `id`. Other fields of the source are preserved. Only the host dispatches it. +/// `modelSourceId`. Other fields of the source are preserved. Only the host +/// dispatches it. /// /// Stability: 1.0 - Early development. public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { public var type: ActionType /// The model source's `id`. - public var id: String + public var modelSourceId: String /// The new status. public var state: ModelSourceState /// Replaces the source's `credentialResource`. Absent clears it, for a @@ -2405,13 +2406,13 @@ public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { public init( type: ActionType, - id: String, + modelSourceId: String, state: ModelSourceState, credentialResource: ProtectedResourceMetadata? = nil, accountId: String? = nil ) { self.type = type - self.id = id + self.modelSourceId = modelSourceId self.state = state self.credentialResource = credentialResource self.accountId = accountId diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift index 200725a5a..3b737763e 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift @@ -39,7 +39,7 @@ public enum AhpErrorCodes { public static let permissionDenied = -32009 /// The target resource already exists and the operation does not allow overwriting public static let alreadyExists = -32010 - /// A request selects a model whose registered model source can't serve it + /// A request or turn needs a registered model source that can't serve it public static let modelSourceUnavailable = -32013 } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 552596507..f55696de3 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1983,8 +1983,7 @@ public struct ModelSourceFormatInfo: Codable, Sendable, Equatable { /// A source that an agent provider offers models from, such as a service, /// subscription, or endpoint. The host lists the sources an agent provides -/// itself, and clients can register more with a definition. Nothing here is -/// a credential. +/// itself, and clients can register more with a definition. /// /// Stability: 1.0 - Early development. public struct ModelSource: Codable, Sendable, Equatable { @@ -2039,7 +2038,7 @@ public struct ModelSource: Codable, Sendable, Equatable { /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example /// `http://localhost:11434/v1`). It's the value a client passes back as - /// `authenticate({ resource })`, and nothing fetches it. + /// `authenticate({ resource })`. public var credentialResource: ProtectedResourceMetadata? /// The {@link AuthenticateParams.accountId} sent with the credential the /// host most recently accepted. Set with `state`. @@ -2047,10 +2046,8 @@ public struct ModelSource: Codable, Sendable, Equatable { /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. public var meta: [String: AnyCodable]? - /// Unrecognized wire members retained for full-object edits. - public var extra: [String: AnyCodable] - enum CodingKeys: String, CodingKey, CaseIterable { + enum CodingKeys: String, CodingKey { case id case provider case displayName @@ -2077,8 +2074,7 @@ public struct ModelSource: Codable, Sendable, Equatable { state: ModelSourceState? = nil, credentialResource: ProtectedResourceMetadata? = nil, accountId: String? = nil, - meta: [String: AnyCodable]? = nil, - extra: [String: AnyCodable] = [:] + meta: [String: AnyCodable]? = nil ) { self.id = id self.provider = provider @@ -2092,41 +2088,6 @@ public struct ModelSource: Codable, Sendable, Equatable { self.credentialResource = credentialResource self.accountId = accountId self.meta = meta - self.extra = extra - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.provider = try container.decode(String.self, forKey: .provider) - self.displayName = try container.decode(String.self, forKey: .displayName) - self.icons = try container.decodeIfPresent([Icon].self, forKey: .icons) - self.format = try container.decodeIfPresent(String.self, forKey: .format) - self.definition = try container.decodeIfPresent([String: AnyCodable].self, forKey: .definition) - self.nonce = try container.decodeIfPresent(String.self, forKey: .nonce) - self.retention = try container.decodeIfPresent(ModelSourceRetentionPolicy.self, forKey: .retention) - self.state = try container.decodeIfPresent(ModelSourceState.self, forKey: .state) - self.credentialResource = try container.decodeIfPresent(ProtectedResourceMetadata.self, forKey: .credentialResource) - self.accountId = try container.decodeIfPresent(String.self, forKey: .accountId) - self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) - self.extra = try decodeUnknownMembers(from: decoder, known: Set(CodingKeys.allCases.map(\.rawValue))) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(self.id, forKey: .id) - try container.encode(self.provider, forKey: .provider) - try container.encode(self.displayName, forKey: .displayName) - try container.encodeIfPresent(self.icons, forKey: .icons) - try container.encodeIfPresent(self.format, forKey: .format) - try container.encodeIfPresent(self.definition, forKey: .definition) - try container.encodeIfPresent(self.nonce, forKey: .nonce) - try container.encodeIfPresent(self.retention, forKey: .retention) - try container.encodeIfPresent(self.state, forKey: .state) - try container.encodeIfPresent(self.credentialResource, forKey: .credentialResource) - try container.encodeIfPresent(self.accountId, forKey: .accountId) - try container.encodeIfPresent(self.meta, forKey: .meta) - try encodeUnknownMembers(extra, to: encoder, known: Set(CodingKeys.allCases.map(\.rawValue))) } } @@ -7710,12 +7671,14 @@ public struct UsageInfo: Codable, Sendable, Equatable { } public struct ErrorInfo: Codable, Sendable, Equatable { - /// Error type identifier. Well-known values: - /// - /// - `modelSourceUnavailable`: a turn's registered model source can't serve - /// it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - /// See [Unavailable sources](/guide/model-sources#unavailable-sources). + /// Error type identifier public var errorType: String + /// The {@link AhpErrorCodes} value for this error, when one applies. For + /// example, a turn whose registered model source can't serve it ends with + /// `ModelSourceUnavailable`. + /// + /// Stability: 1.0 - Early development. + public var errorCode: Int? /// Human-readable error message public var message: String /// Stack trace @@ -7729,6 +7692,7 @@ public struct ErrorInfo: Codable, Sendable, Equatable { enum CodingKeys: String, CodingKey, CaseIterable { case errorType + case errorCode case message case stack case meta = "_meta" @@ -7736,12 +7700,14 @@ public struct ErrorInfo: Codable, Sendable, Equatable { public init( errorType: String, + errorCode: Int? = nil, message: String, stack: String? = nil, meta: [String: AnyCodable]? = nil, extra: [String: AnyCodable] = [:] ) { self.errorType = errorType + self.errorCode = errorCode self.message = message self.stack = stack self.meta = meta @@ -7751,6 +7717,7 @@ public struct ErrorInfo: Codable, Sendable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.errorType = try container.decode(String.self, forKey: .errorType) + self.errorCode = try container.decodeIfPresent(Int.self, forKey: .errorCode) self.message = try container.decode(String.self, forKey: .message) self.stack = try container.decodeIfPresent(String.self, forKey: .stack) self.meta = try container.decodeIfPresent([String: AnyCodable].self, forKey: .meta) @@ -7760,6 +7727,7 @@ public struct ErrorInfo: Codable, Sendable, Equatable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.errorType, forKey: .errorType) + try container.encodeIfPresent(self.errorCode, forKey: .errorCode) try container.encode(self.message, forKey: .message) try container.encodeIfPresent(self.stack, forKey: .stack) try container.encodeIfPresent(self.meta, forKey: .meta) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index 79f3d5744..b0c6c0d7f 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -107,7 +107,7 @@ public struct AHPRootReducer: Reducer { applyModelSourceSet(&state, a.modelSource) case .rootModelSourceRemoved(let a): - _ = applyModelSourceRemoved(&state, id: a.id) + _ = applyModelSourceRemoved(&state, id: a.modelSourceId) case .rootModelSourceStateChanged(let a): _ = applyModelSourceStateChanged(&state, a) @@ -156,7 +156,7 @@ private func sameModelSourceVersion(_ a: ModelSource, _ b: ModelSource) -> Bool /// Returns `false` when none matches. func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelSourceStateChangedAction) -> Bool { guard var list = state.modelSources, - let idx = list.firstIndex(where: { $0.id == action.id }) else { return false } + let idx = list.firstIndex(where: { $0.id == action.modelSourceId }) else { return false } list[idx].state = action.state list[idx].credentialResource = action.credentialResource list[idx].accountId = action.accountId diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index 9c684ffcb..a0a5ec5b6 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -129,7 +129,7 @@ public func rootReducer(state: RootState, action: StateAction) -> RootState { case .rootModelSourceRemoved(let a): var next = state - guard applyModelSourceRemoved(&next, id: a.id) else { return state } + guard applyModelSourceRemoved(&next, id: a.modelSourceId) else { return state } return next case .rootModelSourceStateChanged(let a): diff --git a/docs/.changes/20261123-model-source-registry-migration.json b/docs/.changes/20261123-model-source-registry-migration.json index d9f663e27..44a8a9e91 100644 --- a/docs/.changes/20261123-model-source-registry-migration.json +++ b/docs/.changes/20261123-model-source-registry-migration.json @@ -1,6 +1,6 @@ { "type": "changed", - "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. `AuthenticateTarget` is now a union, so TypeScript code that reads `target.session` or `target.customizationId` must first narrow on `target.kind`. Direct Rust struct literals for `RootState` must now include `model_sources: None`, and those for `AgentCapabilities` must include `model_source_registration: None`.", + "message": "`StateAction`, `AuthenticateTarget`, and `AuthenticateTargetKind` gain model source variants, so exhaustive matches and switches must handle them. `AuthenticateTarget` is now a union, so TypeScript code that reads `target.session` or `target.customizationId` must first narrow on `target.kind`. Direct Rust struct literals for `RootState` must now include `model_sources: None`, those for `AgentCapabilities` must include `model_source_registration: None`, and those for `ErrorInfo` must include `error_code: None`.", "targets": ["rust", "swift", "kotlin", "typescript"], "issues": [619] } diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index 9f1f825d1..6b3a038e4 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,5 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. A registered `ModelSource` carries its `format`, its `definition`, and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. Agents advertise the formats they read as `ModelSourceFormatInfo` entries in `AgentCapabilities.modelSourceRegistration`. Clients deliver each source's credential with a `modelSource` `authenticate` target, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`). A turn on an unavailable source ends with the resumable `modelSourceUnavailable` error, and a request that selects one of its models fails with `ModelSourceUnavailable` (`-32013`).", + "message": "Model source registry: clients can register bring-your-own-key model sources with the host through the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. A registered `ModelSource` carries its `format`, its `definition`, and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. Agents advertise the formats they read as `ModelSourceFormatInfo` entries in `AgentCapabilities.modelSourceRegistration`. Clients deliver each source's credential with a `modelSource` `authenticate` target, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`). Requests and turns that need an unavailable source fail with the new `AhpErrorCodes.ModelSourceUnavailable` (`-32013`), which a turn's error part carries in the new optional `ErrorInfo.errorCode`.", "issues": [619] } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 8afad2ff8..9a2dd9aa8 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -32,7 +32,7 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | | `root/modelSourceSet` | **Yes** | A [model source](/guide/model-sources) was added, re-registered, or updated by `id` | -| `root/modelSourceRemoved` | **Yes** | A model source was removed by `id` | +| `root/modelSourceRemoved` | **Yes** | A model source was removed by `modelSourceId` | | `root/modelSourceStateChanged` | No | The host reported a model source's status and credential fields | ## Automation Catalogue Actions diff --git a/docs/guide/model-sources.md b/docs/guide/model-sources.md index 18f77c680..99b2e27a4 100644 --- a/docs/guide/model-sources.md +++ b/docs/guide/model-sources.md @@ -63,7 +63,7 @@ Each client that registers a source is a **contributing client**. The host track ## Status -The host reports a registered source's status with [`root/modelSourceStateChanged`](/reference/root#rootmodelsourcestatechangedaction), which sets `state`, `credentialResource`, and `accountId` together. The reducer ignores an unknown `id`, so a late report can't bring back a removed source. +The host reports a registered source's status with [`root/modelSourceStateChanged`](/reference/root#rootmodelsourcestatechangedaction), which sets `state`, `credentialResource`, and `accountId` together. The reducer ignores an unknown `modelSourceId`, so a late report can't bring back a removed source. ```mermaid stateDiagram-v2 @@ -123,7 +123,7 @@ The host SHOULD reject an automation that names a model from a `contributingClie ## Unavailable sources -The host checks a selection whenever it uses one, and never runs work on a model other than the one selected. When a turn can't use its source, the host ends the turn with an error part whose `errorType` is `modelSourceUnavailable` and whose `resumable` is `true`. Once the source is ready again, a client can continue the turn with `chat/turnResume`. A request that selects such a model fails with [`ModelSourceUnavailable`](/reference/error-codes#ahp-application-codes) (`-32013`). +The host checks a selection whenever it uses one, and never runs work on a model other than the one selected. Requests and turns that need an unavailable source fail with [`ModelSourceUnavailable`](/reference/error-codes#ahp-application-codes) (`-32013`). A turn ends with an error part whose `error.errorCode` is that code and whose `resumable` is `true`, so once the source is ready again, a client can continue the turn with `chat/turnResume`. When a client removes a source or revokes its credential, the host ends running turns that use it. diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index 5d9944866..f1172d593 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -129,8 +129,8 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | | `root/modelSourceSet` | Server / Client | Adds a source to `modelSources`, or replaces the one with the same `id`. Keeps its host-reported fields when `provider`, `format`, and `nonce` are unchanged | -| `root/modelSourceRemoved` | Server / Client | Removes a source by `id` | -| `root/modelSourceStateChanged` | Server | Sets a source's host-reported fields. A no-op for an unknown `id` | +| `root/modelSourceRemoved` | Server / Client | Removes the source whose `id` is `modelSourceId` | +| `root/modelSourceStateChanged` | Server | Sets a source's host-reported fields. A no-op for an unknown `modelSourceId` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index fb637baa2..042d1a7b8 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -146,29 +146,29 @@ }, "RootModelSourceRemovedAction": { "type": "object", - "description": "Removes the model source with the given `id`, for every client. A no-op\nwhen none matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRemoved" }, - "id": { + "modelSourceId": { "type": "string", "description": "The model source's `id`." } }, "required": [ "type", - "id" + "modelSourceId" ] }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`id`. Other fields of the source are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`modelSourceId`. Other fields of the source are preserved. Only the host\ndispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" }, - "id": { + "modelSourceId": { "type": "string", "description": "The model source's `id`." }, @@ -187,7 +187,7 @@ }, "required": [ "type", - "id", + "modelSourceId", "state" ] }, @@ -3321,7 +3321,11 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." + "description": "Error type identifier" + }, + "errorCode": { + "$ref": "#/$defs/AhpErrorCode", + "description": "The {@link AhpErrorCodes} value for this error, when one applies. For\nexample, a turn whose registered model source can't serve it ends with\n`ModelSourceUnavailable`.\n\nStability: 1.0 - Early development." }, "message": { "type": "string", @@ -3654,7 +3658,7 @@ }, "ModelSource": { "type": "object", - "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -3698,7 +3702,7 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", @@ -10831,6 +10835,10 @@ "type": "string", "description": "How the server resumes sending data on a windowed subscription after\nreconnection." }, + "AhpErrorCode": { + "type": "integer", + "description": "An AHP application error code, such as a value of `AhpErrorCodes`." + }, "PolicyState": { "enum": [ "enabled", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 241feb623..32c0ae906 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -2631,7 +2631,11 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." + "description": "Error type identifier" + }, + "errorCode": { + "$ref": "#/$defs/AhpErrorCode", + "description": "The {@link AhpErrorCodes} value for this error, when one applies. For\nexample, a turn whose registered model source can't serve it ends with\n`ModelSourceUnavailable`.\n\nStability: 1.0 - Early development." }, "message": { "type": "string", @@ -2964,7 +2968,7 @@ }, "ModelSource": { "type": "object", - "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -3008,7 +3012,7 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", @@ -9195,29 +9199,29 @@ }, "RootModelSourceRemovedAction": { "type": "object", - "description": "Removes the model source with the given `id`, for every client. A no-op\nwhen none matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRemoved" }, - "id": { + "modelSourceId": { "type": "string", "description": "The model source's `id`." } }, "required": [ "type", - "id" + "modelSourceId" ] }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`id`. Other fields of the source are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`modelSourceId`. Other fields of the source are preserved. Only the host\ndispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" }, - "id": { + "modelSourceId": { "type": "string", "description": "The model source's `id`." }, @@ -9236,7 +9240,7 @@ }, "required": [ "type", - "id", + "modelSourceId", "state" ] }, @@ -12259,6 +12263,10 @@ ], "description": "A primitive JSON value: a string, number, boolean, or `null`." }, + "AhpErrorCode": { + "type": "integer", + "description": "An AHP application error code, such as a value of `AhpErrorCodes`." + }, "Customization": { "oneOf": [ { diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 659c8f3ba..76de69eef 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -29,7 +29,8 @@ -32008, -32009, -32010, - -32011 + -32011, + -32013 ] }, "AuthRequiredErrorData": { @@ -541,7 +542,11 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." + "description": "Error type identifier" + }, + "errorCode": { + "$ref": "#/$defs/AhpErrorCode", + "description": "The {@link AhpErrorCodes} value for this error, when one applies. For\nexample, a turn whose registered model source can't serve it ends with\n`ModelSourceUnavailable`.\n\nStability: 1.0 - Early development." }, "message": { "type": "string", @@ -874,7 +879,7 @@ }, "ModelSource": { "type": "object", - "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -918,7 +923,7 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", @@ -10549,29 +10554,29 @@ }, "RootModelSourceRemovedAction": { "type": "object", - "description": "Removes the model source with the given `id`, for every client. A no-op\nwhen none matches.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceRemoved" }, - "id": { + "modelSourceId": { "type": "string", "description": "The model source's `id`." } }, "required": [ "type", - "id" + "modelSourceId" ] }, "RootModelSourceStateChangedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`id`. Other fields of the source are preserved. Only the host dispatches it.\n\nStability: 1.0 - Early development.", + "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`modelSourceId`. Other fields of the source are preserved. Only the host\ndispatches it.\n\nStability: 1.0 - Early development.", "properties": { "type": { "const": "root/modelSourceStateChanged" }, - "id": { + "modelSourceId": { "type": "string", "description": "The model source's `id`." }, @@ -10590,7 +10595,7 @@ }, "required": [ "type", - "id", + "modelSourceId", "state" ] }, diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index d5c6f936f..7e69de2ac 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -843,7 +843,11 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." + "description": "Error type identifier" + }, + "errorCode": { + "$ref": "#/$defs/AhpErrorCode", + "description": "The {@link AhpErrorCodes} value for this error, when one applies. For\nexample, a turn whose registered model source can't serve it ends with\n`ModelSourceUnavailable`.\n\nStability: 1.0 - Early development." }, "message": { "type": "string", @@ -1176,7 +1180,7 @@ }, "ModelSource": { "type": "object", - "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -1220,7 +1224,7 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", @@ -7314,6 +7318,10 @@ ], "description": "A primitive JSON value: a string, number, boolean, or `null`." }, + "AhpErrorCode": { + "type": "integer", + "description": "An AHP application error code, such as a value of `AhpErrorCodes`." + }, "Customization": { "oneOf": [ { diff --git a/schema/state.schema.json b/schema/state.schema.json index 006421436..e53d53172 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -452,7 +452,11 @@ "properties": { "errorType": { "type": "string", - "description": "Error type identifier. Well-known values:\n\n- `modelSourceUnavailable`: a turn's registered model source can't serve\n it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`.\n See [Unavailable sources](/guide/model-sources#unavailable-sources)." + "description": "Error type identifier" + }, + "errorCode": { + "$ref": "#/$defs/AhpErrorCode", + "description": "The {@link AhpErrorCodes} value for this error, when one applies. For\nexample, a turn whose registered model source can't serve it ends with\n`ModelSourceUnavailable`.\n\nStability: 1.0 - Early development." }, "message": { "type": "string", @@ -785,7 +789,7 @@ }, "ModelSource": { "type": "object", - "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition. Nothing here is\na credential.\n\nStability: 1.0 - Early development.", + "description": "A source that an agent provider offers models from, such as a service,\nsubscription, or endpoint. The host lists the sources an agent provides\nitself, and clients can register more with a definition.\n\nStability: 1.0 - Early development.", "properties": { "id": { "type": "string", @@ -829,7 +833,7 @@ }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`, and nothing fetches it." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", @@ -7551,6 +7555,10 @@ "type": "string", "description": "How the server resumes sending data on a windowed subscription after\nreconnection." }, + "AhpErrorCode": { + "type": "integer", + "description": "An AHP application error code, such as a value of `AhpErrorCodes`." + }, "PolicyState": { "enum": [ "enabled", diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index f30c997ad..fe5a7459f 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -172,6 +172,7 @@ function mapType(tsType: string): string { if (tsType === 'true' || tsType === 'false') return 'bool'; if (tsType === 'URI') return 'string'; + if (tsType === 'AhpErrorCode') return 'int'; if (tsType === 'StringOrMarkdown') return 'StringOrMarkdown'; // ChildCustomizationType is a TS-only subset alias of CustomizationType. diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index ca939c122..319c9a682 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -2461,7 +2461,7 @@ const ( \tErrorCodeAlreadyExists int32 = -32010 \t// ErrorCodeTcpConnectionOpenFailed indicates that the host could not open a TCP connection. \tErrorCodeTcpConnectionOpenFailed int32 = -32012 -\t// ErrorCodeModelSourceUnavailable indicates that a request selects a model whose registered model source can't serve it. +\t// ErrorCodeModelSourceUnavailable indicates that a request or turn needs a registered model source that can't serve it. \tErrorCodeModelSourceUnavailable int32 = -32013 ) diff --git a/scripts/generate-json-schema.ts b/scripts/generate-json-schema.ts index 1f7196b40..4c9b35587 100644 --- a/scripts/generate-json-schema.ts +++ b/scripts/generate-json-schema.ts @@ -703,7 +703,7 @@ function generateErrorsSchema(project: Project): JsonSchema { AhpErrorCode: { description: 'AHP application-specific error codes.', type: 'number', - enum: [-32001, -32002, -32003, -32004, -32005, -32007, -32008, -32009, -32010, -32011], + enum: [-32001, -32002, -32003, -32004, -32005, -32007, -32008, -32009, -32010, -32011, -32013], }, }, }; @@ -763,6 +763,12 @@ function buildDefForName(project: Project, name: string): JsonSchema | undefined const iface = findInterface(project, name); if (iface) return interfaceToSchema(iface, project); + // An error code carried in state is an integer. Receivers keep codes they + // don't know, so it isn't limited to the current `AhpErrorCodes` values. + if (name === 'AhpErrorCode') { + return { type: 'integer', description: 'An AHP application error code, such as a value of `AhpErrorCodes`.' }; + } + const ta = findTypeAlias(project, name); if (ta) { const typeText = ta.getTypeNode()?.getText() || ''; diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index a0753fa35..dc77c0b10 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -144,6 +144,7 @@ function mapType(tsType: string): string { // Type aliases if (tsType === 'URI') return 'String'; + if (tsType === 'AhpErrorCode') return 'Int'; if (tsType === 'StringOrMarkdown') return 'StringOrMarkdown'; if (tsType === 'ToolInput') return 'ToolInput'; // ChildCustomizationType is a TS-only subset alias of CustomizationType. @@ -2442,7 +2443,7 @@ function generateErrorsFile(project: Project): string { lines.push(' const val PERMISSION_DENIED: Int = -32009'); lines.push(' /** The target resource already exists and the operation does not allow overwriting */'); lines.push(' const val ALREADY_EXISTS: Int = -32010'); - lines.push(" /** A request selects a model whose registered model source can't serve it */"); + lines.push(" /** A request or turn needs a registered model source that can't serve it */"); lines.push(' const val MODEL_SOURCE_UNAVAILABLE: Int = -32013'); lines.push('}'); lines.push(''); diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index e5a16f431..49be5b4f1 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -153,6 +153,7 @@ function mapType(tsType: string, propName?: string, containerName?: string): str if (tsType === 'JsonPrimitive') return 'AnyValue'; if (tsType === 'URI') return 'Uri'; + if (tsType === 'AhpErrorCode') return 'i32'; if (tsType === 'StringOrMarkdown') return 'StringOrMarkdown'; if (tsType === 'ToolInput') return 'ToolInput'; @@ -2493,7 +2494,7 @@ pub mod ahp_error_codes { pub const CONFLICT: i32 = -32011; /// The host could not open the requested TCP connection. pub const TCP_CONNECTION_OPEN_FAILED: i32 = -32012; - /// A request selects a model whose registered model source can't serve it. + /// A request or turn needs a registered model source that can't serve it. pub const MODEL_SOURCE_UNAVAILABLE: i32 = -32013; } diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 0054af5d6..5654a754f 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -114,6 +114,7 @@ function mapType(tsType: string, propName?: string, containerName?: string): str // Type aliases if (tsType === 'URI') return 'String'; + if (tsType === 'AhpErrorCode') return 'Int'; if (tsType === 'StringOrMarkdown') return 'StringOrMarkdown'; if (tsType === 'ToolInput') return 'ToolInput'; // ChildCustomizationType is a TS-only subset alias of CustomizationType. @@ -2431,7 +2432,7 @@ function generateErrorsFile(project: Project): string { lines.push(' public static let permissionDenied = -32009'); lines.push(' /// The target resource already exists and the operation does not allow overwriting'); lines.push(' public static let alreadyExists = -32010'); - lines.push(" /// A request selects a model whose registered model source can't serve it"); + lines.push(" /// A request or turn needs a registered model source that can't serve it"); lines.push(' public static let modelSourceUnavailable = -32013'); lines.push('}'); lines.push(''); diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index d552e4034..613179520 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -95,8 +95,8 @@ export interface RootModelSourceSetAction { } /** - * Removes the model source with the given `id`, for every client. A no-op - * when none matches. + * Removes the model source with the given `modelSourceId`, for every client. + * A no-op when none matches. * * @category Root Actions * @stability 1.0 @@ -106,13 +106,14 @@ export interface RootModelSourceSetAction { export interface RootModelSourceRemovedAction { type: ActionType.RootModelSourceRemoved; /** The model source's `id`. */ - id: string; + modelSourceId: string; } /** * Updates a model source's host-reported fields together: `state`, * `credentialResource`, and `accountId`. A no-op when no model source has - * `id`. Other fields of the source are preserved. Only the host dispatches it. + * `modelSourceId`. Other fields of the source are preserved. Only the host + * dispatches it. * * @category Root Actions * @stability 1.0 @@ -121,7 +122,7 @@ export interface RootModelSourceRemovedAction { export interface RootModelSourceStateChangedAction { type: ActionType.RootModelSourceStateChanged; /** The model source's `id`. */ - id: string; + modelSourceId: string; /** The new status. */ state: ModelSourceState; /** diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index d28401f06..cbcf4cac3 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -55,7 +55,7 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st if (!list) { return state; } - const idx = list.findIndex(source => source.id === action.id); + const idx = list.findIndex(source => source.id === action.modelSourceId); if (idx < 0) { return state; } @@ -69,7 +69,7 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st if (!list) { return state; } - const idx = list.findIndex(source => source.id === action.id); + const idx = list.findIndex(source => source.id === action.modelSourceId); if (idx < 0) { return state; } diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index e6e27ddb9..cf1eb598c 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -319,12 +319,10 @@ export interface ModelSourceFormatInfo { /** * A source that an agent provider offers models from, such as a service, * subscription, or endpoint. The host lists the sources an agent provides - * itself, and clients can register more with a definition. Nothing here is - * a credential. + * itself, and clients can register more with a definition. * * @category Root State * @stability 1.0 - * @preserveUnknownMembers * @see {@link /guide/model-sources | Model Sources guide} */ export interface ModelSource { @@ -390,7 +388,7 @@ export interface ModelSource { * `credentialResource.resource` is the endpoint URL as the definition * names it, in any scheme the agent supports (for example * `http://localhost:11434/v1`). It's the value a client passes back as - * `authenticate({ resource })`, and nothing fetches it. + * `authenticate({ resource })`. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ diff --git a/types/common/errors.ts b/types/common/errors.ts index 821607e80..f81aea3f7 100644 --- a/types/common/errors.ts +++ b/types/common/errors.ts @@ -96,10 +96,9 @@ export const AhpErrorCodes = { /** The host could not open the requested TCP connection. */ TcpConnectionOpenFailed: -32012, /** - * A request selects a model whose registered model source can't serve it, + * A request or turn needs a registered model source that can't serve it, * for example because the source needs a credential or was removed. A turn - * that fails for this reason ends with an error part whose `errorType` is - * `modelSourceUnavailable` instead. + * carries it in its error part's `ErrorInfo.errorCode`. * * @see {@link /guide/model-sources#unavailable-sources | Model Sources guide} */ diff --git a/types/common/state.ts b/types/common/state.ts index 9e3a1c7e7..9dbd6f5cc 100644 --- a/types/common/state.ts +++ b/types/common/state.ts @@ -18,6 +18,7 @@ import type { CanvasState } from '../channels-canvas/state.js'; import type { AutomationState } from '../channels-automation/state.js'; import type { AutomationRunState } from '../channels-automation-run/state.js'; import type { SearchState } from '../channels-search/state.js'; +import type { AhpErrorCode } from './errors.js'; // ─── Type Aliases ──────────────────────────────────────────────────────────── @@ -438,14 +439,16 @@ export interface UsageInfo { * @preserveUnknownMembers */ export interface ErrorInfo { + /** Error type identifier */ + errorType: string; /** - * Error type identifier. Well-known values: + * The {@link AhpErrorCodes} value for this error, when one applies. For + * example, a turn whose registered model source can't serve it ends with + * `ModelSourceUnavailable`. * - * - `modelSourceUnavailable`: a turn's registered model source can't serve - * it, the turn-level counterpart of `AhpErrorCodes.ModelSourceUnavailable`. - * See [Unavailable sources](/guide/model-sources#unavailable-sources). + * @stability 1.0 */ - errorType: string; + errorCode?: AhpErrorCode; /** Human-readable error message */ message: string; /** Stack trace */ diff --git a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json index 300a2c367..0451245c5 100644 --- a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json +++ b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json @@ -47,7 +47,7 @@ "actions": [ { "type": "root/modelSourceRemoved", - "id": "model-source-a" + "modelSourceId": "model-source-a" } ], "expected": { diff --git a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json index 1c7188c56..74edce9c2 100644 --- a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json @@ -24,7 +24,7 @@ "actions": [ { "type": "root/modelSourceRemoved", - "id": "model-source-missing" + "modelSourceId": "model-source-missing" } ], "expected": { diff --git a/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json index 975bb553e..1d10c86ab 100644 --- a/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json +++ b/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json @@ -7,7 +7,7 @@ "actions": [ { "type": "root/modelSourceRemoved", - "id": "model-source-a" + "modelSourceId": "model-source-a" } ], "expected": { diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json index 374e85630..db6a52dd1 100644 --- a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json +++ b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json @@ -43,7 +43,7 @@ "actions": [ { "type": "root/modelSourceStateChanged", - "id": "model-source-b", + "modelSourceId": "model-source-b", "state": { "kind": "authRequired", "reason": "rejected", diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json index df738b847..0f27b7b0b 100644 --- a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json +++ b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json @@ -32,7 +32,7 @@ "actions": [ { "type": "root/modelSourceStateChanged", - "id": "model-source-a", + "modelSourceId": "model-source-a", "state": { "kind": "ready" } diff --git a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json index 095c32da3..6df8f578c 100644 --- a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json @@ -24,7 +24,7 @@ "actions": [ { "type": "root/modelSourceStateChanged", - "id": "model-source-removed", + "modelSourceId": "model-source-removed", "state": { "kind": "ready" } diff --git a/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json b/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json index 5e5bedf59..11c86ccbb 100644 --- a/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json +++ b/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json @@ -7,7 +7,7 @@ "actions": [ { "type": "root/modelSourceStateChanged", - "id": "model-source-a", + "modelSourceId": "model-source-a", "state": { "kind": "starting" } diff --git a/types/test-cases/round-trips/105-root-model-source-removed.json b/types/test-cases/round-trips/105-root-model-source-removed.json index cbb4b9edd..78779e57c 100644 --- a/types/test-cases/round-trips/105-root-model-source-removed.json +++ b/types/test-cases/round-trips/105-root-model-source-removed.json @@ -5,12 +5,12 @@ "type": "StateAction", "input": { "type": "root/modelSourceRemoved", - "id": "source-new" + "modelSourceId": "source-new" }, "acceptableOutputs": [ { "type": "root/modelSourceRemoved", - "id": "source-new" + "modelSourceId": "source-new" } ] } diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json index 3a92d9e08..9b33d6500 100644 --- a/types/test-cases/round-trips/107-root-model-source-state-changed.json +++ b/types/test-cases/round-trips/107-root-model-source-state-changed.json @@ -5,7 +5,7 @@ "type": "StateAction", "input": { "type": "root/modelSourceStateChanged", - "id": "source-new", + "modelSourceId": "source-new", "state": { "kind": "authRequired", "reason": "rejected", @@ -20,7 +20,7 @@ "acceptableOutputs": [ { "type": "root/modelSourceStateChanged", - "id": "source-new", + "modelSourceId": "source-new", "state": { "kind": "authRequired", "reason": "rejected", diff --git a/types/test-cases/round-trips/118-chat-error-part-error-code.json b/types/test-cases/round-trips/118-chat-error-part-error-code.json new file mode 100644 index 000000000..78cd2f162 --- /dev/null +++ b/types/test-cases/round-trips/118-chat-error-part-error-code.json @@ -0,0 +1,36 @@ +{ + "name": "chat-error-part-error-code", + "group": "A", + "description": "A chat/error part's ErrorInfo carries an AhpErrorCodes value in errorCode, here ModelSourceUnavailable for a turn whose registered model source can't serve it.", + "type": "StateAction", + "input": { + "type": "chat/error", + "turnId": "turn-1", + "duration": 250, + "part": { + "kind": "error", + "error": { + "errorType": "modelSourceUnavailable", + "errorCode": -32013, + "message": "The model source needs a credential." + }, + "resumable": true + } + }, + "acceptableOutputs": [ + { + "type": "chat/error", + "turnId": "turn-1", + "duration": 250, + "part": { + "kind": "error", + "error": { + "errorType": "modelSourceUnavailable", + "errorCode": -32013, + "message": "The model source needs a credential." + }, + "resumable": true + } + } + ] +} From 2b520a36320baf85af618d8daa186c820e7fd9cd Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 15:07:27 -0500 Subject: [PATCH 15/17] models: register model sources through a request and a host-only Set Follow the automation pattern, per review: - Clients dispatch `root/modelSourceRegisterRequested`, whose reducer leaves state unchanged. The host publishes every source and status change with `root/modelSourceSet`, now host-only and a plain replace, and `root/modelSourceStateChanged` is removed. - Group `format`, `definition`, and `retention` in `ModelSource.registration`, drop `nonce`, and make `state` required. Hosts compare definitions themselves. - Update the generators, client reducers, fixtures, guide, specs, naming dictionary, changelog, and the proposal's status. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Actions.generated.cs | 61 ++-- .../JsonSerializerContext.generated.cs | 3 +- .../Generated/State.generated.cs | 77 ++-- .../Generated/ActionMetadata.generated.cs | 6 +- .../dotnet/src/AgentHostProtocol/Reducers.cs | 31 +- clients/go/ahp/reducers.go | 49 +-- clients/go/ahptypes/actions.generated.go | 58 ++- clients/go/ahptypes/state.generated.go | 62 ++-- .../microsoft/agenthostprotocol/Reducers.kt | 30 +- .../generated/Actions.generated.kt | 63 ++-- .../generated/State.generated.kt | 89 ++--- clients/rust/crates/ahp-types/src/actions.rs | 72 ++-- clients/rust/crates/ahp-types/src/state.rs | 69 ++-- clients/rust/crates/ahp/src/reducers.rs | 51 +-- .../Generated/ActionOrigin.generated.swift | 4 +- .../Generated/Actions.generated.swift | 90 ++--- .../Generated/State.generated.swift | 105 +++--- .../AgentHostProtocol/NativeReducer.swift | 37 +- .../Sources/AgentHostProtocol/Reducers.swift | 5 - .../20261022-model-source-selection.json | 2 +- .../20261123-model-source-registry.json | 16 +- docs/guide/actions.md | 6 +- docs/guide/model-sources.md | 50 ++- docs/proposals/model-source-registry.md | 7 +- docs/specification/root-channel.md | 20 +- schema/actions.schema.json | 135 ++++--- schema/commands.schema.json | 151 ++++---- schema/errors.schema.json | 151 ++++---- schema/notifications.schema.json | 69 ++-- schema/state.schema.json | 53 +-- scripts/generate-csharp.ts | 3 +- scripts/generate-go.ts | 3 +- scripts/generate-kotlin.ts | 4 +- scripts/generate-rust.ts | 5 +- scripts/generate-swift.ts | 4 +- skills/protocol-authoring/naming.md | 2 +- types/action-origin.generated.ts | 12 +- types/channels-root/actions.ts | 78 ++--- types/channels-root/reducer.ts | 50 +-- types/channels-root/state.ts | 92 ++--- types/common/actions.ts | 6 +- ...odelsourceset-adds-to-absent-registry.json | 46 ++- ...e-register-keeps-host-reported-fields.json | 128 ------- ...1-root-modelsourceset-replaces-source.json | 121 +++++++ ...modelsourceregisterrequested-is-no-op.json | 81 +++++ ...et-update-clears-host-reported-fields.json | 102 ------ ...root-modelsourceremoved-removes-by-id.json | 65 ++-- ...delsourceremoved-no-op-for-unknown-id.json | 56 ++- ...echanged-updates-host-reported-fields.json | 105 ------ ...statechanged-clears-credential-fields.json | 64 ---- ...urcestatechanged-no-op-for-unknown-id.json | 53 --- ...atechanged-no-op-when-registry-absent.json | 19 - ...t-modelsourceset-adds-built-in-source.json | 83 +++++ ...ourceset-built-in-source-re-registers.json | 40 --- .../round-trips/101-model-source-catalog.json | 30 +- .../103-model-source-registry-snapshot.json | 330 +++++++++--------- ...root-model-source-register-requested.json} | 26 +- .../107-root-model-source-set.json | 68 ++++ .../107-root-model-source-state-changed.json | 36 -- types/version/registry.ts | 2 +- 60 files changed, 1561 insertions(+), 1775 deletions(-) delete mode 100644 types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json create mode 100644 types/test-cases/reducers/331-root-modelsourceset-replaces-source.json create mode 100644 types/test-cases/reducers/332-root-modelsourceregisterrequested-is-no-op.json delete mode 100644 types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json delete mode 100644 types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json delete mode 100644 types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json delete mode 100644 types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json delete mode 100644 types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json create mode 100644 types/test-cases/reducers/340-root-modelsourceset-adds-built-in-source.json delete mode 100644 types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json rename types/test-cases/round-trips/{104-root-model-source-set.json => 104-root-model-source-register-requested.json} (67%) create mode 100644 types/test-cases/round-trips/107-root-model-source-set.json delete mode 100644 types/test-cases/round-trips/107-root-model-source-state-changed.json diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index a599ce0ab..487fb79b7 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -201,12 +201,12 @@ public ActionType(string value) public static readonly ActionType RootConfigChanged = new ActionType("root/configChanged"); + public static readonly ActionType RootModelSourceRegisterRequested = new ActionType("root/modelSourceRegisterRequested"); + public static readonly ActionType RootModelSourceSet = new ActionType("root/modelSourceSet"); public static readonly ActionType RootModelSourceRemoved = new ActionType("root/modelSourceRemoved"); - public static readonly ActionType RootModelSourceStateChanged = new ActionType("root/modelSourceStateChanged"); - public static readonly ActionType TerminalData = new ActionType("terminal/data"); public static readonly ActionType TerminalInput = new ActionType("terminal/input"); @@ -354,26 +354,16 @@ public sealed record RootConfigChangedAction public bool? Replace { get; init; } } -/// Adds a model source, or updates the one with the same `id`: -/// -/// - **Add.** When no model source has the `id`, appends `modelSource`. -/// - **Re-register.** When one has, with the same `provider`, `format`, and -/// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, -/// and `accountId`) and takes everything else from the action. -/// - **Update.** When any of the three differs, replaces the source. Its -/// host-reported fields are absent until the host reports again with -/// {@link RootModelSourceStateChangedAction}. -/// -/// A client registers a source with its `format`, `definition`, and `nonce`, -/// and without any host-reported field. The host learns which client -/// registered it from the envelope's `origin`. +/// Adds a model source, or replaces the one with the same `id`. Only the host +/// dispatches it, to publish a registration, a source an agent provides +/// itself, or a change in a source's status. /// /// Stability: 1.0 - Early development. public sealed record RootModelSourceSetAction { public ActionType Type { get; init; } = ActionType.RootModelSourceSet; - /// The model source to add or update, matched by `id`. + /// The model source to add or replace, matched by `id`. public required ModelSource ModelSource { get; init; } } @@ -389,30 +379,39 @@ public sealed record RootModelSourceRemovedAction public required string ModelSourceId { get; init; } } -/// Updates a model source's host-reported fields together: `state`, -/// `credentialResource`, and `accountId`. A no-op when no model source has -/// `modelSourceId`. Other fields of the source are preserved. Only the host -/// dispatches it. +/// Asks the host to register a model source, or to update the one with the +/// same `modelSourceId`. The reducer leaves state unchanged. The host counts +/// the dispatching client as a contributing client, validates the +/// registration, and publishes the result with +/// {@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the +/// source's status and credential when the registration is unchanged. /// /// Stability: 1.0 - Early development. -public sealed record RootModelSourceStateChangedAction +public sealed record RootModelSourceRegisterRequestedAction { - public ActionType Type { get; init; } = ActionType.RootModelSourceStateChanged; + public ActionType Type { get; init; } = ActionType.RootModelSourceRegisterRequested; - /// The model source's `id`. + /// The model source's `id`, chosen by the client. public required string ModelSourceId { get; init; } - /// The new status. - public required ModelSourceState State { get; init; } + /// Agent provider whose agent serves the source's models. + public required string Provider { get; init; } - /// Replaces the source's `credentialResource`. Absent clears it, for a - /// source that needs no credential. + /// Human-readable name. + public required string DisplayName { get; init; } + + /// Icons for UI display. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public ProtectedResourceMetadata? CredentialResource { get; init; } + public List? Icons { get; init; } + + /// The source's format, definition, and retention. + public required ModelSourceRegistration Registration { get; init; } - /// Replaces the source's `accountId`. Absent clears it. + /// Additional implementation-defined metadata for this model source. + /// MUST NOT contain a credential. + [JsonPropertyName("_meta")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? AccountId { get; init; } + public Dictionary? Meta { get; init; } } /// Session backend initialized successfully. @@ -3030,7 +3029,7 @@ public StateActionConverter() ["root/configChanged"] = typeof(RootConfigChangedAction), ["root/modelSourceSet"] = typeof(RootModelSourceSetAction), ["root/modelSourceRemoved"] = typeof(RootModelSourceRemovedAction), - ["root/modelSourceStateChanged"] = typeof(RootModelSourceStateChangedAction), + ["root/modelSourceRegisterRequested"] = typeof(RootModelSourceRegisterRequestedAction), ["session/ready"] = typeof(SessionReadyAction), ["session/creationFailed"] = typeof(SessionCreationFailedAction), ["session/turnStarted"] = typeof(SessionTurnStartedAction), diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs index af0fceada..de74ac693 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -320,6 +320,7 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(ModelSourceErrorState))] [JsonSerializable(typeof(ModelSourceFormatInfo))] [JsonSerializable(typeof(ModelSourceReadyState))] +[JsonSerializable(typeof(ModelSourceRegistration))] [JsonSerializable(typeof(ModelSourceRegistrationCapability))] [JsonSerializable(typeof(ModelSourceRetentionPolicy))] [JsonSerializable(typeof(ModelSourceStartingState))] @@ -385,9 +386,9 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(RootAgentsChangedAction))] [JsonSerializable(typeof(RootConfigChangedAction))] [JsonSerializable(typeof(RootConfigState))] +[JsonSerializable(typeof(RootModelSourceRegisterRequestedAction))] [JsonSerializable(typeof(RootModelSourceRemovedAction))] [JsonSerializable(typeof(RootModelSourceSetAction))] -[JsonSerializable(typeof(RootModelSourceStateChangedAction))] [JsonSerializable(typeof(RootState))] [JsonSerializable(typeof(RootTerminalsChangedAction))] [JsonSerializable(typeof(RuleCustomization))] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index af3c19b43..0c6e2f8f1 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2653,34 +2653,18 @@ public sealed record ModelSourceRegistrationCapability /// Stability: 1.0 - Early development. public sealed record ModelSourceFormatInfo { - /// A {@link ModelSource.format} value. + /// A {@link ModelSourceRegistration.format} value. public required string Format { get; init; } } -/// A source that an agent provider offers models from, such as a service, -/// subscription, or endpoint. The host lists the sources an agent provides -/// itself, and clients can register more with a definition. +/// How a client, or the host from its own configuration, registered a model +/// source. /// /// Stability: 1.0 - Early development. -public sealed record ModelSource +public sealed record ModelSourceRegistration { - /// Host-unique ID, chosen by whoever registers the source. Also the - /// {@link SessionModelInfo.modelSourceId} of its models. - public required string Id { get; init; } - - /// Agent provider whose agent serves the source's models. - public required string Provider { get; init; } - - /// Human-readable name. - public required string DisplayName { get; init; } - - /// Icons for UI display. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public List? Icons { get; init; } - /// The format of `definition`: the `format` of one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. Present on a - /// registered source. + /// {@link ModelSourceRegistrationCapability.formats}. /// /// Agents choose the formats they read. Some may read these common names: /// @@ -2691,41 +2675,56 @@ public sealed record ModelSource /// /// Other formats are named with a namespace, such as /// `example.com/model-source@1`, so they don't collide. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? Format { get; init; } + public required string Format { get; init; } /// How to reach the source, in `format`: endpoint, wire API, models, and so /// on. The agent reads it. Every client can read it, so it MUST NOT contain - /// a credential. Present on a registered source. + /// a credential. /// /// An agent that reads one of the common format names might expect a shape /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is /// the API's base URI and each `models` entry is `{ id, name?, /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, /// named as in {@link SessionModelInfo}. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public Dictionary? Definition { get; init; } - - /// Opaque version token for `definition`, such as a hash of it, chosen by - /// whoever registers the source. Present on a registered source. Reducers - /// compare it, instead of the definition, to tell an update from a - /// re-registration of the same definition. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? Nonce { get; init; } + public required Dictionary Definition { get; init; } /// What happens when the last contributing client leaves. Absent means `contributingClient`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ModelSourceRetentionPolicy? Retention { get; init; } +} + +/// A source that an agent provider offers models from, such as a service, +/// subscription, or endpoint. The host lists the sources an agent provides +/// itself, and clients can register more with a definition. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSource +{ + /// Host-unique ID, chosen by whoever registers the source. Also the + /// {@link SessionModelInfo.modelSourceId} of its models. + public required string Id { get; init; } + + /// Agent provider whose agent serves the source's models. + public required string Provider { get; init; } + + /// Human-readable name. + public required string DisplayName { get; init; } + + /// Icons for UI display. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? Icons { get; init; } - /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after an update replaces the - /// definition until the host reports again. + /// How the source was registered. Absent on a source the agent provides + /// itself. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public ModelSourceState? State { get; init; } + public ModelSourceRegistration? Registration { get; init; } + + /// The source's status. + public required ModelSourceState State { get; init; } /// RFC 9728 metadata for the endpoint a registered source's credential is /// for. Present whenever the source takes a credential, in every state, so - /// any client can deliver or rotate one. Set with `state`. + /// any client can deliver or rotate one. /// /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example @@ -2735,7 +2734,7 @@ public sealed record ModelSource public ProtectedResourceMetadata? CredentialResource { get; init; } /// The {@link AuthenticateParams.accountId} sent with the credential the - /// host most recently accepted. Set with `state`. + /// host most recently accepted. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? AccountId { get; init; } diff --git a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs index 266312be8..75d00fabe 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -214,13 +214,13 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootConfigChangedAction value: actionType = value.Type; return true; - case RootModelSourceRemovedAction value: + case RootModelSourceRegisterRequestedAction value: actionType = value.Type; return true; - case RootModelSourceSetAction value: + case RootModelSourceRemovedAction value: actionType = value.Type; return true; - case RootModelSourceStateChangedAction value: + case RootModelSourceSetAction value: actionType = value.Type; return true; case RootTerminalsChangedAction value: diff --git a/clients/dotnet/src/AgentHostProtocol/Reducers.cs b/clients/dotnet/src/AgentHostProtocol/Reducers.cs index 871af1580..8d5919584 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -680,24 +680,19 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) state.Config.Values = MergeConfig(state.Config.Values, a.Config, a.Replace); return ReduceOutcome.Applied; + case RootModelSourceRegisterRequestedAction: + return ReduceOutcome.NoOp; case RootModelSourceSetAction a: { List list = state.ModelSources ??= new List(); int index = list.FindIndex(s => s.Id == a.ModelSource.Id); - ModelSource? existing = index >= 0 && SameModelSourceVersion(list[index], a.ModelSource) ? list[index] : null; - ModelSource merged = a.ModelSource with - { - State = existing?.State, - CredentialResource = existing?.CredentialResource, - AccountId = existing?.AccountId, - }; if (index < 0) { - list.Add(merged); + list.Add(a.ModelSource); } else { - list[index] = merged; + list[index] = a.ModelSource; } return ReduceOutcome.Applied; @@ -713,27 +708,11 @@ public static ReduceOutcome ApplyToRoot(RootState state, StateAction action) state.ModelSources!.RemoveAt(index); return ReduceOutcome.Applied; } - case RootModelSourceStateChangedAction a: - { - int index = state.ModelSources?.FindIndex(s => s.Id == a.ModelSourceId) ?? -1; - if (index < 0) - { - return ReduceOutcome.NoOp; - } - - List list = state.ModelSources!; - list[index] = list[index] with { State = a.State, CredentialResource = a.CredentialResource, AccountId = a.AccountId }; - return ReduceOutcome.Applied; - } } return ReduceOutcome.OutOfScope; } - // Whether two model sources have the same provider, format, and definition nonce. - private static bool SameModelSourceVersion(ModelSource a, ModelSource b) => - a.Provider == b.Provider && a.Format == b.Format && a.Nonce == b.Nonce; - // Shared config merge for the root, session, and chat `configChanged` actions: // when `replace` is set (or no values exist yet) start fresh, otherwise // mutate the existing map in place; then overlay the incoming entries. @@ -2758,7 +2737,7 @@ public static ReduceOutcome ApplyToAutomationRun( private static readonly string[] s_clientDispatchableActionNames = { "root/configChanged", - "root/modelSourceSet", + "root/modelSourceRegisterRequested", "root/modelSourceRemoved", // Chat-channel actions (post-#213) "chat/turnStarted", diff --git a/clients/go/ahp/reducers.go b/clients/go/ahp/reducers.go index dc69c8d7b..5f9be3c35 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -537,18 +537,14 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R state.Config.Values[k] = v } return ReduceOutcomeApplied + case *ahptypes.RootModelSourceRegisterRequestedAction: + return ReduceOutcomeNoOp case *ahptypes.RootModelSourceSetAction: - updated := a.ModelSource - idx := modelSourceIndex(state.ModelSources, updated.Id) - if idx >= 0 && sameModelSourceVersion(state.ModelSources[idx], updated) { - copyModelSourceHostFields(&updated, state.ModelSources[idx]) - } else { - copyModelSourceHostFields(&updated, ahptypes.ModelSource{}) - } + idx := modelSourceIndex(state.ModelSources, a.ModelSource.Id) if idx >= 0 { - state.ModelSources[idx] = updated + state.ModelSources[idx] = a.ModelSource } else { - state.ModelSources = append(state.ModelSources, updated) + state.ModelSources = append(state.ModelSources, a.ModelSource) } return ReduceOutcomeApplied case *ahptypes.RootModelSourceRemovedAction: @@ -558,18 +554,6 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R } state.ModelSources = append(state.ModelSources[:idx], state.ModelSources[idx+1:]...) return ReduceOutcomeApplied - case *ahptypes.RootModelSourceStateChangedAction: - idx := modelSourceIndex(state.ModelSources, a.ModelSourceId) - if idx < 0 { - return ReduceOutcomeNoOp - } - st := a.State - copyModelSourceHostFields(&state.ModelSources[idx], ahptypes.ModelSource{ - State: &st, - CredentialResource: a.CredentialResource, - AccountId: a.AccountId, - }) - return ReduceOutcomeApplied } return ReduceOutcomeOutOfScope } @@ -583,29 +567,6 @@ func modelSourceIndex(list []ahptypes.ModelSource, id string) int { return -1 } -// copyModelSourceHostFields copies the host-reported fields of from onto to, -// clearing the ones from lacks. -func copyModelSourceHostFields(to *ahptypes.ModelSource, from ahptypes.ModelSource) { - to.State = from.State - to.CredentialResource = from.CredentialResource - to.AccountId = from.AccountId -} - -// sameModelSourceVersion reports whether two model sources have the same -// provider, format, and definition nonce. -func sameModelSourceVersion(a, b ahptypes.ModelSource) bool { - return a.Provider == b.Provider && sameOptionalString(a.Format, b.Format) && sameOptionalString(a.Nonce, b.Nonce) -} - -// sameOptionalString reports whether two optional strings are both absent, or -// both present and equal. -func sameOptionalString(a, b *string) bool { - if a == nil || b == nil { - return a == b - } - return *a == *b -} - // ─── Chat Reducer ────────────────────────────────────────────────────── // ApplyActionToChat applies action to the [ahptypes.ChatState] in diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index 0df00edc5..d2794a6fd 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -107,9 +107,9 @@ const ( ActionTypeAnnotationsEntryRemoved ActionType = "annotations/entryRemoved" ActionTypeRootTerminalsChanged ActionType = "root/terminalsChanged" ActionTypeRootConfigChanged ActionType = "root/configChanged" + ActionTypeRootModelSourceRegisterRequested ActionType = "root/modelSourceRegisterRequested" ActionTypeRootModelSourceSet ActionType = "root/modelSourceSet" ActionTypeRootModelSourceRemoved ActionType = "root/modelSourceRemoved" - ActionTypeRootModelSourceStateChanged ActionType = "root/modelSourceStateChanged" ActionTypeTerminalData ActionType = "terminal/data" ActionTypeTerminalInput ActionType = "terminal/input" ActionTypeTerminalResized ActionType = "terminal/resized" @@ -183,24 +183,14 @@ type RootConfigChangedAction struct { Replace *bool `json:"replace,omitempty"` } -// Adds a model source, or updates the one with the same `id`: -// -// - **Add.** When no model source has the `id`, appends `modelSource`. -// - **Re-register.** When one has, with the same `provider`, `format`, and -// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, -// and `accountId`) and takes everything else from the action. -// - **Update.** When any of the three differs, replaces the source. Its -// host-reported fields are absent until the host reports again with -// {@link RootModelSourceStateChangedAction}. -// -// A client registers a source with its `format`, `definition`, and `nonce`, -// and without any host-reported field. The host learns which client -// registered it from the envelope's `origin`. +// Adds a model source, or replaces the one with the same `id`. Only the host +// dispatches it, to publish a registration, a source an agent provides +// itself, or a change in a source's status. // // Stability: 1.0 - Early development. type RootModelSourceSetAction struct { Type ActionType `json:"type"` - // The model source to add or update, matched by `id`. + // The model source to add or replace, matched by `id`. ModelSource ModelSource `json:"modelSource"` } @@ -214,23 +204,29 @@ type RootModelSourceRemovedAction struct { ModelSourceId string `json:"modelSourceId"` } -// Updates a model source's host-reported fields together: `state`, -// `credentialResource`, and `accountId`. A no-op when no model source has -// `modelSourceId`. Other fields of the source are preserved. Only the host -// dispatches it. +// Asks the host to register a model source, or to update the one with the +// same `modelSourceId`. The reducer leaves state unchanged. The host counts +// the dispatching client as a contributing client, validates the +// registration, and publishes the result with +// {@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the +// source's status and credential when the registration is unchanged. // // Stability: 1.0 - Early development. -type RootModelSourceStateChangedAction struct { +type RootModelSourceRegisterRequestedAction struct { Type ActionType `json:"type"` - // The model source's `id`. + // The model source's `id`, chosen by the client. ModelSourceId string `json:"modelSourceId"` - // The new status. - State ModelSourceState `json:"state"` - // Replaces the source's `credentialResource`. Absent clears it, for a - // source that needs no credential. - CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` - // Replaces the source's `accountId`. Absent clears it. - AccountId *string `json:"accountId,omitempty"` + // Agent provider whose agent serves the source's models. + Provider string `json:"provider"` + // Human-readable name. + DisplayName string `json:"displayName"` + // Icons for UI display. + Icons []Icon `json:"icons,omitempty"` + // The source's format, definition, and retention. + Registration ModelSourceRegistration `json:"registration"` + // Additional implementation-defined metadata for this model source. + // MUST NOT contain a credential. + Meta map[string]json.RawMessage `json:"_meta,omitempty"` } // Session backend initialized successfully. @@ -2005,7 +2001,7 @@ func (*RootActiveSessionsChangedAction) isStateAction() {} func (*RootConfigChangedAction) isStateAction() {} func (*RootModelSourceSetAction) isStateAction() {} func (*RootModelSourceRemovedAction) isStateAction() {} -func (*RootModelSourceStateChangedAction) isStateAction() {} +func (*RootModelSourceRegisterRequestedAction) isStateAction() {} func (*SessionReadyAction) isStateAction() {} func (*SessionCreationFailedAction) isStateAction() {} func (*SessionChatAddedAction) isStateAction() {} @@ -2160,8 +2156,8 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value - case "root/modelSourceStateChanged": - var value RootModelSourceStateChangedAction + case "root/modelSourceRegisterRequested": + var value RootModelSourceRegisterRequestedAction if err := json.Unmarshal(data, &value); err != nil { return err } diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index e47bb057e..7fbbcbbe1 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1035,28 +1035,17 @@ type ModelSourceRegistrationCapability struct { // // Stability: 1.0 - Early development. type ModelSourceFormatInfo struct { - // A {@link ModelSource.format} value. + // A {@link ModelSourceRegistration.format} value. Format string `json:"format"` } -// A source that an agent provider offers models from, such as a service, -// subscription, or endpoint. The host lists the sources an agent provides -// itself, and clients can register more with a definition. +// How a client, or the host from its own configuration, registered a model +// source. // // Stability: 1.0 - Early development. -type ModelSource struct { - // Host-unique ID, chosen by whoever registers the source. Also the - // {@link SessionModelInfo.modelSourceId} of its models. - Id string `json:"id"` - // Agent provider whose agent serves the source's models. - Provider string `json:"provider"` - // Human-readable name. - DisplayName string `json:"displayName"` - // Icons for UI display. - Icons []Icon `json:"icons,omitempty"` +type ModelSourceRegistration struct { // The format of `definition`: the `format` of one of the agent's - // {@link ModelSourceRegistrationCapability.formats}. Present on a - // registered source. + // {@link ModelSourceRegistrationCapability.formats}. // // Agents choose the formats they read. Some may read these common names: // @@ -1067,31 +1056,44 @@ type ModelSource struct { // // Other formats are named with a namespace, such as // `example.com/model-source@1`, so they don't collide. - Format *string `json:"format,omitempty"` + Format string `json:"format"` // How to reach the source, in `format`: endpoint, wire API, models, and so // on. The agent reads it. Every client can read it, so it MUST NOT contain - // a credential. Present on a registered source. + // a credential. // // An agent that reads one of the common format names might expect a shape // like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is // the API's base URI and each `models` entry is `{ id, name?, // maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, // named as in {@link SessionModelInfo}. - Definition map[string]json.RawMessage `json:"definition,omitempty"` - // Opaque version token for `definition`, such as a hash of it, chosen by - // whoever registers the source. Present on a registered source. Reducers - // compare it, instead of the definition, to tell an update from a - // re-registration of the same definition. - Nonce *string `json:"nonce,omitempty"` + Definition map[string]json.RawMessage `json:"definition"` // What happens when the last contributing client leaves. Absent means `contributingClient`. Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` - // Host-reported status, set with {@link RootModelSourceStateChangedAction}. - // Absent until the host reports one, and after an update replaces the - // definition until the host reports again. - State *ModelSourceState `json:"state,omitempty"` +} + +// A source that an agent provider offers models from, such as a service, +// subscription, or endpoint. The host lists the sources an agent provides +// itself, and clients can register more with a definition. +// +// Stability: 1.0 - Early development. +type ModelSource struct { + // Host-unique ID, chosen by whoever registers the source. Also the + // {@link SessionModelInfo.modelSourceId} of its models. + Id string `json:"id"` + // Agent provider whose agent serves the source's models. + Provider string `json:"provider"` + // Human-readable name. + DisplayName string `json:"displayName"` + // Icons for UI display. + Icons []Icon `json:"icons,omitempty"` + // How the source was registered. Absent on a source the agent provides + // itself. + Registration *ModelSourceRegistration `json:"registration,omitempty"` + // The source's status. + State ModelSourceState `json:"state"` // RFC 9728 metadata for the endpoint a registered source's credential is // for. Present whenever the source takes a credential, in every state, so - // any client can deliver or rotate one. Set with `state`. + // any client can deliver or rotate one. // // `credentialResource.resource` is the endpoint URL as the definition // names it, in any scheme the agent supports (for example @@ -1099,7 +1101,7 @@ type ModelSource struct { // `authenticate({ resource })`. CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` // The {@link AuthenticateParams.accountId} sent with the credential the - // host most recently accepted. Set with `state`. + // host most recently accepted. AccountId *string `json:"accountId,omitempty"` // Additional implementation-defined metadata for this model source. // MUST NOT contain a credential. diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt index 9d5e9d4b3..670b176a6 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/Reducers.kt @@ -581,18 +581,14 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when } } + is StateActionRootModelSourceRegisterRequested -> state + is StateActionRootModelSourceSet -> { val source = action.value.modelSource val list = state.modelSources.orEmpty() val idx = list.indexOfFirst { it.id == source.id } - val existing = list.getOrNull(idx)?.takeIf { sameModelSourceVersion(it, source) } - val merged = source.copy( - state = existing?.state, - credentialResource = existing?.credentialResource, - accountId = existing?.accountId, - ) val updated = list.toMutableList() - if (idx < 0) updated.add(merged) else updated[idx] = merged + if (idx < 0) updated.add(source) else updated[idx] = source state.copy(modelSources = updated) } @@ -606,29 +602,9 @@ public fun rootReducer(state: RootState, action: StateAction): RootState = when } } - is StateActionRootModelSourceStateChanged -> { - val list = state.modelSources - val idx = list?.indexOfFirst { it.id == action.value.modelSourceId } ?: -1 - if (list == null || idx < 0) { - state - } else { - val updated = list.toMutableList() - updated[idx] = updated[idx].copy( - state = action.value.state, - credentialResource = action.value.credentialResource, - accountId = action.value.accountId, - ) - state.copy(modelSources = updated) - } - } - else -> state } -/** Whether two model sources have the same `provider`, `format`, and definition `nonce`. */ -private fun sameModelSourceVersion(a: ModelSource, b: ModelSource): Boolean = - a.provider == b.provider && a.format == b.format && a.nonce == b.nonce - // ─── Session Reducer ──────────────────────────────────────────────────────── /** diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index eb53efcb7..6535c6d07 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -117,9 +117,9 @@ value class ActionType(val rawValue: String) { val ANNOTATIONS_ENTRY_REMOVED: ActionType = ActionType("annotations/entryRemoved") val ROOT_TERMINALS_CHANGED: ActionType = ActionType("root/terminalsChanged") val ROOT_CONFIG_CHANGED: ActionType = ActionType("root/configChanged") + val ROOT_MODEL_SOURCE_REGISTER_REQUESTED: ActionType = ActionType("root/modelSourceRegisterRequested") val ROOT_MODEL_SOURCE_SET: ActionType = ActionType("root/modelSourceSet") val ROOT_MODEL_SOURCE_REMOVED: ActionType = ActionType("root/modelSourceRemoved") - val ROOT_MODEL_SOURCE_STATE_CHANGED: ActionType = ActionType("root/modelSourceStateChanged") val TERMINAL_DATA: ActionType = ActionType("terminal/data") val TERMINAL_INPUT: ActionType = ActionType("terminal/input") val TERMINAL_RESIZED: ActionType = ActionType("terminal/resized") @@ -1526,19 +1526,9 @@ data class RootConfigChangedAction( ) /** - * Adds a model source, or updates the one with the same `id`: - * - * - **Add.** When no model source has the `id`, appends `modelSource`. - * - **Re-register.** When one has, with the same `provider`, `format`, and - * `nonce`, keeps its host-reported fields (`state`, `credentialResource`, - * and `accountId`) and takes everything else from the action. - * - **Update.** When any of the three differs, replaces the source. Its - * host-reported fields are absent until the host reports again with - * {@link RootModelSourceStateChangedAction}. - * - * A client registers a source with its `format`, `definition`, and `nonce`, - * and without any host-reported field. The host learns which client - * registered it from the envelope's `origin`. + * Adds a model source, or replaces the one with the same `id`. Only the host + * dispatches it, to publish a registration, a source an agent provides + * itself, or a change in a source's status. * * Stability: 1.0 - Early development. */ @@ -1546,7 +1536,7 @@ data class RootConfigChangedAction( data class RootModelSourceSetAction( val type: ActionType, /** - * The model source to add or update, matched by `id`. + * The model source to add or replace, matched by `id`. */ val modelSource: ModelSource ) @@ -1567,33 +1557,44 @@ data class RootModelSourceRemovedAction( ) /** - * Updates a model source's host-reported fields together: `state`, - * `credentialResource`, and `accountId`. A no-op when no model source has - * `modelSourceId`. Other fields of the source are preserved. Only the host - * dispatches it. + * Asks the host to register a model source, or to update the one with the + * same `modelSourceId`. The reducer leaves state unchanged. The host counts + * the dispatching client as a contributing client, validates the + * registration, and publishes the result with + * {@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the + * source's status and credential when the registration is unchanged. * * Stability: 1.0 - Early development. */ @Serializable -data class RootModelSourceStateChangedAction( +data class RootModelSourceRegisterRequestedAction( val type: ActionType, /** - * The model source's `id`. + * The model source's `id`, chosen by the client. */ val modelSourceId: String, /** - * The new status. + * Agent provider whose agent serves the source's models. + */ + val provider: String, + /** + * Human-readable name. */ - val state: ModelSourceState, + val displayName: String, + /** + * Icons for UI display. + */ + val icons: List? = null, /** - * Replaces the source's `credentialResource`. Absent clears it, for a - * source that needs no credential. + * The source's format, definition, and retention. */ - val credentialResource: ProtectedResourceMetadata? = null, + val registration: ModelSourceRegistration, /** - * Replaces the source's `accountId`. Absent clears it. + * Additional implementation-defined metadata for this model source. + * MUST NOT contain a credential. */ - val accountId: String? = null + @SerialName("_meta") + val meta: Map? = null ) @Serializable @@ -2049,7 +2050,7 @@ sealed interface StateAction @JvmInline value class StateActionRootConfigChanged(val value: RootConfigChangedAction) : StateAction @JvmInline value class StateActionRootModelSourceSet(val value: RootModelSourceSetAction) : StateAction @JvmInline value class StateActionRootModelSourceRemoved(val value: RootModelSourceRemovedAction) : StateAction -@JvmInline value class StateActionRootModelSourceStateChanged(val value: RootModelSourceStateChangedAction) : StateAction +@JvmInline value class StateActionRootModelSourceRegisterRequested(val value: RootModelSourceRegisterRequestedAction) : StateAction @JvmInline value class StateActionTerminalData(val value: TerminalDataAction) : StateAction @JvmInline value class StateActionTerminalInput(val value: TerminalInputAction) : StateAction @JvmInline value class StateActionTerminalResized(val value: TerminalResizedAction) : StateAction @@ -2179,7 +2180,7 @@ internal object StateActionSerializer : KSerializer { "root/configChanged" -> StateActionRootConfigChanged(input.json.decodeFromJsonElement(RootConfigChangedAction.serializer(), element)) "root/modelSourceSet" -> StateActionRootModelSourceSet(input.json.decodeFromJsonElement(RootModelSourceSetAction.serializer(), element)) "root/modelSourceRemoved" -> StateActionRootModelSourceRemoved(input.json.decodeFromJsonElement(RootModelSourceRemovedAction.serializer(), element)) - "root/modelSourceStateChanged" -> StateActionRootModelSourceStateChanged(input.json.decodeFromJsonElement(RootModelSourceStateChangedAction.serializer(), element)) + "root/modelSourceRegisterRequested" -> StateActionRootModelSourceRegisterRequested(input.json.decodeFromJsonElement(RootModelSourceRegisterRequestedAction.serializer(), element)) "terminal/data" -> StateActionTerminalData(input.json.decodeFromJsonElement(TerminalDataAction.serializer(), element)) "terminal/input" -> StateActionTerminalInput(input.json.decodeFromJsonElement(TerminalInputAction.serializer(), element)) "terminal/resized" -> StateActionTerminalResized(input.json.decodeFromJsonElement(TerminalResizedAction.serializer(), element)) @@ -2302,7 +2303,7 @@ internal object StateActionSerializer : KSerializer { is StateActionRootConfigChanged -> output.json.encodeToJsonElement(RootConfigChangedAction.serializer(), value.value) is StateActionRootModelSourceSet -> output.json.encodeToJsonElement(RootModelSourceSetAction.serializer(), value.value) is StateActionRootModelSourceRemoved -> output.json.encodeToJsonElement(RootModelSourceRemovedAction.serializer(), value.value) - is StateActionRootModelSourceStateChanged -> output.json.encodeToJsonElement(RootModelSourceStateChangedAction.serializer(), value.value) + is StateActionRootModelSourceRegisterRequested -> output.json.encodeToJsonElement(RootModelSourceRegisterRequestedAction.serializer(), value.value) is StateActionTerminalData -> output.json.encodeToJsonElement(TerminalDataAction.serializer(), value.value) is StateActionTerminalInput -> output.json.encodeToJsonElement(TerminalInputAction.serializer(), value.value) is StateActionTerminalResized -> output.json.encodeToJsonElement(TerminalResizedAction.serializer(), value.value) 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 275d99b02..69adc363b 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 @@ -1958,7 +1958,7 @@ data class ModelSourceRegistrationCapability( @Serializable data class ModelSourceFormatInfo( /** - * A {@link ModelSource.format} value. + * A {@link ModelSourceRegistration.format} value. */ val format: String ) @@ -1989,10 +1989,50 @@ data class ModelSource( * Icons for UI display. */ val icons: List? = null, + /** + * How the source was registered. Absent on a source the agent provides + * itself. + */ + val registration: ModelSourceRegistration? = null, + /** + * The source's status. + */ + val state: ModelSourceState, + /** + * RFC 9728 metadata for the endpoint a registered source's credential is + * for. Present whenever the source takes a credential, in every state, so + * any client can deliver or rotate one. + * + * `credentialResource.resource` is the endpoint URL as the definition + * names it, in any scheme the agent supports (for example + * `http://localhost:11434/v1`). It's the value a client passes back as + * `authenticate({ resource })`. + */ + val credentialResource: ProtectedResourceMetadata? = null, + /** + * The {@link AuthenticateParams.accountId} sent with the credential the + * host most recently accepted. + */ + val accountId: String? = null, + /** + * Additional implementation-defined metadata for this model source. + * MUST NOT contain a credential. + */ + @SerialName("_meta") + val meta: Map? = null +) + +/** + * How a client, or the host from its own configuration, registered a model + * source. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceRegistration( /** * The format of `definition`: the `format` of one of the agent's - * {@link ModelSourceRegistrationCapability.formats}. Present on a - * registered source. + * {@link ModelSourceRegistrationCapability.formats}. * * Agents choose the formats they read. Some may read these common names: * @@ -2004,11 +2044,11 @@ data class ModelSource( * Other formats are named with a namespace, such as * `example.com/model-source@1`, so they don't collide. */ - val format: String? = null, + val format: String, /** * How to reach the source, in `format`: endpoint, wire API, models, and so * on. The agent reads it. Every client can read it, so it MUST NOT contain - * a credential. Present on a registered source. + * a credential. * * An agent that reads one of the common format names might expect a shape * like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is @@ -2016,46 +2056,11 @@ data class ModelSource( * maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, * named as in {@link SessionModelInfo}. */ - val definition: Map? = null, - /** - * Opaque version token for `definition`, such as a hash of it, chosen by - * whoever registers the source. Present on a registered source. Reducers - * compare it, instead of the definition, to tell an update from a - * re-registration of the same definition. - */ - val nonce: String? = null, + val definition: Map, /** * What happens when the last contributing client leaves. Absent means `contributingClient`. */ - val retention: ModelSourceRetentionPolicy? = null, - /** - * Host-reported status, set with {@link RootModelSourceStateChangedAction}. - * Absent until the host reports one, and after an update replaces the - * definition until the host reports again. - */ - val state: ModelSourceState? = null, - /** - * RFC 9728 metadata for the endpoint a registered source's credential is - * for. Present whenever the source takes a credential, in every state, so - * any client can deliver or rotate one. Set with `state`. - * - * `credentialResource.resource` is the endpoint URL as the definition - * names it, in any scheme the agent supports (for example - * `http://localhost:11434/v1`). It's the value a client passes back as - * `authenticate({ resource })`. - */ - val credentialResource: ProtectedResourceMetadata? = null, - /** - * The {@link AuthenticateParams.accountId} sent with the credential the - * host most recently accepted. Set with `state`. - */ - val accountId: String? = null, - /** - * Additional implementation-defined metadata for this model source. - * MUST NOT contain a credential. - */ - @SerialName("_meta") - val meta: Map? = null + val retention: ModelSourceRetentionPolicy? = null ) /** diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 4ffd363db..7a93c358e 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -19,9 +19,9 @@ use crate::state::{ ChangesetOperation, ChangesetOperationStatus, ChangesetStatus, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ChatSummary, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, - ErrorResponsePart, FileEditCollection, MaterializedTurn, McpAuthRequirement, McpServerState, - Message, ModelSelection, ModelSource, ModelSourceState, PendingMessageKind, - ProtectedResourceMetadata, ResponsePart, SearchLifecycleState, SearchQuery, SearchResult, + ErrorResponsePart, FileEditCollection, Icon, MaterializedTurn, McpAuthRequirement, + McpServerState, Message, ModelSelection, ModelSource, ModelSourceRegistration, + PendingMessageKind, ResponsePart, SearchLifecycleState, SearchQuery, SearchResult, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, @@ -121,9 +121,9 @@ pub enum ActionType { AnnotationsEntryRemoved, RootTerminalsChanged, RootConfigChanged, + RootModelSourceRegisterRequested, RootModelSourceSet, RootModelSourceRemoved, - RootModelSourceStateChanged, TerminalData, TerminalInput, TerminalResized, @@ -296,11 +296,11 @@ impl serde::Serialize for ActionType { Self::AnnotationsEntryRemoved => serializer.serialize_str("annotations/entryRemoved"), Self::RootTerminalsChanged => serializer.serialize_str("root/terminalsChanged"), Self::RootConfigChanged => serializer.serialize_str("root/configChanged"), + Self::RootModelSourceRegisterRequested => { + serializer.serialize_str("root/modelSourceRegisterRequested") + } Self::RootModelSourceSet => serializer.serialize_str("root/modelSourceSet"), Self::RootModelSourceRemoved => serializer.serialize_str("root/modelSourceRemoved"), - Self::RootModelSourceStateChanged => { - serializer.serialize_str("root/modelSourceStateChanged") - } Self::TerminalData => serializer.serialize_str("terminal/data"), Self::TerminalInput => serializer.serialize_str("terminal/input"), Self::TerminalResized => serializer.serialize_str("terminal/resized"), @@ -439,9 +439,9 @@ impl<'de> serde::Deserialize<'de> for ActionType { "annotations/entryRemoved" => Self::AnnotationsEntryRemoved, "root/terminalsChanged" => Self::RootTerminalsChanged, "root/configChanged" => Self::RootConfigChanged, + "root/modelSourceRegisterRequested" => Self::RootModelSourceRegisterRequested, "root/modelSourceSet" => Self::RootModelSourceSet, "root/modelSourceRemoved" => Self::RootModelSourceRemoved, - "root/modelSourceStateChanged" => Self::RootModelSourceStateChanged, "terminal/data" => Self::TerminalData, "terminal/input" => Self::TerminalInput, "terminal/resized" => Self::TerminalResized, @@ -533,25 +533,15 @@ pub struct RootConfigChangedAction { pub replace: Option, } -/// Adds a model source, or updates the one with the same `id`: -/// -/// - **Add.** When no model source has the `id`, appends `modelSource`. -/// - **Re-register.** When one has, with the same `provider`, `format`, and -/// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, -/// and `accountId`) and takes everything else from the action. -/// - **Update.** When any of the three differs, replaces the source. Its -/// host-reported fields are absent until the host reports again with -/// {@link RootModelSourceStateChangedAction}. -/// -/// A client registers a source with its `format`, `definition`, and `nonce`, -/// and without any host-reported field. The host learns which client -/// registered it from the envelope's `origin`. +/// Adds a model source, or replaces the one with the same `id`. Only the host +/// dispatches it, to publish a registration, a source an agent provides +/// itself, or a change in a source's status. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootModelSourceSetAction { - /// The model source to add or update, matched by `id`. + /// The model source to add or replace, matched by `id`. pub model_source: ModelSource, } @@ -566,26 +556,32 @@ pub struct RootModelSourceRemovedAction { pub model_source_id: String, } -/// Updates a model source's host-reported fields together: `state`, -/// `credentialResource`, and `accountId`. A no-op when no model source has -/// `modelSourceId`. Other fields of the source are preserved. Only the host -/// dispatches it. +/// Asks the host to register a model source, or to update the one with the +/// same `modelSourceId`. The reducer leaves state unchanged. The host counts +/// the dispatching client as a contributing client, validates the +/// registration, and publishes the result with +/// {@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the +/// source's status and credential when the registration is unchanged. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RootModelSourceStateChangedAction { - /// The model source's `id`. +pub struct RootModelSourceRegisterRequestedAction { + /// The model source's `id`, chosen by the client. pub model_source_id: String, - /// The new status. - pub state: ModelSourceState, - /// Replaces the source's `credentialResource`. Absent clears it, for a - /// source that needs no credential. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential_resource: Option, - /// Replaces the source's `accountId`. Absent clears it. + /// Agent provider whose agent serves the source's models. + pub provider: String, + /// Human-readable name. + pub display_name: String, + /// Icons for UI display. #[serde(default, skip_serializing_if = "Option::is_none")] - pub account_id: Option, + pub icons: Option>, + /// The source's format, definition, and retention. + pub registration: ModelSourceRegistration, + /// Additional implementation-defined metadata for this model source. + /// MUST NOT contain a credential. + #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] + pub meta: Option, } /// Session backend initialized successfully. @@ -2629,8 +2625,8 @@ pub enum StateAction { RootModelSourceSet(Box), #[serde(rename = "root/modelSourceRemoved")] RootModelSourceRemoved(RootModelSourceRemovedAction), - #[serde(rename = "root/modelSourceStateChanged")] - RootModelSourceStateChanged(RootModelSourceStateChangedAction), + #[serde(rename = "root/modelSourceRegisterRequested")] + RootModelSourceRegisterRequested(RootModelSourceRegisterRequestedAction), #[serde(rename = "session/ready")] SessionReady(SessionReadyAction), #[serde(rename = "session/creationFailed")] diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 2d2ab05fe..40b1a0df8 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2352,31 +2352,19 @@ pub struct ModelSourceRegistrationCapability { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSourceFormatInfo { - /// A {@link ModelSource.format} value. + /// A {@link ModelSourceRegistration.format} value. pub format: String, } -/// A source that an agent provider offers models from, such as a service, -/// subscription, or endpoint. The host lists the sources an agent provides -/// itself, and clients can register more with a definition. +/// How a client, or the host from its own configuration, registered a model +/// source. /// /// Stability: 1.0 - Early development. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ModelSource { - /// Host-unique ID, chosen by whoever registers the source. Also the - /// {@link SessionModelInfo.modelSourceId} of its models. - pub id: String, - /// Agent provider whose agent serves the source's models. - pub provider: String, - /// Human-readable name. - pub display_name: String, - /// Icons for UI display. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub icons: Option>, +pub struct ModelSourceRegistration { /// The format of `definition`: the `format` of one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. Present on a - /// registered source. + /// {@link ModelSourceRegistrationCapability.formats}. /// /// Agents choose the formats they read. Some may read these common names: /// @@ -2387,36 +2375,49 @@ pub struct ModelSource { /// /// Other formats are named with a namespace, such as /// `example.com/model-source@1`, so they don't collide. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub format: Option, + pub format: String, /// How to reach the source, in `format`: endpoint, wire API, models, and so /// on. The agent reads it. Every client can read it, so it MUST NOT contain - /// a credential. Present on a registered source. + /// a credential. /// /// An agent that reads one of the common format names might expect a shape /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is /// the API's base URI and each `models` entry is `{ id, name?, /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, /// named as in {@link SessionModelInfo}. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub definition: Option, - /// Opaque version token for `definition`, such as a hash of it, chosen by - /// whoever registers the source. Present on a registered source. Reducers - /// compare it, instead of the definition, to tell an update from a - /// re-registration of the same definition. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub nonce: Option, + pub definition: JsonObject, /// What happens when the last contributing client leaves. Absent means `contributingClient`. #[serde(default, skip_serializing_if = "Option::is_none")] pub retention: Option, - /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after an update replaces the - /// definition until the host reports again. +} + +/// A source that an agent provider offers models from, such as a service, +/// subscription, or endpoint. The host lists the sources an agent provides +/// itself, and clients can register more with a definition. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelSource { + /// Host-unique ID, chosen by whoever registers the source. Also the + /// {@link SessionModelInfo.modelSourceId} of its models. + pub id: String, + /// Agent provider whose agent serves the source's models. + pub provider: String, + /// Human-readable name. + pub display_name: String, + /// Icons for UI display. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icons: Option>, + /// How the source was registered. Absent on a source the agent provides + /// itself. #[serde(default, skip_serializing_if = "Option::is_none")] - pub state: Option, + pub registration: Option, + /// The source's status. + pub state: ModelSourceState, /// RFC 9728 metadata for the endpoint a registered source's credential is /// for. Present whenever the source takes a credential, in every state, so - /// any client can deliver or rotate one. Set with `state`. + /// any client can deliver or rotate one. /// /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example @@ -2425,7 +2426,7 @@ pub struct ModelSource { #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_resource: Option, /// The {@link AuthenticateParams.accountId} sent with the credential the - /// host most recently accepted. Set with `state`. + /// host most recently accepted. #[serde(default, skip_serializing_if = "Option::is_none")] pub account_id: Option, /// Additional implementation-defined metadata for this model source. diff --git a/clients/rust/crates/ahp/src/reducers.rs b/clients/rust/crates/ahp/src/reducers.rs index a6a2fdbc9..240f1b84a 100644 --- a/clients/rust/crates/ahp/src/reducers.rs +++ b/clients/rust/crates/ahp/src/reducers.rs @@ -62,7 +62,7 @@ use ahp_types::state::{ ChangesetOperationStatus, ChangesetState, ChangesetStatus, ChatConfigState, ChatInputRequest, ChatState, ChildCustomization, ConfirmationOption, Customization, CustomizationEnablement, ErrorResponsePart, InputRequestResponsePart, MaterializedTurn, McpServerCustomization, - McpServerStartingState, McpServerState, McpServerStoppedState, ModelSource, PendingMessage, + McpServerStartingState, McpServerState, McpServerStoppedState, PendingMessage, PendingMessageKind, ResourceWatchState, ResponsePart, RootState, SearchLifecycleState, SearchPendingLifecycleState, SearchRunningLifecycleState, SearchState, SessionInputRequest, SessionLifecycle, SessionState, SessionStatus, TerminalCommandPart, TerminalContentPart, @@ -721,20 +721,12 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu } ReduceOutcome::Applied } + StateAction::RootModelSourceRegisterRequested(_) => ReduceOutcome::NoOp, StateAction::RootModelSourceSet(a) => { let list = state.model_sources.get_or_insert_with(Vec::new); - let idx = list.iter().position(|s| s.id == a.model_source.id); - let mut updated = a.model_source.clone(); - match idx - .map(|i| &list[i]) - .filter(|existing| same_model_source_version(existing, &a.model_source)) - { - Some(existing) => copy_model_source_host_fields(&mut updated, existing), - None => clear_model_source_host_fields(&mut updated), - } - match idx { - Some(i) => list[i] = updated, - None => list.push(updated), + match list.iter().position(|s| s.id == a.model_source.id) { + Some(i) => list[i] = a.model_source.clone(), + None => list.push(a.model_source.clone()), } ReduceOutcome::Applied } @@ -748,43 +740,10 @@ pub fn apply_action_to_root(state: &mut RootState, action: &StateAction) -> Redu list.remove(idx); ReduceOutcome::Applied } - StateAction::RootModelSourceStateChanged(a) => { - let Some(source) = state - .model_sources - .as_mut() - .and_then(|list| list.iter_mut().find(|s| s.id == a.model_source_id)) - else { - return ReduceOutcome::NoOp; - }; - source.state = Some(a.state.clone()); - source.credential_resource = a.credential_resource.clone(); - source.account_id = a.account_id.clone(); - ReduceOutcome::Applied - } _ => ReduceOutcome::OutOfScope, } } -/// Whether two model sources have the same `provider`, `format`, and -/// definition `nonce`. -fn same_model_source_version(a: &ModelSource, b: &ModelSource) -> bool { - a.provider == b.provider && a.format == b.format && a.nonce == b.nonce -} - -/// Copies the host-reported fields of `from` onto `to`. -fn copy_model_source_host_fields(to: &mut ModelSource, from: &ModelSource) { - to.state = from.state.clone(); - to.credential_resource = from.credential_resource.clone(); - to.account_id = from.account_id.clone(); -} - -/// Clears the host-reported fields of `source`. -fn clear_model_source_host_fields(source: &mut ModelSource) { - source.state = None; - source.credential_resource = None; - source.account_id = None; -} - // ─── Session Reducer ────────────────────────────────────────────────── /// Apply a [`StateAction`] to a [`SessionState`] in place. diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift index a52e2b0aa..7dcf08623 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/ActionOrigin.generated.swift @@ -5,7 +5,7 @@ import Foundation /// Set of action types that clients are allowed to dispatch. public let clientDispatchableActions: Set = [ "root/configChanged", - "root/modelSourceSet", + "root/modelSourceRegisterRequested", "root/modelSourceRemoved", "session/titleChanged", "session/activeClientSet", @@ -61,7 +61,7 @@ public let clientDispatchableActions: Set = [ public func isClientDispatchable(_ action: StateAction) -> Bool { switch action { case .rootConfigChanged, - .rootModelSourceSet, + .rootModelSourceRegisterRequested, .rootModelSourceRemoved, .sessionTitleChanged, .sessionActiveClientSet, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index 782a6ddd7..da6ada6ca 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -94,9 +94,9 @@ public enum ActionType: Codable, Sendable, Equatable { case annotationsEntryRemoved case rootTerminalsChanged case rootConfigChanged + case rootModelSourceRegisterRequested case rootModelSourceSet case rootModelSourceRemoved - case rootModelSourceStateChanged case terminalData case terminalInput case terminalResized @@ -216,9 +216,9 @@ public enum ActionType: Codable, Sendable, Equatable { case "annotations/entryRemoved": self = .annotationsEntryRemoved case "root/terminalsChanged": self = .rootTerminalsChanged case "root/configChanged": self = .rootConfigChanged + case "root/modelSourceRegisterRequested": self = .rootModelSourceRegisterRequested case "root/modelSourceSet": self = .rootModelSourceSet case "root/modelSourceRemoved": self = .rootModelSourceRemoved - case "root/modelSourceStateChanged": self = .rootModelSourceStateChanged case "terminal/data": self = .terminalData case "terminal/input": self = .terminalInput case "terminal/resized": self = .terminalResized @@ -338,9 +338,9 @@ public enum ActionType: Codable, Sendable, Equatable { case .annotationsEntryRemoved: try container.encode("annotations/entryRemoved") case .rootTerminalsChanged: try container.encode("root/terminalsChanged") case .rootConfigChanged: try container.encode("root/configChanged") + case .rootModelSourceRegisterRequested: try container.encode("root/modelSourceRegisterRequested") case .rootModelSourceSet: try container.encode("root/modelSourceSet") case .rootModelSourceRemoved: try container.encode("root/modelSourceRemoved") - case .rootModelSourceStateChanged: try container.encode("root/modelSourceStateChanged") case .terminalData: try container.encode("terminal/data") case .terminalInput: try container.encode("terminal/input") case .terminalResized: try container.encode("terminal/resized") @@ -2339,24 +2339,14 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { } } -/// Adds a model source, or updates the one with the same `id`: -/// -/// - **Add.** When no model source has the `id`, appends `modelSource`. -/// - **Re-register.** When one has, with the same `provider`, `format`, and -/// `nonce`, keeps its host-reported fields (`state`, `credentialResource`, -/// and `accountId`) and takes everything else from the action. -/// - **Update.** When any of the three differs, replaces the source. Its -/// host-reported fields are absent until the host reports again with -/// {@link RootModelSourceStateChangedAction}. -/// -/// A client registers a source with its `format`, `definition`, and `nonce`, -/// and without any host-reported field. The host learns which client -/// registered it from the envelope's `origin`. +/// Adds a model source, or replaces the one with the same `id`. Only the host +/// dispatches it, to publish a registration, a source an agent provides +/// itself, or a change in a source's status. /// /// Stability: 1.0 - Early development. public struct RootModelSourceSetAction: Codable, Sendable, Equatable { public var type: ActionType - /// The model source to add or update, matched by `id`. + /// The model source to add or replace, matched by `id`. public var modelSource: ModelSource public init( @@ -2386,36 +2376,56 @@ public struct RootModelSourceRemovedAction: Codable, Sendable, Equatable { } } -/// Updates a model source's host-reported fields together: `state`, -/// `credentialResource`, and `accountId`. A no-op when no model source has -/// `modelSourceId`. Other fields of the source are preserved. Only the host -/// dispatches it. +/// Asks the host to register a model source, or to update the one with the +/// same `modelSourceId`. The reducer leaves state unchanged. The host counts +/// the dispatching client as a contributing client, validates the +/// registration, and publishes the result with +/// {@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the +/// source's status and credential when the registration is unchanged. /// /// Stability: 1.0 - Early development. -public struct RootModelSourceStateChangedAction: Codable, Sendable, Equatable { +public struct RootModelSourceRegisterRequestedAction: Codable, Sendable, Equatable { public var type: ActionType - /// The model source's `id`. + /// The model source's `id`, chosen by the client. public var modelSourceId: String - /// The new status. - public var state: ModelSourceState - /// Replaces the source's `credentialResource`. Absent clears it, for a - /// source that needs no credential. - public var credentialResource: ProtectedResourceMetadata? - /// Replaces the source's `accountId`. Absent clears it. - public var accountId: String? + /// Agent provider whose agent serves the source's models. + public var provider: String + /// Human-readable name. + public var displayName: String + /// Icons for UI display. + public var icons: [Icon]? + /// The source's format, definition, and retention. + public var registration: ModelSourceRegistration + /// Additional implementation-defined metadata for this model source. + /// MUST NOT contain a credential. + public var meta: [String: AnyCodable]? + + enum CodingKeys: String, CodingKey { + case type + case modelSourceId + case provider + case displayName + case icons + case registration + case meta = "_meta" + } public init( type: ActionType, modelSourceId: String, - state: ModelSourceState, - credentialResource: ProtectedResourceMetadata? = nil, - accountId: String? = nil + provider: String, + displayName: String, + icons: [Icon]? = nil, + registration: ModelSourceRegistration, + meta: [String: AnyCodable]? = nil ) { self.type = type self.modelSourceId = modelSourceId - self.state = state - self.credentialResource = credentialResource - self.accountId = accountId + self.provider = provider + self.displayName = displayName + self.icons = icons + self.registration = registration + self.meta = meta } } @@ -2979,7 +2989,7 @@ public enum StateAction: Codable, Sendable, Equatable { case rootConfigChanged(RootConfigChangedAction) case rootModelSourceSet(RootModelSourceSetAction) case rootModelSourceRemoved(RootModelSourceRemovedAction) - case rootModelSourceStateChanged(RootModelSourceStateChangedAction) + case rootModelSourceRegisterRequested(RootModelSourceRegisterRequestedAction) case terminalData(TerminalDataAction) case terminalInput(TerminalInputAction) case terminalResized(TerminalResizedAction) @@ -3196,8 +3206,8 @@ public enum StateAction: Codable, Sendable, Equatable { self = .rootModelSourceSet(try RootModelSourceSetAction(from: decoder)) case "root/modelSourceRemoved": self = .rootModelSourceRemoved(try RootModelSourceRemovedAction(from: decoder)) - case "root/modelSourceStateChanged": - self = .rootModelSourceStateChanged(try RootModelSourceStateChangedAction(from: decoder)) + case "root/modelSourceRegisterRequested": + self = .rootModelSourceRegisterRequested(try RootModelSourceRegisterRequestedAction(from: decoder)) case "terminal/data": self = .terminalData(try TerminalDataAction(from: decoder)) case "terminal/input": @@ -3343,7 +3353,7 @@ public enum StateAction: Codable, Sendable, Equatable { case .rootConfigChanged(let v): try v.encode(to: encoder) case .rootModelSourceSet(let v): try v.encode(to: encoder) case .rootModelSourceRemoved(let v): try v.encode(to: encoder) - case .rootModelSourceStateChanged(let v): try v.encode(to: encoder) + case .rootModelSourceRegisterRequested(let v): try v.encode(to: encoder) case .terminalData(let v): try v.encode(to: encoder) case .terminalInput(let v): try v.encode(to: encoder) case .terminalResized(let v): try v.encode(to: encoder) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index f55696de3..09b252d41 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -1971,7 +1971,7 @@ public struct ModelSourceRegistrationCapability: Codable, Sendable, Equatable { /// /// Stability: 1.0 - Early development. public struct ModelSourceFormatInfo: Codable, Sendable, Equatable { - /// A {@link ModelSource.format} value. + /// A {@link ModelSourceRegistration.format} value. public var format: String public init( @@ -1996,44 +1996,14 @@ public struct ModelSource: Codable, Sendable, Equatable { public var displayName: String /// Icons for UI display. public var icons: [Icon]? - /// The format of `definition`: the `format` of one of the agent's - /// {@link ModelSourceRegistrationCapability.formats}. Present on a - /// registered source. - /// - /// Agents choose the formats they read. Some may read these common names: - /// - /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API. - /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. - /// - `'azureOpenai'`: an Azure OpenAI deployment. - /// - `'gemini'`: Google's Gemini API. - /// - /// Other formats are named with a namespace, such as - /// `example.com/model-source@1`, so they don't collide. - public var format: String? - /// How to reach the source, in `format`: endpoint, wire API, models, and so - /// on. The agent reads it. Every client can read it, so it MUST NOT contain - /// a credential. Present on a registered source. - /// - /// An agent that reads one of the common format names might expect a shape - /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is - /// the API's base URI and each `models` entry is `{ id, name?, - /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, - /// named as in {@link SessionModelInfo}. - public var definition: [String: AnyCodable]? - /// Opaque version token for `definition`, such as a hash of it, chosen by - /// whoever registers the source. Present on a registered source. Reducers - /// compare it, instead of the definition, to tell an update from a - /// re-registration of the same definition. - public var nonce: String? - /// What happens when the last contributing client leaves. Absent means `contributingClient`. - public var retention: ModelSourceRetentionPolicy? - /// Host-reported status, set with {@link RootModelSourceStateChangedAction}. - /// Absent until the host reports one, and after an update replaces the - /// definition until the host reports again. - public var state: ModelSourceState? + /// How the source was registered. Absent on a source the agent provides + /// itself. + public var registration: ModelSourceRegistration? + /// The source's status. + public var state: ModelSourceState /// RFC 9728 metadata for the endpoint a registered source's credential is /// for. Present whenever the source takes a credential, in every state, so - /// any client can deliver or rotate one. Set with `state`. + /// any client can deliver or rotate one. /// /// `credentialResource.resource` is the endpoint URL as the definition /// names it, in any scheme the agent supports (for example @@ -2041,7 +2011,7 @@ public struct ModelSource: Codable, Sendable, Equatable { /// `authenticate({ resource })`. public var credentialResource: ProtectedResourceMetadata? /// The {@link AuthenticateParams.accountId} sent with the credential the - /// host most recently accepted. Set with `state`. + /// host most recently accepted. public var accountId: String? /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. @@ -2052,10 +2022,7 @@ public struct ModelSource: Codable, Sendable, Equatable { case provider case displayName case icons - case format - case definition - case nonce - case retention + case registration case state case credentialResource case accountId @@ -2067,11 +2034,8 @@ public struct ModelSource: Codable, Sendable, Equatable { provider: String, displayName: String, icons: [Icon]? = nil, - format: String? = nil, - definition: [String: AnyCodable]? = nil, - nonce: String? = nil, - retention: ModelSourceRetentionPolicy? = nil, - state: ModelSourceState? = nil, + registration: ModelSourceRegistration? = nil, + state: ModelSourceState, credentialResource: ProtectedResourceMetadata? = nil, accountId: String? = nil, meta: [String: AnyCodable]? = nil @@ -2080,10 +2044,7 @@ public struct ModelSource: Codable, Sendable, Equatable { self.provider = provider self.displayName = displayName self.icons = icons - self.format = format - self.definition = definition - self.nonce = nonce - self.retention = retention + self.registration = registration self.state = state self.credentialResource = credentialResource self.accountId = accountId @@ -2091,6 +2052,48 @@ public struct ModelSource: Codable, Sendable, Equatable { } } +/// How a client, or the host from its own configuration, registered a model +/// source. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceRegistration: Codable, Sendable, Equatable { + /// The format of `definition`: the `format` of one of the agent's + /// {@link ModelSourceRegistrationCapability.formats}. + /// + /// Agents choose the formats they read. Some may read these common names: + /// + /// - `'openaiCompatible'`: an endpoint that implements OpenAI's API. + /// - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + /// - `'azureOpenai'`: an Azure OpenAI deployment. + /// - `'gemini'`: Google's Gemini API. + /// + /// Other formats are named with a namespace, such as + /// `example.com/model-source@1`, so they don't collide. + public var format: String + /// How to reach the source, in `format`: endpoint, wire API, models, and so + /// on. The agent reads it. Every client can read it, so it MUST NOT contain + /// a credential. + /// + /// An agent that reads one of the common format names might expect a shape + /// like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + /// the API's base URI and each `models` entry is `{ id, name?, + /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + /// named as in {@link SessionModelInfo}. + public var definition: [String: AnyCodable] + /// What happens when the last contributing client leaves. Absent means `contributingClient`. + public var retention: ModelSourceRetentionPolicy? + + public init( + format: String, + definition: [String: AnyCodable], + retention: ModelSourceRetentionPolicy? = nil + ) { + self.format = format + self.definition = definition + self.retention = retention + } +} + /// The agent is reading and validating the definition, or listing the /// source's models again after a credential change. /// diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift index b0c6c0d7f..7129f3551 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/NativeReducer.swift @@ -109,30 +109,19 @@ public struct AHPRootReducer: Reducer { case .rootModelSourceRemoved(let a): _ = applyModelSourceRemoved(&state, id: a.modelSourceId) - case .rootModelSourceStateChanged(let a): - _ = applyModelSourceStateChanged(&state, a) - default: break } } } -/// Adds `source`, re-registers the entry with the same `id`, `provider`, -/// `format`, and `nonce` (keeping its host-reported fields), or updates an -/// entry where any of those differ. +/// Adds `source`, or replaces the entry with the same `id`. func applyModelSourceSet(_ state: inout RootState, _ source: ModelSource) { var list = state.modelSources ?? [] - let idx = list.firstIndex(where: { $0.id == source.id }) - let existing = idx.map { list[$0] }.flatMap { sameModelSourceVersion($0, source) ? $0 : nil } - var merged = source - merged.state = existing?.state - merged.credentialResource = existing?.credentialResource - merged.accountId = existing?.accountId - if let idx { - list[idx] = merged + if let idx = list.firstIndex(where: { $0.id == source.id }) { + list[idx] = source } else { - list.append(merged) + list.append(source) } state.modelSources = list } @@ -146,24 +135,6 @@ func applyModelSourceRemoved(_ state: inout RootState, id: String) -> Bool { return true } -/// Whether two model sources have the same `provider`, `format`, and -/// definition `nonce`. -private func sameModelSourceVersion(_ a: ModelSource, _ b: ModelSource) -> Bool { - a.provider == b.provider && a.format == b.format && a.nonce == b.nonce -} - -/// Updates the host-reported fields of the model source with `action.id`. -/// Returns `false` when none matches. -func applyModelSourceStateChanged(_ state: inout RootState, _ action: RootModelSourceStateChangedAction) -> Bool { - guard var list = state.modelSources, - let idx = list.firstIndex(where: { $0.id == action.modelSourceId }) else { return false } - list[idx].state = action.state - list[idx].credentialResource = action.credentialResource - list[idx].accountId = action.accountId - state.modelSources = list - return true -} - // MARK: - Chat Reducer (Protocol-based) diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift index a0a5ec5b6..e0058b2e5 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Reducers.swift @@ -132,11 +132,6 @@ public func rootReducer(state: RootState, action: StateAction) -> RootState { guard applyModelSourceRemoved(&next, id: a.modelSourceId) else { return state } return next - case .rootModelSourceStateChanged(let a): - var next = state - guard applyModelSourceStateChanged(&next, a) else { return state } - return next - default: return state } diff --git a/docs/.changes/20261022-model-source-selection.json b/docs/.changes/20261022-model-source-selection.json index 8782a0748..d3c5f8e7c 100644 --- a/docs/.changes/20261022-model-source-selection.json +++ b/docs/.changes/20261022-model-source-selection.json @@ -4,7 +4,7 @@ "details": [ "```json", "{", - " \"modelSources\": [{ \"id\": \"source-a\", \"provider\": \"example\", \"displayName\": \"Service A\" }],", + " \"modelSources\": [{ \"id\": \"source-a\", \"provider\": \"example\", \"displayName\": \"Service A\", \"state\": { \"kind\": \"ready\" } }],", " \"agents\": [{", " \"provider\": \"example\",", " \"models\": [{ \"id\": \"model-a\", \"provider\": \"example\", \"name\": \"Model\", \"modelSourceId\": \"source-a\" }]", diff --git a/docs/.changes/20261123-model-source-registry.json b/docs/.changes/20261123-model-source-registry.json index 6b3a038e4..90a00bd09 100644 --- a/docs/.changes/20261123-model-source-registry.json +++ b/docs/.changes/20261123-model-source-registry.json @@ -1,5 +1,19 @@ { "type": "added", - "message": "Model source registry: clients can register bring-your-own-key model sources with the host through the client-dispatchable `root/modelSourceSet` and `root/modelSourceRemoved` actions. A registered `ModelSource` carries its `format`, its `definition`, and a `nonce` for it: re-registering the same `provider`, `format`, and `nonce` keeps the source's status and credential. Agents advertise the formats they read as `ModelSourceFormatInfo` entries in `AgentCapabilities.modelSourceRegistration`. Clients deliver each source's credential with a `modelSource` `authenticate` target, naming the key with `authenticate`'s `accountId`. The host reports status, `credentialResource`, and `accountId` with the host-only `root/modelSourceStateChanged` action, using model-source-specific auth reasons (`required`, `expired`, `rejected`, `revoked`). Requests and turns that need an unavailable source fail with the new `AhpErrorCodes.ModelSourceUnavailable` (`-32013`), which a turn's error part carries in the new optional `ErrorInfo.errorCode`.", + "message": "Add a model source registry so clients can register bring-your-own-key model sources with the host, and use their models in any session or automation.", + "details": [ + "```ts", + "// A client asks the host to register a source in a format the agent reads.", + "dispatch({", + " type: 'root/modelSourceRegisterRequested',", + " modelSourceId: 'byok/openrouter', provider: 'copilot', displayName: 'OpenRouter',", + " registration: { format: 'openaiCompatible', definition: { endpoint: 'https://openrouter.ai/api/v1' } },", + "});", + "// The host publishes it with root/modelSourceSet. While its state is authRequired,", + "// the client delivers the key with an authenticate target of kind 'modelSource'.", + "```", + "Agents advertise the formats they read in `AgentCapabilities.modelSourceRegistration`. Requests and turns that need an unavailable source fail with `AhpErrorCodes.ModelSourceUnavailable` (`-32013`), which a turn's error part carries in the new optional `ErrorInfo.errorCode`.", + "Read more in [Model Sources](https://microsoft.github.io/agent-host-protocol/guide/model-sources)." + ], "issues": [619] } diff --git a/docs/guide/actions.md b/docs/guide/actions.md index 9a2dd9aa8..7cd8b5b7e 100644 --- a/docs/guide/actions.md +++ b/docs/guide/actions.md @@ -23,7 +23,7 @@ Individual action payloads do **not** carry their own `session: URI` or `termina ## Root Actions -These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceSet`, and `root/modelSourceRemoved` are client-dispatchable; the rest are server-originated. +These mutate root state and travel on the [Root Channel](/specification/root-channel). `root/configChanged`, `root/modelSourceRegisterRequested`, and `root/modelSourceRemoved` are client-dispatchable; the rest are server-originated. | Type | Client-dispatchable? | When | |---|---|---| @@ -31,9 +31,9 @@ These mutate root state and travel on the [Root Channel](/specification/root-cha | `root/activeSessionsChanged` | No | Count of active sessions changed | | `root/terminalsChanged` | No | Lightweight terminal catalogue changed (full replacement) | | `root/configChanged` | **Yes** | Host-level configuration values changed | -| `root/modelSourceSet` | **Yes** | A [model source](/guide/model-sources) was added, re-registered, or updated by `id` | +| `root/modelSourceRegisterRequested` | **Yes** | A client asked the host to register or update a [model source](/guide/model-sources) | +| `root/modelSourceSet` | No | The host added or replaced a model source by `id` | | `root/modelSourceRemoved` | **Yes** | A model source was removed by `modelSourceId` | -| `root/modelSourceStateChanged` | No | The host reported a model source's status and credential fields | ## Automation Catalogue Actions diff --git a/docs/guide/model-sources.md b/docs/guide/model-sources.md index 99b2e27a4..4d07b61e3 100644 --- a/docs/guide/model-sources.md +++ b/docs/guide/model-sources.md @@ -13,14 +13,14 @@ Reading the definition, validating endpoints, discovering models, and the wire p ## Where model sources appear -Every source is an entry in `RootState.modelSources`, naming the agent `provider` it serves. There are two kinds: +Every source is an entry in `RootState.modelSources`, naming the agent `provider` it serves and its `state`. There are two kinds: -1. **Built-in sources** that an agent provides itself, such as a first-party subscription. The host lists them without a `format` or `definition`, and their sign-in uses [`AgentInfo.protectedResources`](/specification/authentication#discovery). -2. **Registered sources** that a client registered, or that the host registered from its own configuration. They carry a `format`, a `definition`, and a `nonce`, and the host reports their status. +1. **Built-in sources** that an agent provides itself, such as a first-party subscription. The host lists them without a `registration`, and their sign-in uses [`AgentInfo.protectedResources`](/specification/authentication#discovery). +2. **Registered sources** that a client registered, or that the host registered from its own configuration. Their `registration` carries the definition the agent reads. ```typescript const sources = state.modelSources?.filter(s => s.provider === agent.provider) ?? []; -const registered = sources.filter(s => s.definition !== undefined); +const registered = sources.filter(s => s.registration !== undefined); ``` ## Shape @@ -31,13 +31,12 @@ ModelSource { provider: string // agent provider that serves its models displayName: string icons?: Icon[] - format?: string // registered sources only - definition?: Record // how the agent reaches the source; never a credential - nonce?: string // version token for definition - retention?: 'contributingClient' | 'host' - - // Host-reported, set together by root/modelSourceStateChanged - state?: ModelSourceState // starting | ready | authRequired | error + registration?: { // absent on built-in sources + format: string + definition: Record // how the agent reaches the source; never a credential + retention?: 'contributingClient' | 'host' + } + state: ModelSourceState // starting | ready | authRequired | error credentialResource?: ProtectedResourceMetadata accountId?: string } @@ -45,25 +44,22 @@ ModelSource { ## Registering a source -An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads, most preferred first. Each agent decides which formats it reads. `ModelSource.format` notes a few common names that some agents may read, such as `openaiCompatible` and `anthropic`. Other formats are named with a namespace, such as `example.com/model-source@1`. - -A client registers a source with [`root/modelSourceSet`](/reference/root#rootmodelsourcesetaction), giving its `format`, a `definition` that tells the agent how to reach it, and a `nonce` that versions the definition, such as a hash of it. Every client can read a definition, so it MUST NOT contain a credential. +An agent that serves models from client-registered sources advertises [`AgentCapabilities.modelSourceRegistration`](/reference/root#modelsourceregistrationcapability) with the formats it reads, most preferred first. Each agent decides which formats it reads. `ModelSourceRegistration.format` notes a few common names that some agents may read, such as `openaiCompatible` and `anthropic`. Other formats are named with a namespace, such as `example.com/model-source@1`. -`Set` adds the source, or replaces the one with the same `id`: +Registration follows the same pattern as automations: the client asks, and the host publishes the result. -- **Add.** No source has the `id`. -- **Re-register.** One has, with the same `provider`, `format`, and `nonce`. The source keeps its host-reported fields and takes everything else from the action, so re-registering doesn't disturb a working source. -- **Update.** Any of the three differs. The source is replaced, its host-reported fields stay absent until the host reports again, and the host drops its credential. +1. A client dispatches [`root/modelSourceRegisterRequested`](/reference/root#rootmodelsourceregisterrequestedaction) with the source's `modelSourceId`, `provider`, `displayName`, and a `registration` holding its `format` and a `definition` that tells the agent how to reach it. Every client can read a definition, so it MUST NOT contain a credential. The request doesn't change state. +2. The host validates the request and publishes the source with [`root/modelSourceSet`](/reference/root#rootmodelsourcesetaction), which adds it or replaces the one with the same `id`. When the registration is unchanged, the host keeps the source's status and credential. When the definition changes, it drops the credential and the source goes back to `starting`. -[`root/modelSourceRemoved`](/reference/root#rootmodelsourceremovedaction) removes a source for every client. The host rejects either action when it breaks the rules in [Server Validation of Client Actions](/specification/root-channel#server-validation-of-client-actions). +[`root/modelSourceRemoved`](/reference/root#rootmodelsourceremovedaction) removes a source for every client. The host rejects either client action when it breaks the rules in [Server Validation of Client Actions](/specification/root-channel#server-validation-of-client-actions). -A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one. It SHOULD NOT replace a source whose `nonce` differs from its own copy unless the user changed that source; otherwise two clients with different configurations replace each other's source indefinitely. +A client registers its sources when it starts or reconnects, and when the user changes one. It SHOULD derive `id` from a stable key in its own configuration, so every window and device with the same source shares one. It SHOULD NOT replace a source whose definition differs from its own copy unless the user changed that source; otherwise two clients with different configurations replace each other's source indefinitely. -Each client that registers a source is a **contributing client**. The host tracks contributing clients itself, from `ActionEnvelope.origin`, so they aren't in state. Every connected client may change, supply credentials for, and select every source. A host that can verify principals MAY restrict a source to clients of the principal that registered it. +Each client that requests a registration is a **contributing client**. The host tracks contributing clients itself, from `ActionEnvelope.origin`, so they aren't in state. Every connected client may change, supply credentials for, and select every source. A host that can verify principals MAY restrict a source to clients of the principal that registered it. ## Status -The host reports a registered source's status with [`root/modelSourceStateChanged`](/reference/root#rootmodelsourcestatechangedaction), which sets `state`, `credentialResource`, and `accountId` together. The reducer ignores an unknown `modelSourceId`, so a late report can't bring back a removed source. +Only the host dispatches `root/modelSourceSet`, and it uses it for every change to a source, including its `state`, `credentialResource`, and `accountId`. ```mermaid stateDiagram-v2 @@ -91,13 +87,13 @@ sequenceDiagram participant C as Client participant H as Agent Host - C->>H: root/modelSourceSet (format, definition, nonce) - H-->>C: root/modelSourceStateChanged (authRequired, credentialResource) + C->>H: root/modelSourceRegisterRequested (registration) + H-->>C: root/modelSourceSet (authRequired, credentialResource) C->>H: authenticate({ resource, token, accountId, target: { kind: 'modelSource', modelSourceId } }) H-->>C: {} - H-->>C: root/modelSourceStateChanged (ready, accountId) + H-->>C: root/modelSourceSet (ready, accountId) H-->>C: root/agentsChanged (the source's models join the agent's models) ``` @@ -110,11 +106,11 @@ The token is whatever the source's definition calls for, such as an API key. The | `rejected` | The endpoint refused the credential. `accountId` still names it. | Only a key whose `accountId` differs. | | `revoked` | A client revoked the credential. | Nothing, until a user asks. | -Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers one only in answer to the source's current state, and MUST NOT send a stored secret unless the source's `provider` and `format` match its own copy and every endpoint in the source's `definition` that the key would reach is one its own copy sends the key to. +Clients MUST NOT cache a model source credential they delivered, or replay one, for example after a reconnect. A client delivers one only in answer to the source's current state, and MUST NOT send a stored secret unless the source's `provider` and `registration.format` match its own copy and every endpoint in its `registration.definition` that the key would reach is one its own copy sends the key to. ## Retention -A source's `retention` decides what happens when its last contributing client disconnects and doesn't return within a grace period the host chooses: +A registered source's `registration.retention` decides what happens when its last contributing client disconnects and doesn't return within a grace period the host chooses: - `contributingClient`, the default: the host stops new work on the source, lets running turns finish, and then removes it. - `host`: the source stays until a client removes it or host policy expires it. diff --git a/docs/proposals/model-source-registry.md b/docs/proposals/model-source-registry.md index 95612d0ff..5fd95ed03 100644 --- a/docs/proposals/model-source-registry.md +++ b/docs/proposals/model-source-registry.md @@ -4,7 +4,12 @@ ## Status -Implemented by [#627](https://github.com/microsoft/agent-host-protocol/pull/627). The type sketches below show the intended shape; the canonical definitions are in `types/`. +Implemented by [#627](https://github.com/microsoft/agent-host-protocol/pull/627). The type sketches below show the intended shape; the canonical definitions are in `types/` and the [Model Sources guide](/guide/model-sources). Review of #627 changed the shape in these ways: + +- `RootState.modelSources` lists every model source, including an agent's built-in ones, and replaces `ModelSourceInfo` and `AgentInfo.modelSources`. `state` is required. +- A registered source's `format`, `definition`, and `retention` are grouped in `ModelSource.registration`, and there's no `nonce`: the host compares definitions itself. +- Clients dispatch `root/modelSourceRegisterRequested`, which doesn't change state. The host publishes every source and status change with `root/modelSourceSet`, which replaces the entry, so there's no `root/modelSourceStateChanged`. `root/modelSourceRemoved` takes a `modelSourceId`. +- Requests and turns on an unavailable source fail with `AhpErrorCodes.ModelSourceUnavailable`, which a turn carries in `ErrorInfo.errorCode`. An earlier revision proposed model sources as session-scoped plugin customizations. Review pointed out that BYOK configuration belongs to the user rather than to one session, and that automations and long-running headless sessions need model sources that outlive a client's session. This revision moves them to a host-wide registry. [§11](#_11-alternatives-considered) explains the trade-off. diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index f1172d593..d61b8174b 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -44,9 +44,9 @@ An agent provider can offer models from more than one source, such as a service, - Model IDs are stable. A host SHOULD keep a model's ID across catalog updates, so saved selections keep working. It MUST NOT reuse an ID for a different source or upstream model, even after the model leaves `models`. A saved selection whose ID is no longer in `models` is unavailable. - A source can have no models. -A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, which also determines the source. The host lists the sources an agent provides itself. They have no `format` or `definition`, and their sign-in uses `AgentInfo.protectedResources`. +A [`ModelSelection`](/reference/root#modelselection) names a model by its `id`, which also determines the source. The host lists the sources an agent provides itself. They have no `registration`, and their sign-in uses `AgentInfo.protectedResources`. -Clients and hosts can also register sources the agent doesn't have, each with a definition the agent reads. The host reports each registered source's status, and clients deliver its credential with [`authenticate`](/specification/authentication#model-source-credentials). See the [Model Sources guide](/guide/model-sources). +Clients and hosts can also register sources the agent doesn't have, each with a definition the agent reads. A client asks with `root/modelSourceRegisterRequested`, and the host publishes every source and its status with `root/modelSourceSet`, and clients deliver its credential with [`authenticate`](/specification/authentication#model-source-credentials). See the [Model Sources guide](/guide/model-sources). ### Paginating the catalogue @@ -99,7 +99,7 @@ target channel instead. | `root/sessionSummaryChanged` | server → client notification | Session catalogue entry mutated. | | `root/progress` | server → client notification | Generic progress for a long-running operation a client opted into (e.g. an SDK download). | | `unsubscribe` | client → server notification | Stop receiving root-channel messages. | -| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceSet`, or `root/modelSourceRemoved`. | +| `dispatchAction` | client → server notification | Dispatch a root-scoped client action: `root/configChanged`, `root/modelSourceRegisterRequested`, or `root/modelSourceRemoved`. | `auth/required` may also be emitted on `ahp-root://` when the auth requirement is root-scoped; see [Authentication](/specification/authentication). @@ -110,13 +110,11 @@ When the server receives a client-dispatched action on this channel, it MUST val | Action | Condition | Server Behavior | | --- | --- | --- | -| `root/modelSourceSet` | The agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `format` | Server MUST reject the action | -| `root/modelSourceSet` | `format`, `definition`, or `nonce` is absent, or a host-reported field is present | Server MUST reject the action | -| `root/modelSourceSet` | `provider`, `format`, and `nonce` match the existing source's, but `definition` differs | Server MUST reject the action | -| `root/modelSourceSet` | The existing source with that `id` is one the host registered itself | Server MUST reject the action | -| `root/modelSourceSet` | The host won't honor the requested `retention` | Server MUST reject the action | +| `root/modelSourceRegisterRequested` | The agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `registration.format` | Server MUST reject the action | +| `root/modelSourceRegisterRequested` | The existing source with that `modelSourceId` is one the host registered itself | Server MUST reject the action | +| `root/modelSourceRegisterRequested` | The host won't honor the requested `registration.retention` | Server MUST reject the action | | `root/modelSourceRemoved` | The source is one the host registered itself | Server MAY reject the action | -| `root/modelSourceSet`, `root/modelSourceRemoved` | The host restricts sources by principal, and the source belongs to another principal | Server MAY reject the action | +| `root/modelSourceRegisterRequested`, `root/modelSourceRemoved` | The host restricts sources by principal, and the source belongs to another principal | Server MAY reject the action | ## Actions @@ -128,9 +126,9 @@ Root state is mutated by action envelopes broadcast on this channel. Refer to th | `root/activeSessionsChanged` | Server | Replaces `activeSessions` | | `root/terminalsChanged` | Server | Replaces `terminals` | | `root/configChanged` | Server / Client | Merges (or replaces) `config.values` | -| `root/modelSourceSet` | Server / Client | Adds a source to `modelSources`, or replaces the one with the same `id`. Keeps its host-reported fields when `provider`, `format`, and `nonce` are unchanged | +| `root/modelSourceRegisterRequested` | Client | Asks the host to register or update a source. Doesn't change state | +| `root/modelSourceSet` | Server | Adds a source to `modelSources`, or replaces the one with the same `id` | | `root/modelSourceRemoved` | Server / Client | Removes the source whose `id` is `modelSourceId` | -| `root/modelSourceStateChanged` | Server | Sets a source's host-reported fields. A no-op for an unknown `modelSourceId` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 042d1a7b8..cb6a2aad1 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -127,68 +127,82 @@ "config" ] }, - "RootModelSourceSetAction": { + "RootModelSourceRegisterRequestedAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client registers a source with its `format`, `definition`, and `nonce`,\nand without any host-reported field. The host learns which client\nregistered it from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Asks the host to register a model source, or to update the one with the\nsame `modelSourceId`. The reducer leaves state unchanged. The host counts\nthe dispatching client as a contributing client, validates the\nregistration, and publishes the result with\n{@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the\nsource's status and credential when the registration is unchanged.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceSet" + "const": "root/modelSourceRegisterRequested" }, - "modelSource": { - "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`." + "modelSourceId": { + "type": "string", + "description": "The model source's `id`, chosen by the client." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent serves the source's models." + }, + "displayName": { + "type": "string", + "description": "Human-readable name." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "The source's format, definition, and retention." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ "type", - "modelSource" + "modelSourceId", + "provider", + "displayName", + "registration" ] }, - "RootModelSourceRemovedAction": { + "RootModelSourceSetAction": { "type": "object", - "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or replaces the one with the same `id`. Only the host\ndispatches it, to publish a registration, a source an agent provides\nitself, or a change in a source's status.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRemoved" + "const": "root/modelSourceSet" }, - "modelSourceId": { - "type": "string", - "description": "The model source's `id`." + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or replace, matched by `id`." } }, "required": [ "type", - "modelSourceId" + "modelSource" ] }, - "RootModelSourceStateChangedAction": { + "RootModelSourceRemovedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`modelSourceId`. Other fields of the source are preserved. Only the host\ndispatches it.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceStateChanged" + "const": "root/modelSourceRemoved" }, "modelSourceId": { "type": "string", "description": "The model source's `id`." - }, - "state": { - "$ref": "#/$defs/ModelSourceState", - "description": "The new status." - }, - "credentialResource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." - }, - "accountId": { - "type": "string", - "description": "Replaces the source's `accountId`. Absent clears it." } }, "required": [ "type", - "modelSourceId", - "state" + "modelSourceId" ] }, "SessionReadyAction": { @@ -3649,7 +3663,7 @@ "properties": { "format": { "type": "string", - "description": "A {@link ModelSource.format} value." + "description": "A {@link ModelSourceRegistration.format} value." } }, "required": [ @@ -3679,34 +3693,21 @@ }, "description": "Icons for UI display." }, - "format": { - "type": "string", - "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "nonce": { - "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "How the source was registered. Absent on a source the agent provides\nitself." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." + "description": "The source's status." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted." }, "_meta": { "type": "object", @@ -3717,7 +3718,31 @@ "required": [ "id", "provider", - "displayName" + "displayName", + "state" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "How a client, or the host from its own configuration, registered a model\nsource.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + } + }, + "required": [ + "format", + "definition" ] }, "ModelSourceStartingState": { @@ -10427,13 +10452,13 @@ "$ref": "#/$defs/RootConfigChangedAction" }, { - "$ref": "#/$defs/RootModelSourceSetAction" + "$ref": "#/$defs/RootModelSourceRegisterRequestedAction" }, { - "$ref": "#/$defs/RootModelSourceRemovedAction" + "$ref": "#/$defs/RootModelSourceSetAction" }, { - "$ref": "#/$defs/RootModelSourceStateChangedAction" + "$ref": "#/$defs/RootModelSourceRemovedAction" }, { "$ref": "#/$defs/SessionReadyAction" diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 32c0ae906..3fcb85144 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -2959,7 +2959,7 @@ "properties": { "format": { "type": "string", - "description": "A {@link ModelSource.format} value." + "description": "A {@link ModelSourceRegistration.format} value." } }, "required": [ @@ -2989,34 +2989,21 @@ }, "description": "Icons for UI display." }, - "format": { - "type": "string", - "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "nonce": { - "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "How the source was registered. Absent on a source the agent provides\nitself." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." + "description": "The source's status." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted." }, "_meta": { "type": "object", @@ -3027,7 +3014,31 @@ "required": [ "id", "provider", - "displayName" + "displayName", + "state" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "How a client, or the host from its own configuration, registered a model\nsource.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + } + }, + "required": [ + "format", + "definition" ] }, "ModelSourceStartingState": { @@ -9180,68 +9191,82 @@ "config" ] }, - "RootModelSourceSetAction": { + "RootModelSourceRegisterRequestedAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client registers a source with its `format`, `definition`, and `nonce`,\nand without any host-reported field. The host learns which client\nregistered it from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Asks the host to register a model source, or to update the one with the\nsame `modelSourceId`. The reducer leaves state unchanged. The host counts\nthe dispatching client as a contributing client, validates the\nregistration, and publishes the result with\n{@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the\nsource's status and credential when the registration is unchanged.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceSet" + "const": "root/modelSourceRegisterRequested" }, - "modelSource": { - "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`." + "modelSourceId": { + "type": "string", + "description": "The model source's `id`, chosen by the client." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent serves the source's models." + }, + "displayName": { + "type": "string", + "description": "Human-readable name." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "The source's format, definition, and retention." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ "type", - "modelSource" + "modelSourceId", + "provider", + "displayName", + "registration" ] }, - "RootModelSourceRemovedAction": { + "RootModelSourceSetAction": { "type": "object", - "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or replaces the one with the same `id`. Only the host\ndispatches it, to publish a registration, a source an agent provides\nitself, or a change in a source's status.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRemoved" + "const": "root/modelSourceSet" }, - "modelSourceId": { - "type": "string", - "description": "The model source's `id`." + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or replace, matched by `id`." } }, "required": [ "type", - "modelSourceId" + "modelSource" ] }, - "RootModelSourceStateChangedAction": { + "RootModelSourceRemovedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`modelSourceId`. Other fields of the source are preserved. Only the host\ndispatches it.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceStateChanged" + "const": "root/modelSourceRemoved" }, "modelSourceId": { "type": "string", "description": "The model source's `id`." - }, - "state": { - "$ref": "#/$defs/ModelSourceState", - "description": "The new status." - }, - "credentialResource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." - }, - "accountId": { - "type": "string", - "description": "Replaces the source's `accountId`. Absent clears it." } }, "required": [ "type", - "modelSourceId", - "state" + "modelSourceId" ] }, "SessionReadyAction": { @@ -11819,13 +11844,13 @@ "$ref": "#/$defs/RootConfigChangedAction" }, { - "$ref": "#/$defs/RootModelSourceSetAction" + "$ref": "#/$defs/RootModelSourceRegisterRequestedAction" }, { - "$ref": "#/$defs/RootModelSourceRemovedAction" + "$ref": "#/$defs/RootModelSourceSetAction" }, { - "$ref": "#/$defs/RootModelSourceStateChangedAction" + "$ref": "#/$defs/RootModelSourceRemovedAction" }, { "$ref": "#/$defs/SessionReadyAction" @@ -12290,14 +12315,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceState": { "oneOf": [ { @@ -12315,6 +12332,14 @@ ], "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its last contributing client\nleaves." + }, "ModelSourceAuthRequiredReason": { "enum": [ "required", diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 76de69eef..52debf633 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -870,7 +870,7 @@ "properties": { "format": { "type": "string", - "description": "A {@link ModelSource.format} value." + "description": "A {@link ModelSourceRegistration.format} value." } }, "required": [ @@ -900,34 +900,21 @@ }, "description": "Icons for UI display." }, - "format": { - "type": "string", - "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "nonce": { - "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "How the source was registered. Absent on a source the agent provides\nitself." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." + "description": "The source's status." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted." }, "_meta": { "type": "object", @@ -938,7 +925,31 @@ "required": [ "id", "provider", - "displayName" + "displayName", + "state" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "How a client, or the host from its own configuration, registered a model\nsource.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + } + }, + "required": [ + "format", + "definition" ] }, "ModelSourceStartingState": { @@ -9098,14 +9109,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceState": { "oneOf": [ { @@ -9123,6 +9126,14 @@ ], "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its last contributing client\nleaves." + }, "ModelSourceAuthRequiredReason": { "enum": [ "required", @@ -9980,13 +9991,13 @@ "$ref": "#/$defs/RootConfigChangedAction" }, { - "$ref": "#/$defs/RootModelSourceSetAction" + "$ref": "#/$defs/RootModelSourceRegisterRequestedAction" }, { - "$ref": "#/$defs/RootModelSourceRemovedAction" + "$ref": "#/$defs/RootModelSourceSetAction" }, { - "$ref": "#/$defs/RootModelSourceStateChangedAction" + "$ref": "#/$defs/RootModelSourceRemovedAction" }, { "$ref": "#/$defs/SessionReadyAction" @@ -10535,68 +10546,82 @@ "config" ] }, - "RootModelSourceSetAction": { + "RootModelSourceRegisterRequestedAction": { "type": "object", - "description": "Adds a model source, or updates the one with the same `id`:\n\n- **Add.** When no model source has the `id`, appends `modelSource`.\n- **Re-register.** When one has, with the same `provider`, `format`, and\n `nonce`, keeps its host-reported fields (`state`, `credentialResource`,\n and `accountId`) and takes everything else from the action.\n- **Update.** When any of the three differs, replaces the source. Its\n host-reported fields are absent until the host reports again with\n {@link RootModelSourceStateChangedAction}.\n\nA client registers a source with its `format`, `definition`, and `nonce`,\nand without any host-reported field. The host learns which client\nregistered it from the envelope's `origin`.\n\nStability: 1.0 - Early development.", + "description": "Asks the host to register a model source, or to update the one with the\nsame `modelSourceId`. The reducer leaves state unchanged. The host counts\nthe dispatching client as a contributing client, validates the\nregistration, and publishes the result with\n{@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the\nsource's status and credential when the registration is unchanged.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceSet" + "const": "root/modelSourceRegisterRequested" }, - "modelSource": { - "$ref": "#/$defs/ModelSource", - "description": "The model source to add or update, matched by `id`." + "modelSourceId": { + "type": "string", + "description": "The model source's `id`, chosen by the client." + }, + "provider": { + "type": "string", + "description": "Agent provider whose agent serves the source's models." + }, + "displayName": { + "type": "string", + "description": "Human-readable name." + }, + "icons": { + "type": "array", + "items": { + "$ref": "#/$defs/Icon" + }, + "description": "Icons for UI display." + }, + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "The source's format, definition, and retention." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." } }, "required": [ "type", - "modelSource" + "modelSourceId", + "provider", + "displayName", + "registration" ] }, - "RootModelSourceRemovedAction": { + "RootModelSourceSetAction": { "type": "object", - "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", + "description": "Adds a model source, or replaces the one with the same `id`. Only the host\ndispatches it, to publish a registration, a source an agent provides\nitself, or a change in a source's status.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceRemoved" + "const": "root/modelSourceSet" }, - "modelSourceId": { - "type": "string", - "description": "The model source's `id`." + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or replace, matched by `id`." } }, "required": [ "type", - "modelSourceId" + "modelSource" ] }, - "RootModelSourceStateChangedAction": { + "RootModelSourceRemovedAction": { "type": "object", - "description": "Updates a model source's host-reported fields together: `state`,\n`credentialResource`, and `accountId`. A no-op when no model source has\n`modelSourceId`. Other fields of the source are preserved. Only the host\ndispatches it.\n\nStability: 1.0 - Early development.", + "description": "Removes the model source with the given `modelSourceId`, for every client.\nA no-op when none matches.\n\nStability: 1.0 - Early development.", "properties": { "type": { - "const": "root/modelSourceStateChanged" + "const": "root/modelSourceRemoved" }, "modelSourceId": { "type": "string", "description": "The model source's `id`." - }, - "state": { - "$ref": "#/$defs/ModelSourceState", - "description": "The new status." - }, - "credentialResource": { - "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "Replaces the source's `credentialResource`. Absent clears it, for a\nsource that needs no credential." - }, - "accountId": { - "type": "string", - "description": "Replaces the source's `accountId`. Absent clears it." } }, "required": [ "type", - "modelSourceId", - "state" + "modelSourceId" ] }, "SessionReadyAction": { diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 7e69de2ac..08983ecff 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1171,7 +1171,7 @@ "properties": { "format": { "type": "string", - "description": "A {@link ModelSource.format} value." + "description": "A {@link ModelSourceRegistration.format} value." } }, "required": [ @@ -1201,34 +1201,21 @@ }, "description": "Icons for UI display." }, - "format": { - "type": "string", - "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "nonce": { - "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "How the source was registered. Absent on a source the agent provides\nitself." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." + "description": "The source's status." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted." }, "_meta": { "type": "object", @@ -1239,7 +1226,31 @@ "required": [ "id", "provider", - "displayName" + "displayName", + "state" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "How a client, or the host from its own configuration, registered a model\nsource.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + } + }, + "required": [ + "format", + "definition" ] }, "ModelSourceStartingState": { @@ -7345,14 +7356,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceState": { "oneOf": [ { @@ -7370,6 +7373,14 @@ ], "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its last contributing client\nleaves." + }, "ModelSourceAuthRequiredReason": { "enum": [ "required", diff --git a/schema/state.schema.json b/schema/state.schema.json index e53d53172..f96b3756d 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -780,7 +780,7 @@ "properties": { "format": { "type": "string", - "description": "A {@link ModelSource.format} value." + "description": "A {@link ModelSourceRegistration.format} value." } }, "required": [ @@ -810,34 +810,21 @@ }, "description": "Icons for UI display." }, - "format": { - "type": "string", - "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}. Present on a\nregistered source.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." - }, - "definition": { - "type": "object", - "additionalProperties": {}, - "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential. Present on a registered source.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "nonce": { - "type": "string", - "description": "Opaque version token for `definition`, such as a hash of it, chosen by\nwhoever registers the source. Present on a registered source. Reducers\ncompare it, instead of the definition, to tell an update from a\nre-registration of the same definition." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + "registration": { + "$ref": "#/$defs/ModelSourceRegistration", + "description": "How the source was registered. Absent on a source the agent provides\nitself." }, "state": { "$ref": "#/$defs/ModelSourceState", - "description": "Host-reported status, set with {@link RootModelSourceStateChangedAction}.\nAbsent until the host reports one, and after an update replaces the\ndefinition until the host reports again." + "description": "The source's status." }, "credentialResource": { "$ref": "#/$defs/ProtectedResourceMetadata", - "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one. Set with `state`.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." + "description": "RFC 9728 metadata for the endpoint a registered source's credential is\nfor. Present whenever the source takes a credential, in every state, so\nany client can deliver or rotate one.\n\n`credentialResource.resource` is the endpoint URL as the definition\nnames it, in any scheme the agent supports (for example\n`http://localhost:11434/v1`). It's the value a client passes back as\n`authenticate({ resource })`." }, "accountId": { "type": "string", - "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted. Set with `state`." + "description": "The {@link AuthenticateParams.accountId} sent with the credential the\nhost most recently accepted." }, "_meta": { "type": "object", @@ -848,7 +835,31 @@ "required": [ "id", "provider", - "displayName" + "displayName", + "state" + ] + }, + "ModelSourceRegistration": { + "type": "object", + "description": "How a client, or the host from its own configuration, registered a model\nsource.\n\nStability: 1.0 - Early development.", + "properties": { + "format": { + "type": "string", + "description": "The format of `definition`: the `format` of one of the agent's\n{@link ModelSourceRegistrationCapability.formats}.\n\nAgents choose the formats they read. Some may read these common names:\n\n- `'openaiCompatible'`: an endpoint that implements OpenAI's API.\n- `'anthropic'`: an endpoint that implements Anthropic's Messages API.\n- `'azureOpenai'`: an Azure OpenAI deployment.\n- `'gemini'`: Google's Gemini API.\n\nOther formats are named with a namespace, such as\n`example.com/model-source@1`, so they don't collide." + }, + "definition": { + "type": "object", + "additionalProperties": {}, + "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." + } + }, + "required": [ + "format", + "definition" ] }, "ModelSourceStartingState": { diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index fe5a7459f..83d0bbe50 100644 --- a/scripts/generate-csharp.ts +++ b/scripts/generate-csharp.ts @@ -813,6 +813,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, { name: 'ModelSourceFormatInfo' }, + { name: 'ModelSourceRegistration' }, { name: 'ModelSource' }, { name: 'ModelSourceStartingState' }, { name: 'ModelSourceReadyState' }, @@ -1839,7 +1840,7 @@ const ACTION_VARIANTS: { type: string; variantName: string; tsInterface: string { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, - { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, + { type: 'root/modelSourceRegisterRequested', variantName: 'RootModelSourceRegisterRequested', tsInterface: 'RootModelSourceRegisterRequestedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, // Session turn/tool-call/error/usage/reasoning actions have no TypeScript interfaces in diff --git a/scripts/generate-go.ts b/scripts/generate-go.ts index 319c9a682..c2d90ab3b 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -787,6 +787,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, { name: 'ModelSourceFormatInfo' }, + { name: 'ModelSourceRegistration' }, { name: 'ModelSource' }, { name: 'ModelSourceStartingState' }, { name: 'ModelSourceReadyState' }, @@ -1834,7 +1835,7 @@ const ACTION_VARIANTS: { { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, - { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, + { type: 'root/modelSourceRegisterRequested', variantName: 'RootModelSourceRegisterRequested', tsInterface: 'RootModelSourceRegisterRequestedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, { type: 'session/chatAdded', variantName: 'SessionChatAdded', tsInterface: 'SessionChatAddedAction' }, diff --git a/scripts/generate-kotlin.ts b/scripts/generate-kotlin.ts index dc77c0b10..2749ed380 100644 --- a/scripts/generate-kotlin.ts +++ b/scripts/generate-kotlin.ts @@ -1139,7 +1139,7 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceStartingState', + 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceRegistration', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', @@ -1823,7 +1823,7 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'root/configChanged', caseName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceSet', caseName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, { type: 'root/modelSourceRemoved', caseName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, - { type: 'root/modelSourceStateChanged', caseName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, + { type: 'root/modelSourceRegisterRequested', caseName: 'RootModelSourceRegisterRequested', tsInterface: 'RootModelSourceRegisterRequestedAction' }, { type: 'terminal/data', caseName: 'TerminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'TerminalInput', tsInterface: 'TerminalInputAction' }, { type: 'terminal/resized', caseName: 'TerminalResized', tsInterface: 'TerminalResizedAction' }, diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 49be5b4f1..7d4e08705 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -889,6 +889,7 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'MultipleWorkingDirectoriesCapability' }, { name: 'ModelSourceRegistrationCapability' }, { name: 'ModelSourceFormatInfo' }, + { name: 'ModelSourceRegistration' }, { name: 'ModelSource' }, { name: 'ModelSourceStartingState', omitDiscriminants: true }, { name: 'ModelSourceReadyState', omitDiscriminants: true }, @@ -1812,7 +1813,7 @@ const ACTION_VARIANTS: { { type: 'root/configChanged', variantName: 'RootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction', boxed: true }, { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, - { type: 'root/modelSourceStateChanged', variantName: 'RootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, + { type: 'root/modelSourceRegisterRequested', variantName: 'RootModelSourceRegisterRequested', tsInterface: 'RootModelSourceRegisterRequestedAction' }, { type: 'session/ready', variantName: 'SessionReady', tsInterface: 'SessionReadyAction' }, { type: 'session/creationFailed', variantName: 'SessionCreationFailed', tsInterface: 'SessionCreationFailedAction' }, { type: 'session/chatAdded', variantName: 'SessionChatAdded', tsInterface: 'SessionChatAddedAction' }, @@ -1999,7 +2000,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, MaterializedTurn, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary, SearchQuery, SearchLifecycleState, SearchResult, ModelSource, ModelSourceState, ProtectedResourceMetadata};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, MaterializedTurn, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary, SearchQuery, SearchLifecycleState, SearchResult, ModelSource, ModelSourceRegistration, Icon};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); diff --git a/scripts/generate-swift.ts b/scripts/generate-swift.ts index 5654a754f..2f4290b65 100644 --- a/scripts/generate-swift.ts +++ b/scripts/generate-swift.ts @@ -756,7 +756,7 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceStartingState', + 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceRegistration', 'ModelSourceStartingState', 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', 'ModelSourceErrorState', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', @@ -1749,7 +1749,7 @@ const ACTION_VARIANTS: { type: string; caseName: string; tsInterface: string }[] { type: 'root/configChanged', caseName: 'rootConfigChanged', tsInterface: 'RootConfigChangedAction' }, { type: 'root/modelSourceSet', caseName: 'rootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, { type: 'root/modelSourceRemoved', caseName: 'rootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, - { type: 'root/modelSourceStateChanged', caseName: 'rootModelSourceStateChanged', tsInterface: 'RootModelSourceStateChangedAction' }, + { type: 'root/modelSourceRegisterRequested', caseName: 'rootModelSourceRegisterRequested', tsInterface: 'RootModelSourceRegisterRequestedAction' }, { type: 'terminal/data', caseName: 'terminalData', tsInterface: 'TerminalDataAction' }, { type: 'terminal/input', caseName: 'terminalInput', tsInterface: 'TerminalInputAction' }, { type: 'terminal/resized', caseName: 'terminalResized', tsInterface: 'TerminalResizedAction' }, diff --git a/skills/protocol-authoring/naming.md b/skills/protocol-authoring/naming.md index 67aa0df9e..e5c7ed705 100644 --- a/skills/protocol-authoring/naming.md +++ b/skills/protocol-authoring/naming.md @@ -33,7 +33,7 @@ but don't use them as precedent. | **agent provider** (`provider`) | The ID of the agent backing a session or chat (`AgentInfo.provider`, `SessionState.provider`, `ChatState.provider`). Always write "agent provider" in prose. | The **custom agent** (`Message.agent`, `AgentSelection`): a configured persona within an agent provider. The **model vendor** (`SessionModelInfo.vendor`): the company that serves a model. The **model source** (`modelSourceId`): where a model comes from. | | **model** | A model offered by an agent provider (`SessionModelInfo`). It is selected per message (`Message.model`). | | | **model source** (`ModelSource`, `modelSourceId`) | A source of model access, such as a service, subscription, or endpoint, listed in `RootState.modelSources` with the agent provider it serves. Each model names its source in `SessionModelInfo.modelSourceId`. | The **agent provider**. Never write "model provider". | -| **registered model source** | A model source a client added with `root/modelSourceSet`, or the host added from its own configuration, with a `format`, `definition`, and `nonce`, and a host-reported status. Also called a registration. | An agent's **built-in** sources, which the host lists without a definition. | +| **registered model source** | A model source a client registered with `root/modelSourceRegisterRequested`, or the host registered from its own configuration. Its `registration` carries the `format` and `definition` the agent reads. Also called a registration. | An agent's **built-in** sources, which the host lists without a `registration`. | | **contributing client** | A client that added a client-contributed entry. For a model source, it's a client that registered it and hasn't left; the host tracks these itself, from `ActionEnvelope.origin`, and they aren't in state. | The **action origin**'s `clientId`, which names the client that dispatched one action. | | **principal** | The user or account a host has verified a client acts for. AHP doesn't define how a host verifies one. A host MAY restrict model sources by principal. | A **client** (`clientId`), which identifies a connection's client and isn't verified. | | **customization** | The umbrella term for session extensions. **Containers** are plugins and directories. **Children** are agents, skills, prompts, rules, hooks, and MCP servers. An MCP server can also be top-level. | Don't use "plugin" for every customization. | diff --git a/types/action-origin.generated.ts b/types/action-origin.generated.ts index d15ffc1d7..e738cf2e6 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -7,9 +7,9 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, + RootModelSourceRegisterRequestedAction, RootModelSourceSetAction, RootModelSourceRemovedAction, - RootModelSourceStateChangedAction, SessionReadyAction, SessionCreationFailedAction, SessionChatAddedAction, @@ -130,15 +130,15 @@ export type RootAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction + | RootModelSourceRegisterRequestedAction | RootModelSourceSetAction | RootModelSourceRemovedAction - | RootModelSourceStateChangedAction ; /** Union of root actions that clients may dispatch. */ export type ClientRootAction = | RootConfigChangedAction - | RootModelSourceSetAction + | RootModelSourceRegisterRequestedAction | RootModelSourceRemovedAction ; @@ -147,7 +147,7 @@ export type ServerRootAction = | RootAgentsChangedAction | RootActiveSessionsChangedAction | RootTerminalsChangedAction - | RootModelSourceStateChangedAction + | RootModelSourceSetAction ; /** Union of all session-scoped actions. */ @@ -500,9 +500,9 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.RootActiveSessionsChanged]: false, [ActionType.RootTerminalsChanged]: false, [ActionType.RootConfigChanged]: true, - [ActionType.RootModelSourceSet]: true, + [ActionType.RootModelSourceRegisterRequested]: true, + [ActionType.RootModelSourceSet]: false, [ActionType.RootModelSourceRemoved]: true, - [ActionType.RootModelSourceStateChanged]: false, [ActionType.SessionReady]: false, [ActionType.SessionCreationFailed]: false, [ActionType.SessionChatAdded]: false, diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 613179520..8c6864c98 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -4,9 +4,9 @@ * @module channels-root/actions */ -import type { AgentInfo, ModelSource, ModelSourceState } from './state.js'; +import type { AgentInfo, ModelSource, ModelSourceRegistration } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; -import type { ProtectedResourceMetadata } from '../common/state.js'; +import type { Icon } from '../common/state.js'; import { ActionType } from '../common/actions.js'; // ─── Root Actions ──────────────────────────────────────────────────────────── @@ -69,28 +69,49 @@ export interface RootConfigChangedAction { } /** - * Adds a model source, or updates the one with the same `id`: - * - * - **Add.** When no model source has the `id`, appends `modelSource`. - * - **Re-register.** When one has, with the same `provider`, `format`, and - * `nonce`, keeps its host-reported fields (`state`, `credentialResource`, - * and `accountId`) and takes everything else from the action. - * - **Update.** When any of the three differs, replaces the source. Its - * host-reported fields are absent until the host reports again with - * {@link RootModelSourceStateChangedAction}. - * - * A client registers a source with its `format`, `definition`, and `nonce`, - * and without any host-reported field. The host learns which client - * registered it from the envelope's `origin`. + * Asks the host to register a model source, or to update the one with the + * same `modelSourceId`. The reducer leaves state unchanged. The host counts + * the dispatching client as a contributing client, validates the + * registration, and publishes the result with + * {@link RootModelSourceSetAction | `root/modelSourceSet`}. It keeps the + * source's status and credential when the registration is unchanged. * * @category Root Actions * @stability 1.0 * @clientDispatchable * @see {@link /guide/model-sources#registering-a-source | Model Sources guide} */ +export interface RootModelSourceRegisterRequestedAction { + type: ActionType.RootModelSourceRegisterRequested; + /** The model source's `id`, chosen by the client. */ + modelSourceId: string; + /** Agent provider whose agent serves the source's models. */ + provider: string; + /** Human-readable name. */ + displayName: string; + /** Icons for UI display. */ + icons?: Icon[]; + /** The source's format, definition, and retention. */ + registration: ModelSourceRegistration; + /** + * Additional implementation-defined metadata for this model source. + * MUST NOT contain a credential. + */ + _meta?: Record; +} + +/** + * Adds a model source, or replaces the one with the same `id`. Only the host + * dispatches it, to publish a registration, a source an agent provides + * itself, or a change in a source's status. + * + * @category Root Actions + * @stability 1.0 + * @see {@link /guide/model-sources#status | Model Sources guide} + */ export interface RootModelSourceSetAction { type: ActionType.RootModelSourceSet; - /** The model source to add or update, matched by `id`. */ + /** The model source to add or replace, matched by `id`. */ modelSource: ModelSource; } @@ -108,28 +129,3 @@ export interface RootModelSourceRemovedAction { /** The model source's `id`. */ modelSourceId: string; } - -/** - * Updates a model source's host-reported fields together: `state`, - * `credentialResource`, and `accountId`. A no-op when no model source has - * `modelSourceId`. Other fields of the source are preserved. Only the host - * dispatches it. - * - * @category Root Actions - * @stability 1.0 - * @see {@link /guide/model-sources#status | Model Sources guide} - */ -export interface RootModelSourceStateChangedAction { - type: ActionType.RootModelSourceStateChanged; - /** The model source's `id`. */ - modelSourceId: string; - /** The new status. */ - state: ModelSourceState; - /** - * Replaces the source's `credentialResource`. Absent clears it, for a - * source that needs no credential. - */ - credentialResource?: ProtectedResourceMetadata; - /** Replaces the source's `accountId`. Absent clears it. */ - accountId?: string; -} diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index cbcf4cac3..d239502a6 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -5,7 +5,7 @@ */ import { ActionType } from '../common/actions.js'; -import type { ModelSource, RootState } from './state.js'; +import type { RootState } from './state.js'; import type { RootAction } from '../action-origin.generated.js'; import { softAssertNever } from '../common/reducer-helpers.js'; @@ -35,17 +35,17 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st }, }; + case ActionType.RootModelSourceRegisterRequested: + return state; + case ActionType.RootModelSourceSet: { const list = state.modelSources ?? []; const idx = list.findIndex(source => source.id === action.modelSource.id); - const existing = idx < 0 ? undefined : list[idx]; - const updated: ModelSource = { ...action.modelSource }; - copyHostReported(updated, existing && sameVersion(existing, updated) ? existing : {}); const next = list.slice(); if (idx < 0) { - next.push(updated); + next.push(action.modelSource); } else { - next[idx] = updated; + next[idx] = action.modelSource; } return { ...state, modelSources: next }; } @@ -64,46 +64,8 @@ export function rootReducer(state: RootState, action: RootAction, log?: (msg: st return { ...state, modelSources: next }; } - case ActionType.RootModelSourceStateChanged: { - const list = state.modelSources; - if (!list) { - return state; - } - const idx = list.findIndex(source => source.id === action.modelSourceId); - if (idx < 0) { - return state; - } - const updated = { ...list[idx] }; - copyHostReported(updated, action); - const next = list.slice(); - next[idx] = updated; - return { ...state, modelSources: next }; - } - default: softAssertNever(action, log); return state; } } - -// ─── Model source registry helpers ─────────────────────────────────────────── - -const HOST_REPORTED_FIELDS = ['state', 'credentialResource', 'accountId'] as const; - -type HostReportedFields = Partial>; - -/** Copies each host-reported field from `from` onto `to`, removing the ones `from` lacks. */ -function copyHostReported(to: ModelSource, from: HostReportedFields): void { - for (const field of HOST_REPORTED_FIELDS) { - if (from[field] === undefined) { - delete to[field]; - } else { - Object.assign(to, { [field]: from[field] }); - } - } -} - -/** Whether two model sources have the same `provider`, `format`, and definition `nonce`. */ -function sameVersion(a: ModelSource, b: ModelSource): boolean { - return a.provider === b.provider && a.format === b.format && a.nonce === b.nonce; -} diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index cf1eb598c..6420bd925 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -312,7 +312,7 @@ export interface ModelSourceRegistrationCapability { * @stability 1.0 */ export interface ModelSourceFormatInfo { - /** A {@link ModelSource.format} value. */ + /** A {@link ModelSourceRegistration.format} value. */ format: string; } @@ -338,52 +338,16 @@ export interface ModelSource { /** Icons for UI display. */ icons?: Icon[]; /** - * The format of `definition`: the `format` of one of the agent's - * {@link ModelSourceRegistrationCapability.formats}. Present on a - * registered source. - * - * Agents choose the formats they read. Some may read these common names: - * - * - `'openaiCompatible'`: an endpoint that implements OpenAI's API. - * - `'anthropic'`: an endpoint that implements Anthropic's Messages API. - * - `'azureOpenai'`: an Azure OpenAI deployment. - * - `'gemini'`: Google's Gemini API. - * - * Other formats are named with a namespace, such as - * `example.com/model-source@1`, so they don't collide. - */ - format?: string; - /** - * How to reach the source, in `format`: endpoint, wire API, models, and so - * on. The agent reads it. Every client can read it, so it MUST NOT contain - * a credential. Present on a registered source. - * - * An agent that reads one of the common format names might expect a shape - * like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is - * the API's base URI and each `models` entry is `{ id, name?, - * maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, - * named as in {@link SessionModelInfo}. + * How the source was registered. Absent on a source the agent provides + * itself. */ - definition?: Record; - /** - * Opaque version token for `definition`, such as a hash of it, chosen by - * whoever registers the source. Present on a registered source. Reducers - * compare it, instead of the definition, to tell an update from a - * re-registration of the same definition. - */ - nonce?: string; - /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ - retention?: ModelSourceRetentionPolicy; - /** - * Host-reported status, set with {@link RootModelSourceStateChangedAction}. - * Absent until the host reports one, and after an update replaces the - * definition until the host reports again. - */ - state?: ModelSourceState; + registration?: ModelSourceRegistration; + /** The source's status. */ + state: ModelSourceState; /** * RFC 9728 metadata for the endpoint a registered source's credential is * for. Present whenever the source takes a credential, in every state, so - * any client can deliver or rotate one. Set with `state`. + * any client can deliver or rotate one. * * `credentialResource.resource` is the endpoint URL as the definition * names it, in any scheme the agent supports (for example @@ -395,7 +359,7 @@ export interface ModelSource { credentialResource?: ProtectedResourceMetadata; /** * The {@link AuthenticateParams.accountId} sent with the credential the - * host most recently accepted. Set with `state`. + * host most recently accepted. * * @see {@link /specification/authentication#model-source-credentials | Model source credentials} */ @@ -407,6 +371,46 @@ export interface ModelSource { _meta?: Record; } +/** + * How a client, or the host from its own configuration, registered a model + * source. + * + * @category Root State + * @stability 1.0 + * @see {@link /guide/model-sources#registering-a-source | Model Sources guide} + */ +export interface ModelSourceRegistration { + /** + * The format of `definition`: the `format` of one of the agent's + * {@link ModelSourceRegistrationCapability.formats}. + * + * Agents choose the formats they read. Some may read these common names: + * + * - `'openaiCompatible'`: an endpoint that implements OpenAI's API. + * - `'anthropic'`: an endpoint that implements Anthropic's Messages API. + * - `'azureOpenai'`: an Azure OpenAI deployment. + * - `'gemini'`: Google's Gemini API. + * + * Other formats are named with a namespace, such as + * `example.com/model-source@1`, so they don't collide. + */ + format: string; + /** + * How to reach the source, in `format`: endpoint, wire API, models, and so + * on. The agent reads it. Every client can read it, so it MUST NOT contain + * a credential. + * + * An agent that reads one of the common format names might expect a shape + * like `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is + * the API's base URI and each `models` entry is `{ id, name?, + * maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, + * named as in {@link SessionModelInfo}. + */ + definition: Record; + /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ + retention?: ModelSourceRetentionPolicy; +} + /** * How long a registered model source lasts once its last contributing client * leaves. diff --git a/types/common/actions.ts b/types/common/actions.ts index 96eb2ff2b..8afc40304 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -13,9 +13,9 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, + RootModelSourceRegisterRequestedAction, RootModelSourceSetAction, RootModelSourceRemovedAction, - RootModelSourceStateChangedAction, } from '../channels-root/actions.js'; import type { @@ -250,9 +250,9 @@ export const enum ActionType { AnnotationsEntryRemoved = 'annotations/entryRemoved', RootTerminalsChanged = 'root/terminalsChanged', RootConfigChanged = 'root/configChanged', + RootModelSourceRegisterRequested = 'root/modelSourceRegisterRequested', RootModelSourceSet = 'root/modelSourceSet', RootModelSourceRemoved = 'root/modelSourceRemoved', - RootModelSourceStateChanged = 'root/modelSourceStateChanged', TerminalData = 'terminal/data', TerminalInput = 'terminal/input', TerminalResized = 'terminal/resized', @@ -317,9 +317,9 @@ export type StateAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction + | RootModelSourceRegisterRequestedAction | RootModelSourceSetAction | RootModelSourceRemovedAction - | RootModelSourceStateChangedAction | SessionReadyAction | SessionCreationFailedAction | SessionChatAddedAction diff --git a/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json index 905293a14..5eed7f2a6 100644 --- a/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json +++ b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceSet adds a model source, including its definition, to an absent registry", + "description": "root/modelSourceSet adds a model source to an absent registry", "reducer": "root", "initial": { "agents": [] @@ -11,16 +11,20 @@ "id": "model-source-a", "provider": "copilot", "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } }, - "nonce": "definition-a-v1" + "state": { + "kind": "starting" + } } } ], @@ -31,16 +35,20 @@ "id": "model-source-a", "provider": "copilot", "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } }, - "nonce": "definition-a-v1" + "state": { + "kind": "starting" + } } ] } diff --git a/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json b/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json deleted file mode 100644 index 2cda1cb20..000000000 --- a/types/test-cases/reducers/331-root-modelsourceset-re-register-keeps-host-reported-fields.json +++ /dev/null @@ -1,128 +0,0 @@ -{ - "description": "root/modelSourceSet with the same provider, format, and nonce re-registers: it keeps every host-reported field (state, credentialResource, and accountId) and takes everything else from the action, including displayName, icons, retention, and _meta", - "reducer": "root", - "initial": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1", - "state": { - "kind": "ready" - }, - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "accountId": "account-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] - }, - "nonce": "definition-b-v1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceSet", - "modelSource": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a (renamed)", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1", - "icons": [ - { - "src": "https://apia.example.com/icon.png" - } - ], - "retention": "host", - "_meta": { - "example.com/window": "2" - } - } - } - ], - "expected": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a (renamed)", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1", - "icons": [ - { - "src": "https://apia.example.com/icon.png" - } - ], - "retention": "host", - "_meta": { - "example.com/window": "2" - }, - "state": { - "kind": "ready" - }, - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "accountId": "account-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] - }, - "nonce": "definition-b-v1" - } - ] - } -} diff --git a/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json b/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json new file mode 100644 index 000000000..a7f202c3f --- /dev/null +++ b/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json @@ -0,0 +1,121 @@ +{ + "description": "root/modelSourceSet replaces the model source with the same id as given, dropping fields the new source doesn't have, and keeps the registry order", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "accountId": "account-a-1" + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + } + }, + "state": { + "kind": "starting" + } + } + ] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v2", + "models": [ + { + "id": "model-a" + } + ] + }, + "retention": "host" + }, + "state": { + "kind": "starting" + } + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v2", + "models": [ + { + "id": "model-a" + } + ] + }, + "retention": "host" + }, + "state": { + "kind": "starting" + } + }, + { + "id": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + } + }, + "state": { + "kind": "starting" + } + } + ] + } +} diff --git a/types/test-cases/reducers/332-root-modelsourceregisterrequested-is-no-op.json b/types/test-cases/reducers/332-root-modelsourceregisterrequested-is-no-op.json new file mode 100644 index 000000000..60bc2eacc --- /dev/null +++ b/types/test-cases/reducers/332-root-modelsourceregisterrequested-is-no-op.json @@ -0,0 +1,81 @@ +{ + "description": "root/modelSourceRegisterRequested leaves state unchanged; the host publishes the result with root/modelSourceSet", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "accountId": "account-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceRegisterRequested", + "modelSourceId": "model-source-b", + "provider": "copilot", + "displayName": "Source b", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + } + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "accountId": "account-a-1" + } + ] + } +} diff --git a/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json b/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json deleted file mode 100644 index d04ebc6ee..000000000 --- a/types/test-cases/reducers/332-root-modelsourceset-update-clears-host-reported-fields.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "description": "root/modelSourceSet with a different nonce updates the model source: it replaces the source, including its definition, and clears the host-reported fields until the host reports again", - "reducer": "root", - "initial": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1", - "state": { - "kind": "ready" - }, - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "accountId": "account-a-1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] - }, - "nonce": "definition-b-v1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceSet", - "modelSource": { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v2", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v2" - } - } - ], - "expected": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v2", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v2" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] - }, - "nonce": "definition-b-v1" - } - ] - } -} diff --git a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json index 0451245c5..84bb8e4ee 100644 --- a/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json +++ b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceRemoved removes the model source with the given id", + "description": "root/modelSourceRemoved removes the model source with the given modelSourceId", "reducer": "root", "initial": { "agents": [], @@ -8,16 +8,17 @@ "id": "model-source-a", "provider": "copilot", "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } }, - "nonce": "definition-a-v1", "state": { "kind": "ready" }, @@ -31,16 +32,20 @@ "id": "model-source-b", "provider": "copilot", "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + } }, - "nonce": "definition-b-v1" + "state": { + "kind": "starting" + } } ] }, @@ -57,16 +62,20 @@ "id": "model-source-b", "provider": "copilot", "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apib.example.com/v1", + "models": [ + { + "id": "model-b" + } + ] + } }, - "nonce": "definition-b-v1" + "state": { + "kind": "starting" + } } ] } diff --git a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json index 74edce9c2..677f224bf 100644 --- a/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json +++ b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json @@ -1,5 +1,5 @@ { - "description": "root/modelSourceRemoved is a no-op when no model source has the id", + "description": "root/modelSourceRemoved is a no-op when no model source has the modelSourceId", "reducer": "root", "initial": { "agents": [], @@ -8,16 +8,25 @@ "id": "model-source-a", "provider": "copilot", "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } }, - "nonce": "definition-a-v1" + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "accountId": "account-a-1" } ] }, @@ -34,16 +43,25 @@ "id": "model-source-a", "provider": "copilot", "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" }, - "nonce": "definition-a-v1" + "accountId": "account-a-1" } ] } diff --git a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json b/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json deleted file mode 100644 index db6a52dd1..000000000 --- a/types/test-cases/reducers/336-root-modelsourcestatechanged-updates-host-reported-fields.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "description": "root/modelSourceStateChanged sets the matching model source's state, credentialResource, and accountId together, adding credential fields it didn't have, and preserves its other fields and the registry order", - "reducer": "root", - "initial": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] - }, - "nonce": "definition-b-v1", - "retention": "host", - "state": { - "kind": "starting" - } - } - ] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "modelSourceId": "model-source-b", - "state": { - "kind": "authRequired", - "reason": "rejected", - "description": "The endpoint rejected the API key." - }, - "credentialResource": { - "resource": "https://apib.example.com/v1", - "resource_name": "Source b API key" - }, - "accountId": "account-b-1" - } - ], - "expected": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1" - }, - { - "id": "model-source-b", - "provider": "copilot", - "displayName": "Source b", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apib.example.com/v1", - "models": [ - { - "id": "model-b" - } - ] - }, - "nonce": "definition-b-v1", - "retention": "host", - "state": { - "kind": "authRequired", - "reason": "rejected", - "description": "The endpoint rejected the API key." - }, - "credentialResource": { - "resource": "https://apib.example.com/v1", - "resource_name": "Source b API key" - }, - "accountId": "account-b-1" - } - ] - } -} diff --git a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json b/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json deleted file mode 100644 index 0f27b7b0b..000000000 --- a/types/test-cases/reducers/337-root-modelsourcestatechanged-clears-credential-fields.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "description": "root/modelSourceStateChanged without credentialResource or accountId clears the model source's existing ones, for a source that turns out to need no credential", - "reducer": "root", - "initial": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1", - "state": { - "kind": "starting" - }, - "credentialResource": { - "resource": "https://apia.example.com/v1", - "resource_name": "Source a API key" - }, - "accountId": "account-a-1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "modelSourceId": "model-source-a", - "state": { - "kind": "ready" - } - } - ], - "expected": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1", - "state": { - "kind": "ready" - } - } - ] - } -} diff --git a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json b/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json deleted file mode 100644 index 6df8f578c..000000000 --- a/types/test-cases/reducers/338-root-modelsourcestatechanged-no-op-for-unknown-id.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "description": "root/modelSourceStateChanged is a no-op when no model source has the id, so a late status report can't bring back a removed source", - "reducer": "root", - "initial": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1" - } - ] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "modelSourceId": "model-source-removed", - "state": { - "kind": "ready" - } - } - ], - "expected": { - "agents": [], - "modelSources": [ - { - "id": "model-source-a", - "provider": "copilot", - "displayName": "Source a", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://apia.example.com/v1", - "models": [ - { - "id": "model-a" - } - ] - }, - "nonce": "definition-a-v1" - } - ] - } -} diff --git a/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json b/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json deleted file mode 100644 index 11c86ccbb..000000000 --- a/types/test-cases/reducers/339-root-modelsourcestatechanged-no-op-when-registry-absent.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "description": "root/modelSourceStateChanged is a no-op when the registry is absent", - "reducer": "root", - "initial": { - "agents": [] - }, - "actions": [ - { - "type": "root/modelSourceStateChanged", - "modelSourceId": "model-source-a", - "state": { - "kind": "starting" - } - } - ], - "expected": { - "agents": [] - } -} diff --git a/types/test-cases/reducers/340-root-modelsourceset-adds-built-in-source.json b/types/test-cases/reducers/340-root-modelsourceset-adds-built-in-source.json new file mode 100644 index 000000000..3a110faa7 --- /dev/null +++ b/types/test-cases/reducers/340-root-modelsourceset-adds-built-in-source.json @@ -0,0 +1,83 @@ +{ + "description": "root/modelSourceSet appends a source the agent provides itself, with no registration, to an existing registry", + "reducer": "root", + "initial": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "accountId": "account-a-1" + } + ] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "source-builtin", + "provider": "copilot", + "displayName": "Example subscription", + "state": { + "kind": "ready" + } + } + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "id": "model-source-a", + "provider": "copilot", + "displayName": "Source a", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://apia.example.com/v1", + "models": [ + { + "id": "model-a" + } + ] + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://apia.example.com/v1", + "resource_name": "Source a API key" + }, + "accountId": "account-a-1" + }, + { + "id": "source-builtin", + "provider": "copilot", + "displayName": "Example subscription", + "state": { + "kind": "ready" + } + } + ] + } +} diff --git a/types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json b/types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json deleted file mode 100644 index 2ec6d00d5..000000000 --- a/types/test-cases/reducers/340-root-modelsourceset-built-in-source-re-registers.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "description": "root/modelSourceSet for a built-in source with no format, definition, or nonce re-registers it when provider matches and format and nonce are both absent, keeping its host-reported state", - "reducer": "root", - "initial": { - "agents": [], - "modelSources": [ - { - "id": "source-builtin", - "provider": "copilot", - "displayName": "Example subscription", - "state": { - "kind": "ready" - } - } - ] - }, - "actions": [ - { - "type": "root/modelSourceSet", - "modelSource": { - "id": "source-builtin", - "provider": "copilot", - "displayName": "Example subscription (renamed)" - } - } - ], - "expected": { - "agents": [], - "modelSources": [ - { - "id": "source-builtin", - "provider": "copilot", - "displayName": "Example subscription (renamed)", - "state": { - "kind": "ready" - } - } - ] - } -} diff --git a/types/test-cases/round-trips/101-model-source-catalog.json b/types/test-cases/round-trips/101-model-source-catalog.json index 880382389..f4b42d750 100644 --- a/types/test-cases/round-trips/101-model-source-catalog.json +++ b/types/test-cases/round-trips/101-model-source-catalog.json @@ -49,17 +49,26 @@ { "id": "source-a", "provider": "example", - "displayName": "Service A" + "displayName": "Service A", + "state": { + "kind": "ready" + } }, { "id": "source-b", "provider": "example", - "displayName": "Service B" + "displayName": "Service B", + "state": { + "kind": "ready" + } }, { "id": "source-c", "provider": "example", - "displayName": "Service C" + "displayName": "Service C", + "state": { + "kind": "ready" + } } ] } @@ -113,17 +122,26 @@ { "id": "source-a", "provider": "example", - "displayName": "Service A" + "displayName": "Service A", + "state": { + "kind": "ready" + } }, { "id": "source-b", "provider": "example", - "displayName": "Service B" + "displayName": "Service B", + "state": { + "kind": "ready" + } }, { "id": "source-c", "provider": "example", - "displayName": "Service C" + "displayName": "Service C", + "state": { + "kind": "ready" + } } ] } diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index f998bb562..1c0afb6ce 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot lists an agent's built-in model source, with no format, definition, or nonce, alongside registered model sources with no reported state and in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each registered source carries its definition, including members an agent defines itself, and a nonce for it. Sources that take a credential carry a host-reported credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects, and its catalog lists the built-in source's model, the ready source's, and the authRequired one's whose key expired, since models stay listed after a source has been ready.", + "description": "A root snapshot lists an agent's built-in model source, with no registration, alongside registered model sources in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each registered source carries its format and definition, including members an agent defines itself, in its registration. Sources that take a credential carry credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects, and its catalog lists the built-in source's model, the ready source's, and the authRequired one's whose key expired, since models stay listed after a source has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -61,32 +61,26 @@ { "id": "source-builtin", "provider": "example", - "displayName": "Example subscription" - }, - { - "id": "source-unreported", - "provider": "example", - "displayName": "Unreported", - "format": "anthropic", - "definition": { - "endpoint": "https://api.anthropic.example.com/v1" - }, - "nonce": "sha256-unreported-1" + "displayName": "Example subscription", + "state": { + "kind": "ready" + } }, { "id": "source-starting", "provider": "example", "displayName": "Starting", - "format": "gemini", - "definition": { - "endpoint": "https://gemini.example.com/v1beta", - "models": [ - { - "id": "gemini-model" - } - ] + "registration": { + "format": "gemini", + "definition": { + "endpoint": "https://gemini.example.com/v1beta", + "models": [ + { + "id": "gemini-model" + } + ] + } }, - "nonce": "sha256-starting-1", "state": { "kind": "starting" } @@ -95,29 +89,30 @@ "id": "source-ready", "provider": "example", "displayName": "OpenRouter", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://api.example.com/v1", - "wireApi": "chatCompletions", - "models": [ - { - "id": "vendor/model-a", - "name": "Example model", - "maxContextWindow": 128000, - "maxOutputTokens": 16384, - "supportsVision": true, - "supportsTools": true - } - ], - "fileEndpoint": "https://files.example.com/v1" - }, - "nonce": "sha256-ready-1", "icons": [ { "src": "https://example.com/openrouter.svg" } ], - "retention": "host", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "wireApi": "chatCompletions", + "models": [ + { + "id": "vendor/model-a", + "name": "Example model", + "maxContextWindow": 128000, + "maxOutputTokens": 16384, + "supportsVision": true, + "supportsTools": true + } + ], + "fileEndpoint": "https://files.example.com/v1" + }, + "retention": "host" + }, "state": { "kind": "ready" }, @@ -134,18 +129,19 @@ "id": "source-auth", "provider": "example", "displayName": "Azure endpoint", - "format": "azureOpenai", - "definition": { - "endpoint": "https://example.openai.azure.com/openai/v1", - "apiVersion": "2024-10-21", - "models": [ - { - "id": "example-deployment" - } - ] + "registration": { + "format": "azureOpenai", + "definition": { + "endpoint": "https://example.openai.azure.com/openai/v1", + "apiVersion": "2024-10-21", + "models": [ + { + "id": "example-deployment" + } + ] + }, + "retention": "contributingClient" }, - "nonce": "sha256-auth-1", - "retention": "contributingClient", "state": { "kind": "authRequired", "reason": "expired", @@ -167,12 +163,13 @@ "id": "source-local", "provider": "example", "displayName": "Local server", - "format": "openaiCompatible", - "definition": { - "endpoint": "http://localhost:11434/v1", - "wireApi": "responses" + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "http://localhost:11434/v1", + "wireApi": "responses" + } }, - "nonce": "sha256-local-1", "state": { "kind": "authRequired", "reason": "required" @@ -186,22 +183,23 @@ "id": "source-rejected", "provider": "example", "displayName": "Rejected key", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://api.example.com/v1", - "models": [ - { - "id": "vendor/model-a" - } - ] - }, - "nonce": "sha256-rejected-1", "icons": [ { "src": "https://example.com/openrouter.svg" } ], - "retention": "host", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, + "retention": "host" + }, "state": { "kind": "authRequired", "reason": "rejected", @@ -217,22 +215,23 @@ "id": "source-revoked", "provider": "example", "displayName": "Revoked key", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://api.example.com/v1", - "models": [ - { - "id": "vendor/model-a" - } - ] - }, - "nonce": "sha256-revoked-1", "icons": [ { "src": "https://example.com/openrouter.svg" } ], - "retention": "host", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, + "retention": "host" + }, "state": { "kind": "authRequired", "reason": "revoked" @@ -247,14 +246,15 @@ "id": "source-host", "provider": "example", "displayName": "Host-configured", - "format": "example.com/model-source@1", - "definition": { - "endpoint": "https://models.internal.example.com", - "routing": { - "region": "example-1" + "registration": { + "format": "example.com/model-source@1", + "definition": { + "endpoint": "https://models.internal.example.com", + "routing": { + "region": "example-1" + } } }, - "nonce": "sha256-host-1", "state": { "kind": "error", "error": { @@ -325,32 +325,26 @@ { "id": "source-builtin", "provider": "example", - "displayName": "Example subscription" - }, - { - "id": "source-unreported", - "provider": "example", - "displayName": "Unreported", - "format": "anthropic", - "definition": { - "endpoint": "https://api.anthropic.example.com/v1" - }, - "nonce": "sha256-unreported-1" + "displayName": "Example subscription", + "state": { + "kind": "ready" + } }, { "id": "source-starting", "provider": "example", "displayName": "Starting", - "format": "gemini", - "definition": { - "endpoint": "https://gemini.example.com/v1beta", - "models": [ - { - "id": "gemini-model" - } - ] + "registration": { + "format": "gemini", + "definition": { + "endpoint": "https://gemini.example.com/v1beta", + "models": [ + { + "id": "gemini-model" + } + ] + } }, - "nonce": "sha256-starting-1", "state": { "kind": "starting" } @@ -359,29 +353,30 @@ "id": "source-ready", "provider": "example", "displayName": "OpenRouter", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://api.example.com/v1", - "wireApi": "chatCompletions", - "models": [ - { - "id": "vendor/model-a", - "name": "Example model", - "maxContextWindow": 128000, - "maxOutputTokens": 16384, - "supportsVision": true, - "supportsTools": true - } - ], - "fileEndpoint": "https://files.example.com/v1" - }, - "nonce": "sha256-ready-1", "icons": [ { "src": "https://example.com/openrouter.svg" } ], - "retention": "host", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "wireApi": "chatCompletions", + "models": [ + { + "id": "vendor/model-a", + "name": "Example model", + "maxContextWindow": 128000, + "maxOutputTokens": 16384, + "supportsVision": true, + "supportsTools": true + } + ], + "fileEndpoint": "https://files.example.com/v1" + }, + "retention": "host" + }, "state": { "kind": "ready" }, @@ -398,18 +393,19 @@ "id": "source-auth", "provider": "example", "displayName": "Azure endpoint", - "format": "azureOpenai", - "definition": { - "endpoint": "https://example.openai.azure.com/openai/v1", - "apiVersion": "2024-10-21", - "models": [ - { - "id": "example-deployment" - } - ] + "registration": { + "format": "azureOpenai", + "definition": { + "endpoint": "https://example.openai.azure.com/openai/v1", + "apiVersion": "2024-10-21", + "models": [ + { + "id": "example-deployment" + } + ] + }, + "retention": "contributingClient" }, - "nonce": "sha256-auth-1", - "retention": "contributingClient", "state": { "kind": "authRequired", "reason": "expired", @@ -431,12 +427,13 @@ "id": "source-local", "provider": "example", "displayName": "Local server", - "format": "openaiCompatible", - "definition": { - "endpoint": "http://localhost:11434/v1", - "wireApi": "responses" + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "http://localhost:11434/v1", + "wireApi": "responses" + } }, - "nonce": "sha256-local-1", "state": { "kind": "authRequired", "reason": "required" @@ -450,22 +447,23 @@ "id": "source-rejected", "provider": "example", "displayName": "Rejected key", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://api.example.com/v1", - "models": [ - { - "id": "vendor/model-a" - } - ] - }, - "nonce": "sha256-rejected-1", "icons": [ { "src": "https://example.com/openrouter.svg" } ], - "retention": "host", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, + "retention": "host" + }, "state": { "kind": "authRequired", "reason": "rejected", @@ -481,22 +479,23 @@ "id": "source-revoked", "provider": "example", "displayName": "Revoked key", - "format": "openaiCompatible", - "definition": { - "endpoint": "https://api.example.com/v1", - "models": [ - { - "id": "vendor/model-a" - } - ] - }, - "nonce": "sha256-revoked-1", "icons": [ { "src": "https://example.com/openrouter.svg" } ], - "retention": "host", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, + "retention": "host" + }, "state": { "kind": "authRequired", "reason": "revoked" @@ -511,14 +510,15 @@ "id": "source-host", "provider": "example", "displayName": "Host-configured", - "format": "example.com/model-source@1", - "definition": { - "endpoint": "https://models.internal.example.com", - "routing": { - "region": "example-1" + "registration": { + "format": "example.com/model-source@1", + "definition": { + "endpoint": "https://models.internal.example.com", + "routing": { + "region": "example-1" + } } }, - "nonce": "sha256-host-1", "state": { "kind": "error", "error": { diff --git a/types/test-cases/round-trips/104-root-model-source-set.json b/types/test-cases/round-trips/104-root-model-source-register-requested.json similarity index 67% rename from types/test-cases/round-trips/104-root-model-source-set.json rename to types/test-cases/round-trips/104-root-model-source-register-requested.json index 39eb820fc..218f5f841 100644 --- a/types/test-cases/round-trips/104-root-model-source-set.json +++ b/types/test-cases/round-trips/104-root-model-source-register-requested.json @@ -1,14 +1,14 @@ { - "name": "root-model-source-set", + "name": "root-model-source-register-requested", "group": "A", - "description": "A client registers a model source with root/modelSourceSet: the source with its definition, in the suggested openaiCompatible shape plus a member the agent defines, a nonce for it, requested retention, and no host-reported fields.", + "description": "A client asks the host to register a model source with root/modelSourceRegisterRequested, giving its registration: the format, a definition in a common shape plus a member the agent defines, and the requested retention.", "type": "StateAction", "input": { - "type": "root/modelSourceSet", - "modelSource": { - "id": "source-new", - "provider": "example", - "displayName": "OpenRouter", + "type": "root/modelSourceRegisterRequested", + "modelSourceId": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "registration": { "format": "openaiCompatible", "definition": { "endpoint": "https://openrouter.ai/api/v1", @@ -28,17 +28,16 @@ "x-title": "Example" } }, - "nonce": "sha256-new-1", "retention": "host" } }, "acceptableOutputs": [ { - "type": "root/modelSourceSet", - "modelSource": { - "id": "source-new", - "provider": "example", - "displayName": "OpenRouter", + "type": "root/modelSourceRegisterRequested", + "modelSourceId": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "registration": { "format": "openaiCompatible", "definition": { "endpoint": "https://openrouter.ai/api/v1", @@ -58,7 +57,6 @@ "x-title": "Example" } }, - "nonce": "sha256-new-1", "retention": "host" } } diff --git a/types/test-cases/round-trips/107-root-model-source-set.json b/types/test-cases/round-trips/107-root-model-source-set.json new file mode 100644 index 000000000..778a97a3d --- /dev/null +++ b/types/test-cases/round-trips/107-root-model-source-set.json @@ -0,0 +1,68 @@ +{ + "name": "root-model-source-set", + "group": "A", + "description": "The host publishes a model source with root/modelSourceSet after the endpoint rejected a key: the whole source, with its registration, an authRequired state, the credentialResource the key is for, and the rejected key's accountId.", + "type": "StateAction", + "input": { + "type": "root/modelSourceSet", + "modelSource": { + "id": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://openrouter.ai/api/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, + "retention": "host" + }, + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialResource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-openrouter-1" + } + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "id": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://openrouter.ai/api/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + }, + "retention": "host" + }, + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialResource": { + "resource": "https://openrouter.ai/api/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-openrouter-1" + } + } + ] +} diff --git a/types/test-cases/round-trips/107-root-model-source-state-changed.json b/types/test-cases/round-trips/107-root-model-source-state-changed.json deleted file mode 100644 index 9b33d6500..000000000 --- a/types/test-cases/round-trips/107-root-model-source-state-changed.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "root-model-source-state-changed", - "group": "A", - "description": "The host reports with root/modelSourceStateChanged that the endpoint rejected a key, naming the rejected key's accountId, along with the credentialResource the key is for.", - "type": "StateAction", - "input": { - "type": "root/modelSourceStateChanged", - "modelSourceId": "source-new", - "state": { - "kind": "authRequired", - "reason": "rejected", - "description": "The endpoint rejected the API key." - }, - "credentialResource": { - "resource": "https://openrouter.ai/api/v1", - "resource_name": "OpenRouter API key" - }, - "accountId": "keychain-openrouter-1" - }, - "acceptableOutputs": [ - { - "type": "root/modelSourceStateChanged", - "modelSourceId": "source-new", - "state": { - "kind": "authRequired", - "reason": "rejected", - "description": "The endpoint rejected the API key." - }, - "credentialResource": { - "resource": "https://openrouter.ai/api/v1", - "resource_name": "OpenRouter API key" - }, - "accountId": "keychain-openrouter-1" - } - ] -} diff --git a/types/version/registry.ts b/types/version/registry.ts index a8ec646dd..4e2f22117 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -187,9 +187,9 @@ export const ACTION_INTRODUCED_IN: { readonly [K in StateAction['type']]: string [ActionType.AnnotationsEntryRemoved]: '0.4.0', [ActionType.RootTerminalsChanged]: '0.1.0', [ActionType.RootConfigChanged]: '0.1.0', + [ActionType.RootModelSourceRegisterRequested]: '1.2.0', [ActionType.RootModelSourceSet]: '1.2.0', [ActionType.RootModelSourceRemoved]: '1.2.0', - [ActionType.RootModelSourceStateChanged]: '1.2.0', [ActionType.TerminalData]: '0.1.0', [ActionType.TerminalInput]: '0.1.0', [ActionType.TerminalResized]: '0.1.0', From cddbc7e760b0c4bd0c071c0b01b86b2fd8bcbfb7 Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 15:26:11 -0500 Subject: [PATCH 16/17] models: keep model source retention on the registration request only `retention` tells the host what to do when contributing clients leave, and no consumer acts on it, so move it from `ModelSourceRegistration` to `root/modelSourceRegisterRequested`. The host keeps it privately. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Generated/Actions.generated.cs | 7 ++++- .../Generated/State.generated.cs | 4 --- clients/go/ahptypes/actions.generated.go | 5 +++- clients/go/ahptypes/state.generated.go | 2 -- .../generated/Actions.generated.kt | 7 ++++- .../generated/State.generated.kt | 6 +---- clients/rust/crates/ahp-types/src/actions.rs | 16 +++++++----- clients/rust/crates/ahp-types/src/state.rs | 3 --- .../Generated/Actions.generated.swift | 8 +++++- .../Generated/State.generated.swift | 6 +---- docs/guide/model-sources.md | 5 ++-- docs/proposals/model-source-registry.md | 2 +- docs/specification/root-channel.md | 2 +- schema/actions.schema.json | 26 +++++++++---------- schema/commands.schema.json | 26 +++++++++---------- schema/errors.schema.json | 26 +++++++++---------- schema/notifications.schema.json | 12 --------- schema/state.schema.json | 12 --------- scripts/generate-rust.ts | 2 +- types/channels-root/actions.ts | 9 +++++-- types/channels-root/state.ts | 2 -- ...1-root-modelsourceset-replaces-source.json | 6 ++--- .../103-model-source-registry-snapshot.json | 26 +++++++------------ ...-root-model-source-register-requested.json | 14 +++++----- .../107-root-model-source-set.json | 6 ++--- 25 files changed, 106 insertions(+), 134 deletions(-) diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 487fb79b7..8c0fa11d7 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -404,9 +404,14 @@ public sealed record RootModelSourceRegisterRequestedAction [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List? Icons { get; init; } - /// The source's format, definition, and retention. + /// The source's format and definition. public required ModelSourceRegistration Registration { get; init; } + /// What happens to the source when the last contributing client leaves. + /// Absent means `contributingClient`. The host keeps it privately. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ModelSourceRetentionPolicy? Retention { get; init; } + /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. [JsonPropertyName("_meta")] diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs index 0c6e2f8f1..d98720548 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -2687,10 +2687,6 @@ public sealed record ModelSourceRegistration /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, /// named as in {@link SessionModelInfo}. public required Dictionary Definition { get; init; } - - /// What happens when the last contributing client leaves. Absent means `contributingClient`. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public ModelSourceRetentionPolicy? Retention { get; init; } } /// A source that an agent provider offers models from, such as a service, diff --git a/clients/go/ahptypes/actions.generated.go b/clients/go/ahptypes/actions.generated.go index d2794a6fd..b5591677a 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -222,8 +222,11 @@ type RootModelSourceRegisterRequestedAction struct { DisplayName string `json:"displayName"` // Icons for UI display. Icons []Icon `json:"icons,omitempty"` - // The source's format, definition, and retention. + // The source's format and definition. Registration ModelSourceRegistration `json:"registration"` + // What happens to the source when the last contributing client leaves. + // Absent means `contributingClient`. The host keeps it privately. + Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` // Additional implementation-defined metadata for this model source. // MUST NOT contain a credential. Meta map[string]json.RawMessage `json:"_meta,omitempty"` diff --git a/clients/go/ahptypes/state.generated.go b/clients/go/ahptypes/state.generated.go index 7fbbcbbe1..7e66b2ac1 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -1067,8 +1067,6 @@ type ModelSourceRegistration struct { // maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, // named as in {@link SessionModelInfo}. Definition map[string]json.RawMessage `json:"definition"` - // What happens when the last contributing client leaves. Absent means `contributingClient`. - Retention *ModelSourceRetentionPolicy `json:"retention,omitempty"` } // A source that an agent provider offers models from, such as a service, diff --git a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt index 6535c6d07..70ac36a6f 100644 --- a/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt +++ b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Actions.generated.kt @@ -1586,9 +1586,14 @@ data class RootModelSourceRegisterRequestedAction( */ val icons: List? = null, /** - * The source's format, definition, and retention. + * The source's format and definition. */ val registration: ModelSourceRegistration, + /** + * What happens to the source when the last contributing client leaves. + * Absent means `contributingClient`. The host keeps it privately. + */ + val retention: ModelSourceRetentionPolicy? = null, /** * Additional implementation-defined metadata for this model source. * MUST NOT contain a credential. 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 69adc363b..b115aacc3 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 @@ -2056,11 +2056,7 @@ data class ModelSourceRegistration( * maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, * named as in {@link SessionModelInfo}. */ - val definition: Map, - /** - * What happens when the last contributing client leaves. Absent means `contributingClient`. - */ - val retention: ModelSourceRetentionPolicy? = null + val definition: Map ) /** diff --git a/clients/rust/crates/ahp-types/src/actions.rs b/clients/rust/crates/ahp-types/src/actions.rs index 7a93c358e..2010741c9 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -21,11 +21,11 @@ use crate::state::{ ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, Icon, MaterializedTurn, McpAuthRequirement, McpServerState, Message, ModelSelection, ModelSource, ModelSourceRegistration, - PendingMessageKind, ResponsePart, SearchLifecycleState, SearchQuery, SearchResult, - SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, - TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, - ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, - ToolResultContent, Turn, UsageInfo, + ModelSourceRetentionPolicy, PendingMessageKind, ResponsePart, SearchLifecycleState, + SearchQuery, SearchResult, SessionActiveClient, SessionConfigSchema, SessionInputRequest, + SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, + ToolCallConfirmationReason, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, + ToolDefinition, ToolInput, ToolResultContent, Turn, UsageInfo, }; // ─── ActionType ────────────────────────────────────────────────────── @@ -576,8 +576,12 @@ pub struct RootModelSourceRegisterRequestedAction { /// Icons for UI display. #[serde(default, skip_serializing_if = "Option::is_none")] pub icons: Option>, - /// The source's format, definition, and retention. + /// The source's format and definition. pub registration: ModelSourceRegistration, + /// What happens to the source when the last contributing client leaves. + /// Absent means `contributingClient`. The host keeps it privately. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retention: Option, /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] diff --git a/clients/rust/crates/ahp-types/src/state.rs b/clients/rust/crates/ahp-types/src/state.rs index 40b1a0df8..acf7c00fe 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -2386,9 +2386,6 @@ pub struct ModelSourceRegistration { /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, /// named as in {@link SessionModelInfo}. pub definition: JsonObject, - /// What happens when the last contributing client leaves. Absent means `contributingClient`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub retention: Option, } /// A source that an agent provider offers models from, such as a service, diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift index da6ada6ca..afe51ee80 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -2394,8 +2394,11 @@ public struct RootModelSourceRegisterRequestedAction: Codable, Sendable, Equatab public var displayName: String /// Icons for UI display. public var icons: [Icon]? - /// The source's format, definition, and retention. + /// The source's format and definition. public var registration: ModelSourceRegistration + /// What happens to the source when the last contributing client leaves. + /// Absent means `contributingClient`. The host keeps it privately. + public var retention: ModelSourceRetentionPolicy? /// Additional implementation-defined metadata for this model source. /// MUST NOT contain a credential. public var meta: [String: AnyCodable]? @@ -2407,6 +2410,7 @@ public struct RootModelSourceRegisterRequestedAction: Codable, Sendable, Equatab case displayName case icons case registration + case retention case meta = "_meta" } @@ -2417,6 +2421,7 @@ public struct RootModelSourceRegisterRequestedAction: Codable, Sendable, Equatab displayName: String, icons: [Icon]? = nil, registration: ModelSourceRegistration, + retention: ModelSourceRetentionPolicy? = nil, meta: [String: AnyCodable]? = nil ) { self.type = type @@ -2425,6 +2430,7 @@ public struct RootModelSourceRegisterRequestedAction: Codable, Sendable, Equatab self.displayName = displayName self.icons = icons self.registration = registration + self.retention = retention self.meta = meta } } diff --git a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift index 09b252d41..cf5473224 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -2080,17 +2080,13 @@ public struct ModelSourceRegistration: Codable, Sendable, Equatable { /// maxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`, /// named as in {@link SessionModelInfo}. public var definition: [String: AnyCodable] - /// What happens when the last contributing client leaves. Absent means `contributingClient`. - public var retention: ModelSourceRetentionPolicy? public init( format: String, - definition: [String: AnyCodable], - retention: ModelSourceRetentionPolicy? = nil + definition: [String: AnyCodable] ) { self.format = format self.definition = definition - self.retention = retention } } diff --git a/docs/guide/model-sources.md b/docs/guide/model-sources.md index 4d07b61e3..3af9ef770 100644 --- a/docs/guide/model-sources.md +++ b/docs/guide/model-sources.md @@ -34,7 +34,6 @@ ModelSource { registration?: { // absent on built-in sources format: string definition: Record // how the agent reaches the source; never a credential - retention?: 'contributingClient' | 'host' } state: ModelSourceState // starting | ready | authRequired | error credentialResource?: ProtectedResourceMetadata @@ -48,7 +47,7 @@ An agent that serves models from client-registered sources advertises [`AgentCap Registration follows the same pattern as automations: the client asks, and the host publishes the result. -1. A client dispatches [`root/modelSourceRegisterRequested`](/reference/root#rootmodelsourceregisterrequestedaction) with the source's `modelSourceId`, `provider`, `displayName`, and a `registration` holding its `format` and a `definition` that tells the agent how to reach it. Every client can read a definition, so it MUST NOT contain a credential. The request doesn't change state. +1. A client dispatches [`root/modelSourceRegisterRequested`](/reference/root#rootmodelsourceregisterrequestedaction) with the source's `modelSourceId`, `provider`, `displayName`, a `registration` holding its `format` and a `definition` that tells the agent how to reach it, and optionally the [`retention`](#retention) it wants. Every client can read a definition, so it MUST NOT contain a credential. The request doesn't change state. 2. The host validates the request and publishes the source with [`root/modelSourceSet`](/reference/root#rootmodelsourcesetaction), which adds it or replaces the one with the same `id`. When the registration is unchanged, the host keeps the source's status and credential. When the definition changes, it drops the credential and the source goes back to `starting`. [`root/modelSourceRemoved`](/reference/root#rootmodelsourceremovedaction) removes a source for every client. The host rejects either client action when it breaks the rules in [Server Validation of Client Actions](/specification/root-channel#server-validation-of-client-actions). @@ -110,7 +109,7 @@ Clients MUST NOT cache a model source credential they delivered, or replay one, ## Retention -A registered source's `registration.retention` decides what happens when its last contributing client disconnects and doesn't return within a grace period the host chooses: +The `retention` a client requests with `root/modelSourceRegisterRequested` decides what happens when a source's last contributing client disconnects and doesn't return within a grace period the host chooses. The host keeps it privately, so it isn't in state: - `contributingClient`, the default: the host stops new work on the source, lets running turns finish, and then removes it. - `host`: the source stays until a client removes it or host policy expires it. diff --git a/docs/proposals/model-source-registry.md b/docs/proposals/model-source-registry.md index 5fd95ed03..b1c5f35cd 100644 --- a/docs/proposals/model-source-registry.md +++ b/docs/proposals/model-source-registry.md @@ -7,7 +7,7 @@ Implemented by [#627](https://github.com/microsoft/agent-host-protocol/pull/627). The type sketches below show the intended shape; the canonical definitions are in `types/` and the [Model Sources guide](/guide/model-sources). Review of #627 changed the shape in these ways: - `RootState.modelSources` lists every model source, including an agent's built-in ones, and replaces `ModelSourceInfo` and `AgentInfo.modelSources`. `state` is required. -- A registered source's `format`, `definition`, and `retention` are grouped in `ModelSource.registration`, and there's no `nonce`: the host compares definitions itself. +- A registered source's `format` and `definition` are grouped in `ModelSource.registration`, and there's no `nonce`: the host compares definitions itself. `retention` is only on the registration request, and the host keeps it privately. - Clients dispatch `root/modelSourceRegisterRequested`, which doesn't change state. The host publishes every source and status change with `root/modelSourceSet`, which replaces the entry, so there's no `root/modelSourceStateChanged`. `root/modelSourceRemoved` takes a `modelSourceId`. - Requests and turns on an unavailable source fail with `AhpErrorCodes.ModelSourceUnavailable`, which a turn carries in `ErrorInfo.errorCode`. diff --git a/docs/specification/root-channel.md b/docs/specification/root-channel.md index d61b8174b..200791682 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -112,7 +112,7 @@ When the server receives a client-dispatched action on this channel, it MUST val | --- | --- | --- | | `root/modelSourceRegisterRequested` | The agent named by `provider` doesn't advertise `modelSourceRegistration`, or doesn't list `registration.format` | Server MUST reject the action | | `root/modelSourceRegisterRequested` | The existing source with that `modelSourceId` is one the host registered itself | Server MUST reject the action | -| `root/modelSourceRegisterRequested` | The host won't honor the requested `registration.retention` | Server MUST reject the action | +| `root/modelSourceRegisterRequested` | The host won't honor the requested `retention` | Server MUST reject the action | | `root/modelSourceRemoved` | The source is one the host registered itself | Server MAY reject the action | | `root/modelSourceRegisterRequested`, `root/modelSourceRemoved` | The host restricts sources by principal, and the source belongs to another principal | Server MAY reject the action | diff --git a/schema/actions.schema.json b/schema/actions.schema.json index cb6a2aad1..b167f0db8 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -155,7 +155,11 @@ }, "registration": { "$ref": "#/$defs/ModelSourceRegistration", - "description": "The source's format, definition, and retention." + "description": "The source's format and definition." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens to the source when the last contributing client leaves.\nAbsent means `contributingClient`. The host keeps it privately." }, "_meta": { "type": "object", @@ -3734,10 +3738,6 @@ "type": "object", "additionalProperties": {}, "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." } }, "required": [ @@ -10790,6 +10790,14 @@ "type": "string", "description": "A URI string (e.g. `ahp-root://`, `ahp-session:/`, or `ahp-chat:/`)." }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its last contributing client\nleaves." + }, "SessionStatus": { "type": "integer", "minimum": 0, @@ -10873,14 +10881,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceAuthRequiredReason": { "enum": [ "required", diff --git a/schema/commands.schema.json b/schema/commands.schema.json index 3fcb85144..c66d71d20 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -3030,10 +3030,6 @@ "type": "object", "additionalProperties": {}, "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." } }, "required": [ @@ -9219,7 +9215,11 @@ }, "registration": { "$ref": "#/$defs/ModelSourceRegistration", - "description": "The source's format, definition, and retention." + "description": "The source's format and definition." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens to the source when the last contributing client leaves.\nAbsent means `contributingClient`. The host keeps it privately." }, "_meta": { "type": "object", @@ -12332,14 +12332,6 @@ ], "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceAuthRequiredReason": { "enum": [ "required", @@ -13097,6 +13089,14 @@ ], "description": "Discriminated lifecycle of a search." }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its last contributing client\nleaves." + }, "ChatToolCallConfirmedAction": { "oneOf": [ { diff --git a/schema/errors.schema.json b/schema/errors.schema.json index 52debf633..cf78814ec 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -941,10 +941,6 @@ "type": "object", "additionalProperties": {}, "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." } }, "required": [ @@ -9126,14 +9122,6 @@ ], "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceAuthRequiredReason": { "enum": [ "required", @@ -10574,7 +10562,11 @@ }, "registration": { "$ref": "#/$defs/ModelSourceRegistration", - "description": "The source's format, definition, and retention." + "description": "The source's format and definition." + }, + "retention": { + "$ref": "#/$defs/ModelSourceRetentionPolicy", + "description": "What happens to the source when the last contributing client leaves.\nAbsent means `contributingClient`. The host keeps it privately." }, "_meta": { "type": "object", @@ -12980,6 +12972,14 @@ "type" ] }, + "ModelSourceRetentionPolicy": { + "enum": [ + "contributingClient", + "host" + ], + "type": "string", + "description": "How long a registered model source lasts once its last contributing client\nleaves." + }, "ChatToolCallApprovedAction": { "type": "object", "description": "Client approves a pending tool call. The tool transitions to `running`.", diff --git a/schema/notifications.schema.json b/schema/notifications.schema.json index 08983ecff..a685e14c9 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -1242,10 +1242,6 @@ "type": "object", "additionalProperties": {}, "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." } }, "required": [ @@ -7373,14 +7369,6 @@ ], "description": "Lifecycle state of a {@link ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceAuthRequiredReason": { "enum": [ "required", diff --git a/schema/state.schema.json b/schema/state.schema.json index f96b3756d..b0370ee33 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -851,10 +851,6 @@ "type": "object", "additionalProperties": {}, "description": "How to reach the source, in `format`: endpoint, wire API, models, and so\non. The agent reads it. Every client can read it, so it MUST NOT contain\na credential.\n\nAn agent that reads one of the common format names might expect a shape\nlike `{ endpoint, wireApi?, apiVersion?, models? }`, where `endpoint` is\nthe API's base URI and each `models` entry is `{ id, name?,\nmaxContextWindow?, maxOutputTokens?, supportsVision?, supportsTools? }`,\nnamed as in {@link SessionModelInfo}." - }, - "retention": { - "$ref": "#/$defs/ModelSourceRetentionPolicy", - "description": "What happens when the last contributing client leaves. Absent means `contributingClient`." } }, "required": [ @@ -7579,14 +7575,6 @@ "type": "string", "description": "Policy configuration state for a model." }, - "ModelSourceRetentionPolicy": { - "enum": [ - "contributingClient", - "host" - ], - "type": "string", - "description": "How long a registered model source lasts once its last contributing client\nleaves." - }, "ModelSourceAuthRequiredReason": { "enum": [ "required", diff --git a/scripts/generate-rust.ts b/scripts/generate-rust.ts index 7d4e08705..adb33699a 100644 --- a/scripts/generate-rust.ts +++ b/scripts/generate-rust.ts @@ -2000,7 +2000,7 @@ impl Serialize for ChatErrorAction { function generateActionsFile(project: Project): string { const lines: string[] = [GENERATED_HEADER]; lines.push('#[allow(unused_imports)]'); - lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, MaterializedTurn, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary, SearchQuery, SearchLifecycleState, SearchResult, ModelSource, ModelSourceRegistration, Icon};'); + lines.push('use crate::state::{AgentInfo, AgentSelection, Annotation, AnnotationEntry, AnnotationOrigin, AutomationDefinition, AutomationDefinitionPatch, AutomationEntry, AutomationRunLifecycle, AutomationRunSummary, BackgroundWork, CanvasReference, CanvasState, ChangesSummary, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, ErrorResponsePart, FileEditCollection, McpAuthRequirement, McpServerState, ModelSelection, ResponsePart, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolCallConfirmationReason, ToolCallCancellationReason, ToolDefinition, ToolInput, ToolResultContent, UsageInfo, Message, PendingMessageKind, MaterializedTurn, Turn, ChangesetStatus, ChangesetFile, ChangesetOperation, ChangesetOperationStatus, Changeset, ChatSummary, SearchQuery, SearchLifecycleState, SearchResult, ModelSource, ModelSourceRegistration, ModelSourceRetentionPolicy, Icon};'); lines.push(''); // ActionType enum lines.push('// ─── ActionType ──────────────────────────────────────────────────────\n'); diff --git a/types/channels-root/actions.ts b/types/channels-root/actions.ts index 8c6864c98..26864b37a 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -4,7 +4,7 @@ * @module channels-root/actions */ -import type { AgentInfo, ModelSource, ModelSourceRegistration } from './state.js'; +import type { AgentInfo, ModelSource, ModelSourceRegistration, ModelSourceRetentionPolicy } from './state.js'; import type { TerminalInfo } from '../channels-terminal/state.js'; import type { Icon } from '../common/state.js'; import { ActionType } from '../common/actions.js'; @@ -91,8 +91,13 @@ export interface RootModelSourceRegisterRequestedAction { displayName: string; /** Icons for UI display. */ icons?: Icon[]; - /** The source's format, definition, and retention. */ + /** The source's format and definition. */ registration: ModelSourceRegistration; + /** + * What happens to the source when the last contributing client leaves. + * Absent means `contributingClient`. The host keeps it privately. + */ + retention?: ModelSourceRetentionPolicy; /** * Additional implementation-defined metadata for this model source. * MUST NOT contain a credential. diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index 6420bd925..6bee745d5 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -407,8 +407,6 @@ export interface ModelSourceRegistration { * named as in {@link SessionModelInfo}. */ definition: Record; - /** What happens when the last contributing client leaves. Absent means `contributingClient`. */ - retention?: ModelSourceRetentionPolicy; } /** diff --git a/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json b/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json index a7f202c3f..bc38ef40e 100644 --- a/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json +++ b/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json @@ -65,8 +65,7 @@ "id": "model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "starting" @@ -90,8 +89,7 @@ "id": "model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "starting" diff --git a/types/test-cases/round-trips/103-model-source-registry-snapshot.json b/types/test-cases/round-trips/103-model-source-registry-snapshot.json index 1c0afb6ce..78d395728 100644 --- a/types/test-cases/round-trips/103-model-source-registry-snapshot.json +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -1,7 +1,7 @@ { "name": "model-source-registry-snapshot", "group": "A", - "description": "A root snapshot lists an agent's built-in model source, with no registration, alongside registered model sources in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint, a host-retained source, and a host-registered source in a namespaced format. Each registered source carries its format and definition, including members an agent defines itself, in its registration. Sources that take a credential carry credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects, and its catalog lists the built-in source's model, the ready source's, and the authRequired one's whose key expired, since models stay listed after a source has been ready.", + "description": "A root snapshot lists an agent's built-in model source, with no registration, alongside registered model sources in each lifecycle state and auth reason (required, expired, rejected, and revoked), including an http endpoint and a host-registered source in a namespaced format. Each registered source carries its format and definition, including members an agent defines itself, in its registration. Sources that take a credential carry credentialResource in every state, and accountId once the host has accepted a key sent with one. The agent advertises the modelSourceRegistration capability with format objects, and its catalog lists the built-in source's model, the ready source's, and the authRequired one's whose key expired, since models stay listed after a source has been ready.", "type": "Snapshot", "input": { "resource": "ahp-root://", @@ -110,8 +110,7 @@ } ], "fileEndpoint": "https://files.example.com/v1" - }, - "retention": "host" + } }, "state": { "kind": "ready" @@ -139,8 +138,7 @@ "id": "example-deployment" } ] - }, - "retention": "contributingClient" + } }, "state": { "kind": "authRequired", @@ -197,8 +195,7 @@ "id": "vendor/model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "authRequired", @@ -229,8 +226,7 @@ "id": "vendor/model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "authRequired", @@ -374,8 +370,7 @@ } ], "fileEndpoint": "https://files.example.com/v1" - }, - "retention": "host" + } }, "state": { "kind": "ready" @@ -403,8 +398,7 @@ "id": "example-deployment" } ] - }, - "retention": "contributingClient" + } }, "state": { "kind": "authRequired", @@ -461,8 +455,7 @@ "id": "vendor/model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "authRequired", @@ -493,8 +486,7 @@ "id": "vendor/model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "authRequired", diff --git a/types/test-cases/round-trips/104-root-model-source-register-requested.json b/types/test-cases/round-trips/104-root-model-source-register-requested.json index 218f5f841..e3caf2bfc 100644 --- a/types/test-cases/round-trips/104-root-model-source-register-requested.json +++ b/types/test-cases/round-trips/104-root-model-source-register-requested.json @@ -1,7 +1,7 @@ { "name": "root-model-source-register-requested", "group": "A", - "description": "A client asks the host to register a model source with root/modelSourceRegisterRequested, giving its registration: the format, a definition in a common shape plus a member the agent defines, and the requested retention.", + "description": "A client asks the host to register a model source with root/modelSourceRegisterRequested, giving its registration (the format, and a definition in a common shape plus a member the agent defines) and the retention the host keeps privately.", "type": "StateAction", "input": { "type": "root/modelSourceRegisterRequested", @@ -27,9 +27,9 @@ "headers": { "x-title": "Example" } - }, - "retention": "host" - } + } + }, + "retention": "host" }, "acceptableOutputs": [ { @@ -56,9 +56,9 @@ "headers": { "x-title": "Example" } - }, - "retention": "host" - } + } + }, + "retention": "host" } ] } diff --git a/types/test-cases/round-trips/107-root-model-source-set.json b/types/test-cases/round-trips/107-root-model-source-set.json index 778a97a3d..507d3a56d 100644 --- a/types/test-cases/round-trips/107-root-model-source-set.json +++ b/types/test-cases/round-trips/107-root-model-source-set.json @@ -18,8 +18,7 @@ "id": "vendor/model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "authRequired", @@ -49,8 +48,7 @@ "id": "vendor/model-a" } ] - }, - "retention": "host" + } }, "state": { "kind": "authRequired", From 322dc215b88ebd80df770f781400fab9b556f79b Mon Sep 17 00:00:00 2001 From: Logan Ramos Date: Wed, 25 Nov 2026 15:34:53 -0500 Subject: [PATCH 17/17] docs: let clients wait for the model source after a registration request A host may publish `root/modelSourceSet` before or after it confirms `root/modelSourceRegisterRequested`, so clients wait for the source rather than reading a confirmed request as the source being in state. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/guide/model-sources.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/model-sources.md b/docs/guide/model-sources.md index 3af9ef770..834a5c8c4 100644 --- a/docs/guide/model-sources.md +++ b/docs/guide/model-sources.md @@ -48,7 +48,7 @@ An agent that serves models from client-registered sources advertises [`AgentCap Registration follows the same pattern as automations: the client asks, and the host publishes the result. 1. A client dispatches [`root/modelSourceRegisterRequested`](/reference/root#rootmodelsourceregisterrequestedaction) with the source's `modelSourceId`, `provider`, `displayName`, a `registration` holding its `format` and a `definition` that tells the agent how to reach it, and optionally the [`retention`](#retention) it wants. Every client can read a definition, so it MUST NOT contain a credential. The request doesn't change state. -2. The host validates the request and publishes the source with [`root/modelSourceSet`](/reference/root#rootmodelsourcesetaction), which adds it or replaces the one with the same `id`. When the registration is unchanged, the host keeps the source's status and credential. When the definition changes, it drops the credential and the source goes back to `starting`. +2. The host validates the request and publishes the source with [`root/modelSourceSet`](/reference/root#rootmodelsourcesetaction), which adds it or replaces the one with the same `id`. When the registration is unchanged, the host keeps the source's status and credential. When the definition changes, it drops the credential and the source goes back to `starting`. The host may publish the source before or after it confirms the request, so a client waits for `root/modelSourceSet` rather than reading a confirmed request as the source being in state. [`root/modelSourceRemoved`](/reference/root#rootmodelsourceremovedaction) removes a source for every client. The host rejects either client action when it breaks the rules in [Server Validation of Client Actions](/specification/root-channel#server-validation-of-client-actions).