diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs index 47f5d54bd..8c0fa11d7 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Actions.generated.cs @@ -201,6 +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 TerminalData = new ActionType("terminal/data"); public static readonly ActionType TerminalInput = new ActionType("terminal/input"); @@ -348,6 +354,71 @@ public sealed record RootConfigChangedAction public bool? Replace { get; init; } } +/// 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 replace, matched by `id`. + public required ModelSource ModelSource { get; init; } +} + +/// 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 +{ + public ActionType Type { get; init; } = ActionType.RootModelSourceRemoved; + + /// The model source's `id`. + public required string ModelSourceId { get; init; } +} + +/// 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 RootModelSourceRegisterRequestedAction +{ + public ActionType Type { get; init; } = ActionType.RootModelSourceRegisterRequested; + + /// The model source's `id`, chosen by the client. + public required string ModelSourceId { 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 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")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public Dictionary? Meta { get; init; } +} + /// Session backend initialized successfully. public sealed record SessionReadyAction { @@ -2961,6 +3032,9 @@ public StateActionConverter() ["root/agentsChanged"] = typeof(RootAgentsChangedAction), ["root/activeSessionsChanged"] = typeof(RootActiveSessionsChangedAction), ["root/configChanged"] = typeof(RootConfigChangedAction), + ["root/modelSourceSet"] = typeof(RootModelSourceSetAction), + ["root/modelSourceRemoved"] = typeof(RootModelSourceRemovedAction), + ["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/Commands.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Commands.generated.cs index 4f12cff59..02f123d0f 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); @@ -2001,14 +2004,30 @@ public sealed record McpServerAuthenticateTarget public required string CustomizationId { get; init; } } +/// 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 source's `ModelSource.id`. + public required string ModelSourceId { get; init; } +} + /// 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` -/// or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the -/// corresponding MCP server or tool call actually challenges for auth). +/// 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 `ModelSource.credentialResource`. /// Servers MUST accept any `resource` value they have themselves advertised -/// through one of these three mechanisms. +/// through one of these mechanisms, subject to the `target` rules. A +/// `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 @@ -2027,7 +2046,8 @@ 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 `ModelSource.credentialResource`. public required string Resource { get; init; } /// Bearer token obtained from the resource's authorization server @@ -2058,15 +2078,22 @@ public sealed record AuthenticateParams /// 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, 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). /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2499,6 +2526,7 @@ public AuthenticateTargetConverter() variants: new Dictionary { ["mcpServer"] = typeof(McpServerAuthenticateTarget), + ["modelSource"] = typeof(ModelSourceAuthenticateTarget), }, allowUnknown: true) { diff --git a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/Errors.generated.cs index 86864276d..1bde256ca 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 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; } /// 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 b60d5aa3a..de74ac693 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/JsonSerializerContext.generated.cs @@ -312,7 +312,20 @@ namespace Microsoft.AgentHostProtocol; [JsonSerializable(typeof(MessageOrigin))] [JsonSerializable(typeof(MessageResourceAttachment))] [JsonSerializable(typeof(ModelSelection))] -[JsonSerializable(typeof(ModelSourceInfo))] +[JsonSerializable(typeof(ModelSource))] +[JsonSerializable(typeof(ModelSourceAuthenticateTarget))] +[JsonSerializable(typeof(ModelSourceAuthRequiredReason))] +[JsonSerializable(typeof(ModelSourceAuthRequiredState))] +[JsonSerializable(typeof(ModelSourceAuthRequirement))] +[JsonSerializable(typeof(ModelSourceErrorState))] +[JsonSerializable(typeof(ModelSourceFormatInfo))] +[JsonSerializable(typeof(ModelSourceReadyState))] +[JsonSerializable(typeof(ModelSourceRegistration))] +[JsonSerializable(typeof(ModelSourceRegistrationCapability))] +[JsonSerializable(typeof(ModelSourceRetentionPolicy))] +[JsonSerializable(typeof(ModelSourceStartingState))] +[JsonSerializable(typeof(ModelSourceState))] +[JsonSerializable(typeof(ModelSourceStatus))] [JsonSerializable(typeof(MoveChatParams))] [JsonSerializable(typeof(MoveChatResult))] [JsonSerializable(typeof(MultipleChatProvidersCapability))] @@ -373,6 +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(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 63a0b163c..d98720548 100644 --- a/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol.Abstractions/Generated/State.generated.cs @@ -1408,6 +1408,186 @@ 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); +} + +/// How long a registered model source lasts once its last 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 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. + 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); +} + +/// 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 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. + 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); +} + /// Computation lifecycle of a {@link ChangesetState}. [JsonConverter(typeof(ChangesetStatusConverter))] public readonly struct ChangesetStatus : IEquatable @@ -2290,6 +2470,14 @@ public sealed class RootState [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public RootConfigState? Config { get; set; } + /// 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)] + public List? ModelSources { get; set; } + /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -2354,11 +2542,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 @@ -2387,6 +2570,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. @@ -2448,15 +2638,171 @@ public sealed record MultipleWorkingDirectoriesCapability public bool? PrimaryReplacement { get; init; } } -/// A source that an agent provider offers models from, such as a service or -/// subscription. -public sealed record ModelSourceInfo +/// Options for the {@link AgentCapabilities.modelSourceRegistration} capability. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceRegistrationCapability +{ + /// Definition formats the agent reads, most preferred first. + public required List Formats { 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 {@link ModelSourceRegistration.format} value. + public required string Format { get; init; } +} + +/// How a client, or the host from its own configuration, registered a model +/// source. +/// +/// Stability: 1.0 - Early development. +public sealed record 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. + 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. + /// + /// 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 required Dictionary Definition { 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 { - /// Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + /// Host-unique ID, chosen by whoever registers the source. Also the + /// {@link SessionModelInfo.modelSourceId} of its models. public required string Id { get; init; } - /// Human-readable name + /// 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; } + + /// How the source was registered. Absent on a source the agent provides + /// itself. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + 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. + /// + /// `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 })`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ProtectedResourceMetadata? CredentialResource { get; init; } + + /// The {@link AuthenticateParams.accountId} sent with the credential the + /// host most recently accepted. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? AccountId { get; init; } + + /// Additional implementation-defined metadata for this model source. + /// MUST NOT contain a credential. + [JsonPropertyName("_meta")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public Dictionary? Meta { get; init; } +} + +/// 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; +} + +/// 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` +/// and `authRequired` states. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceReadyState +{ + public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.Ready; +} + +/// Why a model source needs a credential before it can be ready. Deliberately +/// carries no credential. The endpoint the credential is for is the +/// model source's {@link ModelSource.credentialResource}. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceAuthRequirement +{ + /// Why a credential is needed. + public ModelSourceAuthRequiredReason Reason { get; init; } + + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Description { get; init; } +} + +/// The source needs a credential before it can be used. A client answers with +/// `authenticate`, the model source's `credentialResource.resource`, and a +/// {@link ModelSourceAuthenticateTarget}. +/// +/// Stability: 1.0 - Early development. +public sealed record ModelSourceAuthRequiredState +{ + /// Why a credential is needed. + public ModelSourceAuthRequiredReason Reason { get; init; } + + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Description { get; init; } + + public ModelSourceStatus Kind { get; init; } = ModelSourceStatus.AuthRequired; +} + +/// 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 the host writes. MUST NOT contain the credential. + public required ErrorInfo Error { get; init; } } public sealed record SessionModelInfo @@ -2517,8 +2863,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}. + /// 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; } } @@ -6652,6 +6999,14 @@ public sealed record ErrorInfo /// 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; } @@ -8715,6 +9070,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 c3b557052..75d00fabe 100644 --- a/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs +++ b/clients/dotnet/src/AgentHostProtocol/Generated/ActionMetadata.generated.cs @@ -214,6 +214,15 @@ public static bool TryGetActionType(object action, out ActionType actionType) case RootConfigChangedAction value: actionType = value.Type; return true; + case RootModelSourceRegisterRequestedAction value: + actionType = value.Type; + return true; + case RootModelSourceRemovedAction value: + actionType = value.Type; + return true; + case RootModelSourceSetAction 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 76ab3ea30..8d5919584 100644 --- a/clients/dotnet/src/AgentHostProtocol/Reducers.cs +++ b/clients/dotnet/src/AgentHostProtocol/Reducers.cs @@ -680,6 +680,34 @@ 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); + if (index < 0) + { + list.Add(a.ModelSource); + } + else + { + list[index] = a.ModelSource; + } + + return ReduceOutcome.Applied; + } + case RootModelSourceRemovedAction a: + { + int index = state.ModelSources?.FindIndex(s => s.Id == a.ModelSourceId) ?? -1; + if (index < 0) + { + return ReduceOutcome.NoOp; + } + + state.ModelSources!.RemoveAt(index); + return ReduceOutcome.Applied; + } } return ReduceOutcome.OutOfScope; @@ -2709,6 +2737,8 @@ public static ReduceOutcome ApplyToAutomationRun( private static readonly string[] s_clientDispatchableActionNames = { "root/configChanged", + "root/modelSourceRegisterRequested", + "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 a5ad3e526..5f9be3c35 100644 --- a/clients/go/ahp/reducers.go +++ b/clients/go/ahp/reducers.go @@ -537,10 +537,36 @@ func ApplyActionToRoot(state *ahptypes.RootState, action ahptypes.StateAction) R state.Config.Values[k] = v } return ReduceOutcomeApplied + case *ahptypes.RootModelSourceRegisterRequestedAction: + return ReduceOutcomeNoOp + case *ahptypes.RootModelSourceSetAction: + idx := modelSourceIndex(state.ModelSources, a.ModelSource.Id) + if idx >= 0 { + state.ModelSources[idx] = a.ModelSource + } else { + state.ModelSources = append(state.ModelSources, a.ModelSource) + } + return ReduceOutcomeApplied + case *ahptypes.RootModelSourceRemovedAction: + idx := modelSourceIndex(state.ModelSources, a.ModelSourceId) + if idx < 0 { + return ReduceOutcomeNoOp + } + state.ModelSources = append(state.ModelSources[:idx], state.ModelSources[idx+1:]...) + return ReduceOutcomeApplied } return ReduceOutcomeOutOfScope } +func modelSourceIndex(list []ahptypes.ModelSource, id string) int { + for i := range list { + if list[i].Id == id { + return i + } + } + return -1 +} + // ─── 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 30c44d7a8..b5591677a 100644 --- a/clients/go/ahptypes/actions.generated.go +++ b/clients/go/ahptypes/actions.generated.go @@ -107,6 +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" ActionTypeTerminalData ActionType = "terminal/data" ActionTypeTerminalInput ActionType = "terminal/input" ActionTypeTerminalResized ActionType = "terminal/resized" @@ -180,6 +183,55 @@ type RootConfigChangedAction struct { Replace *bool `json:"replace,omitempty"` } +// 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 replace, matched by `id`. + ModelSource ModelSource `json:"modelSource"` +} + +// 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`. + ModelSourceId string `json:"modelSourceId"` +} + +// 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 RootModelSourceRegisterRequestedAction struct { + Type ActionType `json:"type"` + // The model source's `id`, chosen by the client. + ModelSourceId string `json:"modelSourceId"` + // 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 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"` +} + // Session backend initialized successfully. type SessionReadyAction struct { Type ActionType `json:"type"` @@ -1950,6 +2002,9 @@ type isStateAction interface{ isStateAction() } func (*RootAgentsChangedAction) isStateAction() {} func (*RootActiveSessionsChangedAction) isStateAction() {} func (*RootConfigChangedAction) isStateAction() {} +func (*RootModelSourceSetAction) isStateAction() {} +func (*RootModelSourceRemovedAction) isStateAction() {} +func (*RootModelSourceRegisterRequestedAction) isStateAction() {} func (*SessionReadyAction) isStateAction() {} func (*SessionCreationFailedAction) isStateAction() {} func (*SessionChatAddedAction) isStateAction() {} @@ -2092,6 +2147,24 @@ func (u *StateAction) UnmarshalJSON(data []byte) error { return err } u.Value = &value + case "root/modelSourceSet": + var value RootModelSourceSetAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "root/modelSourceRemoved": + var value RootModelSourceRemovedAction + if err := json.Unmarshal(data, &value); err != nil { + return err + } + u.Value = &value + case "root/modelSourceRegisterRequested": + var value RootModelSourceRegisterRequestedAction + 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 20a0301a4..ecc800b63 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 ───────────────────────────────────────────────── @@ -1449,14 +1451,28 @@ type McpServerAuthenticateTarget struct { CustomizationId string `json:"customizationId"` } +// 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 source's `ModelSource.id`. + ModelSourceId string `json:"modelSourceId"` +} + // 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` -// or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the -// corresponding MCP server or tool call actually challenges for auth). +// 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 `ModelSource.credentialResource`. // Servers MUST accept any `resource` value they have themselves advertised -// through one of these three mechanisms. +// through one of these mechanisms, subject to the `target` rules. A +// `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 @@ -1471,7 +1487,8 @@ 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 `ModelSource.credentialResource`. Resource string `json:"resource"` // Bearer token obtained from the resource's authorization server Token string `json:"token"` @@ -1496,15 +1513,22 @@ type AuthenticateParams struct { 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, 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). // // Without a target, resource/scope matching is unchanged; the token may // satisfy every matching pending challenge. Older hosts ignore this field. @@ -2059,7 +2083,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 { @@ -2081,6 +2106,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) @@ -2114,6 +2145,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/errors.generated.go b/clients/go/ahptypes/errors.generated.go index cc43b684c..975dbe941 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 or turn needs a registered model source that 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 143d8dbb0..7e66b2ac1 100644 --- a/clients/go/ahptypes/state.generated.go +++ b/clients/go/ahptypes/state.generated.go @@ -436,6 +436,53 @@ 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" +) + +// How long a registered model source lasts once its last contributing client +// leaves. +// +// Stability: 1.0 - Early development. +type ModelSourceRetentionPolicy string + +const ( + // 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. + 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 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" +) + // Computation lifecycle of a {@link ChangesetState}. type ChangesetStatus string @@ -837,6 +884,12 @@ type RootState struct { Terminals []TerminalInfo `json:"terminals,omitempty"` // Agent host configuration schema and current values Config *RootConfigState `json:"config,omitempty"` + // 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"` // Additional implementation-defined metadata about the agent host itself. // // Clients MAY look for well-known keys here to provide enhanced UI. @@ -887,9 +940,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 @@ -914,6 +964,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. @@ -967,13 +1022,141 @@ type MultipleWorkingDirectoriesCapability struct { PrimaryReplacement *bool `json:"primaryReplacement,omitempty"` } -// 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}. +// Options for the {@link AgentCapabilities.modelSourceRegistration} capability. +// +// Stability: 1.0 - Early development. +type ModelSourceRegistrationCapability struct { + // Definition formats the agent reads, most preferred first. + Formats []ModelSourceFormatInfo `json:"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 {@link ModelSourceRegistration.format} value. + Format string `json:"format"` +} + +// How a client, or the host from its own configuration, registered a model +// source. +// +// Stability: 1.0 - Early development. +type ModelSourceRegistration struct { + // 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 `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. + // + // 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"` +} + +// 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"` - // Human-readable name + // 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. + // + // `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 })`. + CredentialResource *ProtectedResourceMetadata `json:"credentialResource,omitempty"` + // The {@link AuthenticateParams.accountId} sent with the credential the + // host most recently accepted. + 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"` +} + +// 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"` +} + +// 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` +// and `authRequired` states. +// +// Stability: 1.0 - Early development. +type ModelSourceReadyState struct { + Kind ModelSourceStatus `json:"kind"` +} + +// Why a model source needs a credential before it can be ready. Deliberately +// carries no credential. The endpoint the credential is for is the +// model source's {@link ModelSource.credentialResource}. +// +// Stability: 1.0 - Early development. +type ModelSourceAuthRequirement struct { + // Why a credential is needed. + Reason ModelSourceAuthRequiredReason `json:"reason"` + // Human-readable hint the host writes, for example "The endpoint rejected + // the API key." + Description *string `json:"description,omitempty"` +} + +// The source needs a credential before it can be used. A client answers with +// `authenticate`, the model source's `credentialResource.resource`, and a +// {@link ModelSourceAuthenticateTarget}. +// +// Stability: 1.0 - Early development. +type ModelSourceAuthRequiredState struct { + // Why a credential is needed. + Reason ModelSourceAuthRequiredReason `json:"reason"` + // Human-readable hint the host writes, for example "The endpoint rejected + // the API key." + Description *string `json:"description,omitempty"` + Kind ModelSourceStatus `json:"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 the host writes. MUST NOT contain the credential. + Error ErrorInfo `json:"error"` } type SessionModelInfo struct { @@ -1013,8 +1196,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}. + // 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"` } @@ -4388,6 +4572,12 @@ type UsageInfo struct { type ErrorInfo struct { // 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 @@ -4402,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 @@ -6951,6 +7141,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 239aed5b9..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,6 +581,27 @@ 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 updated = list.toMutableList() + if (idx < 0) updated.add(source) else updated[idx] = source + state.copy(modelSources = updated) + } + + is StateActionRootModelSourceRemoved -> { + val list = state.modelSources + val idx = list?.indexOfFirst { it.id == action.value.modelSourceId } ?: -1 + if (list == null || idx < 0) { + state + } else { + state.copy(modelSources = 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 60abc817a..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 @@ -117,6 +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 TERMINAL_DATA: ActionType = ActionType("terminal/data") val TERMINAL_INPUT: ActionType = ActionType("terminal/input") val TERMINAL_RESIZED: ActionType = ActionType("terminal/resized") @@ -1522,6 +1525,83 @@ data class RootConfigChangedAction( val replace: Boolean? = null ) +/** + * 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. + */ +@Serializable +data class RootModelSourceSetAction( + val type: ActionType, + /** + * The model source to add or replace, matched by `id`. + */ + val modelSource: ModelSource +) + +/** + * Removes the model source with the given `modelSourceId`, for every client. + * A no-op when none matches. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class RootModelSourceRemovedAction( + val type: ActionType, + /** + * The model source's `id`. + */ + val modelSourceId: String +) + +/** + * 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 RootModelSourceRegisterRequestedAction( + val type: ActionType, + /** + * The model source's `id`, chosen by the client. + */ + val modelSourceId: String, + /** + * Agent provider whose agent serves the source's models. + */ + val provider: String, + /** + * Human-readable name. + */ + val displayName: String, + /** + * Icons for UI display. + */ + val icons: List? = null, + /** + * 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. + */ + @SerialName("_meta") + val meta: Map? = null +) + @Serializable data class TerminalDataAction( val type: ActionType, @@ -1973,6 +2053,9 @@ 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 StateActionRootModelSourceSet(val value: RootModelSourceSetAction) : StateAction +@JvmInline value class StateActionRootModelSourceRemoved(val value: RootModelSourceRemovedAction) : 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 @@ -2100,6 +2183,9 @@ 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/modelSourceSet" -> StateActionRootModelSourceSet(input.json.decodeFromJsonElement(RootModelSourceSetAction.serializer(), element)) + "root/modelSourceRemoved" -> StateActionRootModelSourceRemoved(input.json.decodeFromJsonElement(RootModelSourceRemovedAction.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)) @@ -2220,6 +2306,9 @@ 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 StateActionRootModelSourceSet -> output.json.encodeToJsonElement(RootModelSourceSetAction.serializer(), value.value) + is StateActionRootModelSourceRemoved -> output.json.encodeToJsonElement(RootModelSourceRemovedAction.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/Commands.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Commands.generated.kt index 93708ea3a..ad911f4a9 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") } } @@ -1757,6 +1761,22 @@ data class McpServerAuthenticateTarget( val customizationId: String ) +/** + * 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. + */ +@Serializable +data class ModelSourceAuthenticateTarget( + val kind: AuthenticateTargetKind, + /** + * The source's `ModelSource.id`. + */ + val modelSourceId: String +) + @Serializable data class AuthenticateParams( /** @@ -1773,7 +1793,8 @@ 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 `ModelSource.credentialResource`. */ val resource: String, /** @@ -1806,15 +1827,22 @@ data class AuthenticateParams( /** * 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, 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). * * Without a target, resource/scope matching is unchanged; the token may * satisfy every matching pending challenge. Older hosts ignore this field. @@ -2380,6 +2408,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. * @@ -2405,6 +2435,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) } } @@ -2414,11 +2445,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/Errors.generated.kt b/clients/kotlin/src/main/kotlin/com/microsoft/agenthostprotocol/generated/Errors.generated.kt index c1ba5c42b..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,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 or turn needs a registered model source that 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 b7db214d7..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 @@ -921,6 +921,115 @@ 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()) +} + +/** + * How long a registered model source lasts once its last contributing client + * leaves. + * + * Stability: 1.0 - Early development. + */ +@Serializable(with = ModelSourceRetentionPolicySerializer::class) +@JvmInline +value class ModelSourceRetentionPolicy(val rawValue: String) { + companion object { + /** + * 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. + */ + 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()) +} + +/** + * 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. + */ +@Serializable(with = ModelSourceAuthRequiredReasonSerializer::class) +@JvmInline +value class ModelSourceAuthRequiredReason(val rawValue: String) { + companion object { + /** + * The host holds no credential yet. + */ + val REQUIRED: ModelSourceAuthRequiredReason = ModelSourceAuthRequiredReason("required") + /** + * The credential's lifetime or lease lapsed. A client may renew it. + */ + val EXPIRED: ModelSourceAuthRequiredReason = ModelSourceAuthRequiredReason("expired") + /** + * The endpoint refused the credential. Clients don't send a credential with + * the same {@link ModelSource.accountId} again. + */ + val REJECTED: ModelSourceAuthRequiredReason = ModelSourceAuthRequiredReason("rejected") + /** + * A client revoked the credential. Clients don't send one again without a user's action. + */ + val REVOKED: ModelSourceAuthRequiredReason = ModelSourceAuthRequiredReason("revoked") + } +} + +internal object ModelSourceAuthRequiredReasonSerializer : 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()) +} + /** * Computation lifecycle of a {@link ChangesetState}. */ @@ -1658,6 +1767,14 @@ data class RootState( * Agent host configuration schema and current values */ val config: RootConfigState? = null, + /** + * 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. + */ + val modelSources: List? = null, /** * Additional implementation-defined metadata about the agent host itself. * @@ -1726,12 +1843,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 @@ -1755,7 +1867,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 @@ -1817,16 +1936,205 @@ data class MultipleWorkingDirectoriesCapability( val primaryReplacement: Boolean? = null ) +/** + * Options for the {@link AgentCapabilities.modelSourceRegistration} capability. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceRegistrationCapability( + /** + * Definition formats the agent reads, most preferred first. + */ + val formats: List +) + +/** + * 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. + */ +@Serializable +data class ModelSourceFormatInfo( + /** + * A {@link ModelSourceRegistration.format} value. + */ + val 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. + * + * Stability: 1.0 - Early development. + */ @Serializable -data class ModelSourceInfo( +data class ModelSource( /** - * Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. + * Host-unique ID, chosen by whoever registers the source. Also the + * {@link SessionModelInfo.modelSourceId} of its models. */ val id: String, /** - * Human-readable name + * Agent provider whose agent serves the source's models. */ - val displayName: String + val provider: String, + /** + * Human-readable name. + */ + val displayName: String, + /** + * 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}. + * + * 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. + */ + 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. + * + * 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 +) + +/** + * The agent is reading and validating the definition, or listing the + * source's models again after a credential change. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceStartingState( + val kind: ModelSourceStatus +) + +/** + * 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` + * and `authRequired` states. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceReadyState( + val kind: ModelSourceStatus +) + +/** + * Why a model source needs a credential before it can be ready. Deliberately + * carries no credential. The endpoint the credential is for is the + * model source's {@link ModelSource.credentialResource}. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceAuthRequirement( + /** + * Why a credential is needed. + */ + val reason: ModelSourceAuthRequiredReason, + /** + * Human-readable hint the host writes, for example "The endpoint rejected + * the API key." + */ + val description: String? = null +) + +/** + * The source needs a credential before it can be used. A client answers with + * `authenticate`, the model source's `credentialResource.resource`, and a + * {@link ModelSourceAuthenticateTarget}. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceAuthRequiredState( + /** + * Why a credential is needed. + */ + val reason: ModelSourceAuthRequiredReason, + /** + * Human-readable hint the host writes, for example "The endpoint rejected + * the API key." + */ + val description: String? = null, + val kind: ModelSourceStatus +) + +/** + * The source failed, or the host declined it, for example by policy. + * + * Stability: 1.0 - Early development. + */ +@Serializable +data class ModelSourceErrorState( + val kind: ModelSourceStatus, + /** + * Error details the host writes. MUST NOT contain the credential. + */ + val error: ErrorInfo ) @Serializable @@ -1891,8 +2199,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}. + * 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 ) @@ -5927,6 +6236,14 @@ data class ErrorInfo( * 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 */ @@ -8424,6 +8741,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 1b97f6ada..2010741c9 100644 --- a/clients/rust/crates/ahp-types/src/actions.rs +++ b/clients/rust/crates/ahp-types/src/actions.rs @@ -19,12 +19,13 @@ use crate::state::{ ChangesetOperation, ChangesetOperationStatus, ChangesetStatus, ChatInputAnswer, ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ChatSummary, ConfirmationOption, ContentRef, Customization, CustomizationEnablement, ErrorInfo, - ErrorResponsePart, FileEditCollection, MaterializedTurn, McpAuthRequirement, McpServerState, - Message, ModelSelection, PendingMessageKind, ResponsePart, SearchLifecycleState, SearchQuery, - SearchResult, SessionActiveClient, SessionConfigSchema, SessionInputRequest, SideChatSelection, - TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, ToolCallConfirmationReason, - ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, ToolDefinition, ToolInput, - ToolResultContent, Turn, UsageInfo, + ErrorResponsePart, FileEditCollection, Icon, MaterializedTurn, McpAuthRequirement, + McpServerState, Message, ModelSelection, ModelSource, ModelSourceRegistration, + ModelSourceRetentionPolicy, PendingMessageKind, ResponsePart, SearchLifecycleState, + SearchQuery, SearchResult, SessionActiveClient, SessionConfigSchema, SessionInputRequest, + SideChatSelection, TerminalClaim, TerminalInfo, TextRange, ToolCallCancellationReason, + ToolCallConfirmationReason, ToolCallContributor, ToolCallResult, ToolCallRiskAssessment, + ToolDefinition, ToolInput, ToolResultContent, Turn, UsageInfo, }; // ─── ActionType ────────────────────────────────────────────────────── @@ -120,6 +121,9 @@ pub enum ActionType { AnnotationsEntryRemoved, RootTerminalsChanged, RootConfigChanged, + RootModelSourceRegisterRequested, + RootModelSourceSet, + RootModelSourceRemoved, TerminalData, TerminalInput, TerminalResized, @@ -292,6 +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::TerminalData => serializer.serialize_str("terminal/data"), Self::TerminalInput => serializer.serialize_str("terminal/input"), Self::TerminalResized => serializer.serialize_str("terminal/resized"), @@ -430,6 +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, "terminal/data" => Self::TerminalData, "terminal/input" => Self::TerminalInput, "terminal/resized" => Self::TerminalResized, @@ -521,6 +533,61 @@ pub struct RootConfigChangedAction { pub replace: Option, } +/// 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 replace, matched by `id`. + pub model_source: ModelSource, +} + +/// 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 model_source_id: String, +} + +/// 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 RootModelSourceRegisterRequestedAction { + /// The model source's `id`, chosen by the client. + pub model_source_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>, + /// 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")] + pub meta: Option, +} + /// Session backend initialized successfully. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2558,6 +2625,12 @@ pub enum StateAction { RootActiveSessionsChanged(RootActiveSessionsChangedAction), #[serde(rename = "root/configChanged")] RootConfigChanged(RootConfigChangedAction), + #[serde(rename = "root/modelSourceSet")] + RootModelSourceSet(Box), + #[serde(rename = "root/modelSourceRemoved")] + RootModelSourceRemoved(RootModelSourceRemovedAction), + #[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/commands.rs b/clients/rust/crates/ahp-types/src/commands.rs index 7593e8acb..cf42cbbf9 100644 --- a/clients/rust/crates/ahp-types/src/commands.rs +++ b/clients/rust/crates/ahp-types/src/commands.rs @@ -236,6 +236,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), } @@ -247,6 +249,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), } } @@ -260,6 +263,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), }) } @@ -1857,14 +1861,29 @@ pub struct McpServerAuthenticateTarget { pub customization_id: String, } +/// 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 source's `ModelSource.id`. + pub model_source_id: String, +} + /// 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` -/// or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the -/// corresponding MCP server or tool call actually challenges for auth). +/// 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 `ModelSource.credentialResource`. /// Servers MUST accept any `resource` value they have themselves advertised -/// through one of these three mechanisms. +/// through one of these mechanisms, subject to the `target` rules. A +/// `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 @@ -1882,7 +1901,8 @@ 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 `ModelSource.credentialResource`. pub resource: String, /// Bearer token obtained from the resource's authorization server pub token: String, @@ -1909,15 +1929,22 @@ pub struct AuthenticateParams { 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, 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). /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2336,6 +2363,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/errors.rs b/clients/rust/crates/ahp-types/src/errors.rs index 6f15b4fbd..23ee79114 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 or turn needs a registered model source that 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 614226d92..acf7c00fe 100644 --- a/clients/rust/crates/ahp-types/src/state.rs +++ b/clients/rust/crates/ahp-types/src/state.rs @@ -1165,6 +1165,145 @@ 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), + }) + } +} + +/// How long a registered model source lasts once its last contributing client +/// 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 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), + }) + } +} + +/// 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 ModelSource.accountId} 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), + }) + } +} + /// Computation lifecycle of a {@link ChangesetState}. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ChangesetStatus { @@ -2036,6 +2175,13 @@ pub struct RootState { /// Agent host configuration schema and current values #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option, + /// 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")] + 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. @@ -2094,10 +2240,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 @@ -2126,6 +2268,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. @@ -2187,15 +2335,160 @@ pub struct MultipleWorkingDirectoriesCapability { pub primary_replacement: Option, } -/// A source that an agent provider offers models from, such as a service or -/// subscription. +/// 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. + pub formats: Vec, +} + +/// 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 ModelSourceInfo { - /// Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. +pub struct ModelSourceFormatInfo { + /// A {@link ModelSourceRegistration.format} value. + pub format: String, +} + +/// 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 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. + 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. + /// + /// 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}. + pub definition: JsonObject, +} + +/// 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, - /// Human-readable name + /// 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 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. + /// + /// `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 })`. + #[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. + #[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, +} + +/// 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 {} + +/// 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` +/// and `authRequired` states. +/// +/// Stability: 1.0 - Early development. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +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 +/// model source's {@link ModelSource.credentialResource}. +/// +/// 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: ModelSourceAuthRequiredReason, + /// 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, +} + +/// The source needs a credential before it can be used. A client answers with +/// `authenticate`, the model source's `credentialResource.resource`, 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: ModelSourceAuthRequiredReason, + /// 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, +} + +/// 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 the host writes. MUST NOT contain the credential. + pub error: ErrorInfo, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -2245,8 +2538,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}. + /// 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, } @@ -5906,6 +6200,13 @@ pub struct UsageInfo { pub struct ErrorInfo { /// 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 @@ -7765,6 +8066,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..e28c0255f 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_sources: None, meta: None, }; @@ -38,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/src/hosts/runtime.rs b/clients/rust/crates/ahp/src/hosts/runtime.rs index 681c0b4b0..271201a75 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_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 013229405..f98cd9eeb 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_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 2e1e91f55..f9672caed 100644 --- a/clients/rust/crates/ahp/src/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/src/multi_host_state_mirror.rs @@ -200,6 +200,7 @@ impl MultiHostStateMirror { active_sessions: None, terminals: None, config: 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 058a6553e..240f1b84a 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_sources: None, //! meta: None, //! }; //! @@ -720,6 +721,25 @@ 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); + 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 + } + StateAction::RootModelSourceRemoved(a) => { + let Some(list) = state.model_sources.as_mut() else { + return ReduceOutcome::NoOp; + }; + let Some(idx) = list.iter().position(|s| s.id == a.model_source_id) else { + return ReduceOutcome::NoOp; + }; + list.remove(idx); + ReduceOutcome::Applied + } _ => ReduceOutcome::OutOfScope, } } @@ -2661,6 +2681,7 @@ mod tests { active_sessions: None, terminals: None, config: None, + model_sources: None, meta: None, }; let a = StateAction::RootActiveSessionsChanged( 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 2c79446d9..b54692316 100644 --- a/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs +++ b/clients/rust/crates/ahp/tests/multi_host_state_mirror.rs @@ -31,7 +31,6 @@ fn agent(provider: &str) -> AgentInfo { protected_resources: None, customizations: None, capabilities: None, - model_sources: None, } } @@ -43,6 +42,7 @@ fn root_snapshot(agents: Vec) -> Snapshot { active_sessions: None, terminals: None, config: 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 171a9f920..7dcf08623 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/modelSourceRegisterRequested", + "root/modelSourceRemoved", "session/titleChanged", "session/activeClientSet", "session/activeClientRemoved", @@ -59,6 +61,8 @@ public let clientDispatchableActions: Set = [ public func isClientDispatchable(_ action: StateAction) -> Bool { switch action { case .rootConfigChanged, + .rootModelSourceRegisterRequested, + .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 c1781aaba..afe51ee80 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Actions.generated.swift @@ -94,6 +94,9 @@ public enum ActionType: Codable, Sendable, Equatable { case annotationsEntryRemoved case rootTerminalsChanged case rootConfigChanged + case rootModelSourceRegisterRequested + case rootModelSourceSet + case rootModelSourceRemoved case terminalData case terminalInput case terminalResized @@ -213,6 +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 "terminal/data": self = .terminalData case "terminal/input": self = .terminalInput case "terminal/resized": self = .terminalResized @@ -332,6 +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 .terminalData: try container.encode("terminal/data") case .terminalInput: try container.encode("terminal/input") case .terminalResized: try container.encode("terminal/resized") @@ -2330,6 +2339,102 @@ public struct RootConfigChangedAction: Codable, Sendable, Equatable { } } +/// 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 replace, matched by `id`. + public var modelSource: ModelSource + + public init( + type: ActionType, + modelSource: ModelSource + ) { + self.type = type + self.modelSource = modelSource + } +} + +/// 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 modelSourceId: String + + public init( + type: ActionType, + modelSourceId: String + ) { + self.type = type + self.modelSourceId = modelSourceId + } +} + +/// 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 RootModelSourceRegisterRequestedAction: Codable, Sendable, Equatable { + public var type: ActionType + /// The model source's `id`, chosen by the client. + public var modelSourceId: 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 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]? + + enum CodingKeys: String, CodingKey { + case type + case modelSourceId + case provider + case displayName + case icons + case registration + case retention + case meta = "_meta" + } + + public init( + type: ActionType, + modelSourceId: String, + provider: String, + displayName: String, + icons: [Icon]? = nil, + registration: ModelSourceRegistration, + retention: ModelSourceRetentionPolicy? = nil, + meta: [String: AnyCodable]? = nil + ) { + self.type = type + self.modelSourceId = modelSourceId + self.provider = provider + self.displayName = displayName + self.icons = icons + self.registration = registration + self.retention = retention + self.meta = meta + } +} + public struct TerminalDataAction: Codable, Sendable, Equatable { public var type: ActionType /// Output data (may contain ANSI escape sequences) @@ -2888,6 +2993,9 @@ public enum StateAction: Codable, Sendable, Equatable { case annotationsEntryRemoved(AnnotationsEntryRemovedAction) case rootTerminalsChanged(RootTerminalsChangedAction) case rootConfigChanged(RootConfigChangedAction) + case rootModelSourceSet(RootModelSourceSetAction) + case rootModelSourceRemoved(RootModelSourceRemovedAction) + case rootModelSourceRegisterRequested(RootModelSourceRegisterRequestedAction) case terminalData(TerminalDataAction) case terminalInput(TerminalInputAction) case terminalResized(TerminalResizedAction) @@ -3100,6 +3208,12 @@ public enum StateAction: Codable, Sendable, Equatable { self = .rootTerminalsChanged(try RootTerminalsChangedAction(from: decoder)) case "root/configChanged": self = .rootConfigChanged(try RootConfigChangedAction(from: decoder)) + case "root/modelSourceSet": + self = .rootModelSourceSet(try RootModelSourceSetAction(from: decoder)) + case "root/modelSourceRemoved": + self = .rootModelSourceRemoved(try RootModelSourceRemovedAction(from: decoder)) + case "root/modelSourceRegisterRequested": + self = .rootModelSourceRegisterRequested(try RootModelSourceRegisterRequestedAction(from: decoder)) case "terminal/data": self = .terminalData(try TerminalDataAction(from: decoder)) case "terminal/input": @@ -3243,6 +3357,9 @@ 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 .rootModelSourceSet(let v): try v.encode(to: encoder) + case .rootModelSourceRemoved(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/Commands.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Commands.generated.swift index 15e4ad6cb..4fcabf521 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) } } @@ -2131,6 +2135,25 @@ public struct McpServerAuthenticateTarget: Codable, Sendable, Equatable { } } +/// 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 source's `ModelSource.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 @@ -2140,7 +2163,8 @@ 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 `ModelSource.credentialResource`. public var resource: String /// Bearer token obtained from the resource's authorization server public var token: String @@ -2165,15 +2189,22 @@ public struct AuthenticateParams: Codable, Sendable, Equatable { 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, 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). /// /// Without a target, resource/scope matching is unchanged; the token may /// satisfy every matching pending challenge. Older hosts ignore this field. @@ -2889,6 +2920,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) @@ -2906,6 +2938,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)) } @@ -2916,6 +2950,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/Errors.generated.swift b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/Errors.generated.swift index 7e52f3395..3b737763e 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 or turn needs a registered model source that 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 b1843d38b..cf5473224 100644 --- a/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift +++ b/clients/swift/AgentHostProtocol/Sources/AgentHostProtocol/Generated/State.generated.swift @@ -900,6 +900,118 @@ 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) + } + } +} + +/// How long a registered model source lasts once its last contributing client +/// 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 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) + } + } +} + +/// 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 ModelSource.accountId} 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) + } + } +} + /// Computation lifecycle of a {@link ChangesetState}. public enum ChangesetStatus: Codable, Sendable, Equatable { /// The server is computing this changeset for the first time. @@ -1636,6 +1748,12 @@ public struct RootState: Codable, Sendable, Equatable { public var terminals: [TerminalInfo]? /// Agent host configuration schema and current values public var config: RootConfigState? + /// 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]? /// Additional implementation-defined metadata about the agent host itself. /// /// Clients MAY look for well-known keys here to provide enhanced UI. @@ -1646,6 +1764,7 @@ public struct RootState: Codable, Sendable, Equatable { case activeSessions case terminals case config + case modelSources case meta = "_meta" } @@ -1654,12 +1773,14 @@ public struct RootState: Codable, Sendable, Equatable { activeSessions: Int? = nil, terminals: [TerminalInfo]? = nil, config: RootConfigState? = nil, + modelSources: [ModelSource]? = nil, meta: [String: AnyCodable]? = nil ) { self.agents = agents self.activeSessions = activeSessions self.terminals = terminals self.config = config + self.modelSources = modelSources self.meta = meta } } @@ -1712,9 +1833,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, @@ -1723,8 +1841,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 @@ -1733,7 +1850,6 @@ public struct AgentInfo: Codable, Sendable, Equatable { self.protectedResources = protectedResources self.customizations = customizations self.capabilities = capabilities - self.modelSources = modelSources } } @@ -1754,13 +1870,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 } } @@ -1829,18 +1952,232 @@ public struct MultipleWorkingDirectoriesCapability: Codable, Sendable, Equatable } } -public struct ModelSourceInfo: Codable, Sendable, Equatable { - /// Model source identifier, unique within the agent's {@link AgentInfo.modelSources}. +/// 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. + public var formats: [ModelSourceFormatInfo] + + public init( + formats: [ModelSourceFormatInfo] + ) { + self.formats = 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. +public struct ModelSourceFormatInfo: Codable, Sendable, Equatable { + /// A {@link ModelSourceRegistration.format} value. + public var format: String + + public init( + format: String + ) { + self.format = 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. +/// +/// Stability: 1.0 - Early development. +public struct ModelSource: Codable, Sendable, Equatable { + /// Host-unique ID, chosen by whoever registers the source. Also the + /// {@link SessionModelInfo.modelSourceId} of its models. public var id: String - /// Human-readable name + /// 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]? + /// 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. + /// + /// `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 })`. + public var credentialResource: ProtectedResourceMetadata? + /// The {@link AuthenticateParams.accountId} sent with the credential the + /// host most recently accepted. + public var accountId: String? + /// Additional implementation-defined metadata for this model source. + /// MUST NOT contain a credential. + public var meta: [String: AnyCodable]? + + enum CodingKeys: String, CodingKey { + case id + case provider + case displayName + case icons + case registration + case state + case credentialResource + case accountId + case meta = "_meta" + } public init( id: String, - displayName: String + provider: String, + displayName: String, + icons: [Icon]? = nil, + registration: ModelSourceRegistration? = nil, + state: ModelSourceState, + credentialResource: ProtectedResourceMetadata? = nil, + accountId: String? = nil, + meta: [String: AnyCodable]? = nil ) { self.id = id + self.provider = provider self.displayName = displayName + self.icons = icons + self.registration = registration + self.state = state + self.credentialResource = credentialResource + self.accountId = accountId + self.meta = meta + } +} + +/// 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] + + public init( + format: String, + definition: [String: AnyCodable] + ) { + self.format = format + self.definition = definition + } +} + +/// 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 + + public init( + kind: ModelSourceStatus + ) { + self.kind = kind + } +} + +/// 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` +/// and `authRequired` states. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceReadyState: Codable, Sendable, Equatable { + public var kind: ModelSourceStatus + + public init( + kind: ModelSourceStatus + ) { + self.kind = kind + } +} + +/// Why a model source needs a credential before it can be ready. Deliberately +/// carries no credential. The endpoint the credential is for is the +/// model source's {@link ModelSource.credentialResource}. +/// +/// Stability: 1.0 - Early development. +public struct ModelSourceAuthRequirement: Codable, Sendable, Equatable { + /// Why a credential is needed. + public var reason: ModelSourceAuthRequiredReason + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." + public var description: String? + + public init( + reason: ModelSourceAuthRequiredReason, + description: String? = nil + ) { + self.reason = reason + self.description = description + } +} + +/// The source needs a credential before it can be used. A client answers with +/// `authenticate`, the model source'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: ModelSourceAuthRequiredReason + /// Human-readable hint the host writes, for example "The endpoint rejected + /// the API key." + public var description: String? + public var kind: ModelSourceStatus + + public init( + reason: ModelSourceAuthRequiredReason, + description: String? = nil, + kind: ModelSourceStatus + ) { + self.reason = reason + self.description = description + self.kind = kind + } +} + +/// 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 the host writes. MUST NOT contain the credential. + public var error: ErrorInfo + + public init( + kind: ModelSourceStatus, + error: ErrorInfo + ) { + self.kind = kind + self.error = error } } @@ -1881,8 +2218,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}. + /// 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 { @@ -7334,6 +7672,12 @@ public struct UsageInfo: Codable, Sendable, Equatable { public struct ErrorInfo: Codable, Sendable, Equatable { /// 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 @@ -7347,6 +7691,7 @@ public struct ErrorInfo: Codable, Sendable, Equatable { enum CodingKeys: String, CodingKey, CaseIterable { case errorType + case errorCode case message case stack case meta = "_meta" @@ -7354,12 +7699,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 @@ -7369,6 +7716,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) @@ -7378,6 +7726,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) @@ -10594,6 +10943,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..7129f3551 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 .rootModelSourceSet(let a): + applyModelSourceSet(&state, a.modelSource) + + case .rootModelSourceRemoved(let a): + _ = applyModelSourceRemoved(&state, id: a.modelSourceId) + default: break } } } +/// Adds `source`, or replaces the entry with the same `id`. +func applyModelSourceSet(_ state: inout RootState, _ source: ModelSource) { + var list = state.modelSources ?? [] + if let idx = list.firstIndex(where: { $0.id == source.id }) { + list[idx] = source + } else { + list.append(source) + } + state.modelSources = list +} + +/// 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.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 f750f6f1e..e0058b2e5 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 .rootModelSourceSet(let a): + var next = state + applyModelSourceSet(&next, a.modelSource) + return next + + case .rootModelSourceRemoved(let a): + var next = state + guard applyModelSourceRemoved(&next, id: a.modelSourceId) 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 e12312f29..d3c5f8e7c 100644 --- a/docs/.changes/20261022-model-source-selection.json +++ b/docs/.changes/20261022-model-source-selection.json @@ -1,14 +1,14 @@ { "type": "added", - "message": "Add model source metadata (`ModelSourceInfo`, `AgentInfo.modelSources`, and `SessionModelInfo.modelSourceId`) so clients can label and group models by service or subscription while keeping model IDs unique and stable per agent.", + "message": "Add model source metadata (`RootState.modelSources` and `SessionModelInfo.modelSourceId`) so clients can label and group an agent's models by service or subscription while keeping model IDs unique and stable per agent.", "details": [ "```json", "{", - " \"provider\": \"example\",", - " \"modelSources\": [{ \"id\": \"source-a\", \"displayName\": \"Service A\" }],", - " \"models\": [", - " { \"id\": \"model-a\", \"provider\": \"example\", \"name\": \"Model\", \"modelSourceId\": \"source-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\" }]", + " }]", "}", "```", "Read more in [Root Channel — Model sources](https://microsoft.github.io/agent-host-protocol/specification/root-channel#model-sources)." 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..44a8a9e91 --- /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. `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 new file mode 100644 index 000000000..90a00bd09 --- /dev/null +++ b/docs/.changes/20261123-model-source-registry.json @@ -0,0 +1,19 @@ +{ + "type": "added", + "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/.vitepress/config.mts b/docs/.vitepress/config.mts index 54b7002f3..f51d9ddf2 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 17b31192a..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). 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`, `root/modelSourceRegisterRequested`, and `root/modelSourceRemoved` are client-dispatchable; the rest are server-originated. | Type | Client-dispatchable? | When | |---|---|---| @@ -31,6 +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/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` | ## Automation Catalogue Actions diff --git a/docs/guide/model-sources.md b/docs/guide/model-sources.md new file mode 100644 index 000000000..834a5c8c4 --- /dev/null +++ b/docs/guide/model-sources.md @@ -0,0 +1,129 @@ +# 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 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 `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.registration !== 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[] + registration?: { // absent on built-in sources + format: string + definition: Record // how the agent reaches the source; never a credential + } + 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. `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`. + +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`. 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). + +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 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 + +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 + [*] --> 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/modelSourceRegisterRequested (registration) + H-->>C: root/modelSourceSet (authRequired, credentialResource) + + C->>H: authenticate({ resource, token, accountId, target: { kind: 'modelSource', modelSourceId } }) + H-->>C: {} + + H-->>C: root/modelSourceSet (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 `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 + +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. + +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. 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. + +## 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/guide/state-model.md b/docs/guide/state-model.md index 8a4013c6e..125cc1ead 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 + modelSources?: ModelSource[] // sources agents offer models from } ``` diff --git a/docs/proposals/model-source-registry.md b/docs/proposals/model-source-registry.md index 3b80237dd..b1c5f35cd 100644 --- a/docs/proposals/model-source-registry.md +++ b/docs/proposals/model-source-registry.md @@ -4,7 +4,12 @@ ## 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/` 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` 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`. 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..50afda939 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)): +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 @@ -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,55 @@ 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. 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 [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 +{ + "jsonrpc": "2.0", + "id": 5, + "method": "authenticate", + "params": { + "channel": "ahp-root://", + "resource": "https://api.example.com/v1", + "token": "", + "accountId": "keychain-5c2a", + "target": { + "kind": "modelSource", + "modelSourceId": "2f6c0e1a-model-source" + } + } +} +``` + +When `target.kind` is `modelSource`, the host: + +- 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 the credential. + +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. + +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. + +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`? 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 6891d1f1d..200791682 100644 --- a/docs/specification/root-channel.md +++ b/docs/specification/root-channel.md @@ -22,6 +22,7 @@ RootState { activeSessions?: number terminals?: TerminalInfo[] config?: RootConfigState + modelSources?: ModelSource[] } ``` @@ -29,36 +30,23 @@ 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` — 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 `registration`, 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" } - ] -} -``` +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 @@ -111,11 +99,23 @@ 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/modelSourceRegisterRequested`, or `root/modelSourceRemoved`. | `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/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 `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 | + ## 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: @@ -126,6 +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/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` | All root-scoped action envelopes have `channel: "ahp-root://"`. diff --git a/schema/actions.schema.json b/schema/actions.schema.json index 57ef8a323..b167f0db8 100644 --- a/schema/actions.schema.json +++ b/schema/actions.schema.json @@ -127,6 +127,88 @@ "config" ] }, + "RootModelSourceRegisterRequestedAction": { + "type": "object", + "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/modelSourceRegisterRequested" + }, + "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 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", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "type", + "modelSourceId", + "provider", + "displayName", + "registration" + ] + }, + "RootModelSourceSetAction": { + "type": "object", + "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/modelSourceSet" + }, + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or replace, matched by `id`." + } + }, + "required": [ + "type", + "modelSource" + ] + }, + "RootModelSourceRemovedAction": { + "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.", + "properties": { + "type": { + "const": "root/modelSourceRemoved" + }, + "modelSourceId": { + "type": "string", + "description": "The model source's `id`." + } + }, + "required": [ + "type", + "modelSourceId" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -3259,6 +3341,10 @@ "type": "string", "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", "description": "Human-readable error message" @@ -3369,6 +3455,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSources": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSource" + }, + "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", "additionalProperties": {}, @@ -3418,13 +3511,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": [ @@ -3445,6 +3531,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." } } }, @@ -3476,24 +3566,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 {@link AgentInfo.modelSources}." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -3544,7 +3616,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: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -3573,6 +3645,185 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceFormatInfo" + }, + "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 {@link ModelSourceRegistration.format} value." + } + }, + "required": [ + "format" + ] + }, + "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.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "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 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": "How the source was registered. Absent on a source the agent provides\nitself." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "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.\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." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "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}." + } + }, + "required": [ + "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 model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "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\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/ModelSourceAuthRequiredReason", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + } + }, + "required": [ + "reason" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "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", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "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 the host writes. 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.", @@ -9558,6 +9809,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 ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, "SessionOrigin": { "$ref": "#/$defs/AutomationSessionOrigin", "description": "Durable provenance for sessions created by a higher-level AHP workflow." @@ -10183,6 +10451,15 @@ { "$ref": "#/$defs/RootConfigChangedAction" }, + { + "$ref": "#/$defs/RootModelSourceRegisterRequestedAction" + }, + { + "$ref": "#/$defs/RootModelSourceSetAction" + }, + { + "$ref": "#/$defs/RootModelSourceRemovedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -10513,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, @@ -10583,6 +10868,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", @@ -10592,6 +10881,16 @@ "type": "string", "description": "Policy configuration state for a model." }, + "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/commands.schema.json b/schema/commands.schema.json index 6aa8892d6..c66d71d20 100644 --- a/schema/commands.schema.json +++ b/schema/commands.schema.json @@ -1066,9 +1066,26 @@ "customizationId" ] }, + "ModelSourceAuthenticateTarget": { + "type": "object", + "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 source's `ModelSource.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 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", @@ -1083,7 +1100,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`." + "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", @@ -1103,7 +1120,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, 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, 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", @@ -2076,7 +2093,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": { @@ -2609,6 +2633,10 @@ "type": "string", "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", "description": "Human-readable error message" @@ -2719,6 +2747,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSources": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSource" + }, + "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", "additionalProperties": {}, @@ -2768,13 +2803,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": [ @@ -2795,6 +2823,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." } } }, @@ -2826,24 +2858,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 {@link AgentInfo.modelSources}." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -2894,7 +2908,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: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -2923,6 +2937,185 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceFormatInfo" + }, + "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 {@link ModelSourceRegistration.format} value." + } + }, + "required": [ + "format" + ] + }, + "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.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "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 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": "How the source was registered. Absent on a source the agent provides\nitself." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "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.\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." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "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}." + } + }, + "required": [ + "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 model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "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\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/ModelSourceAuthRequiredReason", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + } + }, + "required": [ + "reason" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "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", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "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 the host writes. 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.", @@ -8994,6 +9187,88 @@ "config" ] }, + "RootModelSourceRegisterRequestedAction": { + "type": "object", + "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/modelSourceRegisterRequested" + }, + "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 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", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "type", + "modelSourceId", + "provider", + "displayName", + "registration" + ] + }, + "RootModelSourceSetAction": { + "type": "object", + "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/modelSourceSet" + }, + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or replace, matched by `id`." + } + }, + "required": [ + "type", + "modelSource" + ] + }, + "RootModelSourceRemovedAction": { + "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.", + "properties": { + "type": { + "const": "root/modelSourceRemoved" + }, + "modelSourceId": { + "type": "string", + "description": "The model source's `id`." + } + }, + "required": [ + "type", + "modelSourceId" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -11568,6 +11843,15 @@ { "$ref": "#/$defs/RootConfigChangedAction" }, + { + "$ref": "#/$defs/RootModelSourceRegisterRequestedAction" + }, + { + "$ref": "#/$defs/RootModelSourceSetAction" + }, + { + "$ref": "#/$defs/RootModelSourceRemovedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -12004,6 +12288,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": [ { @@ -12027,6 +12315,33 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSource}, 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`." + }, "SessionStatus": { "type": "integer", "minimum": 0, @@ -12774,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 0ee8929c9..cf78814ec 100644 --- a/schema/errors.schema.json +++ b/schema/errors.schema.json @@ -29,7 +29,8 @@ -32008, -32009, -32010, - -32011 + -32011, + -32013 ] }, "AuthRequiredErrorData": { @@ -543,6 +544,10 @@ "type": "string", "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", "description": "Human-readable error message" @@ -653,6 +658,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSources": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSource" + }, + "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", "additionalProperties": {}, @@ -702,13 +714,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": [ @@ -729,6 +734,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." } } }, @@ -760,24 +769,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 {@link AgentInfo.modelSources}." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -828,7 +819,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: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -857,6 +848,185 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceFormatInfo" + }, + "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 {@link ModelSourceRegistration.format} value." + } + }, + "required": [ + "format" + ] + }, + "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.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "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 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": "How the source was registered. Absent on a source the agent provides\nitself." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "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.\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." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "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}." + } + }, + "required": [ + "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 model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "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\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/ModelSourceAuthRequiredReason", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + } + }, + "required": [ + "reason" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "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", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "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 the host writes. 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.", @@ -7867,9 +8037,26 @@ "customizationId" ] }, + "ModelSourceAuthenticateTarget": { + "type": "object", + "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 source's `ModelSource.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 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", @@ -7884,7 +8071,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`." + "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", @@ -7904,7 +8091,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, 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, 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", @@ -8918,6 +9105,33 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSource}, 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`." + }, "SessionStatus": { "type": "integer", "minimum": 0, @@ -9764,6 +9978,15 @@ { "$ref": "#/$defs/RootConfigChangedAction" }, + { + "$ref": "#/$defs/RootModelSourceRegisterRequestedAction" + }, + { + "$ref": "#/$defs/RootModelSourceSetAction" + }, + { + "$ref": "#/$defs/RootModelSourceRemovedAction" + }, { "$ref": "#/$defs/SessionReadyAction" }, @@ -10118,7 +10341,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": { @@ -10304,6 +10534,88 @@ "config" ] }, + "RootModelSourceRegisterRequestedAction": { + "type": "object", + "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/modelSourceRegisterRequested" + }, + "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 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", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "type", + "modelSourceId", + "provider", + "displayName", + "registration" + ] + }, + "RootModelSourceSetAction": { + "type": "object", + "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/modelSourceSet" + }, + "modelSource": { + "$ref": "#/$defs/ModelSource", + "description": "The model source to add or replace, matched by `id`." + } + }, + "required": [ + "type", + "modelSource" + ] + }, + "RootModelSourceRemovedAction": { + "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.", + "properties": { + "type": { + "const": "root/modelSourceRemoved" + }, + "modelSourceId": { + "type": "string", + "description": "The model source's `id`." + } + }, + "required": [ + "type", + "modelSourceId" + ] + }, "SessionReadyAction": { "type": "object", "description": "Session backend initialized successfully.", @@ -12660,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 07c95e72d..a685e14c9 100644 --- a/schema/notifications.schema.json +++ b/schema/notifications.schema.json @@ -845,6 +845,10 @@ "type": "string", "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", "description": "Human-readable error message" @@ -955,6 +959,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSources": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSource" + }, + "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", "additionalProperties": {}, @@ -1004,13 +1015,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": [ @@ -1031,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." } } }, @@ -1062,24 +1070,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 {@link AgentInfo.modelSources}." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -1130,7 +1120,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: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -1159,6 +1149,185 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceFormatInfo" + }, + "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 {@link ModelSourceRegistration.format} value." + } + }, + "required": [ + "format" + ] + }, + "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.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "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 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": "How the source was registered. Absent on a source the agent provides\nitself." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "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.\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." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "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}." + } + }, + "required": [ + "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 model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "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\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/ModelSourceAuthRequiredReason", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + } + }, + "required": [ + "reason" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "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", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "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 the host writes. 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.", @@ -7156,6 +7325,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": [ { @@ -7179,6 +7352,33 @@ "type": "string", "description": "Policy configuration state for a model." }, + "ModelSourceState": { + "oneOf": [ + { + "$ref": "#/$defs/ModelSourceStartingState" + }, + { + "$ref": "#/$defs/ModelSourceReadyState" + }, + { + "$ref": "#/$defs/ModelSourceAuthRequiredState" + }, + { + "$ref": "#/$defs/ModelSourceErrorState" + } + ], + "description": "Lifecycle state of a {@link ModelSource}, 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 4d8855fc5..b0370ee33 100644 --- a/schema/state.schema.json +++ b/schema/state.schema.json @@ -454,6 +454,10 @@ "type": "string", "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", "description": "Human-readable error message" @@ -564,6 +568,13 @@ "$ref": "#/$defs/RootConfigState", "description": "Agent host configuration schema and current values" }, + "modelSources": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSource" + }, + "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", "additionalProperties": {}, @@ -613,13 +624,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": [ @@ -640,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." } } }, @@ -671,24 +679,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 {@link AgentInfo.modelSources}." - }, - "displayName": { - "type": "string", - "description": "Human-readable name" - } - }, - "required": [ - "id", - "displayName" - ] - }, "SessionModelInfo": { "type": "object", "properties": { @@ -739,7 +729,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: the {@link ModelSource.id} of an entry\nin {@link RootState.modelSources} whose `provider` is this model's\n{@link provider}." } }, "required": [ @@ -768,6 +758,185 @@ "id" ] }, + "ModelSourceRegistrationCapability": { + "type": "object", + "description": "Options for the {@link AgentCapabilities.modelSourceRegistration} capability.\n\nStability: 1.0 - Early development.", + "properties": { + "formats": { + "type": "array", + "items": { + "$ref": "#/$defs/ModelSourceFormatInfo" + }, + "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 {@link ModelSourceRegistration.format} value." + } + }, + "required": [ + "format" + ] + }, + "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.\n\nStability: 1.0 - Early development.", + "properties": { + "id": { + "type": "string", + "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 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": "How the source was registered. Absent on a source the agent provides\nitself." + }, + "state": { + "$ref": "#/$defs/ModelSourceState", + "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.\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." + }, + "_meta": { + "type": "object", + "additionalProperties": {}, + "description": "Additional implementation-defined metadata for this model source.\nMUST NOT contain a credential." + } + }, + "required": [ + "id", + "provider", + "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}." + } + }, + "required": [ + "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 model source's `provider`. They stay listed through later `starting`\nand `authRequired` states.\n\nStability: 1.0 - Early development.", + "properties": { + "kind": { + "const": "ready" + } + }, + "required": [ + "kind" + ] + }, + "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\nmodel source's {@link ModelSource.credentialResource}.\n\nStability: 1.0 - Early development.", + "properties": { + "reason": { + "$ref": "#/$defs/ModelSourceAuthRequiredReason", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + } + }, + "required": [ + "reason" + ] + }, + "ModelSourceAuthRequiredState": { + "type": "object", + "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", + "description": "Why a credential is needed." + }, + "description": { + "type": "string", + "description": "Human-readable hint the host writes, for example \"The endpoint rejected\nthe API key.\"" + }, + "kind": { + "const": "authRequired" + } + }, + "required": [ + "reason", + "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 the host writes. 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.", @@ -6753,6 +6922,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 ModelSource}, discriminated by\n`kind` (a {@link ModelSourceStatus} value)." + }, "SessionOrigin": { "$ref": "#/$defs/AutomationSessionOrigin", "description": "Durable provenance for sessions created by a higher-level AHP workflow." @@ -7376,6 +7562,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", @@ -7385,6 +7575,16 @@ "type": "string", "description": "Policy configuration state for a model." }, + "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`." + }, "SessionStatus": { "type": "integer", "minimum": 0, diff --git a/scripts/generate-csharp.ts b/scripts/generate-csharp.ts index f03690e66..83d0bbe50 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. @@ -786,6 +787,7 @@ const STATE_ENUMS = [ 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', 'AutomationDisableConditionKind', @@ -809,7 +811,15 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; csName?: strin { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, - { name: 'ModelSourceInfo' }, + { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceFormatInfo' }, + { name: 'ModelSourceRegistration' }, + { name: 'ModelSource' }, + { name: 'ModelSourceStartingState' }, + { name: 'ModelSourceReadyState' }, + { name: 'ModelSourceAuthRequirement' }, + { name: 'ModelSourceAuthRequiredState' }, + { name: 'ModelSourceErrorState' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, { name: 'AgentSelection' }, @@ -1395,6 +1405,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', @@ -1787,7 +1810,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, @@ -1814,6 +1838,9 @@ 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/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, + { 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 @@ -2548,6 +2575,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' }, @@ -2587,6 +2615,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' }, ], }; @@ -3111,7 +3140,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 b8be359c3..c2d90ab3b 100644 --- a/scripts/generate-go.ts +++ b/scripts/generate-go.ts @@ -762,6 +762,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -784,7 +785,15 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; goName?: strin { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, - { name: 'ModelSourceInfo' }, + { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceFormatInfo' }, + { name: 'ModelSourceRegistration' }, + { name: 'ModelSource' }, + { name: 'ModelSourceStartingState' }, + { name: 'ModelSourceReadyState' }, + { name: 'ModelSourceAuthRequirement' }, + { name: 'ModelSourceAuthRequiredState' }, + { name: 'ModelSourceErrorState' }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, { name: 'AgentSelection' }, @@ -1156,6 +1165,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', @@ -1762,6 +1784,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)); @@ -1809,6 +1833,9 @@ 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/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, + { 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' }, @@ -2062,6 +2089,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' }, @@ -2081,6 +2109,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, }; @@ -2433,6 +2462,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 or turn needs a registered model source that can't serve it. +\tErrorCodeModelSourceUnavailable int32 = -32013 ) // AhpErrorCode is the type alias used by AHP application error codes. @@ -2754,6 +2785,7 @@ function checkExhaustiveness(project: Project): void { 'ChildCustomizationType', 'CustomizationLoadState', 'McpServerState', + 'ModelSourceState', 'ToolCallContributor', 'ToolCallRiskAssessment', 'TerminalLifecycleState', 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 c0f43d7e9..2749ed380 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. @@ -1119,6 +1120,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -1137,7 +1139,10 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', + 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceRegistration', 'ModelSourceStartingState', + 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', + 'ModelSourceErrorState', + 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', 'BackgroundShellWork', 'BackgroundSubagentWork', 'CanvasReference', 'CanvasState', @@ -1442,6 +1447,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', @@ -1674,6 +1691,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)); @@ -1802,6 +1821,9 @@ 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/modelSourceSet', caseName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', caseName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, + { 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' }, @@ -2020,7 +2042,7 @@ const COMMAND_STRUCTS = [ 'FetchTurnsParams', 'FetchTurnsResult', 'FetchDeferredTurnsParams', 'FetchDeferredTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', - 'McpServerAuthenticateTarget', + 'McpServerAuthenticateTarget', 'ModelSourceAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', 'CreateTerminalParams', 'DisposeTerminalParams', 'ResolveSessionConfigParams', 'ResolveSessionConfigResult', @@ -2040,6 +2062,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { discriminantField: 'kind', variants: [ { caseName: 'McpServer', structName: 'McpServerAuthenticateTarget', discriminantValue: 'mcpServer' }, + { caseName: 'ModelSource', structName: 'ModelSourceAuthenticateTarget', discriminantValue: 'modelSource' }, ], injectDiscriminantOnSerialize: true, }; @@ -2420,6 +2443,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 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(''); @@ -2683,6 +2708,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 5637bdc08..adb33699a 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'; @@ -858,6 +859,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -885,7 +887,15 @@ const STATE_STRUCTS: { name: string; omitDiscriminants?: boolean; rustName?: str { name: 'AgentCapabilities' }, { name: 'MultipleChatsCapability' }, { name: 'MultipleWorkingDirectoriesCapability' }, - { name: 'ModelSourceInfo' }, + { name: 'ModelSourceRegistrationCapability' }, + { name: 'ModelSourceFormatInfo' }, + { name: 'ModelSourceRegistration' }, + { name: 'ModelSource' }, + { name: 'ModelSourceStartingState', omitDiscriminants: true }, + { name: 'ModelSourceReadyState', omitDiscriminants: true }, + { name: 'ModelSourceAuthRequirement' }, + { name: 'ModelSourceAuthRequiredState', omitDiscriminants: true }, + { name: 'ModelSourceErrorState', omitDiscriminants: true }, { name: 'SessionModelInfo' }, { name: 'ModelSelection' }, { name: 'AgentSelection' }, @@ -1261,6 +1271,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', @@ -1740,6 +1763,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)); @@ -1786,6 +1811,9 @@ 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/modelSourceSet', variantName: 'RootModelSourceSet', tsInterface: 'RootModelSourceSetAction', boxed: true }, + { type: 'root/modelSourceRemoved', variantName: 'RootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, + { 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' }, @@ -1972,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};'); + 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'); @@ -2120,6 +2148,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' }, @@ -2139,6 +2168,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' }, ], }; @@ -2465,6 +2495,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 or turn needs a registered model source that can't serve it. + pub const MODEL_SOURCE_UNAVAILABLE: i32 = -32013; } /// Type alias: AHP application error code. @@ -2714,6 +2746,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 4e8853817..2f4290b65 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. @@ -736,6 +737,7 @@ const STATE_ENUMS = [ 'TerminalClaimKind', 'TerminalLifecycleStatus', 'BackgroundWorkKind', 'McpServerStatus', 'McpAuthRequiredReason', + 'ModelSourceStatus', 'ModelSourceRetentionPolicy', 'ModelSourceAuthRequiredReason', 'ChangesetStatus', 'ChangesetFileStatus', 'ChangesetOperationStatus', 'ChangesetOperationScope', 'ResourceChangeType', 'SessionOriginKind', 'AutomationOperation', 'AutomationMisfirePolicy', 'AutomationTriggerKind', @@ -754,7 +756,10 @@ const STATE_STRUCTS = [ 'AgentCapabilities', 'MultipleChatsCapability', 'MultipleWorkingDirectoriesCapability', - 'ModelSourceInfo', 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', + 'ModelSourceRegistrationCapability', 'ModelSourceFormatInfo', 'ModelSource', 'ModelSourceRegistration', 'ModelSourceStartingState', + 'ModelSourceReadyState', 'ModelSourceAuthRequirement', 'ModelSourceAuthRequiredState', + 'ModelSourceErrorState', + 'SessionModelInfo', 'ModelSelection', 'AgentSelection', 'ConfigPropertySchema', 'ConfigSchema', 'PendingMessage', 'ChatState', 'ChatSummary', 'SideChatSelection', 'SessionState', 'SessionActiveClient', 'BackgroundShellWork', 'BackgroundSubagentWork', 'SessionChatInputRequest', 'SessionToolConfirmationRequest', 'SessionToolClientExecutionRequest', @@ -1009,6 +1014,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', @@ -1602,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)); @@ -1729,6 +1747,9 @@ 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/modelSourceSet', caseName: 'rootModelSourceSet', tsInterface: 'RootModelSourceSetAction' }, + { type: 'root/modelSourceRemoved', caseName: 'rootModelSourceRemoved', tsInterface: 'RootModelSourceRemovedAction' }, + { 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' }, @@ -1984,7 +2005,7 @@ const COMMAND_STRUCTS = [ 'CreateSearchParams', 'CreateSearchResult', 'FetchTurnsParams', 'FetchTurnsResult', 'UnsubscribeParams', 'DispatchActionParams', - 'McpServerAuthenticateTarget', + 'McpServerAuthenticateTarget', 'ModelSourceAuthenticateTarget', 'AuthenticateParams', 'AuthenticateResult', 'CreateTerminalParams', 'DisposeTerminalParams', 'ResolveSessionConfigParams', 'ResolveSessionConfigResult', @@ -2004,6 +2025,7 @@ const AUTHENTICATE_TARGET_UNION: UnionConfig = { discriminantField: 'kind', variants: [ { caseName: 'mcpServer', structName: 'McpServerAuthenticateTarget', discriminantValue: 'mcpServer' }, + { caseName: 'modelSource', structName: 'ModelSourceAuthenticateTarget', discriminantValue: 'modelSource' }, ], injectDiscriminantOnEncode: true, }; @@ -2410,6 +2432,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 or turn needs a registered model source that can't serve it"); + lines.push(' public static let modelSourceUnavailable = -32013'); lines.push('}'); lines.push(''); @@ -2818,6 +2842,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 fd1eca00d..d673c0392 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, 21], [notifications, 6]] as const) { + for (const [file, expected] of [[commands, 22], [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/skills/protocol-authoring/naming.md b/skills/protocol-authoring/naming.md index d5e0d271d..e5c7ed705 100644 --- a/skills/protocol-authoring/naming.md +++ b/skills/protocol-authoring/naming.md @@ -30,8 +30,12 @@ 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** (`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 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. | | **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/types/action-origin.generated.ts b/types/action-origin.generated.ts index 1e227ab92..e738cf2e6 100644 --- a/types/action-origin.generated.ts +++ b/types/action-origin.generated.ts @@ -7,6 +7,9 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, + RootModelSourceRegisterRequestedAction, + RootModelSourceSetAction, + RootModelSourceRemovedAction, SessionReadyAction, SessionCreationFailedAction, SessionChatAddedAction, @@ -127,11 +130,16 @@ export type RootAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction + | RootModelSourceRegisterRequestedAction + | RootModelSourceSetAction + | RootModelSourceRemovedAction ; /** Union of root actions that clients may dispatch. */ export type ClientRootAction = | RootConfigChangedAction + | RootModelSourceRegisterRequestedAction + | RootModelSourceRemovedAction ; /** Union of root actions that only the server may produce. */ @@ -139,6 +147,7 @@ export type ServerRootAction = | RootAgentsChangedAction | RootActiveSessionsChangedAction | RootTerminalsChangedAction + | RootModelSourceSetAction ; /** Union of all session-scoped actions. */ @@ -491,6 +500,9 @@ export const IS_CLIENT_DISPATCHABLE: { readonly [K in StateAction['type']]: bool [ActionType.RootActiveSessionsChanged]: false, [ActionType.RootTerminalsChanged]: false, [ActionType.RootConfigChanged]: true, + [ActionType.RootModelSourceRegisterRequested]: true, + [ActionType.RootModelSourceSet]: false, + [ActionType.RootModelSourceRemoved]: 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..26864b37a 100644 --- a/types/channels-root/actions.ts +++ b/types/channels-root/actions.ts @@ -4,8 +4,9 @@ * @module channels-root/actions */ -import type { AgentInfo } 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'; // ─── Root Actions ──────────────────────────────────────────────────────────── @@ -66,3 +67,70 @@ export interface RootConfigChangedAction { /** When `true`, replaces all config values instead of merging */ replace?: boolean; } + +/** + * 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 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. + */ + _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 replace, matched by `id`. */ + modelSource: ModelSource; +} + +/** + * Removes the model source with the given `modelSourceId`, for every client. + * A no-op when none matches. + * + * @category Root Actions + * @stability 1.0 + * @clientDispatchable + * @see {@link /guide/model-sources#registering-a-source | Model Sources guide} + */ +export interface RootModelSourceRemovedAction { + type: ActionType.RootModelSourceRemoved; + /** The model source's `id`. */ + modelSourceId: string; +} diff --git a/types/channels-root/reducer.ts b/types/channels-root/reducer.ts index e1e7b6665..d239502a6 100644 --- a/types/channels-root/reducer.ts +++ b/types/channels-root/reducer.ts @@ -35,6 +35,35 @@ 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 next = list.slice(); + if (idx < 0) { + next.push(action.modelSource); + } else { + next[idx] = action.modelSource; + } + return { ...state, modelSources: next }; + } + + case ActionType.RootModelSourceRemoved: { + const list = state.modelSources; + if (!list) { + return state; + } + const idx = list.findIndex(source => source.id === action.modelSourceId); + if (idx < 0) { + return state; + } + const next = list.slice(); + next.splice(idx, 1); + return { ...state, modelSources: next }; + } + default: softAssertNever(action, log); return state; diff --git a/types/channels-root/state.ts b/types/channels-root/state.ts index c654a2990..6bee745d5 100644 --- a/types/channels-root/state.ts +++ b/types/channels-root/state.ts @@ -8,6 +8,8 @@ import type { ConfigSchema, + ErrorInfo, + Icon, JsonPrimitive, ProtectedResourceMetadata, } from '../common/state.js'; @@ -42,6 +44,15 @@ export interface RootState { terminals?: TerminalInfo[]; /** Agent host configuration schema and current values */ config?: RootConfigState; + /** + * 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-sources | Model sources} + */ + modelSources?: ModelSource[]; /** * Additional implementation-defined metadata about the agent host itself. * @@ -94,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[]; } /** @@ -133,6 +137,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 /guide/model-sources#registering-a-source | Model Sources guide} + */ + modelSourceRegistration?: ModelSourceRegistrationCapability; } /** @@ -202,19 +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}. */ - id: string; - /** Human-readable name */ - displayName: string; -} - /** * @category Root State */ @@ -224,6 +223,8 @@ export interface SessionModelInfo { * When several model sources serve the same upstream model, the host gives * 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#model-sources | Model sources} */ id: string; /** Agent provider that owns this model. Matches {@link AgentInfo.provider}. */ @@ -264,8 +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}. + * 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; } @@ -289,6 +291,259 @@ export interface ModelSelection { config?: Record; } +// ─── Model Sources ─────────────────────────────────────────────────────────── + +/** + * Options for the {@link AgentCapabilities.modelSourceRegistration} capability. + * + * @category Root State + * @stability 1.0 + */ +export interface ModelSourceRegistrationCapability { + /** Definition formats the agent reads, most preferred first. */ + formats: ModelSourceFormatInfo[]; +} + +/** + * 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 + */ +export interface ModelSourceFormatInfo { + /** A {@link ModelSourceRegistration.format} value. */ + 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. + * + * @category Root State + * @stability 1.0 + * @see {@link /guide/model-sources | Model Sources guide} + */ +export interface ModelSource { + /** + * Host-unique ID, chosen by whoever registers the source. Also the + * {@link SessionModelInfo.modelSourceId} of its models. + */ + id: string; + /** Agent provider whose agent serves the source's models. */ + provider: string; + /** Human-readable name. */ + displayName: string; + /** Icons for UI display. */ + icons?: Icon[]; + /** + * How the source was registered. Absent on a source the agent provides + * itself. + */ + 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. + * + * `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 })`. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + credentialResource?: ProtectedResourceMetadata; + /** + * The {@link AuthenticateParams.accountId} sent with the credential the + * host most recently accepted. + * + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ + accountId?: string; + /** + * Additional implementation-defined metadata for this model source. + * MUST NOT contain a credential. + */ + _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; +} + +/** + * How long a registered model source lasts once its last contributing client + * leaves. + * + * @category Root State + * @stability 1.0 + * @nonexhaustive + */ +export const enum ModelSourceRetentionPolicy { + /** Removed when the last 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 + */ +export interface ModelSourceStartingState { + kind: ModelSourceStatus.Starting; +} + +/** + * 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` + * and `authRequired` states. + * + * @category Root State + * @stability 1.0 + */ +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 /guide/model-sources#credentials | Model Sources guide} + */ +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 ModelSource.accountId} 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 + * model source's {@link ModelSource.credentialResource}. + * + * @category Root State + * @stability 1.0 + */ +export interface ModelSourceAuthRequirement { + /** Why a credential is needed. */ + reason: ModelSourceAuthRequiredReason; + /** + * Human-readable hint the host writes, for example "The endpoint rejected + * the API key." + */ + description?: string; +} + +/** + * The source needs a credential before it can be used. A client answers with + * `authenticate`, the model source's `credentialResource.resource`, and a + * {@link ModelSourceAuthenticateTarget}. + * + * @category Root State + * @stability 1.0 + * @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 + */ +export interface ModelSourceErrorState { + kind: ModelSourceStatus.Error; + /** Error details the host writes. MUST NOT contain the credential. */ + error: ErrorInfo; +} + +/** + * Lifecycle state of a {@link ModelSource}, 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 4b8fd269b..8afc40304 100644 --- a/types/common/actions.ts +++ b/types/common/actions.ts @@ -13,6 +13,9 @@ import type { RootActiveSessionsChangedAction, RootTerminalsChangedAction, RootConfigChangedAction, + RootModelSourceRegisterRequestedAction, + RootModelSourceSetAction, + RootModelSourceRemovedAction, } from '../channels-root/actions.js'; import type { @@ -247,6 +250,9 @@ export const enum ActionType { AnnotationsEntryRemoved = 'annotations/entryRemoved', RootTerminalsChanged = 'root/terminalsChanged', RootConfigChanged = 'root/configChanged', + RootModelSourceRegisterRequested = 'root/modelSourceRegisterRequested', + RootModelSourceSet = 'root/modelSourceSet', + RootModelSourceRemoved = 'root/modelSourceRemoved', TerminalData = 'terminal/data', TerminalInput = 'terminal/input', TerminalResized = 'terminal/resized', @@ -311,6 +317,9 @@ export type StateAction = | RootActiveSessionsChangedAction | RootTerminalsChangedAction | RootConfigChangedAction + | RootModelSourceRegisterRequestedAction + | RootModelSourceSetAction + | RootModelSourceRemovedAction | SessionReadyAction | SessionCreationFailedAction | SessionChatAddedAction diff --git a/types/common/commands.ts b/types/common/commands.ts index d0535dbee..abb2db5c4 100644 --- a/types/common/commands.ts +++ b/types/common/commands.ts @@ -1492,6 +1492,12 @@ export interface ResourceMkdirResult { */ export const enum AuthenticateTargetKind { McpServer = 'mcpServer', + /** + * A {@link ModelSourceAuthenticateTarget}. + * + * @stability 1.0 + */ + ModelSource = 'modelSource', } /** @@ -1511,23 +1517,43 @@ export interface McpServerAuthenticateTarget { customizationId: string; } +/** + * 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 + * @see {@link /specification/authentication#model-source-credentials | Model source credentials} + */ +export interface ModelSourceAuthenticateTarget { + kind: AuthenticateTargetKind.ModelSource; + /** The source's `ModelSource.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 * 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). + * 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 `ModelSource.credentialResource`. * Servers MUST accept any `resource` value they have themselves advertised - * through one of these three mechanisms. + * through one of these mechanisms, subject to the `target` rules. A + * `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 @@ -1560,7 +1586,8 @@ 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 `ModelSource.credentialResource`. */ resource: string; /** Bearer token obtained from the resource's authorization server */ @@ -1594,15 +1621,22 @@ export interface AuthenticateParams extends BaseParams { /** * 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, 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). * * 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/common/errors.ts b/types/common/errors.ts index 6283e13ea..f81aea3f7 100644 --- a/types/common/errors.ts +++ b/types/common/errors.ts @@ -95,6 +95,14 @@ export const AhpErrorCodes = { Conflict: -32011, /** The host could not open the requested TCP connection. */ TcpConnectionOpenFailed: -32012, + /** + * 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} + */ + 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 4616d900d..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 ──────────────────────────────────────────────────────────── @@ -440,6 +441,14 @@ export interface UsageInfo { export interface ErrorInfo { /** Error type identifier */ 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 + */ + errorCode?: AhpErrorCode; /** Human-readable error message */ message: string; /** Stack trace */ 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..5eed7f2a6 --- /dev/null +++ b/types/test-cases/reducers/330-root-modelsourceset-adds-to-absent-registry.json @@ -0,0 +1,55 @@ +{ + "description": "root/modelSourceSet adds a model source to an absent registry", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceSet", + "modelSource": { + "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": "starting" + } + } + } + ], + "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": "starting" + } + } + ] + } +} 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..bc38ef40e --- /dev/null +++ b/types/test-cases/reducers/331-root-modelsourceset-replaces-source.json @@ -0,0 +1,119 @@ +{ + "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" + } + ] + } + }, + "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" + } + ] + } + }, + "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/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..84bb8e4ee --- /dev/null +++ b/types/test-cases/reducers/333-root-modelsourceremoved-removes-by-id.json @@ -0,0 +1,82 @@ +{ + "description": "root/modelSourceRemoved removes the model source with the given modelSourceId", + "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/modelSourceRemoved", + "modelSourceId": "model-source-a" + } + ], + "expected": { + "agents": [], + "modelSources": [ + { + "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/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..677f224bf --- /dev/null +++ b/types/test-cases/reducers/334-root-modelsourceremoved-no-op-for-unknown-id.json @@ -0,0 +1,68 @@ +{ + "description": "root/modelSourceRemoved is a no-op when no model source has the modelSourceId", + "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/modelSourceRemoved", + "modelSourceId": "model-source-missing" + } + ], + "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/335-root-modelsourceremoved-no-op-when-registry-absent.json b/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json new file mode 100644 index 000000000..1d10c86ab --- /dev/null +++ b/types/test-cases/reducers/335-root-modelsourceremoved-no-op-when-registry-absent.json @@ -0,0 +1,16 @@ +{ + "description": "root/modelSourceRemoved is a no-op when the registry is absent", + "reducer": "root", + "initial": { + "agents": [] + }, + "actions": [ + { + "type": "root/modelSourceRemoved", + "modelSourceId": "model-source-a" + } + ], + "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/round-trips/101-model-source-catalog.json b/types/test-cases/round-trips/101-model-source-catalog.json index 0a77f9351..f4b42d750 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,32 @@ } ] } + ], + "modelSources": [ + { + "id": "source-a", + "provider": "example", + "displayName": "Service A", + "state": { + "kind": "ready" + } + }, + { + "id": "source-b", + "provider": "example", + "displayName": "Service B", + "state": { + "kind": "ready" + } + }, + { + "id": "source-c", + "provider": "example", + "displayName": "Service C", + "state": { + "kind": "ready" + } + } ] } } @@ -77,20 +89,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 +117,32 @@ } ] } + ], + "modelSources": [ + { + "id": "source-a", + "provider": "example", + "displayName": "Service A", + "state": { + "kind": "ready" + } + }, + { + "id": "source-b", + "provider": "example", + "displayName": "Service B", + "state": { + "kind": "ready" + } + }, + { + "id": "source-c", + "provider": "example", + "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 new file mode 100644 index 000000000..78d395728 --- /dev/null +++ b/types/test-cases/round-trips/103-model-source-registry-snapshot.json @@ -0,0 +1,526 @@ +{ + "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 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://", + "fromSeq": 4, + "state": { + "agents": [ + { + "provider": "example", + "displayName": "Example", + "description": "Serves registered model sources", + "capabilities": { + "modelSourceRegistration": { + "formats": [ + { + "format": "openaiCompatible" + }, + { + "format": "anthropic" + }, + { + "format": "azureOpenai" + }, + { + "format": "gemini" + }, + { + "format": "example.com/model-source@1" + } + ] + } + }, + "models": [ + { + "id": "builtin-model", + "provider": "example", + "name": "Example built-in model", + "modelSourceId": "source-builtin" + }, + { + "id": "source-ready.8f3a", + "provider": "example", + "name": "Example model", + "vendor": "OpenRouter", + "modelSourceId": "source-ready" + }, + { + "id": "source-auth.c71e", + "provider": "example", + "name": "Example model", + "vendor": "Azure OpenAI", + "modelSourceId": "source-auth" + } + ] + } + ], + "modelSources": [ + { + "id": "source-builtin", + "provider": "example", + "displayName": "Example subscription", + "state": { + "kind": "ready" + } + }, + { + "id": "source-starting", + "provider": "example", + "displayName": "Starting", + "registration": { + "format": "gemini", + "definition": { + "endpoint": "https://gemini.example.com/v1beta", + "models": [ + { + "id": "gemini-model" + } + ] + } + }, + "state": { + "kind": "starting" + } + }, + { + "id": "source-ready", + "provider": "example", + "displayName": "OpenRouter", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "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" + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-openrouter-1", + "_meta": { + "example.com/label": "Laptop" + } + }, + { + "id": "source-auth", + "provider": "example", + "displayName": "Azure endpoint", + "registration": { + "format": "azureOpenai", + "definition": { + "endpoint": "https://example.openai.azure.com/openai/v1", + "apiVersion": "2024-10-21", + "models": [ + { + "id": "example-deployment" + } + ] + } + }, + "state": { + "kind": "authRequired", + "reason": "expired", + "description": "The access token expired." + }, + "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" + ] + }, + "accountId": "entra-azure-1" + }, + { + "id": "source-local", + "provider": "example", + "displayName": "Local server", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "http://localhost:11434/v1", + "wireApi": "responses" + } + }, + "state": { + "kind": "authRequired", + "reason": "required" + }, + "credentialResource": { + "resource": "http://localhost:11434/v1", + "resource_name": "Local server key" + } + }, + { + "id": "source-rejected", + "provider": "example", + "displayName": "Rejected key", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + } + }, + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-rejected-1" + }, + { + "id": "source-revoked", + "provider": "example", + "displayName": "Revoked key", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + } + }, + "state": { + "kind": "authRequired", + "reason": "revoked" + }, + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-revoked-1" + }, + { + "id": "source-host", + "provider": "example", + "displayName": "Host-configured", + "registration": { + "format": "example.com/model-source@1", + "definition": { + "endpoint": "https://models.internal.example.com", + "routing": { + "region": "example-1" + } + } + }, + "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": [ + { + "format": "openaiCompatible" + }, + { + "format": "anthropic" + }, + { + "format": "azureOpenai" + }, + { + "format": "gemini" + }, + { + "format": "example.com/model-source@1" + } + ] + } + }, + "models": [ + { + "id": "builtin-model", + "provider": "example", + "name": "Example built-in model", + "modelSourceId": "source-builtin" + }, + { + "id": "source-ready.8f3a", + "provider": "example", + "name": "Example model", + "vendor": "OpenRouter", + "modelSourceId": "source-ready" + }, + { + "id": "source-auth.c71e", + "provider": "example", + "name": "Example model", + "vendor": "Azure OpenAI", + "modelSourceId": "source-auth" + } + ] + } + ], + "modelSources": [ + { + "id": "source-builtin", + "provider": "example", + "displayName": "Example subscription", + "state": { + "kind": "ready" + } + }, + { + "id": "source-starting", + "provider": "example", + "displayName": "Starting", + "registration": { + "format": "gemini", + "definition": { + "endpoint": "https://gemini.example.com/v1beta", + "models": [ + { + "id": "gemini-model" + } + ] + } + }, + "state": { + "kind": "starting" + } + }, + { + "id": "source-ready", + "provider": "example", + "displayName": "OpenRouter", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "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" + } + }, + "state": { + "kind": "ready" + }, + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-openrouter-1", + "_meta": { + "example.com/label": "Laptop" + } + }, + { + "id": "source-auth", + "provider": "example", + "displayName": "Azure endpoint", + "registration": { + "format": "azureOpenai", + "definition": { + "endpoint": "https://example.openai.azure.com/openai/v1", + "apiVersion": "2024-10-21", + "models": [ + { + "id": "example-deployment" + } + ] + } + }, + "state": { + "kind": "authRequired", + "reason": "expired", + "description": "The access token expired." + }, + "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" + ] + }, + "accountId": "entra-azure-1" + }, + { + "id": "source-local", + "provider": "example", + "displayName": "Local server", + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "http://localhost:11434/v1", + "wireApi": "responses" + } + }, + "state": { + "kind": "authRequired", + "reason": "required" + }, + "credentialResource": { + "resource": "http://localhost:11434/v1", + "resource_name": "Local server key" + } + }, + { + "id": "source-rejected", + "provider": "example", + "displayName": "Rejected key", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + } + }, + "state": { + "kind": "authRequired", + "reason": "rejected", + "description": "The endpoint rejected the API key." + }, + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-rejected-1" + }, + { + "id": "source-revoked", + "provider": "example", + "displayName": "Revoked key", + "icons": [ + { + "src": "https://example.com/openrouter.svg" + } + ], + "registration": { + "format": "openaiCompatible", + "definition": { + "endpoint": "https://api.example.com/v1", + "models": [ + { + "id": "vendor/model-a" + } + ] + } + }, + "state": { + "kind": "authRequired", + "reason": "revoked" + }, + "credentialResource": { + "resource": "https://api.example.com/v1", + "resource_name": "OpenRouter API key" + }, + "accountId": "keychain-revoked-1" + }, + { + "id": "source-host", + "provider": "example", + "displayName": "Host-configured", + "registration": { + "format": "example.com/model-source@1", + "definition": { + "endpoint": "https://models.internal.example.com", + "routing": { + "region": "example-1" + } + } + }, + "state": { + "kind": "error", + "error": { + "errorType": "policy", + "message": "The endpoint is not allowed by host policy." + } + } + } + ] + } + } + ] +} 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 new file mode 100644 index 000000000..e3caf2bfc --- /dev/null +++ b/types/test-cases/round-trips/104-root-model-source-register-requested.json @@ -0,0 +1,64 @@ +{ + "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, 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", + "modelSourceId": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "registration": { + "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" + } + } + }, + "retention": "host" + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceRegisterRequested", + "modelSourceId": "source-new", + "provider": "example", + "displayName": "OpenRouter", + "registration": { + "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" + } + } + }, + "retention": "host" + } + ] +} 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..78779e57c --- /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", + "modelSourceId": "source-new" + }, + "acceptableOutputs": [ + { + "type": "root/modelSourceRemoved", + "modelSourceId": "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 new file mode 100644 index 000000000..678e0d511 --- /dev/null +++ b/types/test-cases/round-trips/106-authenticate-model-source-target.json @@ -0,0 +1,28 @@ +{ + "name": "authenticate-model-source-target", + "group": "A", + "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://", + "resource": "https://openrouter.ai/api/v1", + "token": "test-api-key", + "accountId": "keychain-openrouter-1", + "target": { + "kind": "modelSource", + "modelSourceId": "source-new" + } + }, + "acceptableOutputs": [ + { + "channel": "ahp-root://", + "resource": "https://openrouter.ai/api/v1", + "token": "test-api-key", + "accountId": "keychain-openrouter-1", + "target": { + "kind": "modelSource", + "modelSourceId": "source-new" + } + } + ] +} 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..507d3a56d --- /dev/null +++ b/types/test-cases/round-trips/107-root-model-source-set.json @@ -0,0 +1,66 @@ +{ + "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" + } + ] + } + }, + "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" + } + ] + } + }, + "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/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 + } + } + ] +} diff --git a/types/version/registry.ts b/types/version/registry.ts index b19027d6a..4e2f22117 100644 --- a/types/version/registry.ts +++ b/types/version/registry.ts @@ -187,6 +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.TerminalData]: '0.1.0', [ActionType.TerminalInput]: '0.1.0', [ActionType.TerminalResized]: '0.1.0',