From d726f4d6bc891d7da70abcdf22893fd0f603b7f6 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 11:48:14 +0100 Subject: [PATCH 01/20] Reject unmappable shapes; require .asOpaqueJson() opt-in for JsonElement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C# codegen now hard-errors instead of falling back to `object` for unmappable schema nodes. Schemas tagged with `x-opaque-json: true` map to `JsonElement`/`JsonElement?`. Hand-written types that round-trip arbitrary JSON (ToolInvocation.Arguments, ToolResultObject.ToolTelemetry, hook *Input* ToolArgs/ToolResult) are retyped to JsonElement to match the generated wire types. Boundary code in Session/Client/SessionFsProvider converts between the hand-written user-facing object?-typed dictionaries (ElicitationSchema.Properties, ElicitationResult.Content) and the wire JsonElement form. This is the SDK side of github/copilot-agent-runtime#8375 — replays the non-Generated/* changes from the reverted PR #1343. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Client.cs | 9 +- dotnet/src/Generated/Rpc.cs | 90 +++++++++++-------- dotnet/src/Generated/SessionEvents.cs | 43 +++++---- dotnet/src/Session.cs | 77 ++++++++-------- dotnet/src/SessionFsProvider.cs | 22 ++++- dotnet/src/Types.cs | 10 +-- .../E2E/HookLifecycleAndOutputE2ETests.cs | 2 +- .../E2E/InMemorySessionFsSqliteHandler.cs | 4 +- dotnet/test/E2E/PendingWorkResumeE2ETests.cs | 9 +- dotnet/test/E2E/RpcMcpConfigE2ETests.cs | 8 +- .../test/E2E/RpcTasksAndHandlersE2ETests.cs | 3 +- dotnet/test/E2E/SessionFsE2ETests.cs | 2 +- dotnet/test/E2E/ToolResultsE2ETests.cs | 6 +- dotnet/test/TestJsonContext.cs | 16 ++++ .../Unit/SessionEventSerializationTests.cs | 2 +- scripts/codegen/csharp.ts | 42 +++++++-- 16 files changed, 211 insertions(+), 134 deletions(-) create mode 100644 dotnet/test/TestJsonContext.cs diff --git a/dotnet/src/Client.cs b/dotnet/src/Client.cs index 11f8c90c9..4339754c7 100644 --- a/dotnet/src/Client.cs +++ b/dotnet/src/Client.cs @@ -1803,7 +1803,7 @@ public async ValueTask OnSystemMessageTransfo public async ValueTask OnToolCallV2(string sessionId, string toolCallId, string toolName, - object? arguments, + JsonElement? arguments, string? traceparent = null, string? tracestate = null) { @@ -1840,13 +1840,8 @@ public async ValueTask OnToolCallV2(string sessionId, } }; - if (arguments is not null) + if (arguments is JsonElement incomingJsonArgs) { - if (arguments is not JsonElement incomingJsonArgs) - { - throw new InvalidOperationException($"Incoming arguments must be a {nameof(JsonElement)}; received {arguments.GetType().Name}"); - } - foreach (var prop in incomingJsonArgs.EnumerateObject()) { aiFunctionArgs[prop.Name] = prop.Value; diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index db7ce9d4c..c854cfcee 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -247,7 +247,7 @@ public sealed class Tool /// JSON Schema for the tool's input parameters. [JsonPropertyName("parameters")] - public IDictionary? Parameters { get; set; } + public IDictionary? Parameters { get; set; } } /// Built-in tools available for the requested model, with their parameters and instructions. @@ -362,7 +362,7 @@ public sealed class McpConfigList { /// All MCP servers from user config, keyed by name. [JsonPropertyName("servers")] - public IDictionary Servers { get => field ??= new Dictionary(); set; } + public IDictionary Servers { get => field ??= new Dictionary(); set; } } /// MCP server name and configuration to add to user configuration. @@ -370,7 +370,7 @@ internal sealed class McpConfigAddRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). [JsonPropertyName("config")] - public object Config { get; set; } = null!; + public JsonElement Config { get; set; } /// Unique name for the MCP server. [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] @@ -385,7 +385,7 @@ internal sealed class McpConfigUpdateRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). [JsonPropertyName("config")] - public object Config { get; set; } = null!; + public JsonElement Config { get; set; } /// Name of the MCP server to update. [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] @@ -1058,7 +1058,7 @@ public sealed class InstalledPlugin /// Source for direct repo installs (when marketplace is empty). [JsonPropertyName("source")] - public object? Source { get; set; } + public JsonElement? Source { get; set; } /// Version installed (if available). [JsonPropertyName("version")] @@ -1332,7 +1332,7 @@ internal sealed class SendRequest /// Optional provenance tag copied to the resulting user.message event. Supported values are `system`, `command-*`, and `schedule-*`. [JsonPropertyName("source")] - public object? Source { get; set; } + public JsonElement? Source { get; set; } /// W3C Trace Context traceparent header for distributed tracing of this agent turn. [JsonPropertyName("traceparent")] @@ -2604,7 +2604,7 @@ public sealed class AgentInfo /// MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. [JsonPropertyName("mcpServers")] - public IDictionary? McpServers { get; set; } + public IDictionary? McpServers { get; set; } /// Preferred model id for this agent. When omitted, inherits the outer agent's model. [JsonPropertyName("model")] @@ -3460,7 +3460,7 @@ internal sealed class McpExecuteSamplingParams { /// The original MCP JSON-RPC request ID (string or number). Used by the runtime to correlate the inference with the originating MCP request for telemetry; this is distinct from `requestId` (which is the schema-level cancellation handle). [JsonPropertyName("mcpRequestId")] - public object McpRequestId { get; set; } = null!; + public JsonElement McpRequestId { get; set; } /// Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. [JsonPropertyName("request")] @@ -3654,7 +3654,7 @@ public sealed class SessionInstalledPlugin /// Source descriptor for direct repo installs (when marketplace is empty). [JsonPropertyName("source")] - public object? Source { get; set; } + public JsonElement? Source { get; set; } /// Installed version, if known. [JsonPropertyName("version")] @@ -3667,7 +3667,7 @@ internal sealed class SessionUpdateOptionsParams { /// Additional content-exclusion policies to merge into the session's policy set. Opaque shape; see `ContentExclusionApiResponse` in the runtime. [JsonPropertyName("additionalContentExclusionPolicies")] - public IList? AdditionalContentExclusionPolicies { get; set; } + public IList? AdditionalContentExclusionPolicies { get; set; } /// Runtime context discriminator (e.g., `cli`, `actions`). [JsonPropertyName("agentContext")] @@ -3771,7 +3771,7 @@ internal sealed class SessionUpdateOptionsParams /// Custom model-provider configuration (BYOK). Opaque shape; see `ProviderConfig` in the runtime. [JsonPropertyName("provider")] - public object? Provider { get; set; } + public JsonElement? Provider { get; set; } /// Reasoning effort for the selected model (model-defined enum). [JsonPropertyName("reasoningEffort")] @@ -3783,7 +3783,7 @@ internal sealed class SessionUpdateOptionsParams /// Sandbox configuration shape; opaque to SDK consumers. See `SandboxConfig` in the runtime. [JsonPropertyName("sandboxConfig")] - public object? SandboxConfig { get; set; } + public JsonElement? SandboxConfig { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] @@ -3936,7 +3936,7 @@ internal sealed class HandlePendingToolCallRequest /// Tool call result (string or expanded result object). [JsonPropertyName("result")] - public object? Result { get; set; } + public JsonElement? Result { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] @@ -4353,7 +4353,7 @@ public sealed class UIElicitationResponse /// The form values submitted by the user (present when action is 'accept'). [JsonPropertyName("content")] - public IDictionary? Content { get; set; } + public IDictionary? Content { get; set; } } /// JSON Schema describing the form fields to present to the user. @@ -4362,7 +4362,7 @@ public sealed class UIElicitationSchema { /// Form field definitions, keyed by field name. [JsonPropertyName("properties")] - public IDictionary Properties { get => field ??= new Dictionary(); set; } + public IDictionary Properties { get => field ??= new Dictionary(); set; } /// List of required field names. [JsonPropertyName("required")] @@ -4622,7 +4622,7 @@ public sealed class PermissionsConfigureAdditionalContentExclusionPolicy { /// Gets or sets the last_updated_at value. [JsonPropertyName("last_updated_at")] - public object LastUpdatedAt { get; set; } = null!; + public JsonElement LastUpdatedAt { get; set; } /// Gets or sets the rules value. [JsonPropertyName("rules")] @@ -6296,10 +6296,27 @@ public sealed class HistoryCompactResult public long TokensRemoved { get; set; } } -/// Identifies the target session. +/// Optional compaction parameters. +[Experimental(Diagnostics.Experimental)] +public sealed class HistoryCompactRequest +{ + /// Optional user-provided instructions to focus the compaction summary. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MaxLength(4000)] + [JsonPropertyName("customInstructions")] + public string? CustomInstructions { get; set; } +} + +/// Optional compaction parameters. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionHistoryCompactRequest +internal sealed class HistoryCompactRequestWithSession { + /// Optional user-provided instructions to focus the compaction summary. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MaxLength(4000)] + [JsonPropertyName("customInstructions")] + public string? CustomInstructions { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; @@ -6484,9 +6501,9 @@ internal sealed class EventLogReadRequest [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - /// Either '*' to receive all event types, or a non-empty list of event types to receive. + /// List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. [JsonPropertyName("types")] - public object? Types { get; set; } + public IList? Types { get; set; } /// Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). [JsonConverter(typeof(MillisecondsTimeSpanConverter))] @@ -7108,7 +7125,7 @@ public sealed class SessionFsSqliteQueryResult /// For SELECT: array of row objects. For others: empty array. [JsonPropertyName("rows")] - public IList> Rows { get => field ??= []; set; } + public IList> Rows { get => field ??= []; set; } /// Number of rows affected (for INSERT/UPDATE/DELETE). [JsonPropertyName("rowsAffected")] @@ -7120,7 +7137,7 @@ public sealed class SessionFsSqliteQueryRequest { /// Optional named bind parameters. [JsonPropertyName("params")] - public IDictionary? Params { get; set; } + public IDictionary? Params { get; set; } /// SQL query to execute. [JsonPropertyName("query")] @@ -10289,10 +10306,9 @@ public async Task ListAsync(CancellationToken cancellationToken = /// Unique name for the MCP server. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - public async Task AddAsync(string name, object config, CancellationToken cancellationToken = default) + public async Task AddAsync(string name, JsonElement config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); - ArgumentNullException.ThrowIfNull(config); var request = new McpConfigAddRequest { Name = name, Config = config }; await CopilotClient.InvokeRpcAsync(_rpc, "mcp.config.add", [request], cancellationToken); @@ -10302,10 +10318,9 @@ public async Task AddAsync(string name, object config, CancellationToken cancell /// Name of the MCP server to update. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - public async Task UpdateAsync(string name, object config, CancellationToken cancellationToken = default) + public async Task UpdateAsync(string name, JsonElement config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); - ArgumentNullException.ThrowIfNull(config); var request = new McpConfigUpdateRequest { Name = name, Config = config }; await CopilotClient.InvokeRpcAsync(_rpc, "mcp.config.update", [request], cancellationToken); @@ -10873,7 +10888,7 @@ public async Task SuspendAsync(CancellationToken cancellationToken = default) /// The to monitor for cancellation requests. The default is . /// Result of sending a user message. [Experimental(Diagnostics.Experimental)] - public async Task SendAsync(string prompt, string? displayPrompt = null, IList? attachments = null, SendMode? mode = null, bool? prepend = null, bool? billable = null, string? requiredTool = null, object? source = null, SendAgentMode? agentMode = null, IDictionary? requestHeaders = null, string? traceparent = null, string? tracestate = null, bool? wait = null, CancellationToken cancellationToken = default) + public async Task SendAsync(string prompt, string? displayPrompt = null, IList? attachments = null, SendMode? mode = null, bool? prepend = null, bool? billable = null, string? requiredTool = null, JsonElement? source = null, SendAgentMode? agentMode = null, IDictionary? requestHeaders = null, string? traceparent = null, string? tracestate = null, bool? wait = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(prompt); _session.ThrowIfDisposed(); @@ -11650,11 +11665,10 @@ public async Task ReloadAsync(CancellationToken cancellationToken = default) /// Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. /// The to monitor for cancellation requests. The default is . /// Outcome of an MCP sampling execution: success result, failure error, or cancellation. - public async Task ExecuteSamplingAsync(string requestId, string serverName, object mcpRequestId, McpExecuteSamplingRequest request, CancellationToken cancellationToken = default) + public async Task ExecuteSamplingAsync(string requestId, string serverName, JsonElement mcpRequestId, McpExecuteSamplingRequest request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(requestId); ArgumentNullException.ThrowIfNull(serverName); - ArgumentNullException.ThrowIfNull(mcpRequestId); ArgumentNullException.ThrowIfNull(request); _session.ThrowIfDisposed(); @@ -11806,7 +11820,7 @@ internal OptionsApi(CopilotSession session) /// Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the per-session schedule registry; this flag only controls tool exposure (typically gated to staff users). /// The to monitor for cancellation requests. The default is . /// Indicates whether the session options patch was applied successfully. - public async Task UpdateAsync(string? model = null, string? reasoningEffort = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, object? provider = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, object? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? skipCustomInstructions = null, IList? disabledInstructionSources = null, bool? coauthorEnabled = null, string? trajectoryFile = null, bool? enableStreaming = null, string? copilotUrl = null, bool? askUserDisabled = null, bool? continueOnAutoMode = null, bool? runningInInteractiveMode = null, bool? enableReasoningSummaries = null, string? agentContext = null, string? eventsLogDirectory = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, CancellationToken cancellationToken = default) + public async Task UpdateAsync(string? model = null, string? reasoningEffort = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, JsonElement? provider = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, JsonElement? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? skipCustomInstructions = null, IList? disabledInstructionSources = null, bool? coauthorEnabled = null, string? trajectoryFile = null, bool? enableStreaming = null, string? copilotUrl = null, bool? askUserDisabled = null, bool? continueOnAutoMode = null, bool? runningInInteractiveMode = null, bool? enableReasoningSummaries = null, string? agentContext = null, string? eventsLogDirectory = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); @@ -11914,7 +11928,7 @@ internal ToolsApi(CopilotSession session) /// Error message if the tool call failed. /// The to monitor for cancellation requests. The default is . /// Indicates whether the external tool call result was handled successfully. - public async Task HandlePendingToolCallAsync(string requestId, object? result = null, string? error = null, CancellationToken cancellationToken = default) + public async Task HandlePendingToolCallAsync(string requestId, JsonElement? result = null, string? error = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(requestId); _session.ThrowIfDisposed(); @@ -12651,14 +12665,15 @@ internal HistoryApi(CopilotSession session) } /// Compacts the session history to reduce context usage. + /// Optional compaction parameters. /// The to monitor for cancellation requests. The default is . /// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. - public async Task CompactAsync(CancellationToken cancellationToken = default) + public async Task CompactAsync(HistoryCompactRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new SessionHistoryCompactRequest { SessionId = _session.SessionId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.compact", [request], cancellationToken); + var rpcRequest = new HistoryCompactRequestWithSession { SessionId = _session.SessionId, CustomInstructions = request?.CustomInstructions }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.compact", [rpcRequest], cancellationToken); } /// Truncates persisted session history to a specific event. @@ -12767,11 +12782,11 @@ internal EventLogApi(CopilotSession session) /// Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. /// Maximum number of events to return in this batch (1–1000, default 200). /// Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). - /// Either '*' to receive all event types, or a non-empty list of event types to receive. + /// List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. /// Agent-scope filter: 'primary' returns only main-agent events plus events whose type starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns events from all agents (matching wildcard-subscription behavior). Default is 'all' to preserve wildcard semantics for catch-up callers. /// The to monitor for cancellation requests. The default is . /// Batch of session events returned by a read, with cursor and continuation metadata. - public async Task ReadAsync(string? cursor = null, int? max = null, TimeSpan? waitMs = null, object? types = null, EventsAgentScope? agentScope = null, CancellationToken cancellationToken = default) + public async Task ReadAsync(string? cursor = null, int? max = null, TimeSpan? waitMs = null, IList? types = null, EventsAgentScope? agentScope = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); @@ -13362,6 +13377,8 @@ public static void RegisterClientSessionApiHandlers(JsonRpc rpc, FuncUser-supplied focus instructions provided to a manual `/compact` invocation. Omitted for automatic compaction and for manual compaction with no focus text. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("customInstructions")] + public string? CustomInstructions { get; set; } + /// Error message if compaction failed. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("error")] @@ -1991,7 +1996,7 @@ public sealed partial class AssistantMessageData /// Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("anthropicAdvisorBlocks")] - public object[]? AnthropicAdvisorBlocks { get; set; } + public JsonElement[]? AnthropicAdvisorBlocks { get; set; } /// Anthropic advisor model ID used for this response, for timeline display on replay. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2260,7 +2265,7 @@ public sealed partial class ToolUserRequestedData /// Arguments for the tool invocation. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("arguments")] - public object? Arguments { get; set; } + public JsonElement? Arguments { get; set; } /// Unique identifier for this tool call. [JsonPropertyName("toolCallId")] @@ -2277,7 +2282,7 @@ public sealed partial class ToolExecutionStartData /// Arguments passed to the tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("arguments")] - public object? Arguments { get; set; } + public JsonElement? Arguments { get; set; } /// Name of the MCP server hosting this tool, when the tool is an MCP tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2380,7 +2385,7 @@ public sealed partial class ToolExecutionCompleteData /// Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolTelemetry")] - public IDictionary? ToolTelemetry { get; set; } + public IDictionary? ToolTelemetry { get; set; } /// Identifier for the agent loop turn this tool was invoked in, matching the corresponding assistant.turn_start event. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2562,7 +2567,7 @@ public sealed partial class HookStartData /// Input data passed to the hook. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("input")] - public object? Input { get; set; } + public JsonElement? Input { get; set; } } /// Hook invocation completion details including output, success status, and error information. @@ -2584,7 +2589,7 @@ public sealed partial class HookEndData /// Output data produced by the hook. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("output")] - public object? Output { get; set; } + public JsonElement? Output { get; set; } /// Whether the hook completed successfully. [JsonPropertyName("success")] @@ -2757,7 +2762,7 @@ public sealed partial class ElicitationCompletedData /// The submitted form data when action is 'accept'; keys match the requested schema fields. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("content")] - public IDictionary? Content { get; set; } + public IDictionary? Content { get; set; } /// Request ID of the resolved elicitation request; clients should dismiss any UI for this request. [JsonPropertyName("requestId")] @@ -2769,7 +2774,7 @@ public sealed partial class SamplingRequestedData { /// The JSON-RPC request ID from the MCP protocol. [JsonPropertyName("mcpRequestId")] - public required object McpRequestId { get; set; } + public required JsonElement McpRequestId { get; set; } /// Unique identifier for this sampling request; used to respond via session.respondToSampling(). [JsonPropertyName("requestId")] @@ -2830,7 +2835,7 @@ public sealed partial class SessionCustomNotificationData /// Source-defined JSON payload for the custom notification. [JsonPropertyName("payload")] - public required object Payload { get; set; } + public required JsonElement Payload { get; set; } /// Namespace for the custom notification producer. [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] @@ -2855,7 +2860,7 @@ public sealed partial class ExternalToolRequestedData /// Arguments to pass to the external tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("arguments")] - public object? Arguments { get; set; } + public JsonElement? Arguments { get; set; } /// Unique identifier for this request; used to respond via session.respondToExternalTool(). [JsonPropertyName("requestId")] @@ -3525,7 +3530,7 @@ public sealed partial class AssistantMessageToolRequest /// Arguments to pass to the tool, format depends on the tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("arguments")] - public object? Arguments { get; set; } + public JsonElement? Arguments { get; set; } /// Resolved intention summary describing what this specific call does. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -3983,7 +3988,7 @@ public sealed partial class SystemMessageMetadata /// Template variables used when constructing the prompt. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("variables")] - public IDictionary? Variables { get; set; } + public IDictionary? Variables { get; set; } } /// Schema for the `SystemNotificationAgentCompleted` type. @@ -4289,7 +4294,7 @@ public sealed partial class PermissionRequestMcp : PermissionRequest /// Arguments to pass to the MCP tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("args")] - public object? Args { get; set; } + public JsonElement? Args { get; set; } /// Whether this MCP tool is read-only (no side effects). [JsonPropertyName("readOnly")] @@ -4391,7 +4396,7 @@ public sealed partial class PermissionRequestCustomTool : PermissionRequest /// Arguments to pass to the custom tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("args")] - public object? Args { get; set; } + public JsonElement? Args { get; set; } /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -4423,7 +4428,7 @@ public sealed partial class PermissionRequestHook : PermissionRequest /// Arguments of the tool call being gated. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolArgs")] - public object? ToolArgs { get; set; } + public JsonElement? ToolArgs { get; set; } /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -4606,7 +4611,7 @@ public sealed partial class PermissionPromptRequestMcp : PermissionPromptRequest /// Arguments to pass to the MCP tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("args")] - public object? Args { get; set; } + public JsonElement? Args { get; set; } /// Name of the MCP server providing the tool. [JsonPropertyName("serverName")] @@ -4704,7 +4709,7 @@ public sealed partial class PermissionPromptRequestCustomTool : PermissionPrompt /// Arguments to pass to the custom tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("args")] - public object? Args { get; set; } + public JsonElement? Args { get; set; } /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -4758,7 +4763,7 @@ public sealed partial class PermissionPromptRequestHook : PermissionPromptReques /// Arguments of the tool call being gated. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolArgs")] - public object? ToolArgs { get; set; } + public JsonElement? ToolArgs { get; set; } /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -5128,7 +5133,7 @@ public sealed partial class ElicitationRequestedSchema { /// Form field definitions, keyed by field name. [JsonPropertyName("properties")] - public required IDictionary Properties { get; set; } + public required IDictionary Properties { get; set; } /// List of required field names. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/dotnet/src/Session.cs b/dotnet/src/Session.cs index fc7d82675..cf449e9be 100644 --- a/dotnet/src/Session.cs +++ b/dotnet/src/Session.cs @@ -640,7 +640,7 @@ private async Task HandleBroadcastEventAsync(SessionEvent sessionEvent) ? new ElicitationSchema { Type = data.RequestedSchema.Type, - Properties = data.RequestedSchema.Properties, + Properties = data.RequestedSchema.Properties.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value), Required = data.RequestedSchema.Required?.ToList() } : null; @@ -690,7 +690,7 @@ await HandleElicitationRequestAsync( /// /// Executes a tool handler and sends the result back via the HandlePendingToolCall RPC. /// - private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, string toolCallId, object? arguments, AIFunction tool) + private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, string toolCallId, JsonElement? arguments, AIFunction tool) { try { @@ -710,13 +710,8 @@ private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, } }; - if (arguments is not null) + if (arguments is JsonElement incomingJsonArgs) { - if (arguments is not JsonElement incomingJsonArgs) - { - throw new InvalidOperationException($"Incoming arguments must be a {nameof(JsonElement)}; received {arguments.GetType().Name}"); - } - foreach (var prop in incomingJsonArgs.EnumerateObject()) { aiFunctionArgs[prop.Name] = prop.Value; @@ -734,9 +729,10 @@ private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, toolName); var toolResultObject = ToolResultObject.ConvertFromInvocationResult(result, tool.JsonSerializerOptions); + var toolResultJson = JsonSerializer.SerializeToElement(toolResultObject, TypesJsonContext.Default.ToolResultObject); var responseRpcTimestamp = Stopwatch.GetTimestamp(); - await Rpc.Tools.HandlePendingToolCallAsync(requestId, toolResultObject, error: null); + await Rpc.Tools.HandlePendingToolCallAsync(requestId, toolResultJson, error: null); LoggingHelpers.LogTiming(_logger, LogLevel.Debug, null, "CopilotSession.ExecuteToolAndRespondAsync response sent successfully. Elapsed={Elapsed}, SessionId={SessionId}, RequestId={RequestId}, ToolCallId={ToolCallId}, Tool={ToolName}", responseRpcTimestamp, @@ -957,7 +953,9 @@ private async Task HandleElicitationRequestAsync(ElicitationContext context, str await Rpc.Ui.HandlePendingElicitationAsync(requestId, new UIElicitationResponse { Action = result.Action, - Content = result.Content + Content = result.Content?.ToDictionary( + kvp => kvp.Key, + kvp => JsonSerializer.SerializeToElement(kvp.Value, TypesJsonContext.Default.Object)) }); LoggingHelpers.LogTiming(_logger, LogLevel.Debug, null, "CopilotSession.HandleElicitationRequestAsync response sent successfully. Elapsed={Elapsed}, SessionId={SessionId}, RequestId={RequestId}", @@ -1009,12 +1007,18 @@ public async Task ElicitAsync(ElicitationParams elicitationPa var schema = new UIElicitationSchema { Type = elicitationParams.RequestedSchema.Type, - Properties = elicitationParams.RequestedSchema.Properties, + Properties = elicitationParams.RequestedSchema.Properties.ToDictionary( + kvp => kvp.Key, + kvp => JsonSerializer.SerializeToElement(kvp.Value, TypesJsonContext.Default.Object)), Required = elicitationParams.RequestedSchema.Required }; var result = await session.Rpc.Ui.ElicitationAsync(elicitationParams.Message, schema, cancellationToken); - return new ElicitationResult { Action = result.Action, Content = result.Content }; + return new ElicitationResult + { + Action = result.Action, + Content = result.Content?.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value) + }; } public async Task ConfirmAsync(string message, CancellationToken cancellationToken) @@ -1026,9 +1030,9 @@ public async Task ConfirmAsync(string message, CancellationToken cancellat var schema = new UIElicitationSchema { Type = "object", - Properties = new Dictionary + Properties = new Dictionary { - ["confirmed"] = new Dictionary { ["type"] = "boolean", ["default"] = true } + ["confirmed"] = JsonDocument.Parse("""{"type":"boolean","default":true}""").RootElement.Clone() }, Required = ["confirmed"] }; @@ -1038,11 +1042,10 @@ public async Task ConfirmAsync(string message, CancellationToken cancellat && result.Content != null && result.Content.TryGetValue("confirmed", out var val)) { - return val switch + return val.ValueKind switch { - bool b => b, - JsonElement { ValueKind: JsonValueKind.True } => true, - JsonElement { ValueKind: JsonValueKind.False } => false, + JsonValueKind.True => true, + JsonValueKind.False => false, _ => false }; } @@ -1057,12 +1060,13 @@ public async Task ConfirmAsync(string message, CancellationToken cancellat session.ThrowIfDisposed(); session.AssertElicitation(); + var enumJson = JsonSerializer.Serialize(options, TypesJsonContext.Default.StringArray); var schema = new UIElicitationSchema { Type = "object", - Properties = new Dictionary + Properties = new Dictionary { - ["selection"] = new Dictionary { ["type"] = "string", ["enum"] = options } + ["selection"] = JsonDocument.Parse($$"""{"type":"string","enum":{{enumJson}}}""").RootElement.Clone() }, Required = ["selection"] }; @@ -1072,12 +1076,7 @@ public async Task ConfirmAsync(string message, CancellationToken cancellat && result.Content != null && result.Content.TryGetValue("selection", out var val)) { - return val switch - { - string s => s, - JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), - _ => val.ToString() - }; + return val.ValueKind == JsonValueKind.String ? val.GetString() : val.ToString(); } return null; @@ -1089,18 +1088,21 @@ public async Task ConfirmAsync(string message, CancellationToken cancellat session.ThrowIfDisposed(); session.AssertElicitation(); - var field = new Dictionary { ["type"] = "string" }; - if (options?.Title != null) field["title"] = options.Title; - if (options?.Description != null) field["description"] = options.Description; - if (options?.MinLength != null) field["minLength"] = options.MinLength; - if (options?.MaxLength != null) field["maxLength"] = options.MaxLength; - if (options?.Format != null) field["format"] = options.Format; - if (options?.Default != null) field["default"] = options.Default; + var fieldNode = new System.Text.Json.Nodes.JsonObject { ["type"] = "string" }; + if (options?.Title != null) fieldNode["title"] = options.Title; + if (options?.Description != null) fieldNode["description"] = options.Description; + if (options?.MinLength != null) fieldNode["minLength"] = options.MinLength; + if (options?.MaxLength != null) fieldNode["maxLength"] = options.MaxLength; + if (options?.Format != null) fieldNode["format"] = options.Format; + if (options?.Default != null) fieldNode["default"] = options.Default; var schema = new UIElicitationSchema { Type = "object", - Properties = new Dictionary { ["value"] = field }, + Properties = new Dictionary + { + ["value"] = JsonDocument.Parse(fieldNode.ToJsonString()).RootElement.Clone() + }, Required = ["value"] }; @@ -1109,12 +1111,7 @@ public async Task ConfirmAsync(string message, CancellationToken cancellat && result.Content != null && result.Content.TryGetValue("value", out var val)) { - return val switch - { - string s => s, - JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), - _ => val.ToString() - }; + return val.ValueKind == JsonValueKind.String ? val.GetString() : val.ToString(); } return null; diff --git a/dotnet/src/SessionFsProvider.cs b/dotnet/src/SessionFsProvider.cs index 12dfc8770..0e7202820 100644 --- a/dotnet/src/SessionFsProvider.cs +++ b/dotnet/src/SessionFsProvider.cs @@ -3,6 +3,7 @@ *--------------------------------------------------------------------------------------------*/ using GitHub.Copilot.Rpc; +using System.Text.Json; namespace GitHub.Copilot; @@ -44,7 +45,7 @@ public interface ISessionFsSqliteProvider Task QueryAsync( SessionFsSqliteQueryType queryType, string query, - IDictionary? bindParams, + IDictionary? bindParams, CancellationToken cancellationToken); /// @@ -287,11 +288,16 @@ async Task ISessionFsHandler.SqliteQueryAsync(Sessio try { - var result = await sqliteProvider.QueryAsync(request.QueryType, request.Query, request.Params, cancellationToken).ConfigureAwait(false); + var bindParams = request.Params?.ToDictionary( + kvp => kvp.Key, + kvp => JsonElementToValue(kvp.Value)); + var result = await sqliteProvider.QueryAsync(request.QueryType, request.Query, bindParams, cancellationToken).ConfigureAwait(false); return new SessionFsSqliteQueryResult { - Rows = result?.Rows ?? [], + Rows = result?.Rows?.Select(row => (IDictionary)row.ToDictionary( + kvp => kvp.Key, + kvp => JsonSerializer.SerializeToElement(kvp.Value, TypesJsonContext.Default.Object))).ToList() ?? [], Columns = result?.Columns ?? [], RowsAffected = result?.RowsAffected ?? 0, LastInsertRowid = result?.LastInsertRowid, @@ -329,4 +335,14 @@ private static SessionFsError ToSessionFsError(Exception ex) : SessionFsErrorCode.UNKNOWN; return new SessionFsError { Code = code, Message = ex.Message }; } + + private static object? JsonElementToValue(JsonElement element) => element.ValueKind switch + { + JsonValueKind.Null => null, + JsonValueKind.True => true, + JsonValueKind.False => false, + JsonValueKind.String => element.GetString(), + JsonValueKind.Number => element.TryGetInt64(out var l) ? l : element.GetDouble(), + _ => element.GetRawText(), + }; } diff --git a/dotnet/src/Types.cs b/dotnet/src/Types.cs index 9cc070f78..75f04fd8b 100644 --- a/dotnet/src/Types.cs +++ b/dotnet/src/Types.cs @@ -559,7 +559,7 @@ public sealed class ToolResultObject /// Custom telemetry data associated with the tool execution. /// [JsonPropertyName("toolTelemetry")] - public IDictionary? ToolTelemetry { get; set; } + public IDictionary? ToolTelemetry { get; set; } /// /// Converts the result of an invocation into a @@ -671,7 +671,7 @@ public sealed class ToolInvocation /// /// Arguments passed to the tool by the language model. /// - public object? Arguments { get; set; } + public JsonElement? Arguments { get; set; } } /// Describes the kind of a permission request result. @@ -1227,7 +1227,7 @@ public sealed class PreToolUseHookInput /// Arguments that will be passed to the tool. /// [JsonPropertyName("toolArgs")] - public object? ToolArgs { get; set; } + public JsonElement? ToolArgs { get; set; } } /// @@ -1305,13 +1305,13 @@ public sealed class PostToolUseHookInput /// Arguments that were passed to the tool. /// [JsonPropertyName("toolArgs")] - public object? ToolArgs { get; set; } + public JsonElement? ToolArgs { get; set; } /// /// Result returned by the tool execution. /// [JsonPropertyName("toolResult")] - public object? ToolResult { get; set; } + public JsonElement? ToolResult { get; set; } } /// diff --git a/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs b/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs index b16ee2b56..3c4407bd7 100644 --- a/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs +++ b/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs @@ -327,7 +327,7 @@ public async Task Should_Allow_PostToolUse_To_Return_ModifiedResult() { TextResultForLlm = "modified by post hook", ResultType = "success", - ToolTelemetry = new Dictionary(), + ToolTelemetry = new Dictionary(), }, SuppressOutput = false, }); diff --git a/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs b/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs index 0ae9c9a7d..4e573ff5c 100644 --- a/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs +++ b/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs @@ -43,7 +43,7 @@ private SqliteConnection GetOrCreateDb() public Task QueryAsync( SessionFsSqliteQueryType queryType, string query, - IDictionary? bindParams, + IDictionary? bindParams, CancellationToken cancellationToken) { sqliteCalls.Add(new SqliteCall(sessionId, queryType.Value, query)); @@ -125,7 +125,7 @@ public Task ExistsAsync(CancellationToken cancellationToken) return Task.FromResult(_db is not null); } - private static void AddParams(SqliteCommand cmd, IDictionary? bindParams) + private static void AddParams(SqliteCommand cmd, IDictionary? bindParams) { if (bindParams is null) return; foreach (var (key, value) in bindParams) diff --git a/dotnet/test/E2E/PendingWorkResumeE2ETests.cs b/dotnet/test/E2E/PendingWorkResumeE2ETests.cs index 889dc0050..ffd214de1 100644 --- a/dotnet/test/E2E/PendingWorkResumeE2ETests.cs +++ b/dotnet/test/E2E/PendingWorkResumeE2ETests.cs @@ -5,6 +5,7 @@ using GitHub.Copilot.Test.Harness; using Microsoft.Extensions.AI; using System.ComponentModel; +using System.Text.Json; using Xunit; using Xunit.Abstractions; using RpcPermissionDecisionApproveOnce = GitHub.Copilot.Rpc.PermissionDecisionApproveOnce; @@ -141,7 +142,7 @@ await session1.SendAsync(new MessageOptions var toolResult = await session2.Rpc.Tools.HandlePendingToolCallAsync( toolEvent.Data.RequestId, - result: "EXTERNAL_RESUMED_BETA"); + result: JsonDocument.Parse("\"EXTERNAL_RESUMED_BETA\"").RootElement.Clone()); Assert.True(toolResult.Success); var answer = await TestHelper.GetFinalAssistantMessageAsync(session2, PendingWorkTimeout); @@ -210,7 +211,7 @@ await session1.SendAsync(new MessageOptions var resumedResult = await session2.Rpc.Tools.HandlePendingToolCallAsync( toolEvent.Data.RequestId, - result: "EXTERNAL_RESUMED_BETA"); + result: JsonDocument.Parse("\"EXTERNAL_RESUMED_BETA\"").RootElement.Clone()); Assert.True(resumedResult.Success); // continuePendingWork=false may interrupt agent continuation before this response, @@ -287,11 +288,11 @@ await Task.WhenAll( var toolB = toolEvents["pending_lookup_b"]; var resultB = await session2.Rpc.Tools.HandlePendingToolCallAsync( toolB.Data.RequestId, - result: "PARALLEL_B_BETA"); + result: JsonDocument.Parse("\"PARALLEL_B_BETA\"").RootElement.Clone()); Assert.True(resultB.Success); var resultA = await session2.Rpc.Tools.HandlePendingToolCallAsync( toolA.Data.RequestId, - result: "PARALLEL_A_ALPHA"); + result: JsonDocument.Parse("\"PARALLEL_A_ALPHA\"").RootElement.Clone()); Assert.True(resultA.Success); await session2.DisposeAsync(); diff --git a/dotnet/test/E2E/RpcMcpConfigE2ETests.cs b/dotnet/test/E2E/RpcMcpConfigE2ETests.cs index d26e5535d..1b4de0ca1 100644 --- a/dotnet/test/E2E/RpcMcpConfigE2ETests.cs +++ b/dotnet/test/E2E/RpcMcpConfigE2ETests.cs @@ -34,11 +34,11 @@ public async Task Should_Call_Server_Mcp_Config_Rpcs() try { - await Client.Rpc.Mcp.Config.AddAsync(serverName, config); + await Client.Rpc.Mcp.Config.AddAsync(serverName, JsonSerializer.SerializeToElement(config, TestSharedJsonContext.Default.DictionaryStringObject)); var afterAdd = await Client.Rpc.Mcp.Config.ListAsync(); Assert.Contains(serverName, afterAdd.Servers.Keys); - await Client.Rpc.Mcp.Config.UpdateAsync(serverName, updatedConfig); + await Client.Rpc.Mcp.Config.UpdateAsync(serverName, JsonSerializer.SerializeToElement(updatedConfig, TestSharedJsonContext.Default.DictionaryStringObject)); var afterUpdate = await Client.Rpc.Mcp.Config.ListAsync(); var updated = GetServerConfig(afterUpdate, serverName); Assert.Equal("node", updated.GetProperty("command").GetString()); @@ -84,7 +84,7 @@ public async Task Should_RoundTrip_Http_Mcp_Oauth_Config_Rpc() try { - await Client.Rpc.Mcp.Config.AddAsync(serverName, config); + await Client.Rpc.Mcp.Config.AddAsync(serverName, JsonSerializer.SerializeToElement(config, TestSharedJsonContext.Default.McpServerConfig)); var afterAdd = await Client.Rpc.Mcp.Config.ListAsync(); var added = GetServerConfig(afterAdd, serverName); Assert.Equal("http", added.GetProperty("type").GetString()); @@ -94,7 +94,7 @@ public async Task Should_RoundTrip_Http_Mcp_Oauth_Config_Rpc() Assert.False(added.GetProperty("oauthPublicClient").GetBoolean()); Assert.Equal("client_credentials", added.GetProperty("oauthGrantType").GetString()); - await Client.Rpc.Mcp.Config.UpdateAsync(serverName, updatedConfig); + await Client.Rpc.Mcp.Config.UpdateAsync(serverName, JsonSerializer.SerializeToElement(updatedConfig, TestSharedJsonContext.Default.McpServerConfig)); var afterUpdate = await Client.Rpc.Mcp.Config.ListAsync(); var updated = GetServerConfig(afterUpdate, serverName); Assert.Equal("https://example.com/updated-mcp", updated.GetProperty("url").GetString()); diff --git a/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs b/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs index 2ed338129..61c8d5878 100644 --- a/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs +++ b/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs @@ -4,6 +4,7 @@ using GitHub.Copilot.Rpc; using GitHub.Copilot.Test.Harness; +using System.Text.Json; using Xunit; using Xunit.Abstractions; @@ -143,7 +144,7 @@ public async Task Should_Return_Expected_Results_For_Missing_Pending_Handler_Req var tool = await session.Rpc.Tools.HandlePendingToolCallAsync( requestId: "missing-tool-request", - result: "tool result"); + result: JsonDocument.Parse("\"tool result\"").RootElement.Clone()); Assert.False(tool.Success); var command = await session.Rpc.Commands.HandlePendingCommandAsync( diff --git a/dotnet/test/E2E/SessionFsE2ETests.cs b/dotnet/test/E2E/SessionFsE2ETests.cs index 7986cddcf..e550babf7 100644 --- a/dotnet/test/E2E/SessionFsE2ETests.cs +++ b/dotnet/test/E2E/SessionFsE2ETests.cs @@ -609,7 +609,7 @@ protected override Task RemoveAsync(string path, bool recursive, bool force, Can protected override Task RenameAsync(string src, string dest, CancellationToken cancellationToken) => Task.FromException(exception); - Task ISessionFsSqliteProvider.QueryAsync(SessionFsSqliteQueryType queryType, string query, IDictionary? bindParams, CancellationToken cancellationToken) => + Task ISessionFsSqliteProvider.QueryAsync(SessionFsSqliteQueryType queryType, string query, IDictionary? bindParams, CancellationToken cancellationToken) => Task.FromException(exception); Task ISessionFsSqliteProvider.ExistsAsync(CancellationToken cancellationToken) => diff --git a/dotnet/test/E2E/ToolResultsE2ETests.cs b/dotnet/test/E2E/ToolResultsE2ETests.cs index 75fd9488e..2167d0af8 100644 --- a/dotnet/test/E2E/ToolResultsE2ETests.cs +++ b/dotnet/test/E2E/ToolResultsE2ETests.cs @@ -111,10 +111,10 @@ static ToolResultAIContent AnalyzeCode([Description("File to analyze")] string f { TextResultForLlm = $"Analysis of {file}: no issues found", ResultType = "success", - ToolTelemetry = new Dictionary + ToolTelemetry = new Dictionary { - ["metrics"] = new Dictionary { ["analysisTimeMs"] = 150 }, - ["properties"] = new Dictionary { ["analyzer"] = "eslint" }, + ["metrics"] = JsonDocument.Parse("""{"analysisTimeMs":150}""").RootElement.Clone(), + ["properties"] = JsonDocument.Parse("""{"analyzer":"eslint"}""").RootElement.Clone(), }, }); } diff --git a/dotnet/test/TestJsonContext.cs b/dotnet/test/TestJsonContext.cs new file mode 100644 index 000000000..12a576510 --- /dev/null +++ b/dotnet/test/TestJsonContext.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +using System.Text.Json.Serialization; + +namespace GitHub.Copilot.Test; + +[JsonSourceGenerationOptions(System.Text.Json.JsonSerializerDefaults.Web)] +[JsonSerializable(typeof(string[]))] +[JsonSerializable(typeof(Dictionary))] +[JsonSerializable(typeof(Dictionary))] +[JsonSerializable(typeof(McpServerConfig))] +[JsonSerializable(typeof(McpHttpServerConfig))] +[JsonSerializable(typeof(McpStdioServerConfig))] +internal partial class TestSharedJsonContext : JsonSerializerContext; diff --git a/dotnet/test/Unit/SessionEventSerializationTests.cs b/dotnet/test/Unit/SessionEventSerializationTests.cs index 3e6d4661f..608b47458 100644 --- a/dotnet/test/Unit/SessionEventSerializationTests.cs +++ b/dotnet/test/Unit/SessionEventSerializationTests.cs @@ -66,7 +66,7 @@ public class SessionEventSerializationTests Content = "ok", DetailedContent = "ok", }, - ToolTelemetry = new Dictionary + ToolTelemetry = new Dictionary { ["properties"] = ParseJsonElement("""{"command":"view"}"""), ["metrics"] = ParseJsonElement("""{"resultLength":2}"""), diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index f35c0a52b..1ed1729a6 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -275,9 +275,33 @@ function isNonNullableCSharpValueType(typeName: string): boolean { "long", "DateTimeOffset", "TimeSpan", + "JsonElement", ].includes(typeName) || generatedEnums.has(typeName) || emittedRpcEnumResultTypes.has(typeName) || externalRpcValueTypes.has(typeName); } +/** + * Schemas marked `.asOpaqueJson()` on the runtime side carry + * `x-opaque-json: true`. These are the only shapes that legitimately surface + * as opaque JSON in the SDK (mapped to `JsonElement` in C#). Anything else + * that lacks an idiomatic mapping (untyped fields, non-discriminated unions, + * etc.) is rejected by the runtime's schema-shape lint, so the codegen + * treats reaching an unmappable schema here as a bug. + */ +function isOpaqueJson(schema: JSONSchema7 | undefined): boolean { + if (!schema || typeof schema !== "object") return false; + return (schema as Record)["x-opaque-json"] === true; +} + +function failUnmappable(context: string, schema: JSONSchema7): never { + const summary = JSON.stringify(schema, (key, value) => (key === "description" ? undefined : value)).slice(0, 200); + throw new Error( + `C# codegen: cannot map schema to an idiomatic C# type (${context}). ` + + `On the runtime side, either tighten the Zod schema to a typed shape, or — if it is genuinely free-form JSON — ` + + `mark it \`.asOpaqueJson()\` so the schema emits \`x-opaque-json: true\` and the codegen maps it to JsonElement. ` + + `Offending schema (truncated): ${summary}`, + ); +} + function requiresArgumentNullCheck(typeName: string, isRequired: boolean): boolean { return isRequired && !typeName.endsWith("?") && !isNonNullableCSharpValueType(typeName); } @@ -309,6 +333,9 @@ function localRequestVariableName(paramEntries: [string, JSONSchema7Definition][ } function schemaTypeToCSharp(schema: JSONSchema7, required: boolean, knownTypes: Map, propName?: string): string { + if (isOpaqueJson(schema)) { + return required ? "JsonElement" : "JsonElement?"; + } const nullableInner = getNullableInner(schema); if (nullableInner) { // Pass required=true to get the base type, then add "?" for nullable @@ -361,7 +388,8 @@ function schemaTypeToCSharp(schema: JSONSchema7, required: boolean, knownTypes: if (type === "boolean") return required ? "bool" : "bool?"; if (type === "array") { const items = schema.items as JSONSchema7 | undefined; - const itemType = items ? schemaTypeToCSharp(items, true, knownTypes) : "object"; + if (!items) failUnmappable(`array without items (propName=${propName ?? "?"})`, schema); + const itemType = schemaTypeToCSharp(items, true, knownTypes); return required ? `${itemType}[]` : `${itemType}[]?`; } if (type === "object") { @@ -369,9 +397,9 @@ function schemaTypeToCSharp(schema: JSONSchema7, required: boolean, knownTypes: const valueType = schemaTypeToCSharp(schema.additionalProperties as JSONSchema7, true, knownTypes); return required ? `IDictionary` : `IDictionary?`; } - return required ? "object" : "object?"; + failUnmappable(`object without properties or typed additionalProperties (propName=${propName ?? "?"})`, schema); } - return required ? "object" : "object?"; + failUnmappable(`unknown/missing type (propName=${propName ?? "?"})`, schema); } /** Tracks whether any TimeSpan property was emitted so the converter can be generated. */ @@ -1095,6 +1123,9 @@ function resolveSessionPropertyType( nestedClasses: Map, enumOutput: string[] ): string { + if (isOpaqueJson(propSchema)) { + return isRequired ? "JsonElement" : "JsonElement?"; + } // Handle $ref by resolving against schema definitions if (propSchema.$ref) { const className = typeToClassName(refTypeName(propSchema.$ref, sessionDefinitions)); @@ -1145,12 +1176,12 @@ function resolveSessionPropertyType( } const unionType = tryGenerateSessionJsonUnionType(propSchema, parentClassName, propName, knownTypes, nestedClasses, enumOutput); if (unionType) return isRequired ? unionType : `${unionType}?`; - return !isRequired ? "object?" : "object"; + failUnmappable(`anyOf without discriminator (${parentClassName}.${propName})`, propSchema); } if (propSchema.oneOf) { const unionType = tryGenerateSessionJsonUnionType(propSchema, parentClassName, propName, knownTypes, nestedClasses, enumOutput); if (unionType) return isRequired ? unionType : `${unionType}?`; - return !isRequired ? "object?" : "object"; + failUnmappable(`oneOf without discriminator (${parentClassName}.${propName})`, propSchema); } if (propSchema.enum && Array.isArray(propSchema.enum)) { const enumName = getOrCreateEnum(parentClassName, propName, propSchema.enum as string[], enumOutput, propSchema.description, getEnumValueDescriptions(propSchema), propSchema.title as string | undefined, isSchemaDeprecated(propSchema), isSchemaExperimental(propSchema)); @@ -1610,7 +1641,6 @@ function emitRpcClass( let propAccessors = "{ get; set; }"; if (isReq && !csharpType.endsWith("?")) { if (csharpType === "string") defaultVal = " = string.Empty;"; - else if (csharpType === "object") defaultVal = " = null!;"; else if (csharpType.startsWith("IList<")) { propAccessors = "{ get => field ??= []; set; }"; } else if (csharpType.startsWith("IDictionary<")) { From be97a4dcecf1091fae1ce1d3566d65d797aa709f Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 12:11:36 +0100 Subject: [PATCH 02/20] C# codegen: accept object at RPC boundary for opaque-JSON params MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous change forced consumers to pass JsonElement for RPC method parameters whose schema is opaque-JSON (e.g. Rpc.Tools.HandlePendingToolCallAsync result, McpConfigAddRequest config). This was a UX regression vs. accepting 'object?' as before, since most callers naturally have a typed CLR value (string, dictionary, generated DTO) and would otherwise need to manually SerializeToElement before each call. Boundary special-case in csharp.ts: when the natural C# type for a top-level RPC method parameter is JsonElement/JsonElement?, emit 'object'/'object?' at the public surface and convert in the generated body via a new helper CopilotClient.ToJsonElementForWire(object?). The helper short-circuits when the value is already a JsonElement and otherwise serializes the runtime type using the chained source-generated JsonSerializerContexts that the SDK configures for JSON-RPC message formatting (matching pre-revert behaviour). DTO field types are unaffected — opaque-JSON properties on any generated class continue to be JsonElement(?). The asymmetry is intentional: inbound opaque-JSON (events, hook inputs, tool args) stays as JsonElement so consumers can introspect directly; outbound opaque-JSON (consumer-constructed) accepts 'object' for ergonomics. ToolResultObject.ToolTelemetry reverted to IDictionary? for the same reason — it is a consumer-constructed outbound type. Tests constructing ToolResultObject updated accordingly. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Client.cs | 20 ++++++ dotnet/src/Generated/Rpc.cs | 27 ++++---- dotnet/src/Session.cs | 3 +- dotnet/src/Types.cs | 2 +- .../E2E/HookLifecycleAndOutputE2ETests.cs | 2 +- dotnet/test/E2E/ToolResultsE2ETests.cs | 2 +- go/rpc/zrpc.go | 41 +++++++----- go/rpc/zrpc_encoding.go | 32 ---------- go/rpc/zsession_events.go | 2 + nodejs/src/generated/rpc.ts | 62 ++++++++++++++----- nodejs/src/generated/session-events.ts | 26 ++++++-- python/copilot/generated/rpc.py | 51 ++++++++++----- python/copilot/generated/session_events.py | 5 ++ rust/src/generated/api_types.rs | 40 ++++++------ rust/src/generated/rpc.rs | 33 ++++++++++ rust/src/generated/session_events.rs | 3 + scripts/codegen/csharp.ts | 38 +++++++++--- scripts/codegen/package-lock.json | 1 - 18 files changed, 260 insertions(+), 130 deletions(-) diff --git a/dotnet/src/Client.cs b/dotnet/src/Client.cs index 4339754c7..280ae6d10 100644 --- a/dotnet/src/Client.cs +++ b/dotnet/src/Client.cs @@ -1636,6 +1636,26 @@ private async Task ConnectToServerAsync(Process? cliProcess, string? private static JsonSerializerOptions SerializerOptionsForMessageFormatter { get; } = CreateSerializerOptions(); + /// + /// Converts an arbitrary value into the representation that wire + /// DTOs use for opaque-JSON fields. Pass-through for , otherwise + /// serializes the runtime type using the shared JSON-RPC serializer options so that any + /// type registered in the SDK's source-generated contexts (e.g. primitives, + /// Dictionary<string, object>, generated DTOs) is supported. + /// + [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2026", + Justification = "Opaque-JSON conversion uses the chained source-generated JsonSerializerContexts " + + "configured on SerializerOptionsForMessageFormatter. Any type used at this boundary is reachable via those contexts.")] + [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("AOT", "IL3050", + Justification = "Opaque-JSON conversion uses the chained source-generated JsonSerializerContexts " + + "configured on SerializerOptionsForMessageFormatter. Any type used at this boundary is reachable via those contexts.")] + public static JsonElement? ToJsonElementForWire(object? value) => value switch + { + null => null, + JsonElement je => je, + _ => JsonSerializer.SerializeToElement(value, value.GetType(), SerializerOptionsForMessageFormatter) + }; + private static JsonSerializerOptions CreateSerializerOptions() { var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index c854cfcee..6c1624e26 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -10306,11 +10306,12 @@ public async Task ListAsync(CancellationToken cancellationToken = /// Unique name for the MCP server. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - public async Task AddAsync(string name, JsonElement config, CancellationToken cancellationToken = default) + public async Task AddAsync(string name, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(config); - var request = new McpConfigAddRequest { Name = name, Config = config }; + var request = new McpConfigAddRequest { Name = name, Config = CopilotClient.ToJsonElementForWire(config)!.Value }; await CopilotClient.InvokeRpcAsync(_rpc, "mcp.config.add", [request], cancellationToken); } @@ -10318,11 +10319,12 @@ public async Task AddAsync(string name, JsonElement config, CancellationToken ca /// Name of the MCP server to update. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - public async Task UpdateAsync(string name, JsonElement config, CancellationToken cancellationToken = default) + public async Task UpdateAsync(string name, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(config); - var request = new McpConfigUpdateRequest { Name = name, Config = config }; + var request = new McpConfigUpdateRequest { Name = name, Config = CopilotClient.ToJsonElementForWire(config)!.Value }; await CopilotClient.InvokeRpcAsync(_rpc, "mcp.config.update", [request], cancellationToken); } @@ -10888,12 +10890,12 @@ public async Task SuspendAsync(CancellationToken cancellationToken = default) /// The to monitor for cancellation requests. The default is . /// Result of sending a user message. [Experimental(Diagnostics.Experimental)] - public async Task SendAsync(string prompt, string? displayPrompt = null, IList? attachments = null, SendMode? mode = null, bool? prepend = null, bool? billable = null, string? requiredTool = null, JsonElement? source = null, SendAgentMode? agentMode = null, IDictionary? requestHeaders = null, string? traceparent = null, string? tracestate = null, bool? wait = null, CancellationToken cancellationToken = default) + public async Task SendAsync(string prompt, string? displayPrompt = null, IList? attachments = null, SendMode? mode = null, bool? prepend = null, bool? billable = null, string? requiredTool = null, object? source = null, SendAgentMode? agentMode = null, IDictionary? requestHeaders = null, string? traceparent = null, string? tracestate = null, bool? wait = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(prompt); _session.ThrowIfDisposed(); - var request = new SendRequest { SessionId = _session.SessionId, Prompt = prompt, DisplayPrompt = displayPrompt, Attachments = attachments, Mode = mode, Prepend = prepend, Billable = billable, RequiredTool = requiredTool, Source = source, AgentMode = agentMode, RequestHeaders = requestHeaders, Traceparent = traceparent, Tracestate = tracestate, Wait = wait }; + var request = new SendRequest { SessionId = _session.SessionId, Prompt = prompt, DisplayPrompt = displayPrompt, Attachments = attachments, Mode = mode, Prepend = prepend, Billable = billable, RequiredTool = requiredTool, Source = CopilotClient.ToJsonElementForWire(source), AgentMode = agentMode, RequestHeaders = requestHeaders, Traceparent = traceparent, Tracestate = tracestate, Wait = wait }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.send", [request], cancellationToken); } @@ -11665,14 +11667,15 @@ public async Task ReloadAsync(CancellationToken cancellationToken = default) /// Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. /// The to monitor for cancellation requests. The default is . /// Outcome of an MCP sampling execution: success result, failure error, or cancellation. - public async Task ExecuteSamplingAsync(string requestId, string serverName, JsonElement mcpRequestId, McpExecuteSamplingRequest request, CancellationToken cancellationToken = default) + public async Task ExecuteSamplingAsync(string requestId, string serverName, object mcpRequestId, McpExecuteSamplingRequest request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(requestId); ArgumentNullException.ThrowIfNull(serverName); + ArgumentNullException.ThrowIfNull(mcpRequestId); ArgumentNullException.ThrowIfNull(request); _session.ThrowIfDisposed(); - var rpcRequest = new McpExecuteSamplingParams { SessionId = _session.SessionId, RequestId = requestId, ServerName = serverName, McpRequestId = mcpRequestId, Request = request }; + var rpcRequest = new McpExecuteSamplingParams { SessionId = _session.SessionId, RequestId = requestId, ServerName = serverName, McpRequestId = CopilotClient.ToJsonElementForWire(mcpRequestId)!.Value, Request = request }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.executeSampling", [rpcRequest], cancellationToken); } @@ -11820,11 +11823,11 @@ internal OptionsApi(CopilotSession session) /// Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the per-session schedule registry; this flag only controls tool exposure (typically gated to staff users). /// The to monitor for cancellation requests. The default is . /// Indicates whether the session options patch was applied successfully. - public async Task UpdateAsync(string? model = null, string? reasoningEffort = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, JsonElement? provider = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, JsonElement? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? skipCustomInstructions = null, IList? disabledInstructionSources = null, bool? coauthorEnabled = null, string? trajectoryFile = null, bool? enableStreaming = null, string? copilotUrl = null, bool? askUserDisabled = null, bool? continueOnAutoMode = null, bool? runningInInteractiveMode = null, bool? enableReasoningSummaries = null, string? agentContext = null, string? eventsLogDirectory = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, CancellationToken cancellationToken = default) + public async Task UpdateAsync(string? model = null, string? reasoningEffort = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, object? provider = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, object? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? skipCustomInstructions = null, IList? disabledInstructionSources = null, bool? coauthorEnabled = null, string? trajectoryFile = null, bool? enableStreaming = null, string? copilotUrl = null, bool? askUserDisabled = null, bool? continueOnAutoMode = null, bool? runningInInteractiveMode = null, bool? enableReasoningSummaries = null, string? agentContext = null, string? eventsLogDirectory = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new SessionUpdateOptionsParams { SessionId = _session.SessionId, Model = model, ReasoningEffort = reasoningEffort, ClientName = clientName, LspClientName = lspClientName, IntegrationId = integrationId, FeatureFlags = featureFlags, IsExperimentalMode = isExperimentalMode, Provider = provider, WorkingDirectory = workingDirectory, AvailableTools = availableTools, ExcludedTools = excludedTools, EnableScriptSafety = enableScriptSafety, ShellInitProfile = shellInitProfile, ShellProcessFlags = shellProcessFlags, SandboxConfig = sandboxConfig, LogInteractiveShells = logInteractiveShells, EnvValueMode = envValueMode, SkillDirectories = skillDirectories, DisabledSkills = disabledSkills, EnableOnDemandInstructionDiscovery = enableOnDemandInstructionDiscovery, InstalledPlugins = installedPlugins, CustomAgentsLocalOnly = customAgentsLocalOnly, SkipCustomInstructions = skipCustomInstructions, DisabledInstructionSources = disabledInstructionSources, CoauthorEnabled = coauthorEnabled, TrajectoryFile = trajectoryFile, EnableStreaming = enableStreaming, CopilotUrl = copilotUrl, AskUserDisabled = askUserDisabled, ContinueOnAutoMode = continueOnAutoMode, RunningInInteractiveMode = runningInInteractiveMode, EnableReasoningSummaries = enableReasoningSummaries, AgentContext = agentContext, EventsLogDirectory = eventsLogDirectory, AdditionalContentExclusionPolicies = additionalContentExclusionPolicies, ManageScheduleEnabled = manageScheduleEnabled }; + var request = new SessionUpdateOptionsParams { SessionId = _session.SessionId, Model = model, ReasoningEffort = reasoningEffort, ClientName = clientName, LspClientName = lspClientName, IntegrationId = integrationId, FeatureFlags = featureFlags, IsExperimentalMode = isExperimentalMode, Provider = CopilotClient.ToJsonElementForWire(provider), WorkingDirectory = workingDirectory, AvailableTools = availableTools, ExcludedTools = excludedTools, EnableScriptSafety = enableScriptSafety, ShellInitProfile = shellInitProfile, ShellProcessFlags = shellProcessFlags, SandboxConfig = CopilotClient.ToJsonElementForWire(sandboxConfig), LogInteractiveShells = logInteractiveShells, EnvValueMode = envValueMode, SkillDirectories = skillDirectories, DisabledSkills = disabledSkills, EnableOnDemandInstructionDiscovery = enableOnDemandInstructionDiscovery, InstalledPlugins = installedPlugins, CustomAgentsLocalOnly = customAgentsLocalOnly, SkipCustomInstructions = skipCustomInstructions, DisabledInstructionSources = disabledInstructionSources, CoauthorEnabled = coauthorEnabled, TrajectoryFile = trajectoryFile, EnableStreaming = enableStreaming, CopilotUrl = copilotUrl, AskUserDisabled = askUserDisabled, ContinueOnAutoMode = continueOnAutoMode, RunningInInteractiveMode = runningInInteractiveMode, EnableReasoningSummaries = enableReasoningSummaries, AgentContext = agentContext, EventsLogDirectory = eventsLogDirectory, AdditionalContentExclusionPolicies = additionalContentExclusionPolicies, ManageScheduleEnabled = manageScheduleEnabled }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.options.update", [request], cancellationToken); } } @@ -11928,12 +11931,12 @@ internal ToolsApi(CopilotSession session) /// Error message if the tool call failed. /// The to monitor for cancellation requests. The default is . /// Indicates whether the external tool call result was handled successfully. - public async Task HandlePendingToolCallAsync(string requestId, JsonElement? result = null, string? error = null, CancellationToken cancellationToken = default) + public async Task HandlePendingToolCallAsync(string requestId, object? result = null, string? error = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(requestId); _session.ThrowIfDisposed(); - var request = new HandlePendingToolCallRequest { SessionId = _session.SessionId, RequestId = requestId, Result = result, Error = error }; + var request = new HandlePendingToolCallRequest { SessionId = _session.SessionId, RequestId = requestId, Result = CopilotClient.ToJsonElementForWire(result), Error = error }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.tools.handlePendingToolCall", [request], cancellationToken); } diff --git a/dotnet/src/Session.cs b/dotnet/src/Session.cs index cf449e9be..d4eb0df36 100644 --- a/dotnet/src/Session.cs +++ b/dotnet/src/Session.cs @@ -729,10 +729,9 @@ private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, toolName); var toolResultObject = ToolResultObject.ConvertFromInvocationResult(result, tool.JsonSerializerOptions); - var toolResultJson = JsonSerializer.SerializeToElement(toolResultObject, TypesJsonContext.Default.ToolResultObject); var responseRpcTimestamp = Stopwatch.GetTimestamp(); - await Rpc.Tools.HandlePendingToolCallAsync(requestId, toolResultJson, error: null); + await Rpc.Tools.HandlePendingToolCallAsync(requestId, toolResultObject, error: null); LoggingHelpers.LogTiming(_logger, LogLevel.Debug, null, "CopilotSession.ExecuteToolAndRespondAsync response sent successfully. Elapsed={Elapsed}, SessionId={SessionId}, RequestId={RequestId}, ToolCallId={ToolCallId}, Tool={ToolName}", responseRpcTimestamp, diff --git a/dotnet/src/Types.cs b/dotnet/src/Types.cs index 75f04fd8b..e3569663e 100644 --- a/dotnet/src/Types.cs +++ b/dotnet/src/Types.cs @@ -559,7 +559,7 @@ public sealed class ToolResultObject /// Custom telemetry data associated with the tool execution. /// [JsonPropertyName("toolTelemetry")] - public IDictionary? ToolTelemetry { get; set; } + public IDictionary? ToolTelemetry { get; set; } /// /// Converts the result of an invocation into a diff --git a/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs b/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs index 3c4407bd7..b16ee2b56 100644 --- a/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs +++ b/dotnet/test/E2E/HookLifecycleAndOutputE2ETests.cs @@ -327,7 +327,7 @@ public async Task Should_Allow_PostToolUse_To_Return_ModifiedResult() { TextResultForLlm = "modified by post hook", ResultType = "success", - ToolTelemetry = new Dictionary(), + ToolTelemetry = new Dictionary(), }, SuppressOutput = false, }); diff --git a/dotnet/test/E2E/ToolResultsE2ETests.cs b/dotnet/test/E2E/ToolResultsE2ETests.cs index 2167d0af8..103c7ffe2 100644 --- a/dotnet/test/E2E/ToolResultsE2ETests.cs +++ b/dotnet/test/E2E/ToolResultsE2ETests.cs @@ -111,7 +111,7 @@ static ToolResultAIContent AnalyzeCode([Description("File to analyze")] string f { TextResultForLlm = $"Analysis of {file}: no issues found", ResultType = "success", - ToolTelemetry = new Dictionary + ToolTelemetry = new Dictionary { ["metrics"] = JsonDocument.Parse("""{"analysisTimeMs":150}""").RootElement.Clone(), ["properties"] = JsonDocument.Parse("""{"analyzer":"eslint"}""").RootElement.Clone(), diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index eea56b4ba..c7a777cdc 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -586,8 +586,9 @@ type EventLogReadRequest struct { Cursor *string `json:"cursor,omitempty"` // Maximum number of events to return in this batch (1–1000, default 200). Max *int32 `json:"max,omitempty"` - // Either '*' to receive all event types, or a non-empty list of event types to receive - Types *EventLogTypes `json:"types,omitempty"` + // List of event types to receive. Omit (or pass an empty/absent value) to receive all event + // types. + Types []string `json:"types,omitempty"` // Milliseconds to wait for new events when the cursor is at the tail of history. 0 // (default) returns immediately even if no events are available. Capped at 30000ms. // Ephemeral events that arrive during the wait are delivered in this batch but are NOT @@ -618,13 +619,6 @@ type EventLogTailResult struct { Cursor string `json:"cursor"` } -// Either '*' to receive all event types, or a non-empty list of event types to receive -// Experimental: EventLogTypes is part of an experimental API and may change or be removed. -type EventLogTypes struct { - String *EventLogTypesString - StringArray []string -} - // Batch of session events returned by a read, with cursor and continuation metadata. // Experimental: EventsReadResult is part of an experimental API and may change or be // removed. @@ -1035,6 +1029,14 @@ type HistoryCompactContextWindow struct { ToolDefinitionsTokens *int64 `json:"toolDefinitionsTokens,omitempty"` } +// Optional compaction parameters. +// Experimental: HistoryCompactRequest is part of an experimental API and may change or be +// removed. +type HistoryCompactRequest struct { + // Optional user-provided instructions to focus the compaction summary + CustomInstructions *string `json:"customInstructions,omitempty"` +} + // Compaction outcome with the number of tokens and messages removed, summary text, and the // resulting context window breakdown. // Experimental: HistoryCompactResult is part of an experimental API and may change or be @@ -5928,12 +5930,6 @@ const ( DiscoveredMcpServerTypeStdio DiscoveredMcpServerType = "stdio" ) -type EventLogTypesString string - -const ( - EventLogTypesStringValue EventLogTypesString = "*" -) - // Agent-scope filter: 'primary' returns only main-agent events plus events whose type // starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns // events from all agents (matching wildcard-subscription behavior). Default is 'all' to @@ -7943,7 +7939,7 @@ func (a *EventLogApi) Read(ctx context.Context, params *EventLogReadRequest) (*E req["max"] = *params.Max } if params.Types != nil { - req["types"] = *params.Types + req["types"] = params.Types } if params.WaitMs != nil { req["waitMs"] = *params.WaitMs @@ -8178,10 +8174,21 @@ func (a *HistoryApi) CancelBackgroundCompaction(ctx context.Context) (*HistoryCa // // RPC method: session.history.compact. // +// Parameters: Optional compaction parameters. +// // Returns: Compaction outcome with the number of tokens and messages removed, summary text, // and the resulting context window breakdown. -func (a *HistoryApi) Compact(ctx context.Context) (*HistoryCompactResult, error) { +func (a *HistoryApi) Compact(ctx context.Context, params ...*HistoryCompactRequest) (*HistoryCompactResult, error) { + var requestParams *HistoryCompactRequest + if len(params) > 0 { + requestParams = params[0] + } req := map[string]any{"sessionId": a.sessionID} + if requestParams != nil { + if requestParams.CustomInstructions != nil { + req["customInstructions"] = *requestParams.CustomInstructions + } + } raw, err := a.client.Request("session.history.compact", req) if err != nil { return nil, err diff --git a/go/rpc/zrpc_encoding.go b/go/rpc/zrpc_encoding.go index f013a1fef..4cc9da36f 100644 --- a/go/rpc/zrpc_encoding.go +++ b/go/rpc/zrpc_encoding.go @@ -230,38 +230,6 @@ func (r *CommandsRespondToQueuedCommandRequest) UnmarshalJSON(data []byte) error return nil } -func (r EventLogTypes) MarshalJSON() ([]byte, error) { - if r.String != nil { - return json.Marshal(r.String) - } - if r.StringArray != nil { - return json.Marshal(r.StringArray) - } - return []byte("null"), nil -} - -func (r *EventLogTypes) UnmarshalJSON(data []byte) error { - if string(data) == "null" { - *r = EventLogTypes{} - return nil - } - { - var value EventLogTypesString - if err := json.Unmarshal(data, &value); err == nil { - *r = EventLogTypes{String: &value} - return nil - } - } - { - var value []string - if err := json.Unmarshal(data, &value); err == nil { - *r = EventLogTypes{StringArray: value} - return nil - } - } - return errors.New("data did not match any union variant for EventLogTypes") -} - func unmarshalExternalToolTextResultForLlmContent(data []byte) (ExternalToolTextResultForLlmContent, error) { if string(data) == "null" { return nil, nil diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index 568794119..f8fa95070 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -258,6 +258,8 @@ type SessionCompactionCompleteData struct { CompactionTokensUsed *CompactionCompleteCompactionTokensUsed `json:"compactionTokensUsed,omitempty"` // Token count from non-system messages (user, assistant, tool) after compaction ConversationTokens *int64 `json:"conversationTokens,omitempty"` + // User-supplied focus instructions provided to a manual `/compact` invocation. Omitted for automatic compaction and for manual compaction with no focus text. + CustomInstructions *string `json:"customInstructions,omitempty"` // Error message if compaction failed Error *string `json:"error,omitempty"` // Number of messages removed during compaction diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index 02d2222d3..09f7e8e66 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -134,14 +134,6 @@ export type DiscoveredMcpServerType = | "sse" /** Server is backed by an in-memory runtime implementation. */ | "memory"; -/** - * Either '*' to receive all event types, or a non-empty list of event types to receive - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "EventLogTypes". - */ -/** @experimental */ -export type EventLogTypes = "*" | [string, ...string[]]; /** * Agent-scope filter: 'primary' returns only main-agent events plus events whose type starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns events from all agents (matching wildcard-subscription behavior). Default is 'all' to preserve wildcard semantics for catch-up callers. * @@ -1188,7 +1180,11 @@ export interface AgentInfo { * MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. */ mcpServers?: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }; /** * Skill names preloaded into this agent's context. Omitted means none. @@ -1971,7 +1967,12 @@ export interface EventLogReadRequest { * Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). */ waitMs?: number; - types?: EventLogTypes; + /** + * List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. + * + * @minItems 1 + */ + types?: [string, ...string[]]; agentScope?: EventsAgentScope; } /** @@ -2142,7 +2143,11 @@ export interface ExternalToolTextResultForLlm { * Optional tool-specific telemetry */ toolTelemetry?: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }; /** * Base64-encoded binary results returned to the model @@ -2492,6 +2497,19 @@ export interface HistoryCompactContextWindow { */ toolDefinitionsTokens?: number; } +/** + * Optional compaction parameters. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryCompactRequest". + */ +/** @experimental */ +export interface HistoryCompactRequest { + /** + * Optional user-provided instructions to focus the compaction summary + */ + customInstructions?: string; +} /** * Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. * @@ -6060,7 +6078,11 @@ export interface SessionFsSqliteQueryResult { * For SELECT: array of row objects. For others: empty array. */ rows: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }[]; /** * Column names from the result set @@ -6930,7 +6952,9 @@ export interface SessionUpdateOptionsParams { /** * Additional content-exclusion policies to merge into the session's policy set. Opaque shape; see `ContentExclusionApiResponse` in the runtime. */ - additionalContentExclusionPolicies?: unknown[]; + additionalContentExclusionPolicies?: { + [k: string]: unknown | undefined; + }[]; /** * Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the per-session schedule registry; this flag only controls tool exposure (typically gated to staff users). */ @@ -7763,7 +7787,11 @@ export interface Tool { * JSON Schema for the tool's input parameters */ parameters?: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }; /** * Optional instructions for how to use this tool effectively @@ -9997,10 +10025,12 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin /** * Compacts the session history to reduce context usage. * + * @param params Optional compaction parameters. + * * @returns Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. */ - compact: async (): Promise => - connection.sendRequest("session.history.compact", { sessionId }), + compact: async (params?: HistoryCompactRequest): Promise => + connection.sendRequest("session.history.compact", { sessionId, ...params }), /** * Truncates persisted session history to a specific event. * diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index cf376c3db..caacc3560 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -1748,6 +1748,10 @@ export interface CompactionCompleteData { * Token count from non-system messages (user, assistant, tool) after compaction */ conversationTokens?: number; + /** + * User-supplied focus instructions provided to a manual `/compact` invocation. Omitted for automatic compaction and for manual compaction with no focus text. + */ + customInstructions?: string; /** * Error message if compaction failed */ @@ -2400,7 +2404,9 @@ export interface AssistantMessageData { /** * Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping */ - anthropicAdvisorBlocks?: unknown[]; + anthropicAdvisorBlocks?: { + [k: string]: unknown | undefined; + }[]; /** * Anthropic advisor model ID used for this response, for timeline display on replay */ @@ -3166,7 +3172,11 @@ export interface ToolExecutionCompleteData { * Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts) */ toolTelemetry?: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }; /** * Identifier for the agent loop turn this tool was invoked in, matching the corresponding assistant.turn_start event @@ -3872,7 +3882,11 @@ export interface SystemMessageMetadata { * Template variables used when constructing the prompt */ variables?: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }; } /** @@ -5118,7 +5132,11 @@ export interface ElicitationRequestedSchema { * Form field definitions, keyed by field name */ properties: { - [k: string]: unknown | undefined; + [k: string]: + | { + [k: string]: unknown | undefined; + } + | undefined; }; /** * List of required field names diff --git a/python/copilot/generated/rpc.py b/python/copilot/generated/rpc.py index bb9092b47..5ee9cea22 100644 --- a/python/copilot/generated/rpc.py +++ b/python/copilot/generated/rpc.py @@ -805,10 +805,6 @@ class EventsAgentScope(Enum): ALL = "all" PRIMARY = "primary" -# Experimental: this type is part of an experimental API and may change or be removed. -class EventLogTypes(Enum): - EMPTY = "*" - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class EventLogReleaseInterestResult: @@ -1211,6 +1207,26 @@ def to_dict(self) -> dict: result["toolDefinitionsTokens"] = from_union([from_int, from_none], self.tool_definitions_tokens) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryCompactRequest: + """Optional compaction parameters.""" + + custom_instructions: str | None = None + """Optional user-provided instructions to focus the compaction summary""" + + @staticmethod + def from_dict(obj: Any) -> 'HistoryCompactRequest': + assert isinstance(obj, dict) + custom_instructions = from_union([from_str, from_none], obj.get("customInstructions")) + return HistoryCompactRequest(custom_instructions) + + def to_dict(self) -> dict: + result: dict = {} + if self.custom_instructions is not None: + result["customInstructions"] = from_union([from_str, from_none], self.custom_instructions) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class HistorySummarizeForHandoffResult: @@ -6530,9 +6546,10 @@ class EventLogReadRequest: max: int | None = None """Maximum number of events to return in this batch (1–1000, default 200).""" - types: list[str] | EventLogTypes | None = None - """Either '*' to receive all event types, or a non-empty list of event types to receive""" - + types: list[str] | None = None + """List of event types to receive. Omit (or pass an empty/absent value) to receive all event + types. + """ wait_ms: int | None = None """Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. @@ -6547,7 +6564,7 @@ def from_dict(obj: Any) -> 'EventLogReadRequest': agent_scope = from_union([EventsAgentScope, from_none], obj.get("agentScope")) cursor = from_union([from_str, from_none], obj.get("cursor")) max = from_union([from_int, from_none], obj.get("max")) - types = from_union([lambda x: from_list(from_str, x), EventLogTypes, from_none], obj.get("types")) + types = from_union([lambda x: from_list(from_str, x), from_none], obj.get("types")) wait_ms = from_union([from_int, from_none], obj.get("waitMs")) return EventLogReadRequest(agent_scope, cursor, max, types, wait_ms) @@ -6560,7 +6577,7 @@ def to_dict(self) -> dict: if self.max is not None: result["max"] = from_union([from_int, from_none], self.max) if self.types is not None: - result["types"] = from_union([lambda x: from_list(from_str, x), lambda x: to_enum(EventLogTypes, x), from_none], self.types) + result["types"] = from_union([lambda x: from_list(from_str, x), from_none], self.types) if self.wait_ms is not None: result["waitMs"] = from_union([from_int, from_none], self.wait_ms) return result @@ -14947,7 +14964,6 @@ class RPC: event_log_read_request: EventLogReadRequest event_log_release_interest_result: EventLogReleaseInterestResult event_log_tail_result: EventLogTailResult - event_log_types: list[str] | EventLogTypes events_agent_scope: EventsAgentScope events_cursor_status: EventsCursorStatus events_read_result: EventsReadResult @@ -14985,6 +15001,7 @@ class RPC: history_abort_manual_compaction_result: HistoryAbortManualCompactionResult history_cancel_background_compaction_result: HistoryCancelBackgroundCompactionResult history_compact_context_window: HistoryCompactContextWindow + history_compact_request: HistoryCompactRequest history_compact_result: HistoryCompactResult history_summarize_for_handoff_result: HistorySummarizeForHandoffResult history_truncate_request: HistoryTruncateRequest @@ -15463,7 +15480,6 @@ def from_dict(obj: Any) -> 'RPC': event_log_read_request = EventLogReadRequest.from_dict(obj.get("EventLogReadRequest")) event_log_release_interest_result = EventLogReleaseInterestResult.from_dict(obj.get("EventLogReleaseInterestResult")) event_log_tail_result = EventLogTailResult.from_dict(obj.get("EventLogTailResult")) - event_log_types = from_union([lambda x: from_list(from_str, x), EventLogTypes], obj.get("EventLogTypes")) events_agent_scope = EventsAgentScope(obj.get("EventsAgentScope")) events_cursor_status = EventsCursorStatus(obj.get("EventsCursorStatus")) events_read_result = EventsReadResult.from_dict(obj.get("EventsReadResult")) @@ -15501,6 +15517,7 @@ def from_dict(obj: Any) -> 'RPC': history_abort_manual_compaction_result = HistoryAbortManualCompactionResult.from_dict(obj.get("HistoryAbortManualCompactionResult")) history_cancel_background_compaction_result = HistoryCancelBackgroundCompactionResult.from_dict(obj.get("HistoryCancelBackgroundCompactionResult")) history_compact_context_window = HistoryCompactContextWindow.from_dict(obj.get("HistoryCompactContextWindow")) + history_compact_request = HistoryCompactRequest.from_dict(obj.get("HistoryCompactRequest")) history_compact_result = HistoryCompactResult.from_dict(obj.get("HistoryCompactResult")) history_summarize_for_handoff_result = HistorySummarizeForHandoffResult.from_dict(obj.get("HistorySummarizeForHandoffResult")) history_truncate_request = HistoryTruncateRequest.from_dict(obj.get("HistoryTruncateRequest")) @@ -15930,7 +15947,7 @@ def from_dict(obj: Any) -> 'RPC': session_context_info = from_union([SessionContextInfo.from_dict, from_none], obj.get("SessionContextInfo")) task_progress = from_union([TaskProgress.from_dict, from_none], obj.get("TaskProgress")) workspace_summary = from_union([WorkspaceSummary.from_dict, from_none], obj.get("WorkspaceSummary")) - return RPC(abort_request, abort_result, account_get_quota_request, account_get_quota_result, account_quota_snapshot, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_reload_result, agent_select_request, agent_select_result, api_key_auth_info, auth_info, auth_info_type, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, event_log_types, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_source, installed_plugin_source_github, installed_plugin_source_local, installed_plugin_source_url, instructions_get_sources_result, instructions_sources, instructions_sources_location, instructions_sources_type, log_request, log_result, lsp_initialize_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_oauth_login_request, mcp_oauth_login_result, mcp_remove_git_hub_result, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_config, mcp_server_config_http, mcp_server_config_http_auth, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_list, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, options_update_env_value_mode, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_update_request, plugin, plugin_list, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_mode, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, send_agent_mode, send_attachment, send_attachment_blob, send_attachment_directory, send_attachment_file, send_attachment_file_line_range, send_attachment_github_reference, send_attachment_github_reference_type, send_attachment_selection, send_attachment_selection_details, send_attachment_selection_details_end, send_attachment_selection_details_start, send_mode, send_request, send_result, server_skill, server_skill_list, session_auth_status, session_bulk_delete_result, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_github, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_metadata, session_metadata_snapshot, session_mode, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_prune_old_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_exec_request, shell_exec_result, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_initialize_and_validate_result, tools_list_request, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_tool_session_approval_commands, user_tool_session_approval_custom_tool, user_tool_session_approval_extension_management, user_tool_session_approval_extension_permission_access, user_tool_session_approval_mcp, user_tool_session_approval_memory, user_tool_session_approval_read, user_tool_session_approval_write, workspaces_checkpoints, workspaces_create_file_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, task_progress, workspace_summary) + return RPC(abort_request, abort_result, account_get_quota_request, account_get_quota_result, account_quota_snapshot, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_reload_result, agent_select_request, agent_select_result, api_key_auth_info, auth_info, auth_info_type, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_source, installed_plugin_source_github, installed_plugin_source_local, installed_plugin_source_url, instructions_get_sources_result, instructions_sources, instructions_sources_location, instructions_sources_type, log_request, log_result, lsp_initialize_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_oauth_login_request, mcp_oauth_login_result, mcp_remove_git_hub_result, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_config, mcp_server_config_http, mcp_server_config_http_auth, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_list, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, options_update_env_value_mode, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_update_request, plugin, plugin_list, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_mode, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, send_agent_mode, send_attachment, send_attachment_blob, send_attachment_directory, send_attachment_file, send_attachment_file_line_range, send_attachment_github_reference, send_attachment_github_reference_type, send_attachment_selection, send_attachment_selection_details, send_attachment_selection_details_end, send_attachment_selection_details_start, send_mode, send_request, send_result, server_skill, server_skill_list, session_auth_status, session_bulk_delete_result, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_github, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_metadata, session_metadata_snapshot, session_mode, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_prune_old_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_exec_request, shell_exec_result, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_initialize_and_validate_result, tools_list_request, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_tool_session_approval_commands, user_tool_session_approval_custom_tool, user_tool_session_approval_extension_management, user_tool_session_approval_extension_permission_access, user_tool_session_approval_mcp, user_tool_session_approval_memory, user_tool_session_approval_read, user_tool_session_approval_write, workspaces_checkpoints, workspaces_create_file_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, task_progress, workspace_summary) def to_dict(self) -> dict: result: dict = {} @@ -15979,7 +15996,6 @@ def to_dict(self) -> dict: result["EventLogReadRequest"] = to_class(EventLogReadRequest, self.event_log_read_request) result["EventLogReleaseInterestResult"] = to_class(EventLogReleaseInterestResult, self.event_log_release_interest_result) result["EventLogTailResult"] = to_class(EventLogTailResult, self.event_log_tail_result) - result["EventLogTypes"] = from_union([lambda x: from_list(from_str, x), lambda x: to_enum(EventLogTypes, x)], self.event_log_types) result["EventsAgentScope"] = to_enum(EventsAgentScope, self.events_agent_scope) result["EventsCursorStatus"] = to_enum(EventsCursorStatus, self.events_cursor_status) result["EventsReadResult"] = to_class(EventsReadResult, self.events_read_result) @@ -16017,6 +16033,7 @@ def to_dict(self) -> dict: result["HistoryAbortManualCompactionResult"] = to_class(HistoryAbortManualCompactionResult, self.history_abort_manual_compaction_result) result["HistoryCancelBackgroundCompactionResult"] = to_class(HistoryCancelBackgroundCompactionResult, self.history_cancel_background_compaction_result) result["HistoryCompactContextWindow"] = to_class(HistoryCompactContextWindow, self.history_compact_context_window) + result["HistoryCompactRequest"] = to_class(HistoryCompactRequest, self.history_compact_request) result["HistoryCompactResult"] = to_class(HistoryCompactResult, self.history_compact_result) result["HistorySummarizeForHandoffResult"] = to_class(HistorySummarizeForHandoffResult, self.history_summarize_for_handoff_result) result["HistoryTruncateRequest"] = to_class(HistoryTruncateRequest, self.history_truncate_request) @@ -17489,9 +17506,11 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def compact(self, *, timeout: float | None = None) -> HistoryCompactResult: - "Compacts the session history to reduce context usage.\n\nReturns:\n Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown." - return HistoryCompactResult.from_dict(await self._client.request("session.history.compact", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def compact(self, params: HistoryCompactRequest | None = None, *, timeout: float | None = None) -> HistoryCompactResult: + "Compacts the session history to reduce context usage.\n\nArgs:\n params: Optional compaction parameters.\n\nReturns:\n Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} if params is not None else {} + params_dict["sessionId"] = self._session_id + return HistoryCompactResult.from_dict(await self._client.request("session.history.compact", params_dict, **_timeout_kwargs(timeout))) async def truncate(self, params: HistoryTruncateRequest, *, timeout: float | None = None) -> HistoryTruncateResult: "Truncates persisted session history to a specific event.\n\nArgs:\n params: Identifier of the event to truncate to; this event and all later events are removed.\n\nReturns:\n Number of events that were removed by the truncation." diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index 83d9cb9ed..93903de30 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -2406,6 +2406,7 @@ class SessionCompactionCompleteData: checkpoint_path: str | None = None compaction_tokens_used: CompactionCompleteCompactionTokensUsed | None = None conversation_tokens: int | None = None + custom_instructions: str | None = None error: str | None = None messages_removed: int | None = None post_compaction_tokens: int | None = None @@ -2425,6 +2426,7 @@ def from_dict(obj: Any) -> "SessionCompactionCompleteData": checkpoint_path = from_union([from_none, from_str], obj.get("checkpointPath")) compaction_tokens_used = from_union([from_none, CompactionCompleteCompactionTokensUsed.from_dict], obj.get("compactionTokensUsed")) conversation_tokens = from_union([from_none, from_int], obj.get("conversationTokens")) + custom_instructions = from_union([from_none, from_str], obj.get("customInstructions")) error = from_union([from_none, from_str], obj.get("error")) messages_removed = from_union([from_none, from_int], obj.get("messagesRemoved")) post_compaction_tokens = from_union([from_none, from_int], obj.get("postCompactionTokens")) @@ -2441,6 +2443,7 @@ def from_dict(obj: Any) -> "SessionCompactionCompleteData": checkpoint_path=checkpoint_path, compaction_tokens_used=compaction_tokens_used, conversation_tokens=conversation_tokens, + custom_instructions=custom_instructions, error=error, messages_removed=messages_removed, post_compaction_tokens=post_compaction_tokens, @@ -2464,6 +2467,8 @@ def to_dict(self) -> dict: result["compactionTokensUsed"] = from_union([from_none, lambda x: to_class(CompactionCompleteCompactionTokensUsed, x)], self.compaction_tokens_used) if self.conversation_tokens is not None: result["conversationTokens"] = from_union([from_none, to_int], self.conversation_tokens) + if self.custom_instructions is not None: + result["customInstructions"] = from_union([from_none, from_str], self.custom_instructions) if self.error is not None: result["error"] = from_union([from_none, from_str], self.error) if self.messages_removed is not None: diff --git a/rust/src/generated/api_types.rs b/rust/src/generated/api_types.rs index b7ebd6c48..8acd798b7 100644 --- a/rust/src/generated/api_types.rs +++ b/rust/src/generated/api_types.rs @@ -10,7 +10,8 @@ use super::session_events::{ AbortReason, McpServerSource, McpServerStatus, PermissionPromptRequest, PermissionRule, ReasoningSummary, SessionMode, ShutdownType, SkillSource, UserToolSessionApproval, }; -use crate::types::{RequestId, SessionEvent, SessionId}; +use crate::types::SessionEvent; +use crate::types::{RequestId, SessionId}; /// JSON-RPC method name constants. pub mod rpc_methods { @@ -1249,9 +1250,9 @@ pub struct EventLogReadRequest { /// Maximum number of events to return in this batch (1–1000, default 200). #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, - /// Either '*' to receive all event types, or a non-empty list of event types to receive - #[serde(skip_serializing_if = "Option::is_none")] - pub types: Option, + /// List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. + #[serde(default)] + pub types: Vec, /// Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). #[serde(skip_serializing_if = "Option::is_none")] pub wait_ms: Option, @@ -1812,6 +1813,22 @@ pub struct HistoryCompactContextWindow { pub tool_definitions_tokens: Option, } +/// Optional compaction parameters. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HistoryCompactRequest { + /// Optional user-provided instructions to focus the compaction summary + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_instructions: Option, +} + /// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. /// ///
@@ -10517,21 +10534,6 @@ pub struct SessionShellKillResult { pub killed: bool, } -/// Identifies the target session. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionHistoryCompactParams { - /// Target session identifier - pub session_id: SessionId, -} - /// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. /// ///
diff --git a/rust/src/generated/rpc.rs b/rust/src/generated/rpc.rs index 5831a4553..f73d1bc00 100644 --- a/rust/src/generated/rpc.rs +++ b/rust/src/generated/rpc.rs @@ -2174,6 +2174,39 @@ impl<'a> SessionRpcHistory<'a> { Ok(serde_json::from_value(_value)?) } + /// Compacts the session history to reduce context usage. + /// + /// Wire method: `session.history.compact`. + /// + /// # Parameters + /// + /// * `params` - Optional compaction parameters. + /// + /// # Returns + /// + /// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn compact_with_params( + &self, + params: HistoryCompactRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_HISTORY_COMPACT, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Truncates persisted session history to a specific event. /// /// Wire method: `session.history.truncate`. diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index 053c4f8f8..4ea2a93c0 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -954,6 +954,9 @@ pub struct SessionCompactionCompleteData { /// Token count from non-system messages (user, assistant, tool) after compaction #[serde(skip_serializing_if = "Option::is_none")] pub conversation_tokens: Option, + /// User-supplied focus instructions provided to a manual `/compact` invocation. Omitted for automatic compaction and for manual compaction with no focus text. + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_instructions: Option, /// Error message if compaction failed #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index 1ed1729a6..a4ab9f854 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -1829,12 +1829,24 @@ function emitServerInstanceMethod( const csharpName = requestClassName ? toCSharpPropertyName(pName, jsonSchema) : toPascalCase(pName); - const csType = requestClassName + const naturalType = requestClassName ? resolveRpcType(jsonSchema, isReq, requestClassName, csharpName, classes) : schemaTypeToCSharp(jsonSchema, isReq, rpcKnownTypes, csharpName); + // Boundary special-case: if the natural type is JsonElement/JsonElement? (i.e. the + // schema is opaque-JSON), accept object at the public surface for ergonomics and + // convert at the call site. DTO fields keep JsonElement/JsonElement?. + const opaqueRequired = naturalType === "JsonElement"; + const opaqueOptional = naturalType === "JsonElement?"; + const opaque = opaqueRequired || opaqueOptional; + const csType = opaqueRequired ? "object" : opaqueOptional ? "object?" : naturalType; sigParams.push(`${csType} ${pName}${isReq ? "" : " = null"}`); - bodyAssignments.push(`${csharpName} = ${pName}`); - if (requiresArgumentNullCheck(csType, isReq)) { + const assignedValue = opaqueRequired + ? `CopilotClient.ToJsonElementForWire(${pName})!.Value` + : opaqueOptional + ? `CopilotClient.ToJsonElementForWire(${pName})` + : pName; + bodyAssignments.push(`${csharpName} = ${assignedValue}`); + if (opaqueRequired || (!opaque && requiresArgumentNullCheck(csType, isReq))) { argumentNullChecks.push(`${indent} ArgumentNullException.ThrowIfNull(${pName});`); } parameterDescriptions.push({ name: pName, description: jsonSchema.description }); @@ -1986,14 +1998,24 @@ function emitSessionMethod(key: string, method: RpcMethod, lines: string[], clas for (const [pName, pSchema] of paramEntries) { if (typeof pSchema !== "object") continue; const isReq = requiredSet.has(pName); - const csharpName = toCSharpPropertyName(pName, pSchema as JSONSchema7); - const csType = resolveRpcType(pSchema as JSONSchema7, isReq, requestClassName, csharpName, classes); + const jsonSchema = pSchema as JSONSchema7; + const csharpName = toCSharpPropertyName(pName, jsonSchema); + const naturalType = resolveRpcType(jsonSchema, isReq, requestClassName, csharpName, classes); + const opaqueRequired = naturalType === "JsonElement"; + const opaqueOptional = naturalType === "JsonElement?"; + const opaque = opaqueRequired || opaqueOptional; + const csType = opaqueRequired ? "object" : opaqueOptional ? "object?" : naturalType; sigParams.push(`${csType} ${pName}${isReq ? "" : " = null"}`); - bodyAssignments.push(`${csharpName} = ${pName}`); - if (requiresArgumentNullCheck(csType, isReq)) { + const assignedValue = opaqueRequired + ? `CopilotClient.ToJsonElementForWire(${pName})!.Value` + : opaqueOptional + ? `CopilotClient.ToJsonElementForWire(${pName})` + : pName; + bodyAssignments.push(`${csharpName} = ${assignedValue}`); + if (opaqueRequired || (!opaque && requiresArgumentNullCheck(csType, isReq))) { argumentNullChecks.push(`${indent} ArgumentNullException.ThrowIfNull(${pName});`); } - parameterDescriptions.push({ name: pName, description: (pSchema as JSONSchema7).description }); + parameterDescriptions.push({ name: pName, description: jsonSchema.description }); } } sigParams.push("CancellationToken cancellationToken = default"); diff --git a/scripts/codegen/package-lock.json b/scripts/codegen/package-lock.json index ff7c16f93..b173ddec8 100644 --- a/scripts/codegen/package-lock.json +++ b/scripts/codegen/package-lock.json @@ -795,7 +795,6 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, From a81706d960523788426dadd629a4d52424f09859 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 13:39:19 +0100 Subject: [PATCH 03/20] C# codegen: honor property-level visibility=internal Properties annotated with .asInternal() in the runtime Zod schema now emit as `internal` with [JsonInclude] (required for STJ source-gen to (de)serialize non-public members). Drop the `required` modifier when a property is internal: CS9032 forbids `internal required` members in a public class. The runtime keeps the field's semantic intent (must be present on the wire) but the SDK side no longer requires external callers to initialize a member they cannot see. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/Rpc.cs | 756 +++++++++++--------------- dotnet/src/Generated/SessionEvents.cs | 51 +- scripts/codegen/csharp.ts | 39 +- scripts/codegen/utils.ts | 5 + 4 files changed, 356 insertions(+), 495 deletions(-) diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index 6c1624e26..f9e800c6b 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -16,7 +16,7 @@ using System.Text.Json.Serialization; using System.Threading; -namespace GitHub.Copilot.Rpc; +namespace GitHub.Copilot.SDK.Rpc; /// Server liveness response, including the echoed message, current server timestamp, and protocol version. public sealed class PingResult @@ -1537,9 +1537,8 @@ public sealed class CopilotUserResponseOrganizationListItem public string? Name { get; set; } } -/// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. -[Experimental(Diagnostics.Experimental)] -public sealed class CopilotUserResponseQuotaSnapshotsChat +/// RPC data type for CopilotUserResponseQuotaSnapshotsValue operations. +public sealed class CopilotUserResponseQuotaSnapshotsValue { /// Gets or sets the entitlement value. [JsonPropertyName("entitlement")] @@ -1590,129 +1589,6 @@ public sealed class CopilotUserResponseQuotaSnapshotsChat public bool? Unlimited { get; set; } } -/// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. -[Experimental(Diagnostics.Experimental)] -public sealed class CopilotUserResponseQuotaSnapshotsCompletions -{ - /// Gets or sets the entitlement value. - [JsonPropertyName("entitlement")] - public double? Entitlement { get; set; } - - /// Gets or sets the has_quota value. - [JsonPropertyName("has_quota")] - public bool? HasQuota { get; set; } - - /// Gets or sets the overage_count value. - [JsonPropertyName("overage_count")] - public double? OverageCount { get; set; } - - /// Gets or sets the overage_permitted value. - [JsonPropertyName("overage_permitted")] - public bool? OveragePermitted { get; set; } - - /// Gets or sets the percent_remaining value. - [JsonPropertyName("percent_remaining")] - public double? PercentRemaining { get; set; } - - /// Gets or sets the quota_id value. - [JsonPropertyName("quota_id")] - public string? QuotaId { get; set; } - - /// Gets or sets the quota_remaining value. - [JsonPropertyName("quota_remaining")] - public double? QuotaRemaining { get; set; } - - /// Gets or sets the quota_reset_at value. - [JsonPropertyName("quota_reset_at")] - public double? QuotaResetAt { get; set; } - - /// Gets or sets the remaining value. - [JsonPropertyName("remaining")] - public double? Remaining { get; set; } - - /// Gets or sets the timestamp_utc value. - [JsonPropertyName("timestamp_utc")] - public string? TimestampUtc { get; set; } - - /// Gets or sets the token_based_billing value. - [JsonPropertyName("token_based_billing")] - public bool? TokenBasedBilling { get; set; } - - /// Gets or sets the unlimited value. - [JsonPropertyName("unlimited")] - public bool? Unlimited { get; set; } -} - -/// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. -[Experimental(Diagnostics.Experimental)] -public sealed class CopilotUserResponseQuotaSnapshotsPremiumInteractions -{ - /// Gets or sets the entitlement value. - [JsonPropertyName("entitlement")] - public double? Entitlement { get; set; } - - /// Gets or sets the has_quota value. - [JsonPropertyName("has_quota")] - public bool? HasQuota { get; set; } - - /// Gets or sets the overage_count value. - [JsonPropertyName("overage_count")] - public double? OverageCount { get; set; } - - /// Gets or sets the overage_permitted value. - [JsonPropertyName("overage_permitted")] - public bool? OveragePermitted { get; set; } - - /// Gets or sets the percent_remaining value. - [JsonPropertyName("percent_remaining")] - public double? PercentRemaining { get; set; } - - /// Gets or sets the quota_id value. - [JsonPropertyName("quota_id")] - public string? QuotaId { get; set; } - - /// Gets or sets the quota_remaining value. - [JsonPropertyName("quota_remaining")] - public double? QuotaRemaining { get; set; } - - /// Gets or sets the quota_reset_at value. - [JsonPropertyName("quota_reset_at")] - public double? QuotaResetAt { get; set; } - - /// Gets or sets the remaining value. - [JsonPropertyName("remaining")] - public double? Remaining { get; set; } - - /// Gets or sets the timestamp_utc value. - [JsonPropertyName("timestamp_utc")] - public string? TimestampUtc { get; set; } - - /// Gets or sets the token_based_billing value. - [JsonPropertyName("token_based_billing")] - public bool? TokenBasedBilling { get; set; } - - /// Gets or sets the unlimited value. - [JsonPropertyName("unlimited")] - public bool? Unlimited { get; set; } -} - -/// Schema for the `CopilotUserResponseQuotaSnapshots` type. -[Experimental(Diagnostics.Experimental)] -public sealed class CopilotUserResponseQuotaSnapshots -{ - /// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. - [JsonPropertyName("chat")] - public CopilotUserResponseQuotaSnapshotsChat? Chat { get; set; } - - /// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. - [JsonPropertyName("completions")] - public CopilotUserResponseQuotaSnapshotsCompletions? Completions { get; set; } - - /// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. - [JsonPropertyName("premium_interactions")] - public CopilotUserResponseQuotaSnapshotsPremiumInteractions? PremiumInteractions { get; set; } -} - /// Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. [Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponse @@ -1797,9 +1673,9 @@ public sealed class CopilotUserResponse [JsonPropertyName("quota_reset_date_utc")] public string? QuotaResetDateUtc { get; set; } - /// Schema for the `CopilotUserResponseQuotaSnapshots` type. + /// Gets or sets the quota_snapshots value. [JsonPropertyName("quota_snapshots")] - public CopilotUserResponseQuotaSnapshots? QuotaSnapshots { get; set; } + public IDictionary? QuotaSnapshots { get; set; } /// Gets or sets the restricted_telemetry value. [JsonPropertyName("restricted_telemetry")] @@ -7221,13 +7097,13 @@ public sealed class Converter : JsonConverter /// public override ModelPickerCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ModelPickerCategory value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerCategory)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerCategory)); } } } @@ -7289,13 +7165,13 @@ public sealed class Converter : JsonConverter /// public override ModelPickerPriceCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ModelPickerPriceCategory value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerPriceCategory)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerPriceCategory)); } } } @@ -7354,13 +7230,13 @@ public sealed class Converter : JsonConverter /// public override ModelPolicyState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ModelPolicyState value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPolicyState)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPolicyState)); } } } @@ -7422,13 +7298,13 @@ public sealed class Converter : JsonConverter /// public override DiscoveredMcpServerType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, DiscoveredMcpServerType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DiscoveredMcpServerType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DiscoveredMcpServerType)); } } } @@ -7484,13 +7360,13 @@ public sealed class Converter : JsonConverter /// public override SessionFsSetProviderConventions Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsSetProviderConventions value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSetProviderConventions)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSetProviderConventions)); } } } @@ -7547,13 +7423,13 @@ public sealed class Converter : JsonConverter public override ConnectedRemoteSessionMetadataKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ConnectedRemoteSessionMetadataKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ConnectedRemoteSessionMetadataKind)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ConnectedRemoteSessionMetadataKind)); } } } @@ -7610,13 +7486,13 @@ public sealed class Converter : JsonConverter /// public override SessionContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionContextHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionContextHostType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionContextHostType)); } } } @@ -7679,13 +7555,13 @@ public sealed class Converter : JsonConverter /// public override SendAgentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SendAgentMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAgentMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAgentMode)); } } } @@ -7745,13 +7621,13 @@ public sealed class Converter : JsonConverter /// public override SendAttachmentGithubReferenceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SendAttachmentGithubReferenceType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAttachmentGithubReferenceType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAttachmentGithubReferenceType)); } } } @@ -7808,13 +7684,13 @@ public sealed class Converter : JsonConverter /// public override SendMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SendMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendMode)); } } } @@ -7874,13 +7750,13 @@ public sealed class Converter : JsonConverter /// public override SessionLogLevel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionLogLevel value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLogLevel)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLogLevel)); } } } @@ -7952,13 +7828,13 @@ public sealed class Converter : JsonConverter /// public override AuthInfoType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, AuthInfoType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthInfoType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthInfoType)); } } } @@ -8015,13 +7891,13 @@ public sealed class Converter : JsonConverter public override WorkspacesWorkspaceDetailsHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, WorkspacesWorkspaceDetailsHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); } } } @@ -8084,13 +7960,13 @@ public sealed class Converter : JsonConverter /// public override InstructionsSourcesLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, InstructionsSourcesLocation value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesLocation)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesLocation)); } } } @@ -8162,13 +8038,13 @@ public sealed class Converter : JsonConverter /// public override InstructionsSourcesType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, InstructionsSourcesType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesType)); } } } @@ -8237,13 +8113,13 @@ public sealed class Converter : JsonConverter /// public override AgentInfoSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, AgentInfoSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentInfoSource)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentInfoSource)); } } } @@ -8300,13 +8176,13 @@ public sealed class Converter : JsonConverter /// public override TaskExecutionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, TaskExecutionMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskExecutionMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskExecutionMode)); } } } @@ -8372,13 +8248,13 @@ public sealed class Converter : JsonConverter /// public override TaskStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, TaskStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskStatus)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskStatus)); } } } @@ -8435,13 +8311,13 @@ public sealed class Converter : JsonConverter /// public override TaskShellInfoAttachmentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, TaskShellInfoAttachmentMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskShellInfoAttachmentMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskShellInfoAttachmentMode)); } } } @@ -8501,13 +8377,13 @@ public sealed class Converter : JsonConverter /// public override McpSamplingExecutionAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, McpSamplingExecutionAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSamplingExecutionAction)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSamplingExecutionAction)); } } } @@ -8564,13 +8440,13 @@ public sealed class Converter : JsonConverter /// public override McpSetEnvValueModeDetails Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, McpSetEnvValueModeDetails value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSetEnvValueModeDetails)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSetEnvValueModeDetails)); } } } @@ -8627,13 +8503,13 @@ public sealed class Converter : JsonConverter /// public override OptionsUpdateEnvValueMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, OptionsUpdateEnvValueMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateEnvValueMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateEnvValueMode)); } } } @@ -8690,13 +8566,13 @@ public sealed class Converter : JsonConverter /// public override ExtensionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ExtensionSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionSource)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionSource)); } } } @@ -8759,13 +8635,13 @@ public sealed class Converter : JsonConverter /// public override ExtensionStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ExtensionStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionStatus)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionStatus)); } } } @@ -8819,13 +8695,13 @@ public sealed class Converter : JsonConverter /// public override SlashCommandInputCompletion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SlashCommandInputCompletion value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); } } } @@ -8885,13 +8761,13 @@ public sealed class Converter : JsonConverter /// public override SlashCommandKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SlashCommandKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); } } } @@ -8951,13 +8827,13 @@ public sealed class Converter : JsonConverter /// public override UIElicitationResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, UIElicitationResponseAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); } } } @@ -9017,13 +8893,13 @@ public sealed class Converter : JsonConverter /// public override UIAutoModeSwitchResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, UIAutoModeSwitchResponse value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); } } } @@ -9086,13 +8962,13 @@ public sealed class Converter : JsonConverter /// public override UIExitPlanModeAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, UIExitPlanModeAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIExitPlanModeAction)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIExitPlanModeAction)); } } } @@ -9149,13 +9025,13 @@ public sealed class Converter : JsonConverter public override PermissionsConfigureAdditionalContentExclusionPolicyScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionsConfigureAdditionalContentExclusionPolicyScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsConfigureAdditionalContentExclusionPolicyScope)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsConfigureAdditionalContentExclusionPolicyScope)); } } } @@ -9218,13 +9094,13 @@ public sealed class Converter : JsonConverter /// public override PermissionsSetApproveAllSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionsSetApproveAllSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetApproveAllSource)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetApproveAllSource)); } } } @@ -9281,13 +9157,13 @@ public sealed class Converter : JsonConverter /// public override PermissionsModifyRulesScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionsModifyRulesScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsModifyRulesScope)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsModifyRulesScope)); } } } @@ -9344,13 +9220,13 @@ public sealed class Converter : JsonConverter /// public override PermissionLocationType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionLocationType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionLocationType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionLocationType)); } } } @@ -9410,13 +9286,13 @@ public sealed class Converter : JsonConverter /// public override MetadataSnapshotCurrentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, MetadataSnapshotCurrentMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotCurrentMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotCurrentMode)); } } } @@ -9473,13 +9349,13 @@ public sealed class Converter : JsonConverter public override MetadataSnapshotRemoteMetadataTaskType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, MetadataSnapshotRemoteMetadataTaskType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotRemoteMetadataTaskType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotRemoteMetadataTaskType)); } } } @@ -9536,13 +9412,13 @@ public sealed class Converter : JsonConverter /// public override WorkspaceSummaryHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, WorkspaceSummaryHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceSummaryHostType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceSummaryHostType)); } } } @@ -9599,13 +9475,13 @@ public sealed class Converter : JsonConverter public override SessionWorkingDirectoryContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionWorkingDirectoryContextHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionWorkingDirectoryContextHostType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionWorkingDirectoryContextHostType)); } } } @@ -9665,13 +9541,13 @@ public sealed class Converter : JsonConverter /// public override ShellKillSignal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ShellKillSignal value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellKillSignal)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellKillSignal)); } } } @@ -9728,13 +9604,13 @@ public sealed class Converter : JsonConverter /// public override QueuePendingItemsKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, QueuePendingItemsKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(QueuePendingItemsKind)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(QueuePendingItemsKind)); } } } @@ -9791,13 +9667,13 @@ public sealed class Converter : JsonConverter /// public override EventsCursorStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, EventsCursorStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsCursorStatus)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsCursorStatus)); } } } @@ -9854,13 +9730,13 @@ public sealed class Converter : JsonConverter /// public override EventsAgentScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, EventsAgentScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsAgentScope)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsAgentScope)); } } } @@ -9920,13 +9796,13 @@ public sealed class Converter : JsonConverter /// public override RemoteSessionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, RemoteSessionMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMode)); } } } @@ -9982,13 +9858,13 @@ public sealed class Converter : JsonConverter /// public override SessionFsErrorCode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsErrorCode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsErrorCode)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsErrorCode)); } } } @@ -10044,13 +9920,13 @@ public sealed class Converter : JsonConverter public override SessionFsReaddirWithTypesEntryType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsReaddirWithTypesEntryType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsReaddirWithTypesEntryType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsReaddirWithTypesEntryType)); } } } @@ -10109,13 +9985,13 @@ public sealed class Converter : JsonConverter /// public override SessionFsSqliteQueryType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsSqliteQueryType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSqliteQueryType)); + GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSqliteQueryType)); } } } @@ -13105,225 +12981,224 @@ public static void RegisterClientSessionApiHandlers(JsonRpc rpc, FuncTotal number of premium API requests used during the session.
+ [JsonInclude] [JsonPropertyName("totalPremiumRequests")] - public required double TotalPremiumRequests { get; set; } + internal double TotalPremiumRequests { get; set; } } /// Working directory and git context at session start. @@ -1995,13 +1996,15 @@ public sealed partial class AssistantMessageData { /// Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] [JsonPropertyName("anthropicAdvisorBlocks")] - public JsonElement[]? AnthropicAdvisorBlocks { get; set; } + internal JsonElement[]? AnthropicAdvisorBlocks { get; set; } /// Anthropic advisor model ID used for this response, for timeline display on replay. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] [JsonPropertyName("anthropicAdvisorModel")] - public string? AnthropicAdvisorModel { get; set; } + internal string? AnthropicAdvisorModel { get; set; } /// The assistant's text response content. [JsonPropertyName("content")] @@ -2187,8 +2190,9 @@ public sealed partial class AssistantUsageData /// Per-quota resource usage snapshots, keyed by quota identifier. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] [JsonPropertyName("quotaSnapshots")] - public IDictionary? QuotaSnapshots { get; set; } + internal JsonElement? QuotaSnapshots { get; set; } /// Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max"). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -3600,44 +3604,6 @@ public sealed partial class AssistantUsageCopilotUsage public required double TotalNanoAiu { get; set; } } -/// Schema for the `AssistantUsageQuotaSnapshot` type. -/// Nested data type for AssistantUsageQuotaSnapshot. -public sealed partial class AssistantUsageQuotaSnapshot -{ - /// Total requests allowed by the entitlement. - [JsonPropertyName("entitlementRequests")] - public required long EntitlementRequests { get; set; } - - /// Whether the user has an unlimited usage entitlement. - [JsonPropertyName("isUnlimitedEntitlement")] - public required bool IsUnlimitedEntitlement { get; set; } - - /// Number of requests over the entitlement limit. - [JsonPropertyName("overage")] - public required double Overage { get; set; } - - /// Whether overage is allowed when quota is exhausted. - [JsonPropertyName("overageAllowedWithExhaustedQuota")] - public required bool OverageAllowedWithExhaustedQuota { get; set; } - - /// Percentage of quota remaining (0 to 100). - [JsonPropertyName("remainingPercentage")] - public required double RemainingPercentage { get; set; } - - /// Date when the quota resets. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("resetDate")] - public DateTimeOffset? ResetDate { get; set; } - - /// Whether usage is still permitted after quota exhaustion. - [JsonPropertyName("usageAllowedWithExhaustedQuota")] - public required bool UsageAllowedWithExhaustedQuota { get; set; } - - /// Number of requests already consumed. - [JsonPropertyName("usedRequests")] - public required long UsedRequests { get; set; } -} - /// Error details when the tool execution failed. /// Nested data type for ToolExecutionCompleteError. public sealed partial class ToolExecutionCompleteError @@ -7122,7 +7088,6 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(AssistantUsageCopilotUsageTokenDetail))] [JsonSerializable(typeof(AssistantUsageData))] [JsonSerializable(typeof(AssistantUsageEvent))] -[JsonSerializable(typeof(AssistantUsageQuotaSnapshot))] [JsonSerializable(typeof(AutoModeSwitchCompletedData))] [JsonSerializable(typeof(AutoModeSwitchCompletedEvent))] [JsonSerializable(typeof(AutoModeSwitchRequestedData))] diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index a4ab9f854..07c0c6c9d 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -36,6 +36,7 @@ import { isNodeFullyDeprecated, isSchemaDeprecated, isSchemaExperimental, + isSchemaInternal, isObjectSchema, isVoidSchema, getNullableInner, @@ -777,9 +778,12 @@ function generateFlattenedBooleanDiscriminatedClass( if (isSchemaDeprecated(info.schema)) pushObsoleteAttributes(lines, " "); if (isMillisecondsDurationProperty(propName, info.schema)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); + const propInternal = isSchemaInternal(info.schema); + if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; - lines.push(` public ${reqMod}${csharpType} ${csharpName} { get; set; }`); + const reqMod = isReq && !csharpType.endsWith("?") && !propInternal ? "required " : ""; + const propVisibility = propInternal ? "internal" : "public"; + lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`); } lines.push(`}`); @@ -880,9 +884,12 @@ function generateDerivedClass( if (isSchemaDeprecated(prop)) pushObsoleteAttributes(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); + const propInternal = isSchemaInternal(prop); + if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; - lines.push(` public ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); + const reqMod = isReq && !csharpType.endsWith("?") && !propInternal ? "required " : ""; + const propVisibility = propInternal ? "internal" : "public"; + lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } } @@ -1105,9 +1112,12 @@ function generateNestedClass( if (isSchemaDeprecated(prop)) pushObsoleteAttributes(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); + const propInternal = isSchemaInternal(prop); + if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; - lines.push(` public ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); + const reqMod = isReq && !csharpType.endsWith("?") && !propInternal ? "required " : ""; + const propVisibility = propInternal ? "internal" : "public"; + lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } if (lines[lines.length - 1] === "") lines.pop(); lines.push(`}`); @@ -1251,9 +1261,12 @@ function generateDataClass(variant: EventVariant, knownTypes: Map).stability === "experimental"; } +/** Returns true when a JSON Schema node is marked as visibility:"internal" (set via `.asInternal()` on the Zod source). */ +export function isSchemaInternal(schema: JSONSchema7 | null | undefined): boolean { + return typeof schema === "object" && schema !== null && (schema as Record).visibility === "internal"; +} + // ── $ref resolution ───────────────────────────────────────────────────────── /** Extract the generated type name from a `$ref` path (e.g. "#/definitions/Model" → "Model"). */ From d9681d59477366b3e66c494e694c3b2275151fea Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 13:49:24 +0100 Subject: [PATCH 04/20] C# codegen: honor property-level visibility=experimental Mirror the property-level internal handling for experimental: emit [Experimental(Diagnostics.Experimental)] on properties whose runtime Zod schema is marked .asExperimental(), and drop the `required` modifier in that case to avoid CS9042 (required + obsolete-family attribute on a non-experimental containing class). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/Rpc.cs | 5 +++++ dotnet/src/Generated/SessionEvents.cs | 9 +++++++-- scripts/codegen/csharp.ts | 18 ++++++++++++++---- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index f9e800c6b..33f7bea50 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -2479,6 +2479,7 @@ public sealed class AgentInfo public string Id { get; set; } = string.Empty; /// MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("mcpServers")] public IDictionary? McpServers { get; set; } @@ -3542,6 +3543,7 @@ public sealed class SessionInstalledPlugin internal sealed class SessionUpdateOptionsParams { /// Additional content-exclusion policies to merge into the session's policy set. Opaque shape; see `ContentExclusionApiResponse` in the runtime. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("additionalContentExclusionPolicies")] public IList? AdditionalContentExclusionPolicies { get; set; } @@ -3646,6 +3648,7 @@ internal sealed class SessionUpdateOptionsParams public string? Model { get; set; } /// Custom model-provider configuration (BYOK). Opaque shape; see `ProviderConfig` in the runtime. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("provider")] public JsonElement? Provider { get; set; } @@ -3658,6 +3661,7 @@ internal sealed class SessionUpdateOptionsParams public bool? RunningInInteractiveMode { get; set; } /// Sandbox configuration shape; opaque to SDK consumers. See `SandboxConfig` in the runtime. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("sandboxConfig")] public JsonElement? SandboxConfig { get; set; } @@ -4497,6 +4501,7 @@ public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRule public sealed class PermissionsConfigureAdditionalContentExclusionPolicy { /// Gets or sets the last_updated_at value. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("last_updated_at")] public JsonElement LastUpdatedAt { get; set; } diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index 461db5cae..f643aa5b3 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -1675,6 +1675,7 @@ public sealed partial class SessionShutdownData public required TimeSpan TotalApiDuration { get; set; } /// Session-wide accumulated nano-AI units cost. + [Experimental(Diagnostics.Experimental)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("totalNanoAiu")] public double? TotalNanoAiu { get; set; } @@ -2141,6 +2142,7 @@ public sealed partial class AssistantUsageData public AssistantUsageCopilotUsage? CopilotUsage { get; set; } /// Model multiplier cost for billing purposes. + [Experimental(Diagnostics.Experimental)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("cost")] public double? Cost { get; set; } @@ -3189,12 +3191,14 @@ public sealed partial class ShutdownCodeChanges public sealed partial class ShutdownModelMetricRequests { /// Cumulative cost multiplier for requests to this model. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("cost")] - public required double Cost { get; set; } + public double Cost { get; set; } /// Total number of API requests made to this model. + [Experimental(Diagnostics.Experimental)] [JsonPropertyName("count")] - public required long Count { get; set; } + public long Count { get; set; } } /// Schema for the `ShutdownModelMetricTokenDetail` type. @@ -3246,6 +3250,7 @@ public sealed partial class ShutdownModelMetric public IDictionary? TokenDetails { get; set; } /// Accumulated nano-AI units cost for this model. + [Experimental(Diagnostics.Experimental)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("totalNanoAiu")] public double? TotalNanoAiu { get; set; } diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index 07c0c6c9d..3a946b678 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -776,12 +776,14 @@ function generateFlattenedBooleanDiscriminatedClass( lines.push(...xmlDocPropertyComment(info.schema.description, propName, " ")); lines.push(...emitDataAnnotations(info.schema, " ", csharpType)); if (isSchemaDeprecated(info.schema)) pushObsoleteAttributes(lines, " "); + if (isSchemaExperimental(info.schema)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, info.schema)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); const propInternal = isSchemaInternal(info.schema); + const propExperimental = isSchemaExperimental(info.schema); if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") && !propInternal ? "required " : ""; + const reqMod = isReq && !csharpType.endsWith("?") && !propInternal && !propExperimental ? "required " : ""; const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`); } @@ -882,12 +884,14 @@ function generateDerivedClass( lines.push(...xmlDocPropertyComment(prop.description, propName, " ")); lines.push(...emitDataAnnotations(prop, " ", csharpType)); if (isSchemaDeprecated(prop)) pushObsoleteAttributes(lines, " "); + if (isSchemaExperimental(prop)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); const propInternal = isSchemaInternal(prop); + const propExperimental = isSchemaExperimental(prop); if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") && !propInternal ? "required " : ""; + const reqMod = isReq && !csharpType.endsWith("?") && !propInternal && !propExperimental ? "required " : ""; const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } @@ -1110,12 +1114,14 @@ function generateNestedClass( lines.push(...xmlDocPropertyComment(prop.description, propName, " ")); lines.push(...emitDataAnnotations(prop, " ", csharpType)); if (isSchemaDeprecated(prop)) pushObsoleteAttributes(lines, " "); + if (isSchemaExperimental(prop)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); const propInternal = isSchemaInternal(prop); + const propExperimental = isSchemaExperimental(prop); if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") && !propInternal ? "required " : ""; + const reqMod = isReq && !csharpType.endsWith("?") && !propInternal && !propExperimental ? "required " : ""; const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } @@ -1259,12 +1265,14 @@ function generateDataClass(variant: EventVariant, knownTypes: Map Date: Thu, 21 May 2026 14:35:36 +0100 Subject: [PATCH 05/20] Revert required-drop hack now that runtime rejects bad shapes The runtime schema generator now rejects required properties marked internal/experimental whose containing type isn't, so the C# codegen no longer needs to silently drop \ equired\ to avoid CS9032/CS9042. The property-level marker support stays - it's still useful for optional properties. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/Rpc.cs | 5 +++- dotnet/src/Generated/SessionEvents.cs | 13 +++++---- scripts/codegen/csharp.ts | 42 +++++++++++++-------------- 3 files changed, 32 insertions(+), 28 deletions(-) diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index 33f7bea50..d98652a5b 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -366,6 +366,7 @@ public sealed class McpConfigList } /// MCP server name and configuration to add to user configuration. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigAddRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). @@ -381,6 +382,7 @@ internal sealed class McpConfigAddRequest } /// MCP server name and replacement configuration to write to user configuration. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigUpdateRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). @@ -4501,7 +4503,6 @@ public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRule public sealed class PermissionsConfigureAdditionalContentExclusionPolicy { /// Gets or sets the last_updated_at value. - [Experimental(Diagnostics.Experimental)] [JsonPropertyName("last_updated_at")] public JsonElement LastUpdatedAt { get; set; } @@ -10187,6 +10188,7 @@ public async Task ListAsync(CancellationToken cancellationToken = /// Unique name for the MCP server. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . + [Experimental(Diagnostics.Experimental)] public async Task AddAsync(string name, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); @@ -10200,6 +10202,7 @@ public async Task AddAsync(string name, object config, CancellationToken cancell /// Name of the MCP server to update. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . + [Experimental(Diagnostics.Experimental)] public async Task UpdateAsync(string name, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index f643aa5b3..48ed92aef 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -1681,9 +1681,10 @@ public sealed partial class SessionShutdownData public double? TotalNanoAiu { get; set; } /// Total number of premium API requests used during the session. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonInclude] [JsonPropertyName("totalPremiumRequests")] - internal double TotalPremiumRequests { get; set; } + internal double? TotalPremiumRequests { get; set; } } /// Working directory and git context at session start. @@ -3188,17 +3189,16 @@ public sealed partial class ShutdownCodeChanges /// Request count and cost metrics. /// Nested data type for ShutdownModelMetricRequests. +[Experimental(Diagnostics.Experimental)] public sealed partial class ShutdownModelMetricRequests { /// Cumulative cost multiplier for requests to this model. - [Experimental(Diagnostics.Experimental)] [JsonPropertyName("cost")] - public double Cost { get; set; } + public required double Cost { get; set; } /// Total number of API requests made to this model. - [Experimental(Diagnostics.Experimental)] [JsonPropertyName("count")] - public long Count { get; set; } + public required long Count { get; set; } } /// Schema for the `ShutdownModelMetricTokenDetail` type. @@ -3241,8 +3241,9 @@ public sealed partial class ShutdownModelMetricUsage public sealed partial class ShutdownModelMetric { /// Request count and cost metrics. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("requests")] - public required ShutdownModelMetricRequests Requests { get; set; } + public ShutdownModelMetricRequests? Requests { get; set; } /// Token count details per type. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index 3a946b678..980c08c6e 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -1,4 +1,4 @@ -/*--------------------------------------------------------------------------------------------- +/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. *--------------------------------------------------------------------------------------------*/ @@ -54,9 +54,9 @@ import { const execFileAsync = promisify(execFile); -// ── C# type rename overrides ──────────────────────────────────────────────── +// ── C# type rename overrides ──────────────────────────────────────────────── // Map generated class names to shorter public-facing names. -// Applied to base classes AND their derived variants (e.g., FooBar → Bar, FooBazShell → BarShell). +// Applied to base classes AND their derived variants (e.g., FooBar → Bar, FooBazShell → BarShell). const TYPE_RENAMES: Record = { PermissionRequestedDataPermissionRequest: "PermissionRequest", }; @@ -72,7 +72,7 @@ function applyTypeRename(className: string): string { return className; } -// ── C# utilities ──────────────────────────────────────────────────────────── +// ── C# utilities ──────────────────────────────────────────────────────────── function escapeXml(text: string): string { return text.replace(/&/g, "&").replace(//g, ">"); @@ -177,7 +177,7 @@ function pushRpcMethodXmlDocs( const CANCELLATION_TOKEN_DESCRIPTION = 'The to monitor for cancellation requests. The default is .'; -/** Like xmlDocComment but skips XML escaping — use only for codegen-controlled strings that already contain valid XML tags. */ +/** Like xmlDocComment but skips XML escaping — use only for codegen-controlled strings that already contain valid XML tags. */ function rawXmlDocSummary(text: string, indent: string): string[] { const line = ensureTrailingPunctuation(text.trim()); return [`${indent}/// ${line}`]; @@ -297,7 +297,7 @@ function failUnmappable(context: string, schema: JSONSchema7): never { const summary = JSON.stringify(schema, (key, value) => (key === "description" ? undefined : value)).slice(0, 200); throw new Error( `C# codegen: cannot map schema to an idiomatic C# type (${context}). ` + - `On the runtime side, either tighten the Zod schema to a typed shape, or — if it is genuinely free-form JSON — ` + + `On the runtime side, either tighten the Zod schema to a typed shape, or — if it is genuinely free-form JSON — ` + `mark it \`.asOpaqueJson()\` so the schema emits \`x-opaque-json: true\` and the codegen maps it to JsonElement. ` + `Offending schema (truncated): ${summary}`, ); @@ -311,7 +311,7 @@ async function formatCSharpFile(filePath: string): Promise { try { const projectFile = path.join(REPO_ROOT, "dotnet/src/GitHub.Copilot.SDK.csproj"); await execFileAsync("dotnet", ["format", projectFile, "--include", filePath]); - console.log(` ✓ Formatted with dotnet format`); + console.log(` ✓ Formatted with dotnet format`); } catch { // dotnet format not available, skip } @@ -346,7 +346,7 @@ function schemaTypeToCSharp(schema: JSONSchema7, required: boolean, knownTypes: const refName = schema.$ref.split("/").pop()!; return knownTypes.get(refName) || refName; } - // Titled union schemas (anyOf with a title) — use the title if it's a known generated type + // Titled union schemas (anyOf with a title) — use the title if it's a known generated type if (schema.title && schema.anyOf && knownTypes.has(schema.title)) { return required ? schema.title : `${schema.title}?`; } @@ -518,9 +518,9 @@ function pushObsoleteAttributes(lines: string[], indent = ""): void { lines.push(...obsoleteAttributes(indent)); } -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ // SESSION EVENTS -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ interface EventVariant { typeName: string; @@ -783,7 +783,7 @@ function generateFlattenedBooleanDiscriminatedClass( const propExperimental = isSchemaExperimental(info.schema); if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") && !propInternal && !propExperimental ? "required " : ""; + const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`); } @@ -891,7 +891,7 @@ function generateDerivedClass( const propExperimental = isSchemaExperimental(prop); if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") && !propInternal && !propExperimental ? "required " : ""; + const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } @@ -1121,7 +1121,7 @@ function generateNestedClass( const propExperimental = isSchemaExperimental(prop); if (propInternal) lines.push(` [JsonInclude]`); lines.push(` [JsonPropertyName("${propName}")]`); - const reqMod = isReq && !csharpType.endsWith("?") && !propInternal && !propExperimental ? "required " : ""; + const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } @@ -1272,7 +1272,7 @@ function generateDataClass(variant: EventVariant, knownTypes: Map const processed = postProcessSchema(schema); const code = generateSessionEventsCode(processed); const outPath = await writeGeneratedFile("dotnet/src/Generated/SessionEvents.cs", code); - console.log(` ✓ ${outPath}`); + console.log(` ✓ ${outPath}`); await formatCSharpFile(outPath); } -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ // RPC TYPES -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ let emittedRpcClassSchemas = new Map(); let emittedRpcEnumResultTypes = new Set(); @@ -1524,7 +1524,7 @@ function resolveRpcType(schema: JSONSchema7, isRequired: boolean, parentClassNam return resolveRpcType(refSchema, isRequired, parentClassName, propName, classes); } - // Handle anyOf: [T, null/{not:{}}] → T? (nullable typed property) + // Handle anyOf: [T, null/{not:{}}] → T? (nullable typed property) const nullableInner = getNullableInner(schema); if (nullableInner) { return resolveRpcType(nullableInner, false, parentClassName, propName, classes); @@ -2403,13 +2403,13 @@ export async function generateRpc(schemaPath?: string, sessionEventsSchema?: JSO } const code = generateRpcCode(schema, externalJsonSerializableRefs, externalValueTypes); const outPath = await writeGeneratedFile("dotnet/src/Generated/Rpc.cs", code); - console.log(` ✓ ${outPath}`); + console.log(` ✓ ${outPath}`); await formatCSharpFile(outPath); } -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ // MAIN -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ async function generate(sessionSchemaPath?: string, apiSchemaPath?: string): Promise { await generateSessionEvents(sessionSchemaPath); From 4e96e074ec3a9a758bfa9f62c8c223f5009f7f1f Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 14:41:23 +0100 Subject: [PATCH 06/20] Use chained SerializerOptions for opaque-JSON wire conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 3 callsites converting Dictionary to Dictionary (SessionFsProvider rows, MCP elicitation response Content, elicitation schema Properties) were using TypesJsonContext.Default.Object, which restricts type resolution to the Types source-gen context. This is too narrow — at this boundary the runtime type can be any primitive, dictionary, or generated DTO from any of the chained contexts (Client, Types, Session, SessionEvents, Rpc). Route all 3 through CopilotClient.ToJsonElementForWire, which uses the same chained serializer options that the JSON-RPC message formatter uses, matching pre-opaque-JSON-PR serialization behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Session.cs | 4 ++-- dotnet/src/SessionFsProvider.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dotnet/src/Session.cs b/dotnet/src/Session.cs index d4eb0df36..999ab7f60 100644 --- a/dotnet/src/Session.cs +++ b/dotnet/src/Session.cs @@ -954,7 +954,7 @@ private async Task HandleElicitationRequestAsync(ElicitationContext context, str Action = result.Action, Content = result.Content?.ToDictionary( kvp => kvp.Key, - kvp => JsonSerializer.SerializeToElement(kvp.Value, TypesJsonContext.Default.Object)) + kvp => CopilotClient.ToJsonElementForWire(kvp.Value)!.Value) }); LoggingHelpers.LogTiming(_logger, LogLevel.Debug, null, "CopilotSession.HandleElicitationRequestAsync response sent successfully. Elapsed={Elapsed}, SessionId={SessionId}, RequestId={RequestId}", @@ -1008,7 +1008,7 @@ public async Task ElicitAsync(ElicitationParams elicitationPa Type = elicitationParams.RequestedSchema.Type, Properties = elicitationParams.RequestedSchema.Properties.ToDictionary( kvp => kvp.Key, - kvp => JsonSerializer.SerializeToElement(kvp.Value, TypesJsonContext.Default.Object)), + kvp => CopilotClient.ToJsonElementForWire(kvp.Value)!.Value), Required = elicitationParams.RequestedSchema.Required }; diff --git a/dotnet/src/SessionFsProvider.cs b/dotnet/src/SessionFsProvider.cs index 0e7202820..fbb8df507 100644 --- a/dotnet/src/SessionFsProvider.cs +++ b/dotnet/src/SessionFsProvider.cs @@ -297,7 +297,7 @@ async Task ISessionFsHandler.SqliteQueryAsync(Sessio { Rows = result?.Rows?.Select(row => (IDictionary)row.ToDictionary( kvp => kvp.Key, - kvp => JsonSerializer.SerializeToElement(kvp.Value, TypesJsonContext.Default.Object))).ToList() ?? [], + kvp => CopilotClient.ToJsonElementForWire(kvp.Value)!.Value)).ToList() ?? [], Columns = result?.Columns ?? [], RowsAffected = result?.RowsAffected ?? 0, LastInsertRowid = result?.LastInsertRowid, From cf4cebdae6770b64cc5e3ecf656b73601db1c19b Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 14:57:20 +0100 Subject: [PATCH 07/20] Rust codegen: honor property-level visibility=internal and stability=experimental Mirrors the existing C# codegen support for property-level markers: - isSchemaInternal -> emit #[doc(hidden)] above the field - isSchemaExperimental -> emit the same /// **Experimental.** ... doc block used at the type level, indented to the field Imports isSchemaInternal from ./utils.js (previously only the type-level isSchemaExperimental was used). Regenerated rust/src/generated/* against the current runtime schemas. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- rust/src/generated/api_types.rs | 162 ++++++++------------------- rust/src/generated/rpc.rs | 16 +++ rust/src/generated/session_events.rs | 38 ++++++- scripts/codegen/rust.ts | 5 + 4 files changed, 102 insertions(+), 119 deletions(-) diff --git a/rust/src/generated/api_types.rs b/rust/src/generated/api_types.rs index 8acd798b7..d8a3669c1 100644 --- a/rust/src/generated/api_types.rs +++ b/rust/src/generated/api_types.rs @@ -471,6 +471,13 @@ pub struct AgentInfo { /// Stable identifier for selection. For most agents this is the same as `name`; for plugin/builtin agents it may differ. Always populated; defaults to `name` when no distinct id was assigned. pub id: String, /// MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(default)] pub mcp_servers: HashMap, /// Preferred model id for this agent. When omitted, inherits the outer agent's model. @@ -591,17 +598,9 @@ pub struct CopilotUserResponseEndpoints { pub telemetry: Option, } -/// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CopilotUserResponseQuotaSnapshotsChat { +pub struct CopilotUserResponseQuotaSnapshotsValue { #[serde(skip_serializing_if = "Option::is_none")] pub entitlement: Option, #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] @@ -631,111 +630,6 @@ pub struct CopilotUserResponseQuotaSnapshotsChat { pub unlimited: Option, } -/// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CopilotUserResponseQuotaSnapshotsCompletions { - #[serde(skip_serializing_if = "Option::is_none")] - pub entitlement: Option, - #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] - pub has_quota: Option, - #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] - pub overage_count: Option, - #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] - pub overage_permitted: Option, - #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] - pub percent_remaining: Option, - #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] - pub quota_id: Option, - #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] - pub quota_remaining: Option, - #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] - pub quota_reset_at: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub remaining: Option, - #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] - pub timestamp_utc: Option, - #[serde( - rename = "token_based_billing", - skip_serializing_if = "Option::is_none" - )] - pub token_based_billing: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub unlimited: Option, -} - -/// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CopilotUserResponseQuotaSnapshotsPremiumInteractions { - #[serde(skip_serializing_if = "Option::is_none")] - pub entitlement: Option, - #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] - pub has_quota: Option, - #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] - pub overage_count: Option, - #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] - pub overage_permitted: Option, - #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] - pub percent_remaining: Option, - #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] - pub quota_id: Option, - #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] - pub quota_remaining: Option, - #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] - pub quota_reset_at: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub remaining: Option, - #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] - pub timestamp_utc: Option, - #[serde( - rename = "token_based_billing", - skip_serializing_if = "Option::is_none" - )] - pub token_based_billing: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub unlimited: Option, -} - -/// Schema for the `CopilotUserResponseQuotaSnapshots` type. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CopilotUserResponseQuotaSnapshots { - /// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. - #[serde(skip_serializing_if = "Option::is_none")] - pub chat: Option, - /// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. - #[serde(skip_serializing_if = "Option::is_none")] - pub completions: Option, - /// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. - #[serde( - rename = "premium_interactions", - skip_serializing_if = "Option::is_none" - )] - pub premium_interactions: Option, -} - /// Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. /// ///
@@ -812,9 +706,8 @@ pub struct CopilotUserResponse { skip_serializing_if = "Option::is_none" )] pub quota_reset_date_utc: Option, - /// Schema for the `CopilotUserResponseQuotaSnapshots` type. - #[serde(rename = "quota_snapshots", skip_serializing_if = "Option::is_none")] - pub quota_snapshots: Option, + #[serde(rename = "quota_snapshots", default)] + pub quota_snapshots: HashMap>, #[serde( rename = "restricted_telemetry", skip_serializing_if = "Option::is_none" @@ -2155,6 +2048,13 @@ pub struct McpCancelSamplingExecutionResult { } /// MCP server name and configuration to add to user configuration. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigAddRequest { @@ -2197,6 +2097,13 @@ pub struct McpConfigRemoveRequest { } /// MCP server name and replacement configuration to write to user configuration. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigUpdateRequest { @@ -6380,6 +6287,13 @@ pub struct SessionsSetAdditionalPluginsResult {} #[serde(rename_all = "camelCase")] pub struct SessionUpdateOptionsParams { /// Additional content-exclusion policies to merge into the session's policy set. Opaque shape; see `ContentExclusionApiResponse` in the runtime. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(default)] pub additional_content_exclusion_policies: Vec, /// Runtime context discriminator (e.g., `cli`, `actions`). @@ -6458,6 +6372,13 @@ pub struct SessionUpdateOptionsParams { #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, /// Custom model-provider configuration (BYOK). Opaque shape; see `ProviderConfig` in the runtime. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(skip_serializing_if = "Option::is_none")] pub provider: Option, /// Reasoning effort for the selected model (model-defined enum). @@ -6467,6 +6388,13 @@ pub struct SessionUpdateOptionsParams { #[serde(skip_serializing_if = "Option::is_none")] pub running_in_interactive_mode: Option, /// Sandbox configuration shape; opaque to SDK consumers. See `SandboxConfig` in the runtime. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(skip_serializing_if = "Option::is_none")] pub sandbox_config: Option, /// Shell init profile (`None` or `NonInteractive`). diff --git a/rust/src/generated/rpc.rs b/rust/src/generated/rpc.rs index f73d1bc00..4c09d647c 100644 --- a/rust/src/generated/rpc.rs +++ b/rust/src/generated/rpc.rs @@ -222,6 +222,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name and configuration to add to user configuration. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn add(&self, params: McpConfigAddRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -238,6 +246,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name and replacement configuration to write to user configuration. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn update(&self, params: McpConfigUpdateRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index 4ea2a93c0..07915f59a 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -719,6 +719,13 @@ pub struct ShutdownCodeChanges { } /// Request count and cost metrics +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetricRequests { @@ -758,11 +765,19 @@ pub struct ShutdownModelMetricUsage { #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetric { /// Request count and cost metrics - pub requests: ShutdownModelMetricRequests, + #[serde(skip_serializing_if = "Option::is_none")] + pub requests: Option, /// Token count details per type #[serde(default)] pub token_details: HashMap, /// Accumulated nano-AI units cost for this model + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(skip_serializing_if = "Option::is_none")] pub total_nano_aiu: Option, /// Token usage breakdown @@ -813,10 +828,19 @@ pub struct SessionShutdownData { /// Cumulative time spent in API calls during the session, in milliseconds pub total_api_duration_ms: i64, /// Session-wide accumulated nano-AI units cost + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(skip_serializing_if = "Option::is_none")] pub total_nano_aiu: Option, /// Total number of premium API requests used during the session - pub total_premium_requests: f64, + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub total_premium_requests: Option, } /// Session event "session.context_changed". Updated working directory and git context after the change @@ -1123,9 +1147,11 @@ pub struct AssistantMessageToolRequest { #[serde(rename_all = "camelCase")] pub struct AssistantMessageData { /// Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping + #[doc(hidden)] #[serde(default)] pub anthropic_advisor_blocks: Vec, /// Anthropic advisor model ID used for this response, for timeline display on replay + #[doc(hidden)] #[serde(skip_serializing_if = "Option::is_none")] pub anthropic_advisor_model: Option, /// The assistant's text response content @@ -1270,6 +1296,13 @@ pub struct AssistantUsageData { #[serde(skip_serializing_if = "Option::is_none")] pub copilot_usage: Option, /// Model multiplier cost for billing purposes + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(skip_serializing_if = "Option::is_none")] pub cost: Option, /// Duration of the API call in milliseconds @@ -1298,6 +1331,7 @@ pub struct AssistantUsageData { #[serde(skip_serializing_if = "Option::is_none")] pub provider_call_id: Option, /// Per-quota resource usage snapshots, keyed by quota identifier + #[doc(hidden)] #[serde(default)] pub quota_snapshots: HashMap, /// Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") diff --git a/scripts/codegen/rust.ts b/scripts/codegen/rust.ts index f2056c35c..0f1ae1d06 100644 --- a/scripts/codegen/rust.ts +++ b/scripts/codegen/rust.ts @@ -38,6 +38,7 @@ import { isRpcMethod, isSchemaDeprecated, isSchemaExperimental, + isSchemaInternal, isVoidSchema, parseExternalSchemaRef, postProcessSchema, @@ -818,6 +819,10 @@ function emitRustStruct( lines.push(` /// ${line}`); } } + pushRustExperimentalDocs(lines, isSchemaExperimental(prop), " "); + if (isSchemaInternal(prop)) { + lines.push(` #[doc(hidden)]`); + } if (isSchemaDeprecated(prop)) { lines.push(...rustDeprecatedAttributes(" ")); } From fca140ab1c1807c75bbc594974a6e0f00c30a60c Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 15:06:22 +0100 Subject: [PATCH 08/20] =?UTF-8?q?=EF=BB=BFTypeScript=20codegen:=20honor=20?= =?UTF-8?q?property-level=20visibility=3Dinternal=20and=20stability=3Dexpe?= =?UTF-8?q?rimental?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a shared schema walker in utils.ts that appends @internal / @experimental tags to the description of any property carrying visibility:internal or stability:experimental inline. The typescript codegen calls this on each schemaForCompile before json-schema-to-typescript compiles it, so the tags appear naturally inside the generated JSDoc block for that property (no regex post-processing required). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- nodejs/src/generated/rpc.ts | 126 +++++++------------------ nodejs/src/generated/session-events.ts | 19 +++- scripts/codegen/typescript.ts | 3 + scripts/codegen/utils.ts | 46 +++++++++ 4 files changed, 100 insertions(+), 94 deletions(-) diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index 09f7e8e66..39f398e4b 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -248,6 +248,7 @@ export type ExternalToolTextResultForLlmContentResourceDetails = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "FilterMapping". */ +/** @experimental */ export type FilterMapping = | { [k: string]: ContentFilterMode; @@ -323,6 +324,7 @@ export type SessionLogLevel = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfig". */ +/** @experimental */ export type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp; /** * Remote transport type. Defaults to "http" when omitted. @@ -1178,6 +1180,8 @@ export interface AgentInfo { model?: string; /** * MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. + * + * @experimental */ mcpServers?: { [k: string]: @@ -1322,7 +1326,24 @@ export interface CopilotUserResponse { ) | null; quota_reset_date?: string; - quota_snapshots?: CopilotUserResponseQuotaSnapshots; + quota_snapshots?: { + [k: string]: + | ({ + entitlement?: number; + overage_count?: number; + overage_permitted?: boolean; + percent_remaining?: number; + quota_id?: string; + quota_remaining?: number; + remaining?: number; + unlimited?: boolean; + timestamp_utc?: string; + has_quota?: boolean; + quota_reset_at?: number; + token_based_billing?: boolean; + } | null) + | undefined; + }; restricted_telemetry?: boolean; token_based_billing?: boolean; quota_reset_date_utc?: string; @@ -1349,97 +1370,6 @@ export interface CopilotUserResponseEndpoints { proxy?: string; telemetry?: string; } -/** - * Schema for the `CopilotUserResponseQuotaSnapshots` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "CopilotUserResponseQuotaSnapshots". - */ -/** @experimental */ -export interface CopilotUserResponseQuotaSnapshots { - chat?: CopilotUserResponseQuotaSnapshotsChat; - completions?: CopilotUserResponseQuotaSnapshotsCompletions; - premium_interactions?: CopilotUserResponseQuotaSnapshotsPremiumInteractions; - [k: string]: - | ({ - entitlement?: number; - overage_count?: number; - overage_permitted?: boolean; - percent_remaining?: number; - quota_id?: string; - quota_remaining?: number; - remaining?: number; - unlimited?: boolean; - timestamp_utc?: string; - has_quota?: boolean; - quota_reset_at?: number; - token_based_billing?: boolean; - } | null) - | undefined; -} -/** - * Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "CopilotUserResponseQuotaSnapshotsChat". - */ -/** @experimental */ -export interface CopilotUserResponseQuotaSnapshotsChat { - entitlement?: number; - overage_count?: number; - overage_permitted?: boolean; - percent_remaining?: number; - quota_id?: string; - quota_remaining?: number; - remaining?: number; - unlimited?: boolean; - timestamp_utc?: string; - has_quota?: boolean; - quota_reset_at?: number; - token_based_billing?: boolean; -} -/** - * Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "CopilotUserResponseQuotaSnapshotsCompletions". - */ -/** @experimental */ -export interface CopilotUserResponseQuotaSnapshotsCompletions { - entitlement?: number; - overage_count?: number; - overage_permitted?: boolean; - percent_remaining?: number; - quota_id?: string; - quota_remaining?: number; - remaining?: number; - unlimited?: boolean; - timestamp_utc?: string; - has_quota?: boolean; - quota_reset_at?: number; - token_based_billing?: boolean; -} -/** - * Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "CopilotUserResponseQuotaSnapshotsPremiumInteractions". - */ -/** @experimental */ -export interface CopilotUserResponseQuotaSnapshotsPremiumInteractions { - entitlement?: number; - overage_count?: number; - overage_permitted?: boolean; - percent_remaining?: number; - quota_id?: string; - quota_remaining?: number; - remaining?: number; - unlimited?: boolean; - timestamp_utc?: string; - has_quota?: boolean; - quota_reset_at?: number; - token_based_billing?: boolean; -} /** * Schema for the `HMACAuthInfo` type. * @@ -2803,6 +2733,7 @@ export interface McpCancelSamplingExecutionResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigAddRequest". */ +/** @experimental */ export interface McpConfigAddRequest { /** * Unique name for the MCP server @@ -2959,6 +2890,7 @@ export interface McpConfigRemoveRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigUpdateRequest". */ +/** @experimental */ export interface McpConfigUpdateRequest { /** * Name of the MCP server to update @@ -6842,6 +6774,8 @@ export interface SessionUpdateOptionsParams { isExperimentalMode?: boolean; /** * Custom model-provider configuration (BYOK). Opaque shape; see `ProviderConfig` in the runtime. + * + * @experimental */ provider?: { [k: string]: unknown | undefined; @@ -6872,6 +6806,8 @@ export interface SessionUpdateOptionsParams { shellProcessFlags?: string[]; /** * Sandbox configuration shape; opaque to SDK consumers. See `SandboxConfig` in the runtime. + * + * @experimental */ sandboxConfig?: { [k: string]: unknown | undefined; @@ -6951,6 +6887,8 @@ export interface SessionUpdateOptionsParams { eventsLogDirectory?: string; /** * Additional content-exclusion policies to merge into the session's policy set. Opaque shape; see `ContentExclusionApiResponse` in the runtime. + * + * @experimental */ additionalContentExclusionPolicies?: { [k: string]: unknown | undefined; @@ -8787,6 +8725,8 @@ export function createServerRpc(connection: MessageConnection) { * Adds an MCP server to user configuration. * * @param params MCP server name and configuration to add to user configuration. + * + * @experimental */ add: async (params: McpConfigAddRequest): Promise => connection.sendRequest("mcp.config.add", params), @@ -8794,6 +8734,8 @@ export function createServerRpc(connection: MessageConnection) { * Updates an MCP server in user configuration. * * @param params MCP server name and replacement configuration to write to user configuration. + * + * @experimental */ update: async (params: McpConfigUpdateRequest): Promise => connection.sendRequest("mcp.config.update", params), diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index caacc3560..3196c4731 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -1464,12 +1464,16 @@ export interface ShutdownData { totalApiDurationMs: number; /** * Session-wide accumulated nano-AI units cost + * + * @experimental */ totalNanoAiu?: number; /** * Total number of premium API requests used during the session + * + * @internal */ - totalPremiumRequests: number; + totalPremiumRequests?: number; } /** * Aggregate code change metrics for the session @@ -1492,7 +1496,7 @@ export interface ShutdownCodeChanges { * Schema for the `ShutdownModelMetric` type. */ export interface ShutdownModelMetric { - requests: ShutdownModelMetricRequests; + requests?: ShutdownModelMetricRequests; /** * Token count details per type */ @@ -1501,6 +1505,8 @@ export interface ShutdownModelMetric { }; /** * Accumulated nano-AI units cost for this model + * + * @experimental */ totalNanoAiu?: number; usage: ShutdownModelMetricUsage; @@ -1508,6 +1514,7 @@ export interface ShutdownModelMetric { /** * Request count and cost metrics */ +/** @experimental */ export interface ShutdownModelMetricRequests { /** * Cumulative cost multiplier for requests to this model @@ -2403,12 +2410,16 @@ export interface AssistantMessageEvent { export interface AssistantMessageData { /** * Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping + * + * @internal */ anthropicAdvisorBlocks?: { [k: string]: unknown | undefined; }[]; /** * Anthropic advisor model ID used for this response, for timeline display on replay + * + * @internal */ anthropicAdvisorModel?: string; /** @@ -2681,6 +2692,8 @@ export interface AssistantUsageData { copilotUsage?: AssistantUsageCopilotUsage; /** * Model multiplier cost for billing purposes + * + * @experimental */ cost?: number; /** @@ -2718,6 +2731,8 @@ export interface AssistantUsageData { providerCallId?: string; /** * Per-quota resource usage snapshots, keyed by quota identifier + * + * @internal */ quotaSnapshots?: { [k: string]: AssistantUsageQuotaSnapshot | undefined; diff --git a/scripts/codegen/typescript.ts b/scripts/codegen/typescript.ts index 3afaec395..47def79aa 100644 --- a/scripts/codegen/typescript.ts +++ b/scripts/codegen/typescript.ts @@ -36,6 +36,7 @@ import { isNodeFullyDeprecated, isVoidSchema, isSchemaExperimental, + appendPropertyMarkerTagsToDescriptions, getEnumValueDescriptions, type ApiSchema, type DefinitionCollections, @@ -337,6 +338,7 @@ async function generateSessionEvents(schemaPath?: string): Promise { resolveSchema({ $ref: "#/$defs/SessionEvent" }, definitionCollections) ?? processed; const schemaForCompile = withSharedDefinitions(sessionEvent, definitionCollections); + appendPropertyMarkerTagsToDescriptions(schemaForCompile); const ts = await compile(normalizeSchemaForTypeScript(schemaForCompile), "SessionEvent", { bannerComment: `/** @@ -579,6 +581,7 @@ import type { MessageConnection } from "vscode-jsonrpc/node.js"; } const schemaForCompile = combinedSchema; + appendPropertyMarkerTagsToDescriptions(schemaForCompile); const compiled = await compile(normalizeSchemaForTypeScript(schemaForCompile), "_RpcSchemaRoot", { bannerComment: "", diff --git a/scripts/codegen/utils.ts b/scripts/codegen/utils.ts index 158e2f6f0..6ece5f134 100644 --- a/scripts/codegen/utils.ts +++ b/scripts/codegen/utils.ts @@ -506,6 +506,52 @@ export function isSchemaInternal(schema: JSONSchema7 | null | undefined): boolea return typeof schema === "object" && schema !== null && (schema as Record).visibility === "internal"; } +/** + * Append `@internal` and/or `@experimental` JSDoc-style tags to the `description` + * of every property that carries `visibility: "internal"` or `stability: "experimental"` + * inline. Used by codegens whose output mechanism (e.g. `json-schema-to-typescript`) + * renders `description` verbatim as JSDoc; downstream tooling then picks the tags + * up automatically. + * + * Mutates `schema` in place and returns it. Callers that don't want their input + * mutated should clone first. + */ +export function appendPropertyMarkerTagsToDescriptions(schema: JSONSchema7): JSONSchema7 { + const seen = new WeakSet(); + const visit = (node: unknown): void => { + if (!node || typeof node !== "object") return; + if (seen.has(node)) return; + seen.add(node); + + if (Array.isArray(node)) { + for (const item of node) visit(item); + return; + } + + const record = node as Record; + const props = record.properties; + if (props && typeof props === "object" && !Array.isArray(props)) { + for (const propSchema of Object.values(props as Record)) { + if (!propSchema || typeof propSchema !== "object") continue; + const tags: string[] = []; + if (isSchemaInternal(propSchema as JSONSchema7)) tags.push("@internal"); + if (isSchemaExperimental(propSchema as JSONSchema7)) tags.push("@experimental"); + if (tags.length === 0) continue; + const propRecord = propSchema as Record; + const existing = typeof propRecord.description === "string" ? propRecord.description : ""; + const suffix = tags.join("\n"); + propRecord.description = existing.length > 0 ? `${existing}\n\n${suffix}` : suffix; + } + } + + for (const value of Object.values(record)) { + if (value && typeof value === "object") visit(value); + } + }; + visit(schema); + return schema; +} + // ── $ref resolution ───────────────────────────────────────────────────────── /** Extract the generated type name from a `$ref` path (e.g. "#/definitions/Model" → "Model"). */ From 21ffb14eee056ebc130fc8477cd616165220a5e6 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 15:09:12 +0100 Subject: [PATCH 09/20] Python codegen: honor property-level visibility=internal and stability=experimental Mirrors the existing type-level support: where a property's inline schema carries visibility:internal or stability:experimental, the dataclass field gets the corresponding `# Internal:` / `# Experimental:` comment line. Adds a shared pushPyFieldMarkers helper so the comment block isn't duplicated between the ordinary dataclass emitter and the flat discriminated-union emitter. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- python/copilot/generated/rpc.py | 1379 +++++++++----------- python/copilot/generated/session_events.py | 72 +- scripts/codegen/python.ts | 30 +- 3 files changed, 650 insertions(+), 831 deletions(-) diff --git a/python/copilot/generated/rpc.py b/python/copilot/generated/rpc.py index 5ee9cea22..4c8076aed 100644 --- a/python/copilot/generated/rpc.py +++ b/python/copilot/generated/rpc.py @@ -253,6 +253,66 @@ def to_dict(self) -> dict: result["telemetry"] = from_union([from_str, from_none], self.telemetry) return result +@dataclass +class QuotaSnapshot: + entitlement: float | None = None + has_quota: bool | None = None + overage_count: float | None = None + overage_permitted: bool | None = None + percent_remaining: float | None = None + quota_id: str | None = None + quota_remaining: float | None = None + quota_reset_at: float | None = None + remaining: float | None = None + timestamp_utc: str | None = None + token_based_billing: bool | None = None + unlimited: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'QuotaSnapshot': + assert isinstance(obj, dict) + entitlement = from_union([from_float, from_none], obj.get("entitlement")) + has_quota = from_union([from_bool, from_none], obj.get("has_quota")) + overage_count = from_union([from_float, from_none], obj.get("overage_count")) + overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) + percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) + quota_id = from_union([from_str, from_none], obj.get("quota_id")) + quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) + quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) + remaining = from_union([from_float, from_none], obj.get("remaining")) + timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + unlimited = from_union([from_bool, from_none], obj.get("unlimited")) + return QuotaSnapshot(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + + def to_dict(self) -> dict: + result: dict = {} + if self.entitlement is not None: + result["entitlement"] = from_union([to_float, from_none], self.entitlement) + if self.has_quota is not None: + result["has_quota"] = from_union([from_bool, from_none], self.has_quota) + if self.overage_count is not None: + result["overage_count"] = from_union([to_float, from_none], self.overage_count) + if self.overage_permitted is not None: + result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) + if self.percent_remaining is not None: + result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) + if self.quota_id is not None: + result["quota_id"] = from_union([from_str, from_none], self.quota_id) + if self.quota_remaining is not None: + result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) + if self.quota_reset_at is not None: + result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) + if self.remaining is not None: + result["remaining"] = from_union([to_float, from_none], self.remaining) + if self.timestamp_utc is not None: + result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + if self.unlimited is not None: + result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + return result + class APIKeyAuthInfoType(Enum): API_KEY = "api-key" @@ -524,195 +584,6 @@ class Host(Enum): class CopilotAPITokenAuthInfoType(Enum): COPILOT_API_TOKEN = "copilot-api-token" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CopilotUserResponseQuotaSnapshotsChat: - """Schema for the `CopilotUserResponseQuotaSnapshotsChat` type.""" - - entitlement: float | None = None - has_quota: bool | None = None - overage_count: float | None = None - overage_permitted: bool | None = None - percent_remaining: float | None = None - quota_id: str | None = None - quota_remaining: float | None = None - quota_reset_at: float | None = None - remaining: float | None = None - timestamp_utc: str | None = None - token_based_billing: bool | None = None - unlimited: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsChat': - assert isinstance(obj, dict) - entitlement = from_union([from_float, from_none], obj.get("entitlement")) - has_quota = from_union([from_bool, from_none], obj.get("has_quota")) - overage_count = from_union([from_float, from_none], obj.get("overage_count")) - overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) - percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) - quota_id = from_union([from_str, from_none], obj.get("quota_id")) - quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) - quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) - remaining = from_union([from_float, from_none], obj.get("remaining")) - timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - unlimited = from_union([from_bool, from_none], obj.get("unlimited")) - return CopilotUserResponseQuotaSnapshotsChat(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) - - def to_dict(self) -> dict: - result: dict = {} - if self.entitlement is not None: - result["entitlement"] = from_union([to_float, from_none], self.entitlement) - if self.has_quota is not None: - result["has_quota"] = from_union([from_bool, from_none], self.has_quota) - if self.overage_count is not None: - result["overage_count"] = from_union([to_float, from_none], self.overage_count) - if self.overage_permitted is not None: - result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) - if self.percent_remaining is not None: - result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) - if self.quota_id is not None: - result["quota_id"] = from_union([from_str, from_none], self.quota_id) - if self.quota_remaining is not None: - result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) - if self.quota_reset_at is not None: - result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) - if self.remaining is not None: - result["remaining"] = from_union([to_float, from_none], self.remaining) - if self.timestamp_utc is not None: - result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - if self.unlimited is not None: - result["unlimited"] = from_union([from_bool, from_none], self.unlimited) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CopilotUserResponseQuotaSnapshotsCompletions: - """Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type.""" - - entitlement: float | None = None - has_quota: bool | None = None - overage_count: float | None = None - overage_permitted: bool | None = None - percent_remaining: float | None = None - quota_id: str | None = None - quota_remaining: float | None = None - quota_reset_at: float | None = None - remaining: float | None = None - timestamp_utc: str | None = None - token_based_billing: bool | None = None - unlimited: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsCompletions': - assert isinstance(obj, dict) - entitlement = from_union([from_float, from_none], obj.get("entitlement")) - has_quota = from_union([from_bool, from_none], obj.get("has_quota")) - overage_count = from_union([from_float, from_none], obj.get("overage_count")) - overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) - percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) - quota_id = from_union([from_str, from_none], obj.get("quota_id")) - quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) - quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) - remaining = from_union([from_float, from_none], obj.get("remaining")) - timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - unlimited = from_union([from_bool, from_none], obj.get("unlimited")) - return CopilotUserResponseQuotaSnapshotsCompletions(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) - - def to_dict(self) -> dict: - result: dict = {} - if self.entitlement is not None: - result["entitlement"] = from_union([to_float, from_none], self.entitlement) - if self.has_quota is not None: - result["has_quota"] = from_union([from_bool, from_none], self.has_quota) - if self.overage_count is not None: - result["overage_count"] = from_union([to_float, from_none], self.overage_count) - if self.overage_permitted is not None: - result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) - if self.percent_remaining is not None: - result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) - if self.quota_id is not None: - result["quota_id"] = from_union([from_str, from_none], self.quota_id) - if self.quota_remaining is not None: - result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) - if self.quota_reset_at is not None: - result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) - if self.remaining is not None: - result["remaining"] = from_union([to_float, from_none], self.remaining) - if self.timestamp_utc is not None: - result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - if self.unlimited is not None: - result["unlimited"] = from_union([from_bool, from_none], self.unlimited) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CopilotUserResponseQuotaSnapshotsPremiumInteractions: - """Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type.""" - - entitlement: float | None = None - has_quota: bool | None = None - overage_count: float | None = None - overage_permitted: bool | None = None - percent_remaining: float | None = None - quota_id: str | None = None - quota_remaining: float | None = None - quota_reset_at: float | None = None - remaining: float | None = None - timestamp_utc: str | None = None - token_based_billing: bool | None = None - unlimited: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsPremiumInteractions': - assert isinstance(obj, dict) - entitlement = from_union([from_float, from_none], obj.get("entitlement")) - has_quota = from_union([from_bool, from_none], obj.get("has_quota")) - overage_count = from_union([from_float, from_none], obj.get("overage_count")) - overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) - percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) - quota_id = from_union([from_str, from_none], obj.get("quota_id")) - quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) - quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) - remaining = from_union([from_float, from_none], obj.get("remaining")) - timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - unlimited = from_union([from_bool, from_none], obj.get("unlimited")) - return CopilotUserResponseQuotaSnapshotsPremiumInteractions(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) - - def to_dict(self) -> dict: - result: dict = {} - if self.entitlement is not None: - result["entitlement"] = from_union([to_float, from_none], self.entitlement) - if self.has_quota is not None: - result["has_quota"] = from_union([from_bool, from_none], self.has_quota) - if self.overage_count is not None: - result["overage_count"] = from_union([to_float, from_none], self.overage_count) - if self.overage_permitted is not None: - result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) - if self.percent_remaining is not None: - result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) - if self.quota_id is not None: - result["quota_id"] = from_union([from_str, from_none], self.quota_id) - if self.quota_remaining is not None: - result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) - if self.quota_reset_at is not None: - result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) - if self.remaining is not None: - result["remaining"] = from_union([to_float, from_none], self.remaining) - if self.timestamp_utc is not None: - result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - if self.unlimited is not None: - result["unlimited"] = from_union([from_bool, from_none], self.unlimited) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CurrentModel: @@ -6174,15 +6045,126 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionAuthStatus: - """Authentication status and account metadata for the session.""" - - is_authenticated: bool - """Whether the session has resolved authentication""" - - auth_type: AuthInfoType | None = None - """Authentication type""" - +class CopilotUserResponse: + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + access_type_sku: str | None = None + analytics_tracking_id: str | None = None + assigned_date: Any = None + can_signup_for_limited: bool | None = None + chat_enabled: bool | None = None + cli_remote_control_enabled: bool | None = None + cloud_session_storage_enabled: bool | None = None + codex_agent_enabled: bool | None = None + copilot_plan: str | None = None + copilotignore_enabled: bool | None = None + endpoints: CopilotUserResponseEndpoints | None = None + """Schema for the `CopilotUserResponseEndpoints` type.""" + + is_mcp_enabled: Any = None + limited_user_quotas: dict[str, float] | None = None + limited_user_reset_date: str | None = None + login: str | None = None + monthly_quotas: dict[str, float] | None = None + organization_list: Any = None + organization_login_list: list[str] | None = None + quota_reset_date: str | None = None + quota_reset_date_utc: str | None = None + quota_snapshots: dict[str, QuotaSnapshot | None] | None = None + restricted_telemetry: bool | None = None + token_based_billing: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponse': + assert isinstance(obj, dict) + access_type_sku = from_union([from_str, from_none], obj.get("access_type_sku")) + analytics_tracking_id = from_union([from_str, from_none], obj.get("analytics_tracking_id")) + assigned_date = obj.get("assigned_date") + can_signup_for_limited = from_union([from_bool, from_none], obj.get("can_signup_for_limited")) + chat_enabled = from_union([from_bool, from_none], obj.get("chat_enabled")) + cli_remote_control_enabled = from_union([from_bool, from_none], obj.get("cli_remote_control_enabled")) + cloud_session_storage_enabled = from_union([from_bool, from_none], obj.get("cloud_session_storage_enabled")) + codex_agent_enabled = from_union([from_bool, from_none], obj.get("codex_agent_enabled")) + copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) + copilotignore_enabled = from_union([from_bool, from_none], obj.get("copilotignore_enabled")) + endpoints = from_union([CopilotUserResponseEndpoints.from_dict, from_none], obj.get("endpoints")) + is_mcp_enabled = obj.get("is_mcp_enabled") + limited_user_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("limited_user_quotas")) + limited_user_reset_date = from_union([from_str, from_none], obj.get("limited_user_reset_date")) + login = from_union([from_str, from_none], obj.get("login")) + monthly_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("monthly_quotas")) + organization_list = obj.get("organization_list") + organization_login_list = from_union([lambda x: from_list(from_str, x), from_none], obj.get("organization_login_list")) + quota_reset_date = from_union([from_str, from_none], obj.get("quota_reset_date")) + quota_reset_date_utc = from_union([from_str, from_none], obj.get("quota_reset_date_utc")) + quota_snapshots = from_union([lambda x: from_dict(lambda x: from_union([QuotaSnapshot.from_dict, from_none], x), x), from_none], obj.get("quota_snapshots")) + restricted_telemetry = from_union([from_bool, from_none], obj.get("restricted_telemetry")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + return CopilotUserResponse(access_type_sku, analytics_tracking_id, assigned_date, can_signup_for_limited, chat_enabled, cli_remote_control_enabled, cloud_session_storage_enabled, codex_agent_enabled, copilot_plan, copilotignore_enabled, endpoints, is_mcp_enabled, limited_user_quotas, limited_user_reset_date, login, monthly_quotas, organization_list, organization_login_list, quota_reset_date, quota_reset_date_utc, quota_snapshots, restricted_telemetry, token_based_billing) + + def to_dict(self) -> dict: + result: dict = {} + if self.access_type_sku is not None: + result["access_type_sku"] = from_union([from_str, from_none], self.access_type_sku) + if self.analytics_tracking_id is not None: + result["analytics_tracking_id"] = from_union([from_str, from_none], self.analytics_tracking_id) + if self.assigned_date is not None: + result["assigned_date"] = self.assigned_date + if self.can_signup_for_limited is not None: + result["can_signup_for_limited"] = from_union([from_bool, from_none], self.can_signup_for_limited) + if self.chat_enabled is not None: + result["chat_enabled"] = from_union([from_bool, from_none], self.chat_enabled) + if self.cli_remote_control_enabled is not None: + result["cli_remote_control_enabled"] = from_union([from_bool, from_none], self.cli_remote_control_enabled) + if self.cloud_session_storage_enabled is not None: + result["cloud_session_storage_enabled"] = from_union([from_bool, from_none], self.cloud_session_storage_enabled) + if self.codex_agent_enabled is not None: + result["codex_agent_enabled"] = from_union([from_bool, from_none], self.codex_agent_enabled) + if self.copilot_plan is not None: + result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) + if self.copilotignore_enabled is not None: + result["copilotignore_enabled"] = from_union([from_bool, from_none], self.copilotignore_enabled) + if self.endpoints is not None: + result["endpoints"] = from_union([lambda x: to_class(CopilotUserResponseEndpoints, x), from_none], self.endpoints) + if self.is_mcp_enabled is not None: + result["is_mcp_enabled"] = self.is_mcp_enabled + if self.limited_user_quotas is not None: + result["limited_user_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.limited_user_quotas) + if self.limited_user_reset_date is not None: + result["limited_user_reset_date"] = from_union([from_str, from_none], self.limited_user_reset_date) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.monthly_quotas is not None: + result["monthly_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.monthly_quotas) + if self.organization_list is not None: + result["organization_list"] = self.organization_list + if self.organization_login_list is not None: + result["organization_login_list"] = from_union([lambda x: from_list(from_str, x), from_none], self.organization_login_list) + if self.quota_reset_date is not None: + result["quota_reset_date"] = from_union([from_str, from_none], self.quota_reset_date) + if self.quota_reset_date_utc is not None: + result["quota_reset_date_utc"] = from_union([from_str, from_none], self.quota_reset_date_utc) + if self.quota_snapshots is not None: + result["quota_snapshots"] = from_union([lambda x: from_dict(lambda x: from_union([lambda x: to_class(QuotaSnapshot, x), from_none], x), x), from_none], self.quota_snapshots) + if self.restricted_telemetry is not None: + result["restricted_telemetry"] = from_union([from_bool, from_none], self.restricted_telemetry) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionAuthStatus: + """Authentication status and account metadata for the session.""" + + is_authenticated: bool + """Whether the session has resolved authentication""" + + auth_type: AuthInfoType | None = None + """Authentication type""" + copilot_plan: str | None = None """Copilot plan tier (e.g., individual_pro, business)""" @@ -6427,73 +6409,6 @@ def to_dict(self) -> dict: result["tools"] = from_union([lambda x: from_list(from_str, x), from_none], self.tools) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CopilotUserResponseQuotaSnapshots: - """Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. - - Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. - - Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. - """ - entitlement: float | None = None - has_quota: bool | None = None - overage_count: float | None = None - overage_permitted: bool | None = None - percent_remaining: float | None = None - quota_id: str | None = None - quota_remaining: float | None = None - quota_reset_at: float | None = None - remaining: float | None = None - timestamp_utc: str | None = None - token_based_billing: bool | None = None - unlimited: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshots': - assert isinstance(obj, dict) - entitlement = from_union([from_float, from_none], obj.get("entitlement")) - has_quota = from_union([from_bool, from_none], obj.get("has_quota")) - overage_count = from_union([from_float, from_none], obj.get("overage_count")) - overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) - percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) - quota_id = from_union([from_str, from_none], obj.get("quota_id")) - quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) - quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) - remaining = from_union([from_float, from_none], obj.get("remaining")) - timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - unlimited = from_union([from_bool, from_none], obj.get("unlimited")) - return CopilotUserResponseQuotaSnapshots(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) - - def to_dict(self) -> dict: - result: dict = {} - if self.entitlement is not None: - result["entitlement"] = from_union([to_float, from_none], self.entitlement) - if self.has_quota is not None: - result["has_quota"] = from_union([from_bool, from_none], self.has_quota) - if self.overage_count is not None: - result["overage_count"] = from_union([to_float, from_none], self.overage_count) - if self.overage_permitted is not None: - result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) - if self.percent_remaining is not None: - result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) - if self.quota_id is not None: - result["quota_id"] = from_union([from_str, from_none], self.quota_id) - if self.quota_remaining is not None: - result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) - if self.quota_reset_at is not None: - result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) - if self.remaining is not None: - result["remaining"] = from_union([to_float, from_none], self.remaining) - if self.timestamp_utc is not None: - result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - if self.unlimited is not None: - result["unlimited"] = from_union([from_bool, from_none], self.unlimited) - return result - @dataclass class DiscoveredMCPServer: """Schema for the `DiscoveredMcpServer` type.""" @@ -7253,6 +7168,7 @@ def to_dict(self) -> dict: result["url"] = from_union([from_str, from_none], self.url) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerConfig: """MCP server configuration (stdio process or remote HTTP/SSE) @@ -10438,192 +10354,361 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SlashCommandInfo: - """Schema for the `SlashCommandInfo` type.""" - - allow_during_agent_execution: bool - """Whether the command may run while an agent turn is active""" - - description: str - """Human-readable command description""" +class APIKeyAuthInfo: + """Schema for the `ApiKeyAuthInfo` type.""" - kind: SlashCommandKind - """Coarse command category for grouping and behavior: runtime built-in, skill-backed - command, or SDK/client-owned command - """ - name: str - """Canonical command name without a leading slash""" + api_key: str + """The API key. Treat as a secret.""" - aliases: list[str] | None = None - """Canonical aliases without leading slashes""" + host: str + """Authentication host.""" - experimental: bool | None = None - """Whether the command is experimental""" + type: APIKeyAuthInfoType + """API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style).""" - input: SlashCommandInput | None = None - """Optional unstructured input hint""" + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ @staticmethod - def from_dict(obj: Any) -> 'SlashCommandInfo': + def from_dict(obj: Any) -> 'APIKeyAuthInfo': assert isinstance(obj, dict) - allow_during_agent_execution = from_bool(obj.get("allowDuringAgentExecution")) - description = from_str(obj.get("description")) - kind = SlashCommandKind(obj.get("kind")) - name = from_str(obj.get("name")) - aliases = from_union([lambda x: from_list(from_str, x), from_none], obj.get("aliases")) - experimental = from_union([from_bool, from_none], obj.get("experimental")) - input = from_union([SlashCommandInput.from_dict, from_none], obj.get("input")) - return SlashCommandInfo(allow_during_agent_execution, description, kind, name, aliases, experimental, input) + api_key = from_str(obj.get("apiKey")) + host = from_str(obj.get("host")) + type = APIKeyAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return APIKeyAuthInfo(api_key, host, type, copilot_user) def to_dict(self) -> dict: result: dict = {} - result["allowDuringAgentExecution"] = from_bool(self.allow_during_agent_execution) - result["description"] = from_str(self.description) - result["kind"] = to_enum(SlashCommandKind, self.kind) - result["name"] = from_str(self.name) - if self.aliases is not None: - result["aliases"] = from_union([lambda x: from_list(from_str, x), from_none], self.aliases) - if self.experimental is not None: - result["experimental"] = from_union([from_bool, from_none], self.experimental) - if self.input is not None: - result["input"] = from_union([lambda x: to_class(SlashCommandInput, x), from_none], self.input) + result["apiKey"] = from_str(self.api_key) + result["host"] = from_str(self.host) + result["type"] = to_enum(APIKeyAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class RemoteSessionConnectionResult: - """Remote session connection result.""" +class CopilotAPITokenAuthInfo: + """Schema for the `CopilotApiTokenAuthInfo` type.""" - metadata: ConnectedRemoteSessionMetadata - """Metadata for a connected remote session.""" + host: Host + """Authentication host (always the public GitHub host).""" - session_id: str - """SDK session ID for the connected remote session.""" + type: CopilotAPITokenAuthInfoType + """Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` + environment-variable pair. The token itself is read from the environment by the runtime, + not carried in this struct. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ @staticmethod - def from_dict(obj: Any) -> 'RemoteSessionConnectionResult': + def from_dict(obj: Any) -> 'CopilotAPITokenAuthInfo': assert isinstance(obj, dict) - metadata = ConnectedRemoteSessionMetadata.from_dict(obj.get("metadata")) - session_id = from_str(obj.get("sessionId")) - return RemoteSessionConnectionResult(metadata, session_id) - - def to_dict(self) -> dict: + host = Host(obj.get("host")) + type = CopilotAPITokenAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return CopilotAPITokenAuthInfo(host, type, copilot_user) + + def to_dict(self) -> dict: result: dict = {} - result["metadata"] = to_class(ConnectedRemoteSessionMetadata, self.metadata) - result["sessionId"] = from_str(self.session_id) + result["host"] = to_enum(Host, self.host) + result["type"] = to_enum(CopilotAPITokenAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CopilotUserResponse: +class EnvAuthInfo: + """Schema for the `EnvAuthInfo` type.""" + + env_var: str + """Name of the environment variable the token was sourced from.""" + + host: str + """Authentication host (e.g. https://github.com or a GHES host).""" + + token: str + """The token value itself. Treat as a secret.""" + + type: EnvAuthInfoType + """Personal access token (PAT) or server-to-server token sourced from an environment + variable. + """ + copilot_user: CopilotUserResponse | None = None """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. """ - access_type_sku: str | None = None - analytics_tracking_id: str | None = None - assigned_date: Any = None - can_signup_for_limited: bool | None = None - chat_enabled: bool | None = None - cli_remote_control_enabled: bool | None = None - cloud_session_storage_enabled: bool | None = None - codex_agent_enabled: bool | None = None - copilot_plan: str | None = None - copilotignore_enabled: bool | None = None - endpoints: CopilotUserResponseEndpoints | None = None - """Schema for the `CopilotUserResponseEndpoints` type.""" - - is_mcp_enabled: Any = None - limited_user_quotas: dict[str, float] | None = None - limited_user_reset_date: str | None = None login: str | None = None - monthly_quotas: dict[str, float] | None = None - organization_list: Any = None - organization_login_list: list[str] | None = None - quota_reset_date: str | None = None - quota_reset_date_utc: str | None = None - quota_snapshots: dict[str, CopilotUserResponseQuotaSnapshots | None] | None = None - """Schema for the `CopilotUserResponseQuotaSnapshots` type.""" - - restricted_telemetry: bool | None = None - token_based_billing: bool | None = None + """User login associated with the token. Undefined for server-to-server tokens (those + starting with `ghs_`). + """ @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponse': + def from_dict(obj: Any) -> 'EnvAuthInfo': assert isinstance(obj, dict) - access_type_sku = from_union([from_str, from_none], obj.get("access_type_sku")) - analytics_tracking_id = from_union([from_str, from_none], obj.get("analytics_tracking_id")) - assigned_date = obj.get("assigned_date") - can_signup_for_limited = from_union([from_bool, from_none], obj.get("can_signup_for_limited")) - chat_enabled = from_union([from_bool, from_none], obj.get("chat_enabled")) - cli_remote_control_enabled = from_union([from_bool, from_none], obj.get("cli_remote_control_enabled")) - cloud_session_storage_enabled = from_union([from_bool, from_none], obj.get("cloud_session_storage_enabled")) - codex_agent_enabled = from_union([from_bool, from_none], obj.get("codex_agent_enabled")) - copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) - copilotignore_enabled = from_union([from_bool, from_none], obj.get("copilotignore_enabled")) - endpoints = from_union([CopilotUserResponseEndpoints.from_dict, from_none], obj.get("endpoints")) - is_mcp_enabled = obj.get("is_mcp_enabled") - limited_user_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("limited_user_quotas")) - limited_user_reset_date = from_union([from_str, from_none], obj.get("limited_user_reset_date")) + env_var = from_str(obj.get("envVar")) + host = from_str(obj.get("host")) + token = from_str(obj.get("token")) + type = EnvAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) login = from_union([from_str, from_none], obj.get("login")) - monthly_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("monthly_quotas")) - organization_list = obj.get("organization_list") - organization_login_list = from_union([lambda x: from_list(from_str, x), from_none], obj.get("organization_login_list")) - quota_reset_date = from_union([from_str, from_none], obj.get("quota_reset_date")) - quota_reset_date_utc = from_union([from_str, from_none], obj.get("quota_reset_date_utc")) - quota_snapshots = from_union([lambda x: from_dict(lambda x: from_union([CopilotUserResponseQuotaSnapshots.from_dict, from_none], x), x), from_none], obj.get("quota_snapshots")) - restricted_telemetry = from_union([from_bool, from_none], obj.get("restricted_telemetry")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - return CopilotUserResponse(access_type_sku, analytics_tracking_id, assigned_date, can_signup_for_limited, chat_enabled, cli_remote_control_enabled, cloud_session_storage_enabled, codex_agent_enabled, copilot_plan, copilotignore_enabled, endpoints, is_mcp_enabled, limited_user_quotas, limited_user_reset_date, login, monthly_quotas, organization_list, organization_login_list, quota_reset_date, quota_reset_date_utc, quota_snapshots, restricted_telemetry, token_based_billing) + return EnvAuthInfo(env_var, host, token, type, copilot_user, login) + + def to_dict(self) -> dict: + result: dict = {} + result["envVar"] = from_str(self.env_var) + result["host"] = from_str(self.host) + result["token"] = from_str(self.token) + result["type"] = to_enum(EnvAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class GhCLIAuthInfo: + """Schema for the `GhCliAuthInfo` type.""" + + host: str + """Authentication host.""" + + login: str + """User login as reported by `gh auth status`.""" + + token: str + """The token returned by `gh auth token`. Treat as a secret.""" + + type: GhCLIAuthInfoType + """Authentication via the `gh` CLI's saved credentials.""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'GhCLIAuthInfo': + assert isinstance(obj, dict) + host = from_str(obj.get("host")) + login = from_str(obj.get("login")) + token = from_str(obj.get("token")) + type = GhCLIAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return GhCLIAuthInfo(host, login, token, type, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = from_str(self.host) + result["login"] = from_str(self.login) + result["token"] = from_str(self.token) + result["type"] = to_enum(GhCLIAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HMACAuthInfo: + """Schema for the `HMACAuthInfo` type.""" + + hmac: str + """HMAC secret used to sign requests.""" + + host: Host + """Authentication host. HMAC auth always targets the public GitHub host.""" + + type: HMACAuthInfoType + """HMAC-based authentication used by GitHub-internal services.""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'HMACAuthInfo': + assert isinstance(obj, dict) + hmac = from_str(obj.get("hmac")) + host = Host(obj.get("host")) + type = HMACAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return HMACAuthInfo(hmac, host, type, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["hmac"] = from_str(self.hmac) + result["host"] = to_enum(Host, self.host) + result["type"] = to_enum(HMACAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class TokenAuthInfo: + """Schema for the `TokenAuthInfo` type.""" + + host: str + """Authentication host.""" + + token: str + """The token value itself. Treat as a secret.""" + + type: TokenAuthInfoType + """SDK-side token authentication; the host configured the token directly via the SDK.""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'TokenAuthInfo': + assert isinstance(obj, dict) + host = from_str(obj.get("host")) + token = from_str(obj.get("token")) + type = TokenAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return TokenAuthInfo(host, token, type, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = from_str(self.host) + result["token"] = from_str(self.token) + result["type"] = to_enum(TokenAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UserAuthInfo: + """Schema for the `UserAuthInfo` type.""" + + host: str + """Authentication host.""" + + login: str + """OAuth user login.""" + + type: UserAuthInfoType + """OAuth user authentication. The token itself is held in the runtime's secret token store + (keyed by host+login) and is NOT carried in this struct. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'UserAuthInfo': + assert isinstance(obj, dict) + host = from_str(obj.get("host")) + login = from_str(obj.get("login")) + type = UserAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return UserAuthInfo(host, login, type, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = from_str(self.host) + result["login"] = from_str(self.login) + result["type"] = to_enum(UserAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SlashCommandInfo: + """Schema for the `SlashCommandInfo` type.""" + + allow_during_agent_execution: bool + """Whether the command may run while an agent turn is active""" + + description: str + """Human-readable command description""" + + kind: SlashCommandKind + """Coarse command category for grouping and behavior: runtime built-in, skill-backed + command, or SDK/client-owned command + """ + name: str + """Canonical command name without a leading slash""" + + aliases: list[str] | None = None + """Canonical aliases without leading slashes""" + + experimental: bool | None = None + """Whether the command is experimental""" + + input: SlashCommandInput | None = None + """Optional unstructured input hint""" + + @staticmethod + def from_dict(obj: Any) -> 'SlashCommandInfo': + assert isinstance(obj, dict) + allow_during_agent_execution = from_bool(obj.get("allowDuringAgentExecution")) + description = from_str(obj.get("description")) + kind = SlashCommandKind(obj.get("kind")) + name = from_str(obj.get("name")) + aliases = from_union([lambda x: from_list(from_str, x), from_none], obj.get("aliases")) + experimental = from_union([from_bool, from_none], obj.get("experimental")) + input = from_union([SlashCommandInput.from_dict, from_none], obj.get("input")) + return SlashCommandInfo(allow_during_agent_execution, description, kind, name, aliases, experimental, input) + + def to_dict(self) -> dict: + result: dict = {} + result["allowDuringAgentExecution"] = from_bool(self.allow_during_agent_execution) + result["description"] = from_str(self.description) + result["kind"] = to_enum(SlashCommandKind, self.kind) + result["name"] = from_str(self.name) + if self.aliases is not None: + result["aliases"] = from_union([lambda x: from_list(from_str, x), from_none], self.aliases) + if self.experimental is not None: + result["experimental"] = from_union([from_bool, from_none], self.experimental) + if self.input is not None: + result["input"] = from_union([lambda x: to_class(SlashCommandInput, x), from_none], self.input) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class RemoteSessionConnectionResult: + """Remote session connection result.""" + + metadata: ConnectedRemoteSessionMetadata + """Metadata for a connected remote session.""" + + session_id: str + """SDK session ID for the connected remote session.""" + + @staticmethod + def from_dict(obj: Any) -> 'RemoteSessionConnectionResult': + assert isinstance(obj, dict) + metadata = ConnectedRemoteSessionMetadata.from_dict(obj.get("metadata")) + session_id = from_str(obj.get("sessionId")) + return RemoteSessionConnectionResult(metadata, session_id) def to_dict(self) -> dict: result: dict = {} - if self.access_type_sku is not None: - result["access_type_sku"] = from_union([from_str, from_none], self.access_type_sku) - if self.analytics_tracking_id is not None: - result["analytics_tracking_id"] = from_union([from_str, from_none], self.analytics_tracking_id) - if self.assigned_date is not None: - result["assigned_date"] = self.assigned_date - if self.can_signup_for_limited is not None: - result["can_signup_for_limited"] = from_union([from_bool, from_none], self.can_signup_for_limited) - if self.chat_enabled is not None: - result["chat_enabled"] = from_union([from_bool, from_none], self.chat_enabled) - if self.cli_remote_control_enabled is not None: - result["cli_remote_control_enabled"] = from_union([from_bool, from_none], self.cli_remote_control_enabled) - if self.cloud_session_storage_enabled is not None: - result["cloud_session_storage_enabled"] = from_union([from_bool, from_none], self.cloud_session_storage_enabled) - if self.codex_agent_enabled is not None: - result["codex_agent_enabled"] = from_union([from_bool, from_none], self.codex_agent_enabled) - if self.copilot_plan is not None: - result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) - if self.copilotignore_enabled is not None: - result["copilotignore_enabled"] = from_union([from_bool, from_none], self.copilotignore_enabled) - if self.endpoints is not None: - result["endpoints"] = from_union([lambda x: to_class(CopilotUserResponseEndpoints, x), from_none], self.endpoints) - if self.is_mcp_enabled is not None: - result["is_mcp_enabled"] = self.is_mcp_enabled - if self.limited_user_quotas is not None: - result["limited_user_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.limited_user_quotas) - if self.limited_user_reset_date is not None: - result["limited_user_reset_date"] = from_union([from_str, from_none], self.limited_user_reset_date) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - if self.monthly_quotas is not None: - result["monthly_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.monthly_quotas) - if self.organization_list is not None: - result["organization_list"] = self.organization_list - if self.organization_login_list is not None: - result["organization_login_list"] = from_union([lambda x: from_list(from_str, x), from_none], self.organization_login_list) - if self.quota_reset_date is not None: - result["quota_reset_date"] = from_union([from_str, from_none], self.quota_reset_date) - if self.quota_reset_date_utc is not None: - result["quota_reset_date_utc"] = from_union([from_str, from_none], self.quota_reset_date_utc) - if self.quota_snapshots is not None: - result["quota_snapshots"] = from_union([lambda x: from_dict(lambda x: from_union([lambda x: to_class(CopilotUserResponseQuotaSnapshots, x), from_none], x), x), from_none], self.quota_snapshots) - if self.restricted_telemetry is not None: - result["restricted_telemetry"] = from_union([from_bool, from_none], self.restricted_telemetry) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + result["metadata"] = to_class(ConnectedRemoteSessionMetadata, self.metadata) + result["sessionId"] = from_str(self.session_id) return result @dataclass @@ -11062,6 +11147,7 @@ def to_dict(self) -> dict: result["sources"] = from_list(lambda x: to_class(InstructionsSources, x), self.sources) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigAddRequest: """MCP server name and configuration to add to user configuration.""" @@ -11103,6 +11189,7 @@ def to_dict(self) -> dict: result["servers"] = from_dict(lambda x: to_class(MCPServerConfig, x), self.servers) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigUpdateRequest: """MCP server name and replacement configuration to write to user configuration.""" @@ -12384,303 +12471,130 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CommandList: - """Slash commands available in the session, after applying any include/exclude filters.""" - - commands: list[SlashCommandInfo] - """Commands available in this session""" - - @staticmethod - def from_dict(obj: Any) -> 'CommandList': - assert isinstance(obj, dict) - commands = from_list(SlashCommandInfo.from_dict, obj.get("commands")) - return CommandList(commands) - - def to_dict(self) -> dict: - result: dict = {} - result["commands"] = from_list(lambda x: to_class(SlashCommandInfo, x), self.commands) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class APIKeyAuthInfo: - """Schema for the `ApiKeyAuthInfo` type.""" - - api_key: str - """The API key. Treat as a secret.""" - - host: str - """Authentication host.""" - - type: APIKeyAuthInfoType - """API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style).""" - - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - - @staticmethod - def from_dict(obj: Any) -> 'APIKeyAuthInfo': - assert isinstance(obj, dict) - api_key = from_str(obj.get("apiKey")) - host = from_str(obj.get("host")) - type = APIKeyAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return APIKeyAuthInfo(api_key, host, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["apiKey"] = from_str(self.api_key) - result["host"] = from_str(self.host) - result["type"] = to_enum(APIKeyAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CopilotAPITokenAuthInfo: - """Schema for the `CopilotApiTokenAuthInfo` type.""" - - host: Host - """Authentication host (always the public GitHub host).""" - - type: CopilotAPITokenAuthInfoType - """Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` - environment-variable pair. The token itself is read from the environment by the runtime, - not carried in this struct. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ +class AuthInfo: + """The new auth credentials to install on the session. When omitted or `undefined`, the call + is a no-op and the session's existing credentials are preserved. The runtime stores the + value verbatim and uses it for outbound model/API requests; it does NOT re-validate or + re-fetch the associated Copilot user response. Several variants carry secret material; + treat this method's params as containing secrets at rest and in transit. - @staticmethod - def from_dict(obj: Any) -> 'CopilotAPITokenAuthInfo': - assert isinstance(obj, dict) - host = Host(obj.get("host")) - type = CopilotAPITokenAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return CopilotAPITokenAuthInfo(host, type, copilot_user) + Schema for the `HMACAuthInfo` type. - def to_dict(self) -> dict: - result: dict = {} - result["host"] = to_enum(Host, self.host) - result["type"] = to_enum(CopilotAPITokenAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result + Schema for the `EnvAuthInfo` type. -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class EnvAuthInfo: - """Schema for the `EnvAuthInfo` type.""" + Schema for the `TokenAuthInfo` type. - env_var: str - """Name of the environment variable the token was sourced from.""" + Schema for the `CopilotApiTokenAuthInfo` type. - host: str - """Authentication host (e.g. https://github.com or a GHES host).""" + Schema for the `UserAuthInfo` type. - token: str - """The token value itself. Treat as a secret.""" + Schema for the `GhCliAuthInfo` type. - type: EnvAuthInfoType - """Personal access token (PAT) or server-to-server token sourced from an environment - variable. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - login: str | None = None - """User login associated with the token. Undefined for server-to-server tokens (those - starting with `ghs_`). + Schema for the `ApiKeyAuthInfo` type. """ - - @staticmethod - def from_dict(obj: Any) -> 'EnvAuthInfo': - assert isinstance(obj, dict) - env_var = from_str(obj.get("envVar")) - host = from_str(obj.get("host")) - token = from_str(obj.get("token")) - type = EnvAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - login = from_union([from_str, from_none], obj.get("login")) - return EnvAuthInfo(env_var, host, token, type, copilot_user, login) - - def to_dict(self) -> dict: - result: dict = {} - result["envVar"] = from_str(self.env_var) - result["host"] = from_str(self.host) - result["token"] = from_str(self.token) - result["type"] = to_enum(EnvAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class GhCLIAuthInfo: - """Schema for the `GhCliAuthInfo` type.""" - host: str - """Authentication host.""" - - login: str - """User login as reported by `gh auth status`.""" + """Authentication host. HMAC auth always targets the public GitHub host. - token: str - """The token returned by `gh auth token`. Treat as a secret.""" + Authentication host (e.g. https://github.com or a GHES host). - type: GhCLIAuthInfoType - """Authentication via the `gh` CLI's saved credentials.""" + Authentication host. - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + Authentication host (always the public GitHub host). """ + type: AuthInfoType + """HMAC-based authentication used by GitHub-internal services. - @staticmethod - def from_dict(obj: Any) -> 'GhCLIAuthInfo': - assert isinstance(obj, dict) - host = from_str(obj.get("host")) - login = from_str(obj.get("login")) - token = from_str(obj.get("token")) - type = GhCLIAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return GhCLIAuthInfo(host, login, token, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["host"] = from_str(self.host) - result["login"] = from_str(self.login) - result["token"] = from_str(self.token) - result["type"] = to_enum(GhCLIAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result + Personal access token (PAT) or server-to-server token sourced from an environment + variable. -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HMACAuthInfo: - """Schema for the `HMACAuthInfo` type.""" + SDK-side token authentication; the host configured the token directly via the SDK. - hmac: str - """HMAC secret used to sign requests.""" + Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` + environment-variable pair. The token itself is read from the environment by the runtime, + not carried in this struct. - host: Host - """Authentication host. HMAC auth always targets the public GitHub host.""" + OAuth user authentication. The token itself is held in the runtime's secret token store + (keyed by host+login) and is NOT carried in this struct. - type: HMACAuthInfoType - """HMAC-based authentication used by GitHub-internal services.""" + Authentication via the `gh` CLI's saved credentials. + API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). + """ copilot_user: CopilotUserResponse | None = None """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. """ + hmac: str | None = None + """HMAC secret used to sign requests.""" - @staticmethod - def from_dict(obj: Any) -> 'HMACAuthInfo': - assert isinstance(obj, dict) - hmac = from_str(obj.get("hmac")) - host = Host(obj.get("host")) - type = HMACAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return HMACAuthInfo(hmac, host, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["hmac"] = from_str(self.hmac) - result["host"] = to_enum(Host, self.host) - result["type"] = to_enum(HMACAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class TokenAuthInfo: - """Schema for the `TokenAuthInfo` type.""" + env_var: str | None = None + """Name of the environment variable the token was sourced from.""" - host: str - """Authentication host.""" + login: str | None = None + """User login associated with the token. Undefined for server-to-server tokens (those + starting with `ghs_`). - token: str - """The token value itself. Treat as a secret.""" + OAuth user login. - type: TokenAuthInfoType - """SDK-side token authentication; the host configured the token directly via the SDK.""" + User login as reported by `gh auth status`. + """ + token: str | None = None + """The token value itself. Treat as a secret. - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + The token returned by `gh auth token`. Treat as a secret. """ + api_key: str | None = None + """The API key. Treat as a secret.""" @staticmethod - def from_dict(obj: Any) -> 'TokenAuthInfo': + def from_dict(obj: Any) -> 'AuthInfo': assert isinstance(obj, dict) host = from_str(obj.get("host")) - token = from_str(obj.get("token")) - type = TokenAuthInfoType(obj.get("type")) + type = AuthInfoType(obj.get("type")) copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return TokenAuthInfo(host, token, type, copilot_user) + hmac = from_union([from_str, from_none], obj.get("hmac")) + env_var = from_union([from_str, from_none], obj.get("envVar")) + login = from_union([from_str, from_none], obj.get("login")) + token = from_union([from_str, from_none], obj.get("token")) + api_key = from_union([from_str, from_none], obj.get("apiKey")) + return AuthInfo(host, type, copilot_user, hmac, env_var, login, token, api_key) def to_dict(self) -> dict: result: dict = {} result["host"] = from_str(self.host) - result["token"] = from_str(self.token) - result["type"] = to_enum(TokenAuthInfoType, self.type) + result["type"] = to_enum(AuthInfoType, self.type) if self.copilot_user is not None: result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + if self.hmac is not None: + result["hmac"] = from_union([from_str, from_none], self.hmac) + if self.env_var is not None: + result["envVar"] = from_union([from_str, from_none], self.env_var) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.token is not None: + result["token"] = from_union([from_str, from_none], self.token) + if self.api_key is not None: + result["apiKey"] = from_union([from_str, from_none], self.api_key) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class UserAuthInfo: - """Schema for the `UserAuthInfo` type.""" - - host: str - """Authentication host.""" - - login: str - """OAuth user login.""" +class CommandList: + """Slash commands available in the session, after applying any include/exclude filters.""" - type: UserAuthInfoType - """OAuth user authentication. The token itself is held in the runtime's secret token store - (keyed by host+login) and is NOT carried in this struct. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ + commands: list[SlashCommandInfo] + """Commands available in this session""" @staticmethod - def from_dict(obj: Any) -> 'UserAuthInfo': + def from_dict(obj: Any) -> 'CommandList': assert isinstance(obj, dict) - host = from_str(obj.get("host")) - login = from_str(obj.get("login")) - type = UserAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return UserAuthInfo(host, login, type, copilot_user) + commands = from_list(SlashCommandInfo.from_dict, obj.get("commands")) + return CommandList(commands) def to_dict(self) -> dict: result: dict = {} - result["host"] = from_str(self.host) - result["login"] = from_str(self.login) - result["type"] = to_enum(UserAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["commands"] = from_list(lambda x: to_class(SlashCommandInfo, x), self.commands) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -13591,111 +13505,27 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class AuthInfo: +class SessionSetCredentialsParams: + """New auth credentials to install on the session. Omit to leave credentials unchanged.""" + + credentials: AuthInfo | None = None """The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime stores the value verbatim and uses it for outbound model/API requests; it does NOT re-validate or re-fetch the associated Copilot user response. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. - - Schema for the `HMACAuthInfo` type. - - Schema for the `EnvAuthInfo` type. - - Schema for the `TokenAuthInfo` type. - - Schema for the `CopilotApiTokenAuthInfo` type. - - Schema for the `UserAuthInfo` type. - - Schema for the `GhCliAuthInfo` type. - - Schema for the `ApiKeyAuthInfo` type. - """ - host: str - """Authentication host. HMAC auth always targets the public GitHub host. - - Authentication host (e.g. https://github.com or a GHES host). - - Authentication host. - - Authentication host (always the public GitHub host). - """ - type: AuthInfoType - """HMAC-based authentication used by GitHub-internal services. - - Personal access token (PAT) or server-to-server token sourced from an environment - variable. - - SDK-side token authentication; the host configured the token directly via the SDK. - - Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` - environment-variable pair. The token itself is read from the environment by the runtime, - not carried in this struct. - - OAuth user authentication. The token itself is held in the runtime's secret token store - (keyed by host+login) and is NOT carried in this struct. - - Authentication via the `gh` CLI's saved credentials. - - API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - hmac: str | None = None - """HMAC secret used to sign requests.""" - - env_var: str | None = None - """Name of the environment variable the token was sourced from.""" - - login: str | None = None - """User login associated with the token. Undefined for server-to-server tokens (those - starting with `ghs_`). - - OAuth user login. - - User login as reported by `gh auth status`. - """ - token: str | None = None - """The token value itself. Treat as a secret. - - The token returned by `gh auth token`. Treat as a secret. """ - api_key: str | None = None - """The API key. Treat as a secret.""" @staticmethod - def from_dict(obj: Any) -> 'AuthInfo': + def from_dict(obj: Any) -> 'SessionSetCredentialsParams': assert isinstance(obj, dict) - host = from_str(obj.get("host")) - type = AuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - hmac = from_union([from_str, from_none], obj.get("hmac")) - env_var = from_union([from_str, from_none], obj.get("envVar")) - login = from_union([from_str, from_none], obj.get("login")) - token = from_union([from_str, from_none], obj.get("token")) - api_key = from_union([from_str, from_none], obj.get("apiKey")) - return AuthInfo(host, type, copilot_user, hmac, env_var, login, token, api_key) + credentials = from_union([AuthInfo.from_dict, from_none], obj.get("credentials")) + return SessionSetCredentialsParams(credentials) def to_dict(self) -> dict: result: dict = {} - result["host"] = from_str(self.host) - result["type"] = to_enum(AuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - if self.hmac is not None: - result["hmac"] = from_union([from_str, from_none], self.hmac) - if self.env_var is not None: - result["envVar"] = from_union([from_str, from_none], self.env_var) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - if self.token is not None: - result["token"] = from_union([from_str, from_none], self.token) - if self.api_key is not None: - result["apiKey"] = from_union([from_str, from_none], self.api_key) + if self.credentials is not None: + result["credentials"] = from_union([lambda x: to_class(AuthInfo, x), from_none], self.credentials) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -14098,31 +13928,6 @@ def to_dict(self) -> dict: result["requestedSchema"] = to_class(UIElicitationSchema, self.requested_schema) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionSetCredentialsParams: - """New auth credentials to install on the session. Omit to leave credentials unchanged.""" - - credentials: AuthInfo | None = None - """The new auth credentials to install on the session. When omitted or `undefined`, the call - is a no-op and the session's existing credentials are preserved. The runtime stores the - value verbatim and uses it for outbound model/API requests; it does NOT re-validate or - re-fetch the associated Copilot user response. Several variants carry secret material; - treat this method's params as containing secrets at rest and in transit. - """ - - @staticmethod - def from_dict(obj: Any) -> 'SessionSetCredentialsParams': - assert isinstance(obj, dict) - credentials = from_union([AuthInfo.from_dict, from_none], obj.get("credentials")) - return SessionSetCredentialsParams(credentials) - - def to_dict(self) -> dict: - result: dict = {} - if self.credentials is not None: - result["credentials"] = from_union([lambda x: to_class(AuthInfo, x), from_none], self.credentials) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecision: @@ -14951,10 +14756,6 @@ class RPC: copilot_api_token_auth_info: CopilotAPITokenAuthInfo copilot_user_response: CopilotUserResponse copilot_user_response_endpoints: CopilotUserResponseEndpoints - copilot_user_response_quota_snapshots: dict[str, CopilotUserResponseQuotaSnapshots | None] - copilot_user_response_quota_snapshots_chat: CopilotUserResponseQuotaSnapshotsChat - copilot_user_response_quota_snapshots_completions: CopilotUserResponseQuotaSnapshotsCompletions - copilot_user_response_quota_snapshots_premium_interactions: CopilotUserResponseQuotaSnapshotsPremiumInteractions current_model: CurrentModel discovered_mcp_server: DiscoveredMCPServer discovered_mcp_server_type: DiscoveredMCPServerType @@ -15467,10 +15268,6 @@ def from_dict(obj: Any) -> 'RPC': copilot_api_token_auth_info = CopilotAPITokenAuthInfo.from_dict(obj.get("CopilotApiTokenAuthInfo")) copilot_user_response = CopilotUserResponse.from_dict(obj.get("CopilotUserResponse")) copilot_user_response_endpoints = CopilotUserResponseEndpoints.from_dict(obj.get("CopilotUserResponseEndpoints")) - copilot_user_response_quota_snapshots = from_dict(lambda x: from_union([CopilotUserResponseQuotaSnapshots.from_dict, from_none], x), obj.get("CopilotUserResponseQuotaSnapshots")) - copilot_user_response_quota_snapshots_chat = CopilotUserResponseQuotaSnapshotsChat.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsChat")) - copilot_user_response_quota_snapshots_completions = CopilotUserResponseQuotaSnapshotsCompletions.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsCompletions")) - copilot_user_response_quota_snapshots_premium_interactions = CopilotUserResponseQuotaSnapshotsPremiumInteractions.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsPremiumInteractions")) current_model = CurrentModel.from_dict(obj.get("CurrentModel")) discovered_mcp_server = DiscoveredMCPServer.from_dict(obj.get("DiscoveredMcpServer")) discovered_mcp_server_type = DiscoveredMCPServerType(obj.get("DiscoveredMcpServerType")) @@ -15947,7 +15744,7 @@ def from_dict(obj: Any) -> 'RPC': session_context_info = from_union([SessionContextInfo.from_dict, from_none], obj.get("SessionContextInfo")) task_progress = from_union([TaskProgress.from_dict, from_none], obj.get("TaskProgress")) workspace_summary = from_union([WorkspaceSummary.from_dict, from_none], obj.get("WorkspaceSummary")) - return RPC(abort_request, abort_result, account_get_quota_request, account_get_quota_result, account_quota_snapshot, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_reload_result, agent_select_request, agent_select_result, api_key_auth_info, auth_info, auth_info_type, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_source, installed_plugin_source_github, installed_plugin_source_local, installed_plugin_source_url, instructions_get_sources_result, instructions_sources, instructions_sources_location, instructions_sources_type, log_request, log_result, lsp_initialize_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_oauth_login_request, mcp_oauth_login_result, mcp_remove_git_hub_result, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_config, mcp_server_config_http, mcp_server_config_http_auth, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_list, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, options_update_env_value_mode, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_update_request, plugin, plugin_list, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_mode, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, send_agent_mode, send_attachment, send_attachment_blob, send_attachment_directory, send_attachment_file, send_attachment_file_line_range, send_attachment_github_reference, send_attachment_github_reference_type, send_attachment_selection, send_attachment_selection_details, send_attachment_selection_details_end, send_attachment_selection_details_start, send_mode, send_request, send_result, server_skill, server_skill_list, session_auth_status, session_bulk_delete_result, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_github, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_metadata, session_metadata_snapshot, session_mode, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_prune_old_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_exec_request, shell_exec_result, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_initialize_and_validate_result, tools_list_request, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_tool_session_approval_commands, user_tool_session_approval_custom_tool, user_tool_session_approval_extension_management, user_tool_session_approval_extension_permission_access, user_tool_session_approval_mcp, user_tool_session_approval_memory, user_tool_session_approval_read, user_tool_session_approval_write, workspaces_checkpoints, workspaces_create_file_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, task_progress, workspace_summary) + return RPC(abort_request, abort_result, account_get_quota_request, account_get_quota_result, account_quota_snapshot, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_reload_result, agent_select_request, agent_select_result, api_key_auth_info, auth_info, auth_info_type, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, current_model, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_source, installed_plugin_source_github, installed_plugin_source_local, installed_plugin_source_url, instructions_get_sources_result, instructions_sources, instructions_sources_location, instructions_sources_type, log_request, log_result, lsp_initialize_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_oauth_login_request, mcp_oauth_login_result, mcp_remove_git_hub_result, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_config, mcp_server_config_http, mcp_server_config_http_auth, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_list, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, options_update_env_value_mode, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_update_request, plugin, plugin_list, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_mode, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, send_agent_mode, send_attachment, send_attachment_blob, send_attachment_directory, send_attachment_file, send_attachment_file_line_range, send_attachment_github_reference, send_attachment_github_reference_type, send_attachment_selection, send_attachment_selection_details, send_attachment_selection_details_end, send_attachment_selection_details_start, send_mode, send_request, send_result, server_skill, server_skill_list, session_auth_status, session_bulk_delete_result, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_github, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_metadata, session_metadata_snapshot, session_mode, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_prune_old_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_exec_request, shell_exec_result, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_initialize_and_validate_result, tools_list_request, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_tool_session_approval_commands, user_tool_session_approval_custom_tool, user_tool_session_approval_extension_management, user_tool_session_approval_extension_permission_access, user_tool_session_approval_mcp, user_tool_session_approval_memory, user_tool_session_approval_read, user_tool_session_approval_write, workspaces_checkpoints, workspaces_create_file_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, task_progress, workspace_summary) def to_dict(self) -> dict: result: dict = {} @@ -15983,10 +15780,6 @@ def to_dict(self) -> dict: result["CopilotApiTokenAuthInfo"] = to_class(CopilotAPITokenAuthInfo, self.copilot_api_token_auth_info) result["CopilotUserResponse"] = to_class(CopilotUserResponse, self.copilot_user_response) result["CopilotUserResponseEndpoints"] = to_class(CopilotUserResponseEndpoints, self.copilot_user_response_endpoints) - result["CopilotUserResponseQuotaSnapshots"] = from_dict(lambda x: from_union([lambda x: to_class(CopilotUserResponseQuotaSnapshots, x), from_none], x), self.copilot_user_response_quota_snapshots) - result["CopilotUserResponseQuotaSnapshotsChat"] = to_class(CopilotUserResponseQuotaSnapshotsChat, self.copilot_user_response_quota_snapshots_chat) - result["CopilotUserResponseQuotaSnapshotsCompletions"] = to_class(CopilotUserResponseQuotaSnapshotsCompletions, self.copilot_user_response_quota_snapshots_completions) - result["CopilotUserResponseQuotaSnapshotsPremiumInteractions"] = to_class(CopilotUserResponseQuotaSnapshotsPremiumInteractions, self.copilot_user_response_quota_snapshots_premium_interactions) result["CurrentModel"] = to_class(CurrentModel, self.current_model) result["DiscoveredMcpServer"] = to_class(DiscoveredMCPServer, self.discovered_mcp_server) result["DiscoveredMcpServerType"] = to_enum(DiscoveredMCPServerType, self.discovered_mcp_server_type) @@ -16551,12 +16344,12 @@ async def list(self, *, timeout: float | None = None) -> MCPConfigList: return MCPConfigList.from_dict(await self._client.request("mcp.config.list", {}, **_timeout_kwargs(timeout))) async def add(self, params: MCPConfigAddRequest, *, timeout: float | None = None) -> None: - "Adds an MCP server to user configuration.\n\nArgs:\n params: MCP server name and configuration to add to user configuration." + "Adds an MCP server to user configuration.\n\nArgs:\n params: MCP server name and configuration to add to user configuration.\n\n.. warning:: This API is experimental and may change or be removed in future versions." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} await self._client.request("mcp.config.add", params_dict, **_timeout_kwargs(timeout)) async def update(self, params: MCPConfigUpdateRequest, *, timeout: float | None = None) -> None: - "Updates an MCP server in user configuration.\n\nArgs:\n params: MCP server name and replacement configuration to write to user configuration." + "Updates an MCP server in user configuration.\n\nArgs:\n params: MCP server name and replacement configuration to write to user configuration.\n\n.. warning:: This API is experimental and may change or be removed in future versions." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} await self._client.request("mcp.config.update", params_dict, **_timeout_kwargs(timeout)) diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index 93903de30..de2d87dfc 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -277,6 +277,30 @@ def to_dict(self) -> dict: return {_compat_to_json_key(key): _compat_to_json_value(value) for key, value in self._values.items() if value is not None} +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ShutdownModelMetricRequests: + "Request count and cost metrics" + cost: float + count: int + + @staticmethod + def from_dict(obj: Any) -> "ShutdownModelMetricRequests": + assert isinstance(obj, dict) + cost = from_float(obj.get("cost")) + count = from_int(obj.get("count")) + return ShutdownModelMetricRequests( + cost=cost, + count=count, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["cost"] = to_float(self.cost) + result["count"] = to_int(self.count) + return result + + @dataclass class AbortData: "Turn abort information including the reason for termination" @@ -320,7 +344,9 @@ class AssistantMessageData: "Assistant response containing text content, optional tool requests, and interaction metadata" content: str message_id: str + # Internal: this field is an internal SDK API and is not part of the public surface. anthropic_advisor_blocks: list[Any] | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. anthropic_advisor_model: str | None = None encrypted_content: str | None = None interaction_id: str | None = None @@ -681,6 +707,7 @@ class AssistantUsageData: cache_read_tokens: int | None = None cache_write_tokens: int | None = None copilot_usage: AssistantUsageCopilotUsage | None = None + # Experimental: this field is part of an experimental API and may change or be removed. cost: float | None = None duration: timedelta | None = None initiator: str | None = None @@ -690,6 +717,7 @@ class AssistantUsageData: # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None provider_call_id: str | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. quota_snapshots: dict[str, AssistantUsageQuotaSnapshot] | None = None reasoning_effort: str | None = None reasoning_tokens: int | None = None @@ -3092,7 +3120,6 @@ class SessionShutdownData: session_start_time: int shutdown_type: ShutdownType total_api_duration: timedelta - total_premium_requests: float conversation_tokens: int | None = None current_model: str | None = None current_tokens: int | None = None @@ -3100,7 +3127,10 @@ class SessionShutdownData: system_tokens: int | None = None token_details: dict[str, ShutdownTokenDetail] | None = None tool_definitions_tokens: int | None = None + # Experimental: this field is part of an experimental API and may change or be removed. total_nano_aiu: float | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. + total_premium_requests: float | None = None @staticmethod def from_dict(obj: Any) -> "SessionShutdownData": @@ -3110,7 +3140,6 @@ def from_dict(obj: Any) -> "SessionShutdownData": session_start_time = from_int(obj.get("sessionStartTime")) shutdown_type = parse_enum(ShutdownType, obj.get("shutdownType")) total_api_duration = from_timedelta(obj.get("totalApiDurationMs")) - total_premium_requests = from_float(obj.get("totalPremiumRequests")) conversation_tokens = from_union([from_none, from_int], obj.get("conversationTokens")) current_model = from_union([from_none, from_str], obj.get("currentModel")) current_tokens = from_union([from_none, from_int], obj.get("currentTokens")) @@ -3119,13 +3148,13 @@ def from_dict(obj: Any) -> "SessionShutdownData": token_details = from_union([from_none, lambda x: from_dict(ShutdownTokenDetail.from_dict, x)], obj.get("tokenDetails")) tool_definitions_tokens = from_union([from_none, from_int], obj.get("toolDefinitionsTokens")) total_nano_aiu = from_union([from_none, from_float], obj.get("totalNanoAiu")) + total_premium_requests = from_union([from_none, from_float], obj.get("totalPremiumRequests")) return SessionShutdownData( code_changes=code_changes, model_metrics=model_metrics, session_start_time=session_start_time, shutdown_type=shutdown_type, total_api_duration=total_api_duration, - total_premium_requests=total_premium_requests, conversation_tokens=conversation_tokens, current_model=current_model, current_tokens=current_tokens, @@ -3134,6 +3163,7 @@ def from_dict(obj: Any) -> "SessionShutdownData": token_details=token_details, tool_definitions_tokens=tool_definitions_tokens, total_nano_aiu=total_nano_aiu, + total_premium_requests=total_premium_requests, ) def to_dict(self) -> dict: @@ -3143,7 +3173,6 @@ def to_dict(self) -> dict: result["sessionStartTime"] = to_int(self.session_start_time) result["shutdownType"] = to_enum(ShutdownType, self.shutdown_type) result["totalApiDurationMs"] = to_timedelta_int(self.total_api_duration) - result["totalPremiumRequests"] = to_float(self.total_premium_requests) if self.conversation_tokens is not None: result["conversationTokens"] = from_union([from_none, to_int], self.conversation_tokens) if self.current_model is not None: @@ -3160,6 +3189,8 @@ def to_dict(self) -> dict: result["toolDefinitionsTokens"] = from_union([from_none, to_int], self.tool_definitions_tokens) if self.total_nano_aiu is not None: result["totalNanoAiu"] = from_union([from_none, to_float], self.total_nano_aiu) + if self.total_premium_requests is not None: + result["totalPremiumRequests"] = from_union([from_none, to_float], self.total_premium_requests) return result @@ -3513,29 +3544,31 @@ def to_dict(self) -> dict: @dataclass class ShutdownModelMetric: "Schema for the `ShutdownModelMetric` type." - requests: ShutdownModelMetricRequests usage: ShutdownModelMetricUsage + requests: ShutdownModelMetricRequests | None = None token_details: dict[str, ShutdownModelMetricTokenDetail] | None = None + # Experimental: this field is part of an experimental API and may change or be removed. total_nano_aiu: float | None = None @staticmethod def from_dict(obj: Any) -> "ShutdownModelMetric": assert isinstance(obj, dict) - requests = ShutdownModelMetricRequests.from_dict(obj.get("requests")) usage = ShutdownModelMetricUsage.from_dict(obj.get("usage")) + requests = from_union([from_none, ShutdownModelMetricRequests.from_dict], obj.get("requests")) token_details = from_union([from_none, lambda x: from_dict(ShutdownModelMetricTokenDetail.from_dict, x)], obj.get("tokenDetails")) total_nano_aiu = from_union([from_none, from_float], obj.get("totalNanoAiu")) return ShutdownModelMetric( - requests=requests, usage=usage, + requests=requests, token_details=token_details, total_nano_aiu=total_nano_aiu, ) def to_dict(self) -> dict: result: dict = {} - result["requests"] = to_class(ShutdownModelMetricRequests, self.requests) result["usage"] = to_class(ShutdownModelMetricUsage, self.usage) + if self.requests is not None: + result["requests"] = from_union([from_none, lambda x: to_class(ShutdownModelMetricRequests, x)], self.requests) if self.token_details is not None: result["tokenDetails"] = from_union([from_none, lambda x: from_dict(lambda x: to_class(ShutdownModelMetricTokenDetail, x), x)], self.token_details) if self.total_nano_aiu is not None: @@ -3543,29 +3576,6 @@ def to_dict(self) -> dict: return result -@dataclass -class ShutdownModelMetricRequests: - "Request count and cost metrics" - cost: float - count: int - - @staticmethod - def from_dict(obj: Any) -> "ShutdownModelMetricRequests": - assert isinstance(obj, dict) - cost = from_float(obj.get("cost")) - count = from_int(obj.get("count")) - return ShutdownModelMetricRequests( - cost=cost, - count=count, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["cost"] = to_float(self.cost) - result["count"] = to_int(self.count) - return result - - @dataclass class ShutdownModelMetricTokenDetail: "Schema for the `ShutdownModelMetricTokenDetail` type." diff --git a/scripts/codegen/python.ts b/scripts/codegen/python.ts index 52b11ed59..45071e2db 100644 --- a/scripts/codegen/python.ts +++ b/scripts/codegen/python.ts @@ -25,6 +25,7 @@ import { isNodeFullyDeprecated, isSchemaDeprecated, isSchemaExperimental, + isSchemaInternal, postProcessSchema, stripBooleanLiterals, writeGeneratedFile, @@ -271,6 +272,24 @@ function pushPyExperimentalApiGroupComment(lines: string[]): void { lines.push("# Experimental: this API group is experimental and may change or be removed."); } +/** + * Emit `# Deprecated:` / `# Experimental:` / `# Internal:` comments above a + * dataclass field. Order matches our other codegens (deprecated, experimental, + * internal) and keeps the comments out of the field declaration itself. + */ +function pushPyFieldMarkers(lines: string[], propSchema: JSONSchema7 | null | undefined): void { + if (!propSchema) return; + if (isSchemaDeprecated(propSchema)) { + lines.push(` # Deprecated: this field is deprecated.`); + } + if (isSchemaExperimental(propSchema)) { + lines.push(` # Experimental: this field is part of an experimental API and may change or be removed.`); + } + if (isSchemaInternal(propSchema)) { + lines.push(` # Internal: this field is an internal SDK API and is not part of the public surface.`); + } +} + /** * Modernize quicktype's Python 3.7 output to Python 3.11+ syntax: * - Optional[T] → T | None @@ -1561,9 +1580,8 @@ function emitPyClass( for (const field of fieldInfos) { const suffix = field.isRequired ? "" : " = None"; - if (isSchemaDeprecated(orderedFieldEntries.find(([n]) => n === field.jsonName)?.[1] as JSONSchema7)) { - lines.push(` # Deprecated: this field is deprecated.`); - } + const propSchema = orderedFieldEntries.find(([n]) => n === field.jsonName)?.[1] as JSONSchema7 | undefined; + pushPyFieldMarkers(lines, propSchema); lines.push(` ${field.fieldName}: ${field.resolved.annotation}${suffix}`); } @@ -1703,10 +1721,8 @@ function emitPyFlatDiscriminatedUnion( } for (const field of fieldInfos) { const suffix = field.isRequired ? "" : " = None"; - const fieldSchema = orderedFieldEntries.find(([n]) => n === field.jsonName)?.[1]; - if (fieldSchema && isSchemaDeprecated(fieldSchema)) { - lines.push(` # Deprecated: this field is deprecated.`); - } + const fieldSchema = orderedFieldEntries.find(([n]) => n === field.jsonName)?.[1] as JSONSchema7 | undefined; + pushPyFieldMarkers(lines, fieldSchema); lines.push(` ${field.fieldName}: ${field.resolved.annotation}${suffix}`); } lines.push(``); From 4759835ae311476a9aa28af84428be5304663470 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 15:12:53 +0100 Subject: [PATCH 10/20] Go codegen: emit property-level Internal/Experimental doc comments Mirrors the existing C#/Rust/TypeScript/Python prop-marker treatment: when a field carries x-internal or x-experimental in the JSON Schema, emit a `// Internal: ...` / `// Experimental: ...` doc comment above the Go struct field. Factor the four near-identical field-emission sites in go.ts through a new `pushGoFieldMarkers` helper that consolidates Deprecated/Experimental/ Internal `pushGo*` calls in one place. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- go/rpc/zrpc.go | 108 +++++++++++++++----------------------- go/rpc/zsession_events.go | 12 ++++- scripts/codegen/go.ts | 42 ++++++++++----- 3 files changed, 82 insertions(+), 80 deletions(-) diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index c7a777cdc..7284603a6 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -81,6 +81,7 @@ type AgentInfo struct { ID string `json:"id"` // MCP server configurations attached to this agent, keyed by server name. Server config // shape mirrors the MCP `mcpServers` schema. + // Experimental: McpServers is part of an experimental API and may change or be removed. McpServers map[string]any `json:"mcpServers,omitempty"` // Preferred model id for this agent. When omitted, inherits the outer agent's model. Model *string `json:"model,omitempty"` @@ -434,20 +435,19 @@ type CopilotUserResponse struct { CopilotignoreEnabled *bool `json:"copilotignore_enabled,omitempty"` CopilotPlan *string `json:"copilot_plan,omitempty"` // Schema for the `CopilotUserResponseEndpoints` type. - Endpoints *CopilotUserResponseEndpoints `json:"endpoints,omitempty"` - IsMcpEnabled *bool `json:"is_mcp_enabled,omitempty"` - LimitedUserQuotas map[string]float64 `json:"limited_user_quotas,omitempty"` - LimitedUserResetDate *string `json:"limited_user_reset_date,omitempty"` - Login *string `json:"login,omitempty"` - MonthlyQuotas map[string]float64 `json:"monthly_quotas,omitempty"` - OrganizationList []CopilotUserResponseOrganizationListItem `json:"organization_list,omitempty"` - OrganizationLoginList []string `json:"organization_login_list,omitempty"` - QuotaResetDate *string `json:"quota_reset_date,omitempty"` - QuotaResetDateUtc *string `json:"quota_reset_date_utc,omitempty"` - // Schema for the `CopilotUserResponseQuotaSnapshots` type. - QuotaSnapshots *CopilotUserResponseQuotaSnapshots `json:"quota_snapshots,omitempty"` - RestrictedTelemetry *bool `json:"restricted_telemetry,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + Endpoints *CopilotUserResponseEndpoints `json:"endpoints,omitempty"` + IsMcpEnabled *bool `json:"is_mcp_enabled,omitempty"` + LimitedUserQuotas map[string]float64 `json:"limited_user_quotas,omitempty"` + LimitedUserResetDate *string `json:"limited_user_reset_date,omitempty"` + Login *string `json:"login,omitempty"` + MonthlyQuotas map[string]float64 `json:"monthly_quotas,omitempty"` + OrganizationList []CopilotUserResponseOrganizationListItem `json:"organization_list,omitempty"` + OrganizationLoginList []string `json:"organization_login_list,omitempty"` + QuotaResetDate *string `json:"quota_reset_date,omitempty"` + QuotaResetDateUtc *string `json:"quota_reset_date_utc,omitempty"` + QuotaSnapshots map[string]*CopilotUserResponseQuotaSnapshotsValue `json:"quota_snapshots,omitempty"` + RestrictedTelemetry *bool `json:"restricted_telemetry,omitempty"` + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` } // Schema for the `CopilotUserResponseEndpoints` type. @@ -465,58 +465,7 @@ type CopilotUserResponseOrganizationListItem struct { Name *string `json:"name,omitempty"` } -// Schema for the `CopilotUserResponseQuotaSnapshots` type. -// Experimental: CopilotUserResponseQuotaSnapshots is part of an experimental API and may -// change or be removed. -type CopilotUserResponseQuotaSnapshots struct { - // Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. - Chat *CopilotUserResponseQuotaSnapshotsChat `json:"chat,omitempty"` - // Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. - Completions *CopilotUserResponseQuotaSnapshotsCompletions `json:"completions,omitempty"` - // Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. - PremiumInteractions *CopilotUserResponseQuotaSnapshotsPremiumInteractions `json:"premium_interactions,omitempty"` -} - -// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. -// Experimental: CopilotUserResponseQuotaSnapshotsChat is part of an experimental API and -// may change or be removed. -type CopilotUserResponseQuotaSnapshotsChat struct { - Entitlement *float64 `json:"entitlement,omitempty"` - HasQuota *bool `json:"has_quota,omitempty"` - OverageCount *float64 `json:"overage_count,omitempty"` - OveragePermitted *bool `json:"overage_permitted,omitempty"` - PercentRemaining *float64 `json:"percent_remaining,omitempty"` - QuotaID *string `json:"quota_id,omitempty"` - QuotaRemaining *float64 `json:"quota_remaining,omitempty"` - QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` - Remaining *float64 `json:"remaining,omitempty"` - TimestampUtc *string `json:"timestamp_utc,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` - Unlimited *bool `json:"unlimited,omitempty"` -} - -// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. -// Experimental: CopilotUserResponseQuotaSnapshotsCompletions is part of an experimental API -// and may change or be removed. -type CopilotUserResponseQuotaSnapshotsCompletions struct { - Entitlement *float64 `json:"entitlement,omitempty"` - HasQuota *bool `json:"has_quota,omitempty"` - OverageCount *float64 `json:"overage_count,omitempty"` - OveragePermitted *bool `json:"overage_permitted,omitempty"` - PercentRemaining *float64 `json:"percent_remaining,omitempty"` - QuotaID *string `json:"quota_id,omitempty"` - QuotaRemaining *float64 `json:"quota_remaining,omitempty"` - QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` - Remaining *float64 `json:"remaining,omitempty"` - TimestampUtc *string `json:"timestamp_utc,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` - Unlimited *bool `json:"unlimited,omitempty"` -} - -// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. -// Experimental: CopilotUserResponseQuotaSnapshotsPremiumInteractions is part of an -// experimental API and may change or be removed. -type CopilotUserResponseQuotaSnapshotsPremiumInteractions struct { +type CopilotUserResponseQuotaSnapshotsValue struct { Entitlement *float64 `json:"entitlement,omitempty"` HasQuota *bool `json:"has_quota,omitempty"` OverageCount *float64 `json:"overage_count,omitempty"` @@ -922,6 +871,7 @@ type ExternalToolTextResultForLlmContentResourceLinkIcon struct { // Content filtering mode to apply to all tools, or a map of tool name to content filtering // mode. +// Experimental: FilterMapping is part of an experimental API and may change or be removed. type FilterMapping interface { filterMapping() } @@ -1102,6 +1052,8 @@ type InstalledPlugin struct { // Source for direct repo installs (when marketplace is empty) // Experimental: InstalledPluginSource is part of an experimental API and may change or be // removed. +// Experimental: InstalledPluginSource is part of an experimental API and may change or be +// removed. type InstalledPluginSource struct { InstalledPluginSourceGithub *InstalledPluginSourceGithub InstalledPluginSourceLocal *InstalledPluginSourceLocal @@ -1235,6 +1187,10 @@ type McpCancelSamplingExecutionResult struct { } // MCP server name and configuration to add to user configuration. +// Experimental: McpConfigAddRequest is part of an experimental API and may change or be +// removed. +// Experimental: McpConfigAddRequest is part of an experimental API and may change or be +// removed. type McpConfigAddRequest struct { // MCP server configuration (stdio process or remote HTTP/SSE) Config McpServerConfig `json:"config"` @@ -1242,6 +1198,8 @@ type McpConfigAddRequest struct { Name string `json:"name"` } +// Experimental: McpConfigAddResult is part of an experimental API and may change or be +// removed. type McpConfigAddResult struct { } @@ -1282,6 +1240,10 @@ type McpConfigRemoveResult struct { } // MCP server name and replacement configuration to write to user configuration. +// Experimental: McpConfigUpdateRequest is part of an experimental API and may change or be +// removed. +// Experimental: McpConfigUpdateRequest is part of an experimental API and may change or be +// removed. type McpConfigUpdateRequest struct { // MCP server configuration (stdio process or remote HTTP/SSE) Config McpServerConfig `json:"config"` @@ -1289,6 +1251,8 @@ type McpConfigUpdateRequest struct { Name string `json:"name"` } +// Experimental: McpConfigUpdateResult is part of an experimental API and may change or be +// removed. type McpConfigUpdateResult struct { } @@ -1433,6 +1397,7 @@ type McpServer struct { } // MCP server configuration (stdio process or remote HTTP/SSE) +// Experimental: McpServerConfig is part of an experimental API and may change or be removed. type McpServerConfig interface { mcpServerConfig() } @@ -2599,6 +2564,8 @@ type PermissionRulesSet struct { // Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. // Experimental: PermissionsConfigureAdditionalContentExclusionPolicy is part of an // experimental API and may change or be removed. +// Experimental: PermissionsConfigureAdditionalContentExclusionPolicy is part of an +// experimental API and may change or be removed. type PermissionsConfigureAdditionalContentExclusionPolicy struct { LastUpdatedAt any `json:"last_updated_at"` Rules []PermissionsConfigureAdditionalContentExclusionPolicyRule `json:"rules"` @@ -3779,6 +3746,8 @@ type SessionInstalledPlugin struct { // Source descriptor for direct repo installs (when marketplace is empty) // Experimental: SessionInstalledPluginSource is part of an experimental API and may change // or be removed. +// Experimental: SessionInstalledPluginSource is part of an experimental API and may change +// or be removed. type SessionInstalledPluginSource struct { SessionInstalledPluginSourceGithub *SessionInstalledPluginSourceGithub SessionInstalledPluginSourceLocal *SessionInstalledPluginSourceLocal @@ -4304,6 +4273,8 @@ type SessionTelemetrySetFeatureOverridesResult struct { type SessionUpdateOptionsParams struct { // Additional content-exclusion policies to merge into the session's policy set. Opaque // shape; see `ContentExclusionApiResponse` in the runtime. + // Experimental: AdditionalContentExclusionPolicies is part of an experimental API and may + // change or be removed. AdditionalContentExclusionPolicies []any `json:"additionalContentExclusionPolicies,omitempty"` // Runtime context discriminator (e.g., `cli`, `actions`). AgentContext *string `json:"agentContext,omitempty"` @@ -4364,12 +4335,14 @@ type SessionUpdateOptionsParams struct { Model *string `json:"model,omitempty"` // Custom model-provider configuration (BYOK). Opaque shape; see `ProviderConfig` in the // runtime. + // Experimental: Provider is part of an experimental API and may change or be removed. Provider any `json:"provider,omitempty"` // Reasoning effort for the selected model (model-defined enum). ReasoningEffort *string `json:"reasoningEffort,omitempty"` // Whether the session is running in an interactive UI. RunningInInteractiveMode *bool `json:"runningInInteractiveMode,omitempty"` // Sandbox configuration shape; opaque to SDK consumers. See `SandboxConfig` in the runtime. + // Experimental: SandboxConfig is part of an experimental API and may change or be removed. SandboxConfig any `json:"sandboxConfig,omitempty"` // Shell init profile (`None` or `NonInteractive`). ShellInitProfile *string `json:"shellInitProfile,omitempty"` @@ -6908,6 +6881,7 @@ type ServerMcpConfigApi serverApi // RPC method: mcp.config.add. // // Parameters: MCP server name and configuration to add to user configuration. +// Experimental: Add is an experimental API and may change or be removed in future versions. func (a *ServerMcpConfigApi) Add(ctx context.Context, params *McpConfigAddRequest) (*McpConfigAddResult, error) { raw, err := a.client.Request("mcp.config.add", params) if err != nil { @@ -6993,6 +6967,8 @@ func (a *ServerMcpConfigApi) Remove(ctx context.Context, params *McpConfigRemove // RPC method: mcp.config.update. // // Parameters: MCP server name and replacement configuration to write to user configuration. +// Experimental: Update is an experimental API and may change or be removed in future +// versions. func (a *ServerMcpConfigApi) Update(ctx context.Context, params *McpConfigUpdateRequest) (*McpConfigUpdateResult, error) { raw, err := a.client.Request("mcp.config.update", params) if err != nil { diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index f8fa95070..cec7d28af 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -170,8 +170,10 @@ func (*AssistantReasoningData) Type() SessionEventType { return SessionEventType // Assistant response containing text content, optional tool requests, and interaction metadata type AssistantMessageData struct { // Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping + // Internal: AnthropicAdvisorBlocks is part of the SDK's internal API surface and is not intended for external use. AnthropicAdvisorBlocks []any `json:"anthropicAdvisorBlocks,omitempty"` // Anthropic advisor model ID used for this response, for timeline display on replay + // Internal: AnthropicAdvisorModel is part of the SDK's internal API surface and is not intended for external use. AnthropicAdvisorModel *string `json:"anthropicAdvisorModel,omitempty"` // The assistant's text response content Content string `json:"content"` @@ -534,6 +536,7 @@ type AssistantUsageData struct { // Per-request cost and usage data from the CAPI copilot_usage response field CopilotUsage *AssistantUsageCopilotUsage `json:"copilotUsage,omitempty"` // Model multiplier cost for billing purposes + // Experimental: Cost is part of an experimental API and may change or be removed. Cost *float64 `json:"cost,omitempty"` // Duration of the API call in milliseconds Duration *int64 `json:"duration,omitempty"` @@ -553,6 +556,7 @@ type AssistantUsageData struct { // GitHub request tracing ID (x-github-request-id header) for server-side log correlation ProviderCallID *string `json:"providerCallId,omitempty"` // Per-quota resource usage snapshots, keyed by quota identifier + // Internal: QuotaSnapshots is part of the SDK's internal API surface and is not intended for external use. QuotaSnapshots map[string]AssistantUsageQuotaSnapshot `json:"quotaSnapshots,omitempty"` // Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") ReasoningEffort *string `json:"reasoningEffort,omitempty"` @@ -1052,9 +1056,11 @@ type SessionShutdownData struct { // Cumulative time spent in API calls during the session, in milliseconds TotalAPIDurationMs int64 `json:"totalApiDurationMs"` // Session-wide accumulated nano-AI units cost + // Experimental: TotalNanoAiu is part of an experimental API and may change or be removed. TotalNanoAiu *float64 `json:"totalNanoAiu,omitempty"` // Total number of premium API requests used during the session - TotalPremiumRequests float64 `json:"totalPremiumRequests"` + // Internal: TotalPremiumRequests is part of the SDK's internal API surface and is not intended for external use. + TotalPremiumRequests *float64 `json:"totalPremiumRequests,omitempty"` } func (*SessionShutdownData) sessionEventData() {} @@ -2223,16 +2229,18 @@ type ShutdownCodeChanges struct { // Schema for the `ShutdownModelMetric` type. type ShutdownModelMetric struct { // Request count and cost metrics - Requests ShutdownModelMetricRequests `json:"requests"` + Requests *ShutdownModelMetricRequests `json:"requests,omitempty"` // Token count details per type TokenDetails map[string]ShutdownModelMetricTokenDetail `json:"tokenDetails,omitempty"` // Accumulated nano-AI units cost for this model + // Experimental: TotalNanoAiu is part of an experimental API and may change or be removed. TotalNanoAiu *float64 `json:"totalNanoAiu,omitempty"` // Token usage breakdown Usage ShutdownModelMetricUsage `json:"usage"` } // Request count and cost metrics +// Experimental: ShutdownModelMetricRequests is part of an experimental API and may change or be removed. type ShutdownModelMetricRequests struct { // Cumulative cost multiplier for requests to this model Cost float64 `json:"cost"` diff --git a/scripts/codegen/go.ts b/scripts/codegen/go.ts index 03a8da8e8..ee8d76ed9 100644 --- a/scripts/codegen/go.ts +++ b/scripts/codegen/go.ts @@ -37,6 +37,7 @@ import { isRpcMethod, isSchemaDeprecated, isSchemaExperimental, + isSchemaInternal, isVoidSchema, parseExternalSchemaRef, postProcessSchema, @@ -174,6 +175,31 @@ function pushGoExperimentalMethodComment(lines: string[], methodName: string, in pushGoComment(lines, `Experimental: ${methodName} is an experimental API and may change or be removed in future versions.`, indent); } +function pushGoInternalPropertyComment(lines: string[], goName: string, ctx: GoCodegenCtx, indent = "\t"): void { + pushGoCommentForContext(lines, `Internal: ${goName} is part of the SDK's internal API surface and is not intended for external use.`, ctx, indent); +} + +function pushGoExperimentalPropertyComment(lines: string[], goName: string, ctx: GoCodegenCtx, indent = "\t"): void { + pushGoCommentForContext(lines, `Experimental: ${goName} is part of an experimental API and may change or be removed.`, ctx, indent); +} + +/** + * Emit `Deprecated:` / `Experimental:` / `Internal:` doc comments above a Go + * struct field. Centralises the per-field marker logic shared between the + * regular struct emitter and the discriminated-union variant emitters. + */ +function pushGoFieldMarkers(lines: string[], prop: JSONSchema7, goName: string, ctx: GoCodegenCtx, indent = "\t"): void { + if (isSchemaDeprecated(prop)) { + pushGoCommentForContext(lines, `Deprecated: ${goName} is deprecated.`, ctx, indent); + } + if (isSchemaExperimental(prop)) { + pushGoExperimentalPropertyComment(lines, goName, ctx, indent); + } + if (isSchemaInternal(prop)) { + pushGoInternalPropertyComment(lines, goName, ctx, indent); + } +} + function lowerFirst(value: string): string { if (value.length === 0) return value; return value.charAt(0).toLowerCase() + value.slice(1); @@ -1084,9 +1110,7 @@ function emitGoStruct( if (prop.description) { pushGoCommentForContext(lines, prop.description, ctx, "\t"); } - if (isSchemaDeprecated(prop)) { - pushGoCommentForContext(lines, `Deprecated: ${goName} is deprecated.`, ctx, "\t"); - } + pushGoFieldMarkers(lines, prop, goName, ctx); const jsonTag = `json:"${propName}${omit}"`; lines.push(`\t${goName} ${goType} \`${jsonTag}\``); fields.push({ propName, goName, goType, jsonTag }); @@ -1775,9 +1799,7 @@ function emitGoFlatDiscriminatedUnion( if (prop.description) { pushGoCommentForContext(lines, prop.description, ctx, "\t"); } - if (isSchemaDeprecated(prop)) { - pushGoCommentForContext(lines, `Deprecated: ${goName} is deprecated.`, ctx, "\t"); - } + pushGoFieldMarkers(lines, prop, goName, ctx); const jsonTag = `json:"${propName}${omit}"`; lines.push(`\t${goName} ${goType} \`${jsonTag}\``); fields.push({ propName, goName, goType, jsonTag }); @@ -1904,9 +1926,7 @@ function emitGoRequiredFieldDiscriminatedUnion( if (prop.description) { pushGoCommentForContext(lines, prop.description, ctx, "\t"); } - if (isSchemaDeprecated(prop)) { - pushGoCommentForContext(lines, `Deprecated: ${goName} is deprecated.`, ctx, "\t"); - } + pushGoFieldMarkers(lines, prop, goName, ctx); const jsonTag = `json:"${propName}${omit}"`; lines.push(`\t${goName} ${goType} \`${jsonTag}\``); fields.push({ propName, goName, goType, jsonTag }); @@ -3016,9 +3036,7 @@ export function generateGoSessionEventsCode(schema: JSONSchema7, packageName: st if (prop.description) { pushGoCommentForContext(lines, prop.description, ctx, "\t"); } - if (isSchemaDeprecated(prop)) { - pushGoCommentForContext(lines, `Deprecated: ${goName} is deprecated.`, ctx, "\t"); - } + pushGoFieldMarkers(lines, prop, goName, ctx); const jsonTag = `json:"${propName}${omit}"`; lines.push(`\t${goName} ${goType} \`${jsonTag}\``); fields.push({ propName, goName, goType, jsonTag }); From 1469a23e3b5514411e053d616a82f69c88ffa792 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 15:28:01 +0100 Subject: [PATCH 11/20] Fix mojibake in csharp.ts and factor [JsonInclude] helper Commit b4841985 introduced 590 UTF-8 double-encoded byte sequences in scripts/codegen/csharp.ts (box-drawing characters in section banners and em-dashes in comments). This commit restores the file to a clean UTF-8 encoding and reapplies the intended logic change (removing the unnecessary !propInternal && !propExperimental guards from the reqMod expressions in the four sites that had it). While here, factor the duplicated propInternal + [JsonInclude] + visibility pattern into a small pushCSharpInternalAttribute helper used by all six property-emission sites in this file, and delete the dead propExperimental declarations that were left over from the original revert hack. Generated output (SessionEvents.cs, Rpc.cs) is byte-identical to before this commit; the change is purely TypeScript-side cleanup. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- scripts/codegen/csharp.ts | 76 +++++++++++++++++++-------------------- 1 file changed, 37 insertions(+), 39 deletions(-) diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index 980c08c6e..e71af7231 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -1,4 +1,4 @@ -/*--------------------------------------------------------------------------------------------- +/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. *--------------------------------------------------------------------------------------------*/ @@ -54,9 +54,9 @@ import { const execFileAsync = promisify(execFile); -// ── C# type rename overrides ──────────────────────────────────────────────── +// ── C# type rename overrides ──────────────────────────────────────────────── // Map generated class names to shorter public-facing names. -// Applied to base classes AND their derived variants (e.g., FooBar → Bar, FooBazShell → BarShell). +// Applied to base classes AND their derived variants (e.g., FooBar → Bar, FooBazShell → BarShell). const TYPE_RENAMES: Record = { PermissionRequestedDataPermissionRequest: "PermissionRequest", }; @@ -72,7 +72,7 @@ function applyTypeRename(className: string): string { return className; } -// ── C# utilities ──────────────────────────────────────────────────────────── +// ── C# utilities ──────────────────────────────────────────────────────────── function escapeXml(text: string): string { return text.replace(/&/g, "&").replace(//g, ">"); @@ -177,7 +177,7 @@ function pushRpcMethodXmlDocs( const CANCELLATION_TOKEN_DESCRIPTION = 'The to monitor for cancellation requests. The default is .'; -/** Like xmlDocComment but skips XML escaping — use only for codegen-controlled strings that already contain valid XML tags. */ +/** Like xmlDocComment but skips XML escaping — use only for codegen-controlled strings that already contain valid XML tags. */ function rawXmlDocSummary(text: string, indent: string): string[] { const line = ensureTrailingPunctuation(text.trim()); return [`${indent}/// ${line}`]; @@ -297,7 +297,7 @@ function failUnmappable(context: string, schema: JSONSchema7): never { const summary = JSON.stringify(schema, (key, value) => (key === "description" ? undefined : value)).slice(0, 200); throw new Error( `C# codegen: cannot map schema to an idiomatic C# type (${context}). ` + - `On the runtime side, either tighten the Zod schema to a typed shape, or — if it is genuinely free-form JSON — ` + + `On the runtime side, either tighten the Zod schema to a typed shape, or — if it is genuinely free-form JSON — ` + `mark it \`.asOpaqueJson()\` so the schema emits \`x-opaque-json: true\` and the codegen maps it to JsonElement. ` + `Offending schema (truncated): ${summary}`, ); @@ -311,7 +311,7 @@ async function formatCSharpFile(filePath: string): Promise { try { const projectFile = path.join(REPO_ROOT, "dotnet/src/GitHub.Copilot.SDK.csproj"); await execFileAsync("dotnet", ["format", projectFile, "--include", filePath]); - console.log(` ✓ Formatted with dotnet format`); + console.log(` ✓ Formatted with dotnet format`); } catch { // dotnet format not available, skip } @@ -346,7 +346,7 @@ function schemaTypeToCSharp(schema: JSONSchema7, required: boolean, knownTypes: const refName = schema.$ref.split("/").pop()!; return knownTypes.get(refName) || refName; } - // Titled union schemas (anyOf with a title) — use the title if it's a known generated type + // Titled union schemas (anyOf with a title) — use the title if it's a known generated type if (schema.title && schema.anyOf && knownTypes.has(schema.title)) { return required ? schema.title : `${schema.title}?`; } @@ -518,9 +518,23 @@ function pushObsoleteAttributes(lines: string[], indent = ""): void { lines.push(...obsoleteAttributes(indent)); } -// ══════════════════════════════════════════════════════════════════════════════ +/** + * Emit the `[JsonInclude]` attribute for an internally-marked property and + * return the C# access modifier to use for the property declaration. + * + * `[JsonInclude]` is required because System.Text.Json only auto-(de)serialises + * public members by default; without it, the `internal` setter would silently + * be skipped. + */ +function pushCSharpInternalAttribute(lines: string[], schema: JSONSchema7, indent = " "): "public" | "internal" { + const propInternal = isSchemaInternal(schema); + if (propInternal) lines.push(`${indent}[JsonInclude]`); + return propInternal ? "internal" : "public"; +} + +// ══════════════════════════════════════════════════════════════════════════════ // SESSION EVENTS -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ interface EventVariant { typeName: string; @@ -779,12 +793,9 @@ function generateFlattenedBooleanDiscriminatedClass( if (isSchemaExperimental(info.schema)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, info.schema)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); - const propInternal = isSchemaInternal(info.schema); - const propExperimental = isSchemaExperimental(info.schema); - if (propInternal) lines.push(` [JsonInclude]`); + const propVisibility = pushCSharpInternalAttribute(lines, info.schema); lines.push(` [JsonPropertyName("${propName}")]`); const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; - const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`); } @@ -887,12 +898,9 @@ function generateDerivedClass( if (isSchemaExperimental(prop)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); - const propInternal = isSchemaInternal(prop); - const propExperimental = isSchemaExperimental(prop); - if (propInternal) lines.push(` [JsonInclude]`); + const propVisibility = pushCSharpInternalAttribute(lines, prop); lines.push(` [JsonPropertyName("${propName}")]`); const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; - const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } } @@ -1117,12 +1125,9 @@ function generateNestedClass( if (isSchemaExperimental(prop)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); if (!isReq) lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`); - const propInternal = isSchemaInternal(prop); - const propExperimental = isSchemaExperimental(prop); - if (propInternal) lines.push(` [JsonInclude]`); + const propVisibility = pushCSharpInternalAttribute(lines, prop); lines.push(` [JsonPropertyName("${propName}")]`); const reqMod = isReq && !csharpType.endsWith("?") ? "required " : ""; - const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${reqMod}${csharpType} ${csharpName} { get; set; }`, ""); } if (lines[lines.length - 1] === "") lines.pop(); @@ -1268,12 +1273,9 @@ function generateDataClass(variant: EventVariant, knownTypes: Map const processed = postProcessSchema(schema); const code = generateSessionEventsCode(processed); const outPath = await writeGeneratedFile("dotnet/src/Generated/SessionEvents.cs", code); - console.log(` ✓ ${outPath}`); + console.log(` ✓ ${outPath}`); await formatCSharpFile(outPath); } -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ // RPC TYPES -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ let emittedRpcClassSchemas = new Map(); let emittedRpcEnumResultTypes = new Set(); @@ -1524,7 +1524,7 @@ function resolveRpcType(schema: JSONSchema7, isRequired: boolean, parentClassNam return resolveRpcType(refSchema, isRequired, parentClassName, propName, classes); } - // Handle anyOf: [T, null/{not:{}}] → T? (nullable typed property) + // Handle anyOf: [T, null/{not:{}}] → T? (nullable typed property) const nullableInner = getNullableInner(schema); if (nullableInner) { return resolveRpcType(nullableInner, false, parentClassName, propName, classes); @@ -1661,8 +1661,7 @@ function emitRpcClass( if (isSchemaDeprecated(prop)) pushObsoleteAttributes(lines, " "); if (isSchemaExperimental(prop)) pushExperimentalAttribute(lines, " "); if (isMillisecondsDurationProperty(propName, prop)) lines.push(` [JsonConverter(typeof(MillisecondsTimeSpanConverter))]`); - const propInternal = isSchemaInternal(prop); - if (propInternal) lines.push(` [JsonInclude]`); + const propVisibility = pushCSharpInternalAttribute(lines, prop); lines.push(` [JsonPropertyName("${propName}")]`); let defaultVal = ""; @@ -1680,7 +1679,6 @@ function emitRpcClass( defaultVal = " = null!;"; } } - const propVisibility = propInternal ? "internal" : "public"; lines.push(` ${propVisibility} ${csharpType} ${csharpName} ${propAccessors}${defaultVal}`); if (i < props.length - 1) lines.push(""); } @@ -2403,13 +2401,13 @@ export async function generateRpc(schemaPath?: string, sessionEventsSchema?: JSO } const code = generateRpcCode(schema, externalJsonSerializableRefs, externalValueTypes); const outPath = await writeGeneratedFile("dotnet/src/Generated/Rpc.cs", code); - console.log(` ✓ ${outPath}`); + console.log(` ✓ ${outPath}`); await formatCSharpFile(outPath); } -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ // MAIN -// ══════════════════════════════════════════════════════════════════════════════ +// ══════════════════════════════════════════════════════════════════════════════ async function generate(sessionSchemaPath?: string, apiSchemaPath?: string): Promise { await generateSessionEvents(sessionSchemaPath); From 12d383716e7436fc5b756d9b68b3699f097b8582 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 15:44:18 +0100 Subject: [PATCH 12/20] Regenerate SDK code after rebase on main Refreshes generated output (C# Rpc.cs, TS rpc.ts, Python rpc.py, Go zrpc.go/zsession_events.go, Rust *.rs) to pick up two changes that landed on main while the branch was open: - namespace renamed from GitHub.Copilot.SDK.* to GitHub.Copilot.* - improved description wording for AccountQuotaSnapshot.overage fields Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/Rpc.cs | 622 ++++++++++++++++---------------- go/rpc/zrpc.go | 4 +- nodejs/src/generated/rpc.ts | 4 +- python/copilot/generated/rpc.py | 4 +- rust/src/generated/api_types.rs | 4 +- 5 files changed, 319 insertions(+), 319 deletions(-) diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index d98652a5b..d1b61f929 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -16,7 +16,7 @@ using System.Text.Json.Serialization; using System.Threading; -namespace GitHub.Copilot.SDK.Rpc; +namespace GitHub.Copilot.Rpc; /// Server liveness response, including the echoed message, current server timestamp, and protocol version. public sealed class PingResult @@ -277,11 +277,11 @@ public sealed class AccountQuotaSnapshot [JsonPropertyName("isUnlimitedEntitlement")] public bool IsUnlimitedEntitlement { get; set; } - /// Number of overage requests made this period. + /// Number of additional usage requests made this period. [JsonPropertyName("overage")] public double Overage { get; set; } - /// Whether overage is allowed when quota is exhausted. + /// Whether additional usage is allowed when quota is exhausted. [JsonPropertyName("overageAllowedWithExhaustedQuota")] public bool OverageAllowedWithExhaustedQuota { get; set; } @@ -7103,13 +7103,13 @@ public sealed class Converter : JsonConverter /// public override ModelPickerCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ModelPickerCategory value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerCategory)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerCategory)); } } } @@ -7171,13 +7171,13 @@ public sealed class Converter : JsonConverter /// public override ModelPickerPriceCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ModelPickerPriceCategory value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerPriceCategory)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerPriceCategory)); } } } @@ -7236,13 +7236,13 @@ public sealed class Converter : JsonConverter /// public override ModelPolicyState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ModelPolicyState value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPolicyState)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPolicyState)); } } } @@ -7304,13 +7304,13 @@ public sealed class Converter : JsonConverter /// public override DiscoveredMcpServerType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, DiscoveredMcpServerType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DiscoveredMcpServerType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DiscoveredMcpServerType)); } } } @@ -7366,13 +7366,13 @@ public sealed class Converter : JsonConverter /// public override SessionFsSetProviderConventions Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsSetProviderConventions value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSetProviderConventions)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSetProviderConventions)); } } } @@ -7429,13 +7429,13 @@ public sealed class Converter : JsonConverter public override ConnectedRemoteSessionMetadataKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ConnectedRemoteSessionMetadataKind value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ConnectedRemoteSessionMetadataKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ConnectedRemoteSessionMetadataKind)); } } } @@ -7492,13 +7492,13 @@ public sealed class Converter : JsonConverter /// public override SessionContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionContextHostType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionContextHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionContextHostType)); } } } @@ -7561,13 +7561,13 @@ public sealed class Converter : JsonConverter /// public override SendAgentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SendAgentMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAgentMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAgentMode)); } } } @@ -7627,13 +7627,13 @@ public sealed class Converter : JsonConverter /// public override SendAttachmentGithubReferenceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SendAttachmentGithubReferenceType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAttachmentGithubReferenceType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAttachmentGithubReferenceType)); } } } @@ -7690,13 +7690,13 @@ public sealed class Converter : JsonConverter /// public override SendMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SendMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendMode)); } } } @@ -7756,13 +7756,13 @@ public sealed class Converter : JsonConverter /// public override SessionLogLevel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionLogLevel value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLogLevel)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLogLevel)); } } } @@ -7834,13 +7834,13 @@ public sealed class Converter : JsonConverter /// public override AuthInfoType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, AuthInfoType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthInfoType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthInfoType)); } } } @@ -7897,13 +7897,13 @@ public sealed class Converter : JsonConverter public override WorkspacesWorkspaceDetailsHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, WorkspacesWorkspaceDetailsHostType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); } } } @@ -7966,13 +7966,13 @@ public sealed class Converter : JsonConverter /// public override InstructionsSourcesLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, InstructionsSourcesLocation value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesLocation)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesLocation)); } } } @@ -8044,13 +8044,13 @@ public sealed class Converter : JsonConverter /// public override InstructionsSourcesType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, InstructionsSourcesType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionsSourcesType)); } } } @@ -8119,13 +8119,13 @@ public sealed class Converter : JsonConverter /// public override AgentInfoSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, AgentInfoSource value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentInfoSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentInfoSource)); } } } @@ -8182,13 +8182,13 @@ public sealed class Converter : JsonConverter /// public override TaskExecutionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, TaskExecutionMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskExecutionMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskExecutionMode)); } } } @@ -8254,13 +8254,13 @@ public sealed class Converter : JsonConverter /// public override TaskStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, TaskStatus value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskStatus)); } } } @@ -8317,13 +8317,13 @@ public sealed class Converter : JsonConverter /// public override TaskShellInfoAttachmentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, TaskShellInfoAttachmentMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskShellInfoAttachmentMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskShellInfoAttachmentMode)); } } } @@ -8383,13 +8383,13 @@ public sealed class Converter : JsonConverter /// public override McpSamplingExecutionAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, McpSamplingExecutionAction value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSamplingExecutionAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSamplingExecutionAction)); } } } @@ -8446,13 +8446,13 @@ public sealed class Converter : JsonConverter /// public override McpSetEnvValueModeDetails Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, McpSetEnvValueModeDetails value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSetEnvValueModeDetails)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSetEnvValueModeDetails)); } } } @@ -8509,13 +8509,13 @@ public sealed class Converter : JsonConverter /// public override OptionsUpdateEnvValueMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, OptionsUpdateEnvValueMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateEnvValueMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateEnvValueMode)); } } } @@ -8572,13 +8572,13 @@ public sealed class Converter : JsonConverter /// public override ExtensionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ExtensionSource value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionSource)); } } } @@ -8641,13 +8641,13 @@ public sealed class Converter : JsonConverter /// public override ExtensionStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ExtensionStatus value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionStatus)); } } } @@ -8701,13 +8701,13 @@ public sealed class Converter : JsonConverter /// public override SlashCommandInputCompletion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SlashCommandInputCompletion value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); } } } @@ -8767,13 +8767,13 @@ public sealed class Converter : JsonConverter /// public override SlashCommandKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SlashCommandKind value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); } } } @@ -8833,13 +8833,13 @@ public sealed class Converter : JsonConverter /// public override UIElicitationResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, UIElicitationResponseAction value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); } } } @@ -8899,13 +8899,13 @@ public sealed class Converter : JsonConverter /// public override UIAutoModeSwitchResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, UIAutoModeSwitchResponse value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); } } } @@ -8968,13 +8968,13 @@ public sealed class Converter : JsonConverter /// public override UIExitPlanModeAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, UIExitPlanModeAction value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIExitPlanModeAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIExitPlanModeAction)); } } } @@ -9031,13 +9031,13 @@ public sealed class Converter : JsonConverter public override PermissionsConfigureAdditionalContentExclusionPolicyScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionsConfigureAdditionalContentExclusionPolicyScope value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsConfigureAdditionalContentExclusionPolicyScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsConfigureAdditionalContentExclusionPolicyScope)); } } } @@ -9100,13 +9100,13 @@ public sealed class Converter : JsonConverter /// public override PermissionsSetApproveAllSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionsSetApproveAllSource value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetApproveAllSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetApproveAllSource)); } } } @@ -9163,13 +9163,13 @@ public sealed class Converter : JsonConverter /// public override PermissionsModifyRulesScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionsModifyRulesScope value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsModifyRulesScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsModifyRulesScope)); } } } @@ -9226,13 +9226,13 @@ public sealed class Converter : JsonConverter /// public override PermissionLocationType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, PermissionLocationType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionLocationType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionLocationType)); } } } @@ -9292,13 +9292,13 @@ public sealed class Converter : JsonConverter /// public override MetadataSnapshotCurrentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, MetadataSnapshotCurrentMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotCurrentMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotCurrentMode)); } } } @@ -9355,13 +9355,13 @@ public sealed class Converter : JsonConverter public override MetadataSnapshotRemoteMetadataTaskType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, MetadataSnapshotRemoteMetadataTaskType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotRemoteMetadataTaskType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotRemoteMetadataTaskType)); } } } @@ -9418,13 +9418,13 @@ public sealed class Converter : JsonConverter /// public override WorkspaceSummaryHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, WorkspaceSummaryHostType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceSummaryHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceSummaryHostType)); } } } @@ -9481,13 +9481,13 @@ public sealed class Converter : JsonConverter public override SessionWorkingDirectoryContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionWorkingDirectoryContextHostType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionWorkingDirectoryContextHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionWorkingDirectoryContextHostType)); } } } @@ -9547,13 +9547,13 @@ public sealed class Converter : JsonConverter /// public override ShellKillSignal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, ShellKillSignal value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellKillSignal)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellKillSignal)); } } } @@ -9610,13 +9610,13 @@ public sealed class Converter : JsonConverter /// public override QueuePendingItemsKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, QueuePendingItemsKind value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(QueuePendingItemsKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(QueuePendingItemsKind)); } } } @@ -9673,13 +9673,13 @@ public sealed class Converter : JsonConverter /// public override EventsCursorStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, EventsCursorStatus value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsCursorStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsCursorStatus)); } } } @@ -9736,13 +9736,13 @@ public sealed class Converter : JsonConverter /// public override EventsAgentScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, EventsAgentScope value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsAgentScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsAgentScope)); } } } @@ -9802,13 +9802,13 @@ public sealed class Converter : JsonConverter /// public override RemoteSessionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, RemoteSessionMode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMode)); } } } @@ -9864,13 +9864,13 @@ public sealed class Converter : JsonConverter /// public override SessionFsErrorCode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsErrorCode value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsErrorCode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsErrorCode)); } } } @@ -9926,13 +9926,13 @@ public sealed class Converter : JsonConverter public override SessionFsReaddirWithTypesEntryType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsReaddirWithTypesEntryType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsReaddirWithTypesEntryType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsReaddirWithTypesEntryType)); } } } @@ -9991,13 +9991,13 @@ public sealed class Converter : JsonConverter /// public override SessionFsSqliteQueryType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return new(GitHub.Copilot.SDK.GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// public override void Write(Utf8JsonWriter writer, SessionFsSqliteQueryType value, JsonSerializerOptions options) { - GitHub.Copilot.SDK.GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSqliteQueryType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSqliteQueryType)); } } } @@ -12989,224 +12989,224 @@ public static void RegisterClientSessionApiHandlers(JsonRpc rpc, Func Date: Thu, 21 May 2026 15:52:44 +0100 Subject: [PATCH 13/20] Use JsonTypeInfo in ToJsonElementForWire to drop trim/AOT suppressions Per @stephentoub: passing JsonTypeInfo (looked up via the configured resolver chain) instead of Type avoids the need for IL2026/IL3050 suppressions because the typed overload is statically analyzable. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Client.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/dotnet/src/Client.cs b/dotnet/src/Client.cs index 280ae6d10..3fab77c89 100644 --- a/dotnet/src/Client.cs +++ b/dotnet/src/Client.cs @@ -1643,17 +1643,11 @@ private async Task ConnectToServerAsync(Process? cliProcess, string? /// type registered in the SDK's source-generated contexts (e.g. primitives, /// Dictionary<string, object>, generated DTOs) is supported. /// - [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2026", - Justification = "Opaque-JSON conversion uses the chained source-generated JsonSerializerContexts " + - "configured on SerializerOptionsForMessageFormatter. Any type used at this boundary is reachable via those contexts.")] - [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("AOT", "IL3050", - Justification = "Opaque-JSON conversion uses the chained source-generated JsonSerializerContexts " + - "configured on SerializerOptionsForMessageFormatter. Any type used at this boundary is reachable via those contexts.")] public static JsonElement? ToJsonElementForWire(object? value) => value switch { null => null, JsonElement je => je, - _ => JsonSerializer.SerializeToElement(value, value.GetType(), SerializerOptionsForMessageFormatter) + _ => JsonSerializer.SerializeToElement(value, SerializerOptionsForMessageFormatter.GetTypeInfo(value.GetType())) }; private static JsonSerializerOptions CreateSerializerOptions() From f946952bd49b7bed50f36d55dcbaeab800e426dd Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 17:57:53 +0100 Subject: [PATCH 14/20] TS codegen: honor x-opaque-json; share isOpaqueJson helper - Add shared isOpaqueJson() in scripts/codegen/utils.ts; csharp.ts imports it instead of defining its own copy. - typescript.ts: map {x-opaque-json: true} schemas to `unknown` instead of letting json-schema-to-typescript fabricate a {[k:string]:unknown} object shape from the missing type keyword. - Narrow SDK surface casts at boundaries where the wire is opaque JSON but the SDK contract requires a tighter shape (session.ts elicitation, sessionFsProvider sqlite bindParams). - Regenerated all language outputs against the latest runtime schema. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/SessionEvents.cs | 8 +- go/rpc/zsession_events.go | 6 +- nodejs/src/generated/rpc.ts | 658 ++++++++++----------- nodejs/src/generated/session-events.ts | 131 +--- nodejs/src/session.ts | 9 +- nodejs/src/sessionFsProvider.ts | 5 +- nodejs/test/session-event-types.test.ts | 2 +- python/copilot/generated/session_events.py | 66 +-- rust/src/generated/session_events.rs | 14 +- scripts/codegen/csharp.ts | 8 +- scripts/codegen/typescript.ts | 16 + scripts/codegen/utils.ts | 10 + 12 files changed, 405 insertions(+), 528 deletions(-) diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index 48ed92aef..23cfaedaf 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -1681,10 +1681,8 @@ public sealed partial class SessionShutdownData public double? TotalNanoAiu { get; set; } /// Total number of premium API requests used during the session. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonInclude] [JsonPropertyName("totalPremiumRequests")] - internal double? TotalPremiumRequests { get; set; } + public required double TotalPremiumRequests { get; set; } } /// Working directory and git context at session start. @@ -3189,7 +3187,6 @@ public sealed partial class ShutdownCodeChanges /// Request count and cost metrics. /// Nested data type for ShutdownModelMetricRequests. -[Experimental(Diagnostics.Experimental)] public sealed partial class ShutdownModelMetricRequests { /// Cumulative cost multiplier for requests to this model. @@ -3241,9 +3238,8 @@ public sealed partial class ShutdownModelMetricUsage public sealed partial class ShutdownModelMetric { /// Request count and cost metrics. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("requests")] - public ShutdownModelMetricRequests? Requests { get; set; } + public required ShutdownModelMetricRequests Requests { get; set; } /// Token count details per type. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index cec7d28af..36a24ba3d 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -1059,8 +1059,7 @@ type SessionShutdownData struct { // Experimental: TotalNanoAiu is part of an experimental API and may change or be removed. TotalNanoAiu *float64 `json:"totalNanoAiu,omitempty"` // Total number of premium API requests used during the session - // Internal: TotalPremiumRequests is part of the SDK's internal API surface and is not intended for external use. - TotalPremiumRequests *float64 `json:"totalPremiumRequests,omitempty"` + TotalPremiumRequests float64 `json:"totalPremiumRequests"` } func (*SessionShutdownData) sessionEventData() {} @@ -2229,7 +2228,7 @@ type ShutdownCodeChanges struct { // Schema for the `ShutdownModelMetric` type. type ShutdownModelMetric struct { // Request count and cost metrics - Requests *ShutdownModelMetricRequests `json:"requests,omitempty"` + Requests ShutdownModelMetricRequests `json:"requests"` // Token count details per type TokenDetails map[string]ShutdownModelMetricTokenDetail `json:"tokenDetails,omitempty"` // Accumulated nano-AI units cost for this model @@ -2240,7 +2239,6 @@ type ShutdownModelMetric struct { } // Request count and cost metrics -// Experimental: ShutdownModelMetricRequests is part of an experimental API and may change or be removed. type ShutdownModelMetricRequests struct { // Cumulative cost multiplier for requests to this model Cost float64 `json:"cost"` diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index bc835d78a..c17b4fb67 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -193,7 +193,7 @@ export type ExtensionStatus = * via the `definition` "ExternalToolResult". */ /** @experimental */ -export type ExternalToolResult = string | ExternalToolTextResultForLlm; +export type ExternalToolResult = unknown; /** * Binary result type discriminator. Use "image" for images and "resource" for other binary data. * @@ -249,11 +249,7 @@ export type ExternalToolTextResultForLlmContentResourceDetails = * via the `definition` "FilterMapping". */ /** @experimental */ -export type FilterMapping = - | { - [k: string]: ContentFilterMode; - } - | ContentFilterMode; +export type FilterMapping = unknown; /** * Source for direct repo installs (when marketplace is empty) * @@ -261,11 +257,7 @@ export type FilterMapping = * via the `definition` "InstalledPluginSource". */ /** @experimental */ -export type InstalledPluginSource = - | string - | InstalledPluginSourceGithub - | InstalledPluginSourceUrl - | InstalledPluginSourceLocal; +export type InstalledPluginSource = unknown; /** * Category of instruction source — used for merge logic * @@ -325,29 +317,23 @@ export type SessionLogLevel = * via the `definition` "McpServerConfig". */ /** @experimental */ -export type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp; +export type McpServerConfig = unknown; /** - * Remote transport type. Defaults to "http" when omitted. + * Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigHttpType". + * via the `definition` "McpExecuteSamplingRequest". */ -export type McpServerConfigHttpType = - /** Streamable HTTP transport. */ - | "http" - /** Server-Sent Events transport. */ - | "sse"; +/** @experimental */ +export type McpExecuteSamplingRequest = unknown; /** - * OAuth grant type to use when authenticating to the remote MCP server. + * MCP CreateMessageResult payload (with optional 'tools' extension), present when action='success'. Treated as opaque at the schema layer; consumers should construct/consume it per the MCP CreateMessageResult shape. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigHttpOauthGrantType". + * via the `definition` "McpExecuteSamplingResult". */ -export type McpServerConfigHttpOauthGrantType = - /** Interactive browser-based authorization code flow with PKCE. */ - | "authorization_code" - /** Headless client credentials flow using the configured OAuth client. */ - | "client_credentials"; +/** @experimental */ +export type McpExecuteSamplingResult = unknown; /** * Outcome of the sampling inference. 'success' produced a response; 'failure' encountered an error (including agent-side rejection by content filter or criteria); 'cancelled' the caller cancelled this execution via cancelSamplingExecution. * @@ -362,6 +348,28 @@ export type McpSamplingExecutionAction = | "failure" /** The sampling inference was cancelled before completion. */ | "cancelled"; +/** + * Remote transport type. Defaults to "http" when omitted. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigHttpType". + */ +export type McpServerConfigHttpType = + /** Streamable HTTP transport. */ + | "http" + /** Server-Sent Events transport. */ + | "sse"; +/** + * OAuth grant type to use when authenticating to the remote MCP server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigHttpOauthGrantType". + */ +export type McpServerConfigHttpOauthGrantType = + /** Interactive browser-based authorization code flow with PKCE. */ + | "authorization_code" + /** Headless client credentials flow using the configured OAuth client. */ + | "client_credentials"; /** * How environment-variable values supplied to MCP servers are resolved. "direct" passes literal string values; "indirect" treats values as references (e.g. names of environment variables on the host) that the runtime resolves before launch. Defaults to the runtime's startup mode; clients that intentionally launch MCP servers with literal values (e.g. CLI prompt mode and ACP) set this to "direct". * @@ -782,11 +790,7 @@ export type SessionFsSqliteQueryType = * via the `definition` "SessionInstalledPluginSource". */ /** @experimental */ -export type SessionInstalledPluginSource = - | string - | SessionInstalledPluginSourceGithub - | SessionInstalledPluginSourceUrl - | SessionInstalledPluginSourceLocal; +export type SessionInstalledPluginSource = unknown; /** * Public-facing workspace metadata for this session, or null if the session has no associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, internal flags). * @@ -946,7 +950,7 @@ export type UIAutoModeSwitchResponse = * via the `definition` "UIElicitationFieldValue". */ /** @experimental */ -export type UIElicitationFieldValue = string | number | boolean | string[]; +export type UIElicitationFieldValue = unknown; /** * Definition for a single elicitation form field. * @@ -954,33 +958,21 @@ export type UIElicitationFieldValue = string | number | boolean | string[]; * via the `definition` "UIElicitationSchemaProperty". */ /** @experimental */ -export type UIElicitationSchemaProperty = - | ( - | UIElicitationStringEnumField - | UIElicitationStringOneOfField - | UIElicitationArrayEnumField - | UIElicitationArrayAnyOfField - | UIElicitationSchemaPropertyBoolean - | UIElicitationSchemaPropertyString - | UIElicitationSchemaPropertyNumber - ) - | undefined; +export type UIElicitationSchemaProperty = unknown | undefined; /** - * Optional format hint that constrains the accepted input. + * The user's response: accept (submitted), decline (rejected), or cancel (dismissed) * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationSchemaPropertyStringFormat". + * via the `definition` "UIElicitationResponseAction". */ /** @experimental */ -export type UIElicitationSchemaPropertyStringFormat = - /** Email address string format. */ - | "email" - /** URI string format. */ - | "uri" - /** Calendar date string format. */ - | "date" - /** Date-time string format. */ - | "date-time"; +export type UIElicitationResponseAction = + /** The user submitted the requested form values. */ + | "accept" + /** The user explicitly declined to provide the requested input. */ + | "decline" + /** The user dismissed the elicitation request. */ + | "cancel"; /** * Numeric type accepted by the field. * @@ -994,19 +986,21 @@ export type UIElicitationSchemaPropertyNumberType = /** Integer JSON number. */ | "integer"; /** - * The user's response: accept (submitted), decline (rejected), or cancel (dismissed) + * Optional format hint that constrains the accepted input. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResponseAction". + * via the `definition` "UIElicitationSchemaPropertyStringFormat". */ /** @experimental */ -export type UIElicitationResponseAction = - /** The user submitted the requested form values. */ - | "accept" - /** The user explicitly declined to provide the requested input. */ - | "decline" - /** The user dismissed the elicitation request. */ - | "cancel"; +export type UIElicitationSchemaPropertyStringFormat = + /** Email address string format. */ + | "email" + /** URI string format. */ + | "uri" + /** Calendar date string format. */ + | "date" + /** Date-time string format. */ + | "date-time"; /** * The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. * @@ -1023,6 +1017,14 @@ export type UIExitPlanModeAction = | "autopilot" /** Exit plan mode and continue in autopilot mode with parallel subagent execution. */ | "autopilot_fleet"; +/** + * Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UIHandlePendingSamplingResponse". + */ +/** @experimental */ +export type UIHandlePendingSamplingResponse = unknown; /** * Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. * @@ -1184,11 +1186,7 @@ export interface AgentInfo { * @experimental */ mcpServers?: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }; /** * Skill names preloaded into this agent's context. Omitted means none. @@ -2073,11 +2071,7 @@ export interface ExternalToolTextResultForLlm { * Optional tool-specific telemetry */ toolTelemetry?: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }; /** * Base64-encoded binary results returned to the model @@ -2556,34 +2550,34 @@ export interface InstalledPluginSourceGithub { path?: string; } /** - * Schema for the `InstalledPluginSourceUrl` type. + * Schema for the `InstalledPluginSourceLocal` type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "InstalledPluginSourceUrl". + * via the `definition` "InstalledPluginSourceLocal". */ /** @experimental */ -export interface InstalledPluginSourceUrl { +export interface InstalledPluginSourceLocal { /** - * Constant value. Always "url". + * Constant value. Always "local". */ - source: "url"; - url: string; - ref?: string; - path?: string; + source: "local"; + path: string; } /** - * Schema for the `InstalledPluginSourceLocal` type. + * Schema for the `InstalledPluginSourceUrl` type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "InstalledPluginSourceLocal". + * via the `definition` "InstalledPluginSourceUrl". */ /** @experimental */ -export interface InstalledPluginSourceLocal { +export interface InstalledPluginSourceUrl { /** - * Constant value. Always "local". + * Constant value. Always "url". */ - source: "local"; - path: string; + source: "url"; + url: string; + ref?: string; + path?: string; } /** * Instruction sources loaded for the session, in merge order. @@ -2741,99 +2735,6 @@ export interface McpConfigAddRequest { name: string; config: McpServerConfig; } -/** - * Stdio MCP server configuration launched as a child process. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigStdio". - */ -export interface McpServerConfigStdio { - /** - * Tools to include. Defaults to all tools if not specified. - */ - tools?: string[]; - /** - * Whether this server is a built-in fallback used when the user has not configured their own server. - */ - isDefaultServer?: boolean; - filterMapping?: FilterMapping; - /** - * Timeout in milliseconds for tool calls to this server. - */ - timeout?: number; - /** - * Executable command used to start the Stdio MCP server process. - */ - command: string; - /** - * Command-line arguments passed to the Stdio MCP server process. - */ - args?: string[]; - /** - * Working directory for the Stdio MCP server process. - */ - cwd?: string; - /** - * Environment variables to pass to the Stdio MCP server process. - */ - env?: { - [k: string]: string | undefined; - }; -} -/** - * Remote MCP server configuration accessed over HTTP or SSE. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigHttp". - */ -export interface McpServerConfigHttp { - /** - * Tools to include. Defaults to all tools if not specified. - */ - tools?: string[]; - type?: McpServerConfigHttpType; - /** - * Whether this server is a built-in fallback used when the user has not configured their own server. - */ - isDefaultServer?: boolean; - filterMapping?: FilterMapping; - /** - * Timeout in milliseconds for tool calls to this server. - */ - timeout?: number; - /** - * URL of the remote MCP server endpoint. - */ - url: string; - /** - * HTTP headers to include in requests to the remote MCP server. - */ - headers?: { - [k: string]: string | undefined; - }; - /** - * OAuth client ID for a pre-registered remote MCP OAuth client. - */ - oauthClientId?: string; - /** - * Whether the configured OAuth client is public and does not require a client secret. - */ - oauthPublicClient?: boolean; - oauthGrantType?: McpServerConfigHttpOauthGrantType; - auth?: McpServerConfigHttpAuth; -} -/** - * Additional authentication configuration for this server. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigHttpAuth". - */ -export interface McpServerConfigHttpAuth { - /** - * Fixed port for the OAuth redirect callback server. - */ - redirectPort?: number; -} /** * MCP server names to disable for new sessions. * @@ -2967,29 +2868,9 @@ export interface McpExecuteSamplingParams { /** * The original MCP JSON-RPC request ID (string or number). Used by the runtime to correlate the inference with the originating MCP request for telemetry; this is distinct from `requestId` (which is the schema-level cancellation handle). */ - mcpRequestId: string | number; + mcpRequestId: unknown; request: McpExecuteSamplingRequest; } -/** - * Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpExecuteSamplingRequest". - */ -/** @experimental */ -export interface McpExecuteSamplingRequest { - [k: string]: unknown | undefined; -} -/** - * MCP CreateMessageResult payload (with optional 'tools' extension), present when action='success'. Treated as opaque at the schema layer; consumers should construct/consume it per the MCP CreateMessageResult shape. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpExecuteSamplingResult". - */ -/** @experimental */ -export interface McpExecuteSamplingResult { - [k: string]: unknown | undefined; -} /** * Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, and the callback success-page copy. * @@ -3052,28 +2933,121 @@ export interface McpSamplingExecutionResult { action: McpSamplingExecutionAction; result?: McpExecuteSamplingResult; /** - * Error description, present when action='failure'. + * Error description, present when action='failure'. + */ + error?: string; +} +/** + * Schema for the `McpServer` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServer". + */ +/** @experimental */ +export interface McpServer { + /** + * Server name (config key) + */ + name: string; + status: McpServerStatus; + source?: McpServerSource; + /** + * Error message if the server failed to connect + */ + error?: string; +} +/** + * Remote MCP server configuration accessed over HTTP or SSE. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigHttp". + */ +export interface McpServerConfigHttp { + /** + * Tools to include. Defaults to all tools if not specified. + */ + tools?: string[]; + type?: McpServerConfigHttpType; + /** + * Whether this server is a built-in fallback used when the user has not configured their own server. + */ + isDefaultServer?: boolean; + filterMapping?: FilterMapping; + /** + * Timeout in milliseconds for tool calls to this server. + */ + timeout?: number; + /** + * URL of the remote MCP server endpoint. + */ + url: string; + /** + * HTTP headers to include in requests to the remote MCP server. + */ + headers?: { + [k: string]: string | undefined; + }; + /** + * OAuth client ID for a pre-registered remote MCP OAuth client. + */ + oauthClientId?: string; + /** + * Whether the configured OAuth client is public and does not require a client secret. + */ + oauthPublicClient?: boolean; + oauthGrantType?: McpServerConfigHttpOauthGrantType; + auth?: McpServerConfigHttpAuth; +} +/** + * Additional authentication configuration for this server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigHttpAuth". + */ +export interface McpServerConfigHttpAuth { + /** + * Fixed port for the OAuth redirect callback server. + */ + redirectPort?: number; +} +/** + * Stdio MCP server configuration launched as a child process. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigStdio". + */ +export interface McpServerConfigStdio { + /** + * Tools to include. Defaults to all tools if not specified. + */ + tools?: string[]; + /** + * Whether this server is a built-in fallback used when the user has not configured their own server. + */ + isDefaultServer?: boolean; + filterMapping?: FilterMapping; + /** + * Timeout in milliseconds for tool calls to this server. + */ + timeout?: number; + /** + * Executable command used to start the Stdio MCP server process. + */ + command: string; + /** + * Command-line arguments passed to the Stdio MCP server process. */ - error?: string; -} -/** - * Schema for the `McpServer` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServer". - */ -/** @experimental */ -export interface McpServer { + args?: string[]; /** - * Server name (config key) + * Working directory for the Stdio MCP server process. */ - name: string; - status: McpServerStatus; - source?: McpServerSource; + cwd?: string; /** - * Error message if the server failed to connect + * Environment variables to pass to the Stdio MCP server process. */ - error?: string; + env?: { + [k: string]: string | undefined; + }; } /** * MCP servers configured for the session, with their connection status. @@ -4650,7 +4624,7 @@ export interface PermissionRulesSet { /** @experimental */ export interface PermissionsConfigureAdditionalContentExclusionPolicy { rules: PermissionsConfigureAdditionalContentExclusionPolicyRule[]; - last_updated_at: string | number; + last_updated_at: unknown; scope: PermissionsConfigureAdditionalContentExclusionPolicyScope; [k: string]: unknown | undefined; } @@ -5486,9 +5460,7 @@ export interface SendRequest { /** * Optional provenance tag copied to the resulting user.message event. Supported values are `system`, `command-*`, and `schedule-*`. */ - source?: { - [k: string]: unknown | undefined; - }; + source?: unknown; agentMode?: SendAgentMode; /** * Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. @@ -5996,7 +5968,7 @@ export interface SessionFsSqliteQueryRequest { * Optional named bind parameters */ params?: { - [k: string]: (string | number | null) | undefined; + [k: string]: unknown | undefined; }; } /** @@ -6010,11 +5982,7 @@ export interface SessionFsSqliteQueryResult { * For SELECT: array of row objects. For others: empty array. */ rows: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }[]; /** * Column names from the result set @@ -6150,34 +6118,34 @@ export interface SessionInstalledPluginSourceGithub { path?: string; } /** - * Schema for the `SessionInstalledPluginSourceUrl` type. + * Schema for the `SessionInstalledPluginSourceLocal` type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SessionInstalledPluginSourceUrl". + * via the `definition` "SessionInstalledPluginSourceLocal". */ /** @experimental */ -export interface SessionInstalledPluginSourceUrl { +export interface SessionInstalledPluginSourceLocal { /** - * Constant value. Always "url". + * Constant value. Always "local". */ - source: "url"; - url: string; - ref?: string; - path?: string; + source: "local"; + path: string; } /** - * Schema for the `SessionInstalledPluginSourceLocal` type. + * Schema for the `SessionInstalledPluginSourceUrl` type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SessionInstalledPluginSourceLocal". + * via the `definition` "SessionInstalledPluginSourceUrl". */ /** @experimental */ -export interface SessionInstalledPluginSourceLocal { +export interface SessionInstalledPluginSourceUrl { /** - * Constant value. Always "local". + * Constant value. Always "url". */ - source: "local"; - path: string; + source: "url"; + url: string; + ref?: string; + path?: string; } /** * Persisted sessions matching the filter, ordered most-recently-modified first. @@ -6777,9 +6745,7 @@ export interface SessionUpdateOptionsParams { * * @experimental */ - provider?: { - [k: string]: unknown | undefined; - }; + provider?: unknown; /** * Absolute working-directory path for shell tools. */ @@ -6809,9 +6775,7 @@ export interface SessionUpdateOptionsParams { * * @experimental */ - sandboxConfig?: { - [k: string]: unknown | undefined; - }; + sandboxConfig?: unknown; /** * Whether interactive shell sessions are logged. */ @@ -6890,9 +6854,7 @@ export interface SessionUpdateOptionsParams { * * @experimental */ - additionalContentExclusionPolicies?: { - [k: string]: unknown | undefined; - }[]; + additionalContentExclusionPolicies?: unknown[]; /** * Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the per-session schedule registry; this flag only controls tool exposure (typically gated to staff users). */ @@ -7725,11 +7687,7 @@ export interface Tool { * JSON Schema for the tool's input parameters */ parameters?: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }; /** * Optional instructions for how to use this tool effectively @@ -7921,83 +7879,38 @@ export interface UIElicitationSchema { required?: string[]; } /** - * Single-select string field whose allowed values are defined inline. + * The elicitation response (accept with form values, decline, or cancel) * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationStringEnumField". + * via the `definition` "UIElicitationResponse". */ /** @experimental */ -export interface UIElicitationStringEnumField { - /** - * Type discriminator. Always "string". - */ - type: "string"; - /** - * Human-readable label for the field. - */ - title?: string; - /** - * Help text describing the field. - */ - description?: string; - /** - * Allowed string values. - */ - enum: string[]; - /** - * Optional display labels for each enum value, in the same order as `enum`. - */ - enumNames?: string[]; - /** - * Default value selected when the form is first shown. - */ - default?: string; +export interface UIElicitationResponse { + action: UIElicitationResponseAction; + content?: UIElicitationResponseContent; } /** - * Single-select string field where each option pairs a value with a display label. + * The form values submitted by the user (present when action is 'accept') * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationStringOneOfField". + * via the `definition` "UIElicitationResponseContent". */ /** @experimental */ -export interface UIElicitationStringOneOfField { - /** - * Type discriminator. Always "string". - */ - type: "string"; - /** - * Human-readable label for the field. - */ - title?: string; - /** - * Help text describing the field. - */ - description?: string; - /** - * Selectable options, each with a value and a display label. - */ - oneOf: UIElicitationStringOneOfFieldOneOf[]; - /** - * Default value selected when the form is first shown. - */ - default?: string; +export interface UIElicitationResponseContent { + [k: string]: UIElicitationFieldValue; } /** - * Schema for the `UIElicitationStringOneOfFieldOneOf` type. + * Indicates whether the elicitation response was accepted; false if it was already resolved by another client. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationStringOneOfFieldOneOf". + * via the `definition` "UIElicitationResult". */ /** @experimental */ -export interface UIElicitationStringOneOfFieldOneOf { - /** - * Value submitted when this option is selected. - */ - const: string; +export interface UIElicitationResult { /** - * Display label for this option. + * Whether the response was accepted. False if the request was already resolved by another client. */ - title: string; + success: boolean; } /** * Boolean field rendered as a yes/no toggle. @@ -8024,6 +7937,36 @@ export interface UIElicitationSchemaPropertyBoolean { */ default?: boolean; } +/** + * Numeric field accepting either a number or an integer. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UIElicitationSchemaPropertyNumber". + */ +/** @experimental */ +export interface UIElicitationSchemaPropertyNumber { + type: UIElicitationSchemaPropertyNumberType; + /** + * Human-readable label for the field. + */ + title?: string; + /** + * Help text describing the field. + */ + description?: string; + /** + * Minimum allowed value (inclusive). + */ + minimum?: number; + /** + * Maximum allowed value (inclusive). + */ + maximum?: number; + /** + * Default value populated in the input when the form is first shown. + */ + default?: number; +} /** * Free-text string field with optional length and format constraints. * @@ -8059,14 +8002,17 @@ export interface UIElicitationSchemaPropertyString { default?: string; } /** - * Numeric field accepting either a number or an integer. + * Single-select string field whose allowed values are defined inline. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationSchemaPropertyNumber". + * via the `definition` "UIElicitationStringEnumField". */ /** @experimental */ -export interface UIElicitationSchemaPropertyNumber { - type: UIElicitationSchemaPropertyNumberType; +export interface UIElicitationStringEnumField { + /** + * Type discriminator. Always "string". + */ + type: "string"; /** * Human-readable label for the field. */ @@ -8076,51 +8022,63 @@ export interface UIElicitationSchemaPropertyNumber { */ description?: string; /** - * Minimum allowed value (inclusive). + * Allowed string values. */ - minimum?: number; + enum: string[]; /** - * Maximum allowed value (inclusive). + * Optional display labels for each enum value, in the same order as `enum`. */ - maximum?: number; + enumNames?: string[]; /** - * Default value populated in the input when the form is first shown. + * Default value selected when the form is first shown. */ - default?: number; -} -/** - * The elicitation response (accept with form values, decline, or cancel) - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResponse". - */ -/** @experimental */ -export interface UIElicitationResponse { - action: UIElicitationResponseAction; - content?: UIElicitationResponseContent; + default?: string; } /** - * The form values submitted by the user (present when action is 'accept') + * Single-select string field where each option pairs a value with a display label. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResponseContent". + * via the `definition` "UIElicitationStringOneOfField". */ /** @experimental */ -export interface UIElicitationResponseContent { - [k: string]: UIElicitationFieldValue; +export interface UIElicitationStringOneOfField { + /** + * Type discriminator. Always "string". + */ + type: "string"; + /** + * Human-readable label for the field. + */ + title?: string; + /** + * Help text describing the field. + */ + description?: string; + /** + * Selectable options, each with a value and a display label. + */ + oneOf: UIElicitationStringOneOfFieldOneOf[]; + /** + * Default value selected when the form is first shown. + */ + default?: string; } /** - * Indicates whether the elicitation response was accepted; false if it was already resolved by another client. + * Schema for the `UIElicitationStringOneOfFieldOneOf` type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResult". + * via the `definition` "UIElicitationStringOneOfFieldOneOf". */ /** @experimental */ -export interface UIElicitationResult { +export interface UIElicitationStringOneOfFieldOneOf { /** - * Whether the response was accepted. False if the request was already resolved by another client. + * Value submitted when this option is selected. */ - success: boolean; + const: string; + /** + * Display label for this option. + */ + title: string; } /** * Schema for the `UIExitPlanModeResponse` type. @@ -8213,16 +8171,6 @@ export interface UIHandlePendingSamplingRequest { requestId: string; response?: UIHandlePendingSamplingResponse; } -/** - * Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIHandlePendingSamplingResponse". - */ -/** @experimental */ -export interface UIHandlePendingSamplingResponse { - [k: string]: unknown | undefined; -} /** * Request ID of a pending `user_input.requested` event and the user's response. * diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index 3196c4731..c15720a59 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -370,19 +370,11 @@ export type ElicitationCompletedAction = /** * Schema for the `ElicitationCompletedContent` type. */ -export type ElicitationCompletedContent = (string | number | boolean | string[]) | undefined; +export type ElicitationCompletedContent = unknown | undefined; /** * Source-defined JSON payload for the custom notification */ -export type CustomNotificationPayload = - | string - | number - | boolean - | null - | unknown[] - | { - [k: string]: unknown | undefined; - }; +export type CustomNotificationPayload = unknown; /** * The user's auto-mode-switch choice */ @@ -1470,10 +1462,8 @@ export interface ShutdownData { totalNanoAiu?: number; /** * Total number of premium API requests used during the session - * - * @internal */ - totalPremiumRequests?: number; + totalPremiumRequests: number; } /** * Aggregate code change metrics for the session @@ -1496,7 +1486,7 @@ export interface ShutdownCodeChanges { * Schema for the `ShutdownModelMetric` type. */ export interface ShutdownModelMetric { - requests?: ShutdownModelMetricRequests; + requests: ShutdownModelMetricRequests; /** * Token count details per type */ @@ -1514,7 +1504,6 @@ export interface ShutdownModelMetric { /** * Request count and cost metrics */ -/** @experimental */ export interface ShutdownModelMetricRequests { /** * Cumulative cost multiplier for requests to this model @@ -2413,9 +2402,7 @@ export interface AssistantMessageData { * * @internal */ - anthropicAdvisorBlocks?: { - [k: string]: unknown | undefined; - }[]; + anthropicAdvisorBlocks?: unknown[]; /** * Anthropic advisor model ID used for this response, for timeline display on replay * @@ -2483,9 +2470,7 @@ export interface AssistantMessageToolRequest { /** * Arguments to pass to the tool, format depends on the tool */ - arguments?: { - [k: string]: unknown | undefined; - }; + arguments?: unknown; /** * Resolved intention summary describing what this specific call does */ @@ -2734,9 +2719,7 @@ export interface AssistantUsageData { * * @internal */ - quotaSnapshots?: { - [k: string]: AssistantUsageQuotaSnapshot | undefined; - }; + quotaSnapshots?: unknown; /** * Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") */ @@ -2784,43 +2767,6 @@ export interface AssistantUsageCopilotUsageTokenDetail { */ tokenType: string; } -/** - * Schema for the `AssistantUsageQuotaSnapshot` type. - */ -export interface AssistantUsageQuotaSnapshot { - /** - * Total requests allowed by the entitlement - */ - entitlementRequests: number; - /** - * Whether the user has an unlimited usage entitlement - */ - isUnlimitedEntitlement: boolean; - /** - * Number of requests over the entitlement limit - */ - overage: number; - /** - * Whether overage is allowed when quota is exhausted - */ - overageAllowedWithExhaustedQuota: boolean; - /** - * Percentage of quota remaining (0 to 100) - */ - remainingPercentage: number; - /** - * Date when the quota resets - */ - resetDate?: string; - /** - * Whether usage is still permitted after quota exhaustion - */ - usageAllowedWithExhaustedQuota: boolean; - /** - * Number of requests already consumed - */ - usedRequests: number; -} /** * Session event "model.call_failure". Failed LLM API call metadata for telemetry */ @@ -2958,9 +2904,7 @@ export interface ToolUserRequestedData { /** * Arguments for the tool invocation */ - arguments?: { - [k: string]: unknown | undefined; - }; + arguments?: unknown; /** * Unique identifier for this tool call */ @@ -3007,9 +2951,7 @@ export interface ToolExecutionStartData { /** * Arguments passed to the tool */ - arguments?: { - [k: string]: unknown | undefined; - }; + arguments?: unknown; /** * Name of the MCP server hosting this tool, when the tool is an MCP tool */ @@ -3187,11 +3129,7 @@ export interface ToolExecutionCompleteData { * Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts) */ toolTelemetry?: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }; /** * Identifier for the agent loop turn this tool was invoked in, matching the corresponding assistant.turn_start event @@ -3769,9 +3707,7 @@ export interface HookStartData { /** * Input data passed to the hook */ - input?: { - [k: string]: unknown | undefined; - }; + input?: unknown; } /** * Session event "hook.end". Hook invocation completion details including output, success status, and error information @@ -3819,9 +3755,7 @@ export interface HookEndData { /** * Output data produced by the hook */ - output?: { - [k: string]: unknown | undefined; - }; + output?: unknown; /** * Whether the hook completed successfully */ @@ -3897,11 +3831,7 @@ export interface SystemMessageMetadata { * Template variables used when constructing the prompt */ variables?: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }; } /** @@ -4252,9 +4182,7 @@ export interface PermissionRequestMcp { /** * Arguments to pass to the MCP tool */ - args?: { - [k: string]: unknown | undefined; - }; + args?: unknown; /** * Permission kind discriminator */ @@ -4339,9 +4267,7 @@ export interface PermissionRequestCustomTool { /** * Arguments to pass to the custom tool */ - args?: { - [k: string]: unknown | undefined; - }; + args?: unknown; /** * Permission kind discriminator */ @@ -4374,9 +4300,7 @@ export interface PermissionRequestHook { /** * Arguments of the tool call being gated */ - toolArgs?: { - [k: string]: unknown | undefined; - }; + toolArgs?: unknown; /** * Tool call ID that triggered this permission request */ @@ -4519,6 +4443,9 @@ export interface PermissionPromptRequestRead { * MCP tool invocation permission prompt */ export interface PermissionPromptRequestMcp { + /** + * Arguments to pass to the MCP tool + */ args?: unknown; /** * Prompt kind discriminator @@ -4600,9 +4527,7 @@ export interface PermissionPromptRequestCustomTool { /** * Arguments to pass to the custom tool */ - args?: { - [k: string]: unknown | undefined; - }; + args?: unknown; /** * Prompt kind discriminator */ @@ -4653,9 +4578,7 @@ export interface PermissionPromptRequestHook { /** * Arguments of the tool call being gated */ - toolArgs?: { - [k: string]: unknown | undefined; - }; + toolArgs?: unknown; /** * Tool call ID that triggered this permission request */ @@ -5147,11 +5070,7 @@ export interface ElicitationRequestedSchema { * Form field definitions, keyed by field name */ properties: { - [k: string]: - | { - [k: string]: unknown | undefined; - } - | undefined; + [k: string]: unknown | undefined; }; /** * List of required field names @@ -5245,7 +5164,7 @@ export interface SamplingRequestedData { /** * The JSON-RPC request ID from the MCP protocol */ - mcpRequestId: string | number; + mcpRequestId: unknown; /** * Unique identifier for this sampling request; used to respond via session.respondToSampling() */ @@ -5491,9 +5410,7 @@ export interface ExternalToolRequestedData { /** * Arguments to pass to the external tool */ - arguments?: { - [k: string]: unknown | undefined; - }; + arguments?: unknown; /** * Unique identifier for this request; used to respond via session.respondToExternalTool() */ diff --git a/nodejs/src/session.ts b/nodejs/src/session.ts index 343fb42ec..8653a14b7 100644 --- a/nodejs/src/session.ts +++ b/nodejs/src/session.ts @@ -760,10 +760,15 @@ export class CopilotSession { private async _elicitation(params: ElicitationParams): Promise { this.assertElicitation(); - return this.rpc.ui.elicitation({ + // The wire shape of `content` is `Record` (the runtime + // schema marks each field value as opaque JSON to allow MCP-style + // string|number|boolean|string[] values without a JSON-schema union). + // The SDK surface narrows it to `Record` + // because that's the only shape MCP-compatible hosts will produce. + return (await this.rpc.ui.elicitation({ message: params.message, requestedSchema: params.requestedSchema, - }); + })) as ElicitationResult; } private async _confirm(message: string): Promise { diff --git a/nodejs/src/sessionFsProvider.ts b/nodejs/src/sessionFsProvider.ts index 7e959849e..e941450f9 100644 --- a/nodejs/src/sessionFsProvider.ts +++ b/nodejs/src/sessionFsProvider.ts @@ -215,7 +215,10 @@ export function createSessionFsAdapter(provider: SessionFsProvider): SessionFsHa const result = await provider.sqlite.query( queryType, query, - normalizeSqliteParams(bindParams) + // Wire shape is `Record` (each bind value is + // opaque JSON on the wire); the SDK provider contract narrows + // it to the primitives SQLite actually accepts. + normalizeSqliteParams(bindParams as Record | undefined) ); return result ?? { rows: [], columns: [], rowsAffected: 0 }; }, diff --git a/nodejs/test/session-event-types.test.ts b/nodejs/test/session-event-types.test.ts index de21ba2ba..5c5d0eccc 100644 --- a/nodejs/test/session-event-types.test.ts +++ b/nodejs/test/session-event-types.test.ts @@ -97,7 +97,7 @@ describe("Session event type exports (#1156)", () => { expect(data.toolName).toBe("shell"); expect(data.toolCallId).toBe("call-1"); - expect(data.arguments?.command).toBe("ls"); + expect((data.arguments as { command?: string } | undefined)?.command).toBe("ls"); expect(data.mcpServerName).toBe("filesystem"); expect(data.mcpToolName).toBe("list_dir"); expect(data.turnId).toBe("turn-1"); diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index de2d87dfc..c655a2370 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -277,30 +277,6 @@ def to_dict(self) -> dict: return {_compat_to_json_key(key): _compat_to_json_value(value) for key, value in self._values.items() if value is not None} -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ShutdownModelMetricRequests: - "Request count and cost metrics" - cost: float - count: int - - @staticmethod - def from_dict(obj: Any) -> "ShutdownModelMetricRequests": - assert isinstance(obj, dict) - cost = from_float(obj.get("cost")) - count = from_int(obj.get("count")) - return ShutdownModelMetricRequests( - cost=cost, - count=count, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["cost"] = to_float(self.cost) - result["count"] = to_int(self.count) - return result - - @dataclass class AbortData: "Turn abort information including the reason for termination" @@ -3120,6 +3096,7 @@ class SessionShutdownData: session_start_time: int shutdown_type: ShutdownType total_api_duration: timedelta + total_premium_requests: float conversation_tokens: int | None = None current_model: str | None = None current_tokens: int | None = None @@ -3129,8 +3106,6 @@ class SessionShutdownData: tool_definitions_tokens: int | None = None # Experimental: this field is part of an experimental API and may change or be removed. total_nano_aiu: float | None = None - # Internal: this field is an internal SDK API and is not part of the public surface. - total_premium_requests: float | None = None @staticmethod def from_dict(obj: Any) -> "SessionShutdownData": @@ -3140,6 +3115,7 @@ def from_dict(obj: Any) -> "SessionShutdownData": session_start_time = from_int(obj.get("sessionStartTime")) shutdown_type = parse_enum(ShutdownType, obj.get("shutdownType")) total_api_duration = from_timedelta(obj.get("totalApiDurationMs")) + total_premium_requests = from_float(obj.get("totalPremiumRequests")) conversation_tokens = from_union([from_none, from_int], obj.get("conversationTokens")) current_model = from_union([from_none, from_str], obj.get("currentModel")) current_tokens = from_union([from_none, from_int], obj.get("currentTokens")) @@ -3148,13 +3124,13 @@ def from_dict(obj: Any) -> "SessionShutdownData": token_details = from_union([from_none, lambda x: from_dict(ShutdownTokenDetail.from_dict, x)], obj.get("tokenDetails")) tool_definitions_tokens = from_union([from_none, from_int], obj.get("toolDefinitionsTokens")) total_nano_aiu = from_union([from_none, from_float], obj.get("totalNanoAiu")) - total_premium_requests = from_union([from_none, from_float], obj.get("totalPremiumRequests")) return SessionShutdownData( code_changes=code_changes, model_metrics=model_metrics, session_start_time=session_start_time, shutdown_type=shutdown_type, total_api_duration=total_api_duration, + total_premium_requests=total_premium_requests, conversation_tokens=conversation_tokens, current_model=current_model, current_tokens=current_tokens, @@ -3163,7 +3139,6 @@ def from_dict(obj: Any) -> "SessionShutdownData": token_details=token_details, tool_definitions_tokens=tool_definitions_tokens, total_nano_aiu=total_nano_aiu, - total_premium_requests=total_premium_requests, ) def to_dict(self) -> dict: @@ -3173,6 +3148,7 @@ def to_dict(self) -> dict: result["sessionStartTime"] = to_int(self.session_start_time) result["shutdownType"] = to_enum(ShutdownType, self.shutdown_type) result["totalApiDurationMs"] = to_timedelta_int(self.total_api_duration) + result["totalPremiumRequests"] = to_float(self.total_premium_requests) if self.conversation_tokens is not None: result["conversationTokens"] = from_union([from_none, to_int], self.conversation_tokens) if self.current_model is not None: @@ -3189,8 +3165,6 @@ def to_dict(self) -> dict: result["toolDefinitionsTokens"] = from_union([from_none, to_int], self.tool_definitions_tokens) if self.total_nano_aiu is not None: result["totalNanoAiu"] = from_union([from_none, to_float], self.total_nano_aiu) - if self.total_premium_requests is not None: - result["totalPremiumRequests"] = from_union([from_none, to_float], self.total_premium_requests) return result @@ -3544,8 +3518,8 @@ def to_dict(self) -> dict: @dataclass class ShutdownModelMetric: "Schema for the `ShutdownModelMetric` type." + requests: ShutdownModelMetricRequests usage: ShutdownModelMetricUsage - requests: ShutdownModelMetricRequests | None = None token_details: dict[str, ShutdownModelMetricTokenDetail] | None = None # Experimental: this field is part of an experimental API and may change or be removed. total_nano_aiu: float | None = None @@ -3553,22 +3527,21 @@ class ShutdownModelMetric: @staticmethod def from_dict(obj: Any) -> "ShutdownModelMetric": assert isinstance(obj, dict) + requests = ShutdownModelMetricRequests.from_dict(obj.get("requests")) usage = ShutdownModelMetricUsage.from_dict(obj.get("usage")) - requests = from_union([from_none, ShutdownModelMetricRequests.from_dict], obj.get("requests")) token_details = from_union([from_none, lambda x: from_dict(ShutdownModelMetricTokenDetail.from_dict, x)], obj.get("tokenDetails")) total_nano_aiu = from_union([from_none, from_float], obj.get("totalNanoAiu")) return ShutdownModelMetric( - usage=usage, requests=requests, + usage=usage, token_details=token_details, total_nano_aiu=total_nano_aiu, ) def to_dict(self) -> dict: result: dict = {} + result["requests"] = to_class(ShutdownModelMetricRequests, self.requests) result["usage"] = to_class(ShutdownModelMetricUsage, self.usage) - if self.requests is not None: - result["requests"] = from_union([from_none, lambda x: to_class(ShutdownModelMetricRequests, x)], self.requests) if self.token_details is not None: result["tokenDetails"] = from_union([from_none, lambda x: from_dict(lambda x: to_class(ShutdownModelMetricTokenDetail, x), x)], self.token_details) if self.total_nano_aiu is not None: @@ -3576,6 +3549,29 @@ def to_dict(self) -> dict: return result +@dataclass +class ShutdownModelMetricRequests: + "Request count and cost metrics" + cost: float + count: int + + @staticmethod + def from_dict(obj: Any) -> "ShutdownModelMetricRequests": + assert isinstance(obj, dict) + cost = from_float(obj.get("cost")) + count = from_int(obj.get("count")) + return ShutdownModelMetricRequests( + cost=cost, + count=count, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["cost"] = to_float(self.cost) + result["count"] = to_int(self.count) + return result + + @dataclass class ShutdownModelMetricTokenDetail: "Schema for the `ShutdownModelMetricTokenDetail` type." diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index 07915f59a..d9efe0290 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -719,13 +719,6 @@ pub struct ShutdownCodeChanges { } /// Request count and cost metrics -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetricRequests { @@ -765,8 +758,7 @@ pub struct ShutdownModelMetricUsage { #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetric { /// Request count and cost metrics - #[serde(skip_serializing_if = "Option::is_none")] - pub requests: Option, + pub requests: ShutdownModelMetricRequests, /// Token count details per type #[serde(default)] pub token_details: HashMap, @@ -838,9 +830,7 @@ pub struct SessionShutdownData { #[serde(skip_serializing_if = "Option::is_none")] pub total_nano_aiu: Option, /// Total number of premium API requests used during the session - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub total_premium_requests: Option, + pub total_premium_requests: f64, } /// Session event "session.context_changed". Updated working directory and git context after the change diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index e71af7231..9c2825ab1 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -37,6 +37,7 @@ import { isSchemaDeprecated, isSchemaExperimental, isSchemaInternal, + isOpaqueJson, isObjectSchema, isVoidSchema, getNullableInner, @@ -287,12 +288,9 @@ function isNonNullableCSharpValueType(typeName: string): boolean { * that lacks an idiomatic mapping (untyped fields, non-discriminated unions, * etc.) is rejected by the runtime's schema-shape lint, so the codegen * treats reaching an unmappable schema here as a bug. + * + * The predicate itself lives in {@link "./utils".isOpaqueJson} for reuse. */ -function isOpaqueJson(schema: JSONSchema7 | undefined): boolean { - if (!schema || typeof schema !== "object") return false; - return (schema as Record)["x-opaque-json"] === true; -} - function failUnmappable(context: string, schema: JSONSchema7): never { const summary = JSON.stringify(schema, (key, value) => (key === "description" ? undefined : value)).slice(0, 200); throw new Error( diff --git a/scripts/codegen/typescript.ts b/scripts/codegen/typescript.ts index 47def79aa..e7ede9538 100644 --- a/scripts/codegen/typescript.ts +++ b/scripts/codegen/typescript.ts @@ -36,6 +36,7 @@ import { isNodeFullyDeprecated, isVoidSchema, isSchemaExperimental, + isOpaqueJson, appendPropertyMarkerTagsToDescriptions, getEnumValueDescriptions, type ApiSchema, @@ -277,6 +278,21 @@ export function normalizeSchemaForTypeScript(schema: JSONSchema7): JSONSchema7 { return value; } + // Schemas marked `.asOpaqueJson()` carry `x-opaque-json: true`. Map them + // to `unknown` so consumers see a single flat type (`unknown`, or + // `Record` when this node is an `additionalProperties` + // schema, etc.) instead of json-schema-to-typescript walking into the + // shape and emitting a nested map. Preserve description so the generated + // JSDoc still surfaces. + if (isOpaqueJson(value as JSONSchema7)) { + const descriptionRaw = (value as Record).description; + const opaque: Record = { tsType: "unknown" }; + if (typeof descriptionRaw === "string") { + opaque.description = descriptionRaw; + } + return opaque; + } + const rewritten = Object.fromEntries( Object.entries(value as Record).map(([key, child]) => [key, rewrite(child)]) ) as Record; diff --git a/scripts/codegen/utils.ts b/scripts/codegen/utils.ts index 6ece5f134..743f43d34 100644 --- a/scripts/codegen/utils.ts +++ b/scripts/codegen/utils.ts @@ -506,6 +506,16 @@ export function isSchemaInternal(schema: JSONSchema7 | null | undefined): boolea return typeof schema === "object" && schema !== null && (schema as Record).visibility === "internal"; } +/** + * Returns true when a JSON Schema node is marked `x-opaque-json: true` (set via + * `.asOpaqueJson()` on the Zod source). These are the only shapes that legitimately + * surface as opaque JSON in the SDK; everything else with an underspecified type + * is rejected by the runtime's schema lint pass. + */ +export function isOpaqueJson(schema: JSONSchema7 | null | undefined): boolean { + return typeof schema === "object" && schema !== null && (schema as Record)["x-opaque-json"] === true; +} + /** * Append `@internal` and/or `@experimental` JSDoc-style tags to the `description` * of every property that carries `visibility: "internal"` or `stability: "experimental"` From e7b77d04449b347078698127d6b87c3aa2212428 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 18:04:02 +0100 Subject: [PATCH 15/20] Preserve TS shape for x-opaque-json fields The previous commit mapped x-opaque-json schemas to `unknown` in the TS codegen, which broke backcompat: fields that used to be `Record` (compiled from empty schemas by json-schema-to-typescript) became bare `unknown`, forcing SDK consumers and tests to add casts. Instead, strip the x-opaque-json marker during the TS normalize step. j-s-to-ts then sees the same typeless schema it saw on main and emits the same `{[k: string]: unknown | undefined}` shape. C# codegen still reads the marker (from the un-normalized schema) and emits JsonElement. Reverts the unnecessary narrowing casts in session.ts/sessionFsProvider.ts and the test cast in session-event-types.test.ts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- nodejs/src/generated/rpc.ts | 650 ++++++++++++------------ nodejs/src/generated/session-events.ts | 114 +++-- nodejs/src/session.ts | 9 +- nodejs/src/sessionFsProvider.ts | 5 +- nodejs/test/session-event-types.test.ts | 2 +- scripts/codegen/typescript.ts | 27 +- 6 files changed, 434 insertions(+), 373 deletions(-) diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index c17b4fb67..cd5d950ff 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -193,7 +193,7 @@ export type ExtensionStatus = * via the `definition` "ExternalToolResult". */ /** @experimental */ -export type ExternalToolResult = unknown; +export type ExternalToolResult = string | ExternalToolTextResultForLlm; /** * Binary result type discriminator. Use "image" for images and "resource" for other binary data. * @@ -249,7 +249,11 @@ export type ExternalToolTextResultForLlmContentResourceDetails = * via the `definition` "FilterMapping". */ /** @experimental */ -export type FilterMapping = unknown; +export type FilterMapping = + | { + [k: string]: ContentFilterMode; + } + | ContentFilterMode; /** * Source for direct repo installs (when marketplace is empty) * @@ -257,7 +261,11 @@ export type FilterMapping = unknown; * via the `definition` "InstalledPluginSource". */ /** @experimental */ -export type InstalledPluginSource = unknown; +export type InstalledPluginSource = + | string + | InstalledPluginSourceGithub + | InstalledPluginSourceUrl + | InstalledPluginSourceLocal; /** * Category of instruction source — used for merge logic * @@ -317,37 +325,7 @@ export type SessionLogLevel = * via the `definition` "McpServerConfig". */ /** @experimental */ -export type McpServerConfig = unknown; -/** - * Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpExecuteSamplingRequest". - */ -/** @experimental */ -export type McpExecuteSamplingRequest = unknown; -/** - * MCP CreateMessageResult payload (with optional 'tools' extension), present when action='success'. Treated as opaque at the schema layer; consumers should construct/consume it per the MCP CreateMessageResult shape. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpExecuteSamplingResult". - */ -/** @experimental */ -export type McpExecuteSamplingResult = unknown; -/** - * Outcome of the sampling inference. 'success' produced a response; 'failure' encountered an error (including agent-side rejection by content filter or criteria); 'cancelled' the caller cancelled this execution via cancelSamplingExecution. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpSamplingExecutionAction". - */ -/** @experimental */ -export type McpSamplingExecutionAction = - /** The sampling inference completed and produced a result. */ - | "success" - /** The sampling inference failed or was rejected. */ - | "failure" - /** The sampling inference was cancelled before completion. */ - | "cancelled"; +export type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp; /** * Remote transport type. Defaults to "http" when omitted. * @@ -370,6 +348,20 @@ export type McpServerConfigHttpOauthGrantType = | "authorization_code" /** Headless client credentials flow using the configured OAuth client. */ | "client_credentials"; +/** + * Outcome of the sampling inference. 'success' produced a response; 'failure' encountered an error (including agent-side rejection by content filter or criteria); 'cancelled' the caller cancelled this execution via cancelSamplingExecution. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpSamplingExecutionAction". + */ +/** @experimental */ +export type McpSamplingExecutionAction = + /** The sampling inference completed and produced a result. */ + | "success" + /** The sampling inference failed or was rejected. */ + | "failure" + /** The sampling inference was cancelled before completion. */ + | "cancelled"; /** * How environment-variable values supplied to MCP servers are resolved. "direct" passes literal string values; "indirect" treats values as references (e.g. names of environment variables on the host) that the runtime resolves before launch. Defaults to the runtime's startup mode; clients that intentionally launch MCP servers with literal values (e.g. CLI prompt mode and ACP) set this to "direct". * @@ -790,7 +782,11 @@ export type SessionFsSqliteQueryType = * via the `definition` "SessionInstalledPluginSource". */ /** @experimental */ -export type SessionInstalledPluginSource = unknown; +export type SessionInstalledPluginSource = + | string + | SessionInstalledPluginSourceGithub + | SessionInstalledPluginSourceUrl + | SessionInstalledPluginSourceLocal; /** * Public-facing workspace metadata for this session, or null if the session has no associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, internal flags). * @@ -950,7 +946,7 @@ export type UIAutoModeSwitchResponse = * via the `definition` "UIElicitationFieldValue". */ /** @experimental */ -export type UIElicitationFieldValue = unknown; +export type UIElicitationFieldValue = string | number | boolean | string[]; /** * Definition for a single elicitation form field. * @@ -958,21 +954,33 @@ export type UIElicitationFieldValue = unknown; * via the `definition` "UIElicitationSchemaProperty". */ /** @experimental */ -export type UIElicitationSchemaProperty = unknown | undefined; +export type UIElicitationSchemaProperty = + | ( + | UIElicitationStringEnumField + | UIElicitationStringOneOfField + | UIElicitationArrayEnumField + | UIElicitationArrayAnyOfField + | UIElicitationSchemaPropertyBoolean + | UIElicitationSchemaPropertyString + | UIElicitationSchemaPropertyNumber + ) + | undefined; /** - * The user's response: accept (submitted), decline (rejected), or cancel (dismissed) + * Optional format hint that constrains the accepted input. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResponseAction". + * via the `definition` "UIElicitationSchemaPropertyStringFormat". */ /** @experimental */ -export type UIElicitationResponseAction = - /** The user submitted the requested form values. */ - | "accept" - /** The user explicitly declined to provide the requested input. */ - | "decline" - /** The user dismissed the elicitation request. */ - | "cancel"; +export type UIElicitationSchemaPropertyStringFormat = + /** Email address string format. */ + | "email" + /** URI string format. */ + | "uri" + /** Calendar date string format. */ + | "date" + /** Date-time string format. */ + | "date-time"; /** * Numeric type accepted by the field. * @@ -986,21 +994,19 @@ export type UIElicitationSchemaPropertyNumberType = /** Integer JSON number. */ | "integer"; /** - * Optional format hint that constrains the accepted input. + * The user's response: accept (submitted), decline (rejected), or cancel (dismissed) * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationSchemaPropertyStringFormat". + * via the `definition` "UIElicitationResponseAction". */ /** @experimental */ -export type UIElicitationSchemaPropertyStringFormat = - /** Email address string format. */ - | "email" - /** URI string format. */ - | "uri" - /** Calendar date string format. */ - | "date" - /** Date-time string format. */ - | "date-time"; +export type UIElicitationResponseAction = + /** The user submitted the requested form values. */ + | "accept" + /** The user explicitly declined to provide the requested input. */ + | "decline" + /** The user dismissed the elicitation request. */ + | "cancel"; /** * The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. * @@ -1017,14 +1023,6 @@ export type UIExitPlanModeAction = | "autopilot" /** Exit plan mode and continue in autopilot mode with parallel subagent execution. */ | "autopilot_fleet"; -/** - * Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIHandlePendingSamplingResponse". - */ -/** @experimental */ -export type UIHandlePendingSamplingResponse = unknown; /** * Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. * @@ -1182,8 +1180,6 @@ export interface AgentInfo { model?: string; /** * MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. - * - * @experimental */ mcpServers?: { [k: string]: unknown | undefined; @@ -2549,20 +2545,6 @@ export interface InstalledPluginSourceGithub { ref?: string; path?: string; } -/** - * Schema for the `InstalledPluginSourceLocal` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "InstalledPluginSourceLocal". - */ -/** @experimental */ -export interface InstalledPluginSourceLocal { - /** - * Constant value. Always "local". - */ - source: "local"; - path: string; -} /** * Schema for the `InstalledPluginSourceUrl` type. * @@ -2579,6 +2561,20 @@ export interface InstalledPluginSourceUrl { ref?: string; path?: string; } +/** + * Schema for the `InstalledPluginSourceLocal` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "InstalledPluginSourceLocal". + */ +/** @experimental */ +export interface InstalledPluginSourceLocal { + /** + * Constant value. Always "local". + */ + source: "local"; + path: string; +} /** * Instruction sources loaded for the session, in merge order. * @@ -2735,6 +2731,99 @@ export interface McpConfigAddRequest { name: string; config: McpServerConfig; } +/** + * Stdio MCP server configuration launched as a child process. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigStdio". + */ +export interface McpServerConfigStdio { + /** + * Tools to include. Defaults to all tools if not specified. + */ + tools?: string[]; + /** + * Whether this server is a built-in fallback used when the user has not configured their own server. + */ + isDefaultServer?: boolean; + filterMapping?: FilterMapping; + /** + * Timeout in milliseconds for tool calls to this server. + */ + timeout?: number; + /** + * Executable command used to start the Stdio MCP server process. + */ + command: string; + /** + * Command-line arguments passed to the Stdio MCP server process. + */ + args?: string[]; + /** + * Working directory for the Stdio MCP server process. + */ + cwd?: string; + /** + * Environment variables to pass to the Stdio MCP server process. + */ + env?: { + [k: string]: string | undefined; + }; +} +/** + * Remote MCP server configuration accessed over HTTP or SSE. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigHttp". + */ +export interface McpServerConfigHttp { + /** + * Tools to include. Defaults to all tools if not specified. + */ + tools?: string[]; + type?: McpServerConfigHttpType; + /** + * Whether this server is a built-in fallback used when the user has not configured their own server. + */ + isDefaultServer?: boolean; + filterMapping?: FilterMapping; + /** + * Timeout in milliseconds for tool calls to this server. + */ + timeout?: number; + /** + * URL of the remote MCP server endpoint. + */ + url: string; + /** + * HTTP headers to include in requests to the remote MCP server. + */ + headers?: { + [k: string]: string | undefined; + }; + /** + * OAuth client ID for a pre-registered remote MCP OAuth client. + */ + oauthClientId?: string; + /** + * Whether the configured OAuth client is public and does not require a client secret. + */ + oauthPublicClient?: boolean; + oauthGrantType?: McpServerConfigHttpOauthGrantType; + auth?: McpServerConfigHttpAuth; +} +/** + * Additional authentication configuration for this server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServerConfigHttpAuth". + */ +export interface McpServerConfigHttpAuth { + /** + * Fixed port for the OAuth redirect callback server. + */ + redirectPort?: number; +} /** * MCP server names to disable for new sessions. * @@ -2868,9 +2957,29 @@ export interface McpExecuteSamplingParams { /** * The original MCP JSON-RPC request ID (string or number). Used by the runtime to correlate the inference with the originating MCP request for telemetry; this is distinct from `requestId` (which is the schema-level cancellation handle). */ - mcpRequestId: unknown; + mcpRequestId: string | number; request: McpExecuteSamplingRequest; } +/** + * Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpExecuteSamplingRequest". + */ +/** @experimental */ +export interface McpExecuteSamplingRequest { + [k: string]: unknown | undefined; +} +/** + * MCP CreateMessageResult payload (with optional 'tools' extension), present when action='success'. Treated as opaque at the schema layer; consumers should construct/consume it per the MCP CreateMessageResult shape. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpExecuteSamplingResult". + */ +/** @experimental */ +export interface McpExecuteSamplingResult { + [k: string]: unknown | undefined; +} /** * Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, and the callback success-page copy. * @@ -2926,128 +3035,35 @@ export interface McpRemoveGitHubResult { * Outcome of an MCP sampling execution: success result, failure error, or cancellation. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpSamplingExecutionResult". - */ -/** @experimental */ -export interface McpSamplingExecutionResult { - action: McpSamplingExecutionAction; - result?: McpExecuteSamplingResult; - /** - * Error description, present when action='failure'. - */ - error?: string; -} -/** - * Schema for the `McpServer` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServer". - */ -/** @experimental */ -export interface McpServer { - /** - * Server name (config key) - */ - name: string; - status: McpServerStatus; - source?: McpServerSource; - /** - * Error message if the server failed to connect - */ - error?: string; -} -/** - * Remote MCP server configuration accessed over HTTP or SSE. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigHttp". - */ -export interface McpServerConfigHttp { - /** - * Tools to include. Defaults to all tools if not specified. - */ - tools?: string[]; - type?: McpServerConfigHttpType; - /** - * Whether this server is a built-in fallback used when the user has not configured their own server. - */ - isDefaultServer?: boolean; - filterMapping?: FilterMapping; - /** - * Timeout in milliseconds for tool calls to this server. - */ - timeout?: number; - /** - * URL of the remote MCP server endpoint. - */ - url: string; - /** - * HTTP headers to include in requests to the remote MCP server. - */ - headers?: { - [k: string]: string | undefined; - }; - /** - * OAuth client ID for a pre-registered remote MCP OAuth client. - */ - oauthClientId?: string; - /** - * Whether the configured OAuth client is public and does not require a client secret. - */ - oauthPublicClient?: boolean; - oauthGrantType?: McpServerConfigHttpOauthGrantType; - auth?: McpServerConfigHttpAuth; -} -/** - * Additional authentication configuration for this server. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigHttpAuth". - */ -export interface McpServerConfigHttpAuth { - /** - * Fixed port for the OAuth redirect callback server. - */ - redirectPort?: number; -} -/** - * Stdio MCP server configuration launched as a child process. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpServerConfigStdio". - */ -export interface McpServerConfigStdio { - /** - * Tools to include. Defaults to all tools if not specified. - */ - tools?: string[]; - /** - * Whether this server is a built-in fallback used when the user has not configured their own server. - */ - isDefaultServer?: boolean; - filterMapping?: FilterMapping; - /** - * Timeout in milliseconds for tool calls to this server. - */ - timeout?: number; - /** - * Executable command used to start the Stdio MCP server process. - */ - command: string; + * via the `definition` "McpSamplingExecutionResult". + */ +/** @experimental */ +export interface McpSamplingExecutionResult { + action: McpSamplingExecutionAction; + result?: McpExecuteSamplingResult; /** - * Command-line arguments passed to the Stdio MCP server process. + * Error description, present when action='failure'. */ - args?: string[]; + error?: string; +} +/** + * Schema for the `McpServer` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpServer". + */ +/** @experimental */ +export interface McpServer { /** - * Working directory for the Stdio MCP server process. + * Server name (config key) */ - cwd?: string; + name: string; + status: McpServerStatus; + source?: McpServerSource; /** - * Environment variables to pass to the Stdio MCP server process. + * Error message if the server failed to connect */ - env?: { - [k: string]: string | undefined; - }; + error?: string; } /** * MCP servers configured for the session, with their connection status. @@ -4624,7 +4640,7 @@ export interface PermissionRulesSet { /** @experimental */ export interface PermissionsConfigureAdditionalContentExclusionPolicy { rules: PermissionsConfigureAdditionalContentExclusionPolicyRule[]; - last_updated_at: unknown; + last_updated_at: string | number; scope: PermissionsConfigureAdditionalContentExclusionPolicyScope; [k: string]: unknown | undefined; } @@ -5460,7 +5476,9 @@ export interface SendRequest { /** * Optional provenance tag copied to the resulting user.message event. Supported values are `system`, `command-*`, and `schedule-*`. */ - source?: unknown; + source?: { + [k: string]: unknown | undefined; + }; agentMode?: SendAgentMode; /** * Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. @@ -5968,7 +5986,7 @@ export interface SessionFsSqliteQueryRequest { * Optional named bind parameters */ params?: { - [k: string]: unknown | undefined; + [k: string]: (string | number | null) | undefined; }; } /** @@ -6117,20 +6135,6 @@ export interface SessionInstalledPluginSourceGithub { ref?: string; path?: string; } -/** - * Schema for the `SessionInstalledPluginSourceLocal` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SessionInstalledPluginSourceLocal". - */ -/** @experimental */ -export interface SessionInstalledPluginSourceLocal { - /** - * Constant value. Always "local". - */ - source: "local"; - path: string; -} /** * Schema for the `SessionInstalledPluginSourceUrl` type. * @@ -6147,6 +6151,20 @@ export interface SessionInstalledPluginSourceUrl { ref?: string; path?: string; } +/** + * Schema for the `SessionInstalledPluginSourceLocal` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionInstalledPluginSourceLocal". + */ +/** @experimental */ +export interface SessionInstalledPluginSourceLocal { + /** + * Constant value. Always "local". + */ + source: "local"; + path: string; +} /** * Persisted sessions matching the filter, ordered most-recently-modified first. * @@ -6742,10 +6760,10 @@ export interface SessionUpdateOptionsParams { isExperimentalMode?: boolean; /** * Custom model-provider configuration (BYOK). Opaque shape; see `ProviderConfig` in the runtime. - * - * @experimental */ - provider?: unknown; + provider?: { + [k: string]: unknown | undefined; + }; /** * Absolute working-directory path for shell tools. */ @@ -6772,10 +6790,10 @@ export interface SessionUpdateOptionsParams { shellProcessFlags?: string[]; /** * Sandbox configuration shape; opaque to SDK consumers. See `SandboxConfig` in the runtime. - * - * @experimental */ - sandboxConfig?: unknown; + sandboxConfig?: { + [k: string]: unknown | undefined; + }; /** * Whether interactive shell sessions are logged. */ @@ -6851,8 +6869,6 @@ export interface SessionUpdateOptionsParams { eventsLogDirectory?: string; /** * Additional content-exclusion policies to merge into the session's policy set. Opaque shape; see `ContentExclusionApiResponse` in the runtime. - * - * @experimental */ additionalContentExclusionPolicies?: unknown[]; /** @@ -7879,38 +7895,83 @@ export interface UIElicitationSchema { required?: string[]; } /** - * The elicitation response (accept with form values, decline, or cancel) + * Single-select string field whose allowed values are defined inline. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResponse". + * via the `definition` "UIElicitationStringEnumField". */ /** @experimental */ -export interface UIElicitationResponse { - action: UIElicitationResponseAction; - content?: UIElicitationResponseContent; +export interface UIElicitationStringEnumField { + /** + * Type discriminator. Always "string". + */ + type: "string"; + /** + * Human-readable label for the field. + */ + title?: string; + /** + * Help text describing the field. + */ + description?: string; + /** + * Allowed string values. + */ + enum: string[]; + /** + * Optional display labels for each enum value, in the same order as `enum`. + */ + enumNames?: string[]; + /** + * Default value selected when the form is first shown. + */ + default?: string; } /** - * The form values submitted by the user (present when action is 'accept') + * Single-select string field where each option pairs a value with a display label. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResponseContent". + * via the `definition` "UIElicitationStringOneOfField". */ /** @experimental */ -export interface UIElicitationResponseContent { - [k: string]: UIElicitationFieldValue; +export interface UIElicitationStringOneOfField { + /** + * Type discriminator. Always "string". + */ + type: "string"; + /** + * Human-readable label for the field. + */ + title?: string; + /** + * Help text describing the field. + */ + description?: string; + /** + * Selectable options, each with a value and a display label. + */ + oneOf: UIElicitationStringOneOfFieldOneOf[]; + /** + * Default value selected when the form is first shown. + */ + default?: string; } /** - * Indicates whether the elicitation response was accepted; false if it was already resolved by another client. + * Schema for the `UIElicitationStringOneOfFieldOneOf` type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationResult". + * via the `definition` "UIElicitationStringOneOfFieldOneOf". */ /** @experimental */ -export interface UIElicitationResult { +export interface UIElicitationStringOneOfFieldOneOf { /** - * Whether the response was accepted. False if the request was already resolved by another client. + * Value submitted when this option is selected. */ - success: boolean; + const: string; + /** + * Display label for this option. + */ + title: string; } /** * Boolean field rendered as a yes/no toggle. @@ -7937,36 +7998,6 @@ export interface UIElicitationSchemaPropertyBoolean { */ default?: boolean; } -/** - * Numeric field accepting either a number or an integer. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationSchemaPropertyNumber". - */ -/** @experimental */ -export interface UIElicitationSchemaPropertyNumber { - type: UIElicitationSchemaPropertyNumberType; - /** - * Human-readable label for the field. - */ - title?: string; - /** - * Help text describing the field. - */ - description?: string; - /** - * Minimum allowed value (inclusive). - */ - minimum?: number; - /** - * Maximum allowed value (inclusive). - */ - maximum?: number; - /** - * Default value populated in the input when the form is first shown. - */ - default?: number; -} /** * Free-text string field with optional length and format constraints. * @@ -8002,17 +8033,14 @@ export interface UIElicitationSchemaPropertyString { default?: string; } /** - * Single-select string field whose allowed values are defined inline. + * Numeric field accepting either a number or an integer. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationStringEnumField". + * via the `definition` "UIElicitationSchemaPropertyNumber". */ /** @experimental */ -export interface UIElicitationStringEnumField { - /** - * Type discriminator. Always "string". - */ - type: "string"; +export interface UIElicitationSchemaPropertyNumber { + type: UIElicitationSchemaPropertyNumberType; /** * Human-readable label for the field. */ @@ -8022,63 +8050,51 @@ export interface UIElicitationStringEnumField { */ description?: string; /** - * Allowed string values. + * Minimum allowed value (inclusive). */ - enum: string[]; + minimum?: number; /** - * Optional display labels for each enum value, in the same order as `enum`. + * Maximum allowed value (inclusive). */ - enumNames?: string[]; + maximum?: number; /** - * Default value selected when the form is first shown. + * Default value populated in the input when the form is first shown. */ - default?: string; + default?: number; } /** - * Single-select string field where each option pairs a value with a display label. + * The elicitation response (accept with form values, decline, or cancel) * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationStringOneOfField". + * via the `definition` "UIElicitationResponse". */ /** @experimental */ -export interface UIElicitationStringOneOfField { - /** - * Type discriminator. Always "string". - */ - type: "string"; - /** - * Human-readable label for the field. - */ - title?: string; - /** - * Help text describing the field. - */ - description?: string; - /** - * Selectable options, each with a value and a display label. - */ - oneOf: UIElicitationStringOneOfFieldOneOf[]; - /** - * Default value selected when the form is first shown. - */ - default?: string; +export interface UIElicitationResponse { + action: UIElicitationResponseAction; + content?: UIElicitationResponseContent; } /** - * Schema for the `UIElicitationStringOneOfFieldOneOf` type. + * The form values submitted by the user (present when action is 'accept') * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "UIElicitationStringOneOfFieldOneOf". + * via the `definition` "UIElicitationResponseContent". */ /** @experimental */ -export interface UIElicitationStringOneOfFieldOneOf { - /** - * Value submitted when this option is selected. - */ - const: string; +export interface UIElicitationResponseContent { + [k: string]: UIElicitationFieldValue; +} +/** + * Indicates whether the elicitation response was accepted; false if it was already resolved by another client. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UIElicitationResult". + */ +/** @experimental */ +export interface UIElicitationResult { /** - * Display label for this option. + * Whether the response was accepted. False if the request was already resolved by another client. */ - title: string; + success: boolean; } /** * Schema for the `UIExitPlanModeResponse` type. @@ -8171,6 +8187,16 @@ export interface UIHandlePendingSamplingRequest { requestId: string; response?: UIHandlePendingSamplingResponse; } +/** + * Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UIHandlePendingSamplingResponse". + */ +/** @experimental */ +export interface UIHandlePendingSamplingResponse { + [k: string]: unknown | undefined; +} /** * Request ID of a pending `user_input.requested` event and the user's response. * diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index c15720a59..3fc9d3c3b 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -370,11 +370,19 @@ export type ElicitationCompletedAction = /** * Schema for the `ElicitationCompletedContent` type. */ -export type ElicitationCompletedContent = unknown | undefined; +export type ElicitationCompletedContent = (string | number | boolean | string[]) | undefined; /** * Source-defined JSON payload for the custom notification */ -export type CustomNotificationPayload = unknown; +export type CustomNotificationPayload = + | string + | number + | boolean + | null + | unknown[] + | { + [k: string]: unknown | undefined; + }; /** * The user's auto-mode-switch choice */ @@ -1456,8 +1464,6 @@ export interface ShutdownData { totalApiDurationMs: number; /** * Session-wide accumulated nano-AI units cost - * - * @experimental */ totalNanoAiu?: number; /** @@ -1495,8 +1501,6 @@ export interface ShutdownModelMetric { }; /** * Accumulated nano-AI units cost for this model - * - * @experimental */ totalNanoAiu?: number; usage: ShutdownModelMetricUsage; @@ -2399,14 +2403,10 @@ export interface AssistantMessageEvent { export interface AssistantMessageData { /** * Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping - * - * @internal */ anthropicAdvisorBlocks?: unknown[]; /** * Anthropic advisor model ID used for this response, for timeline display on replay - * - * @internal */ anthropicAdvisorModel?: string; /** @@ -2470,7 +2470,9 @@ export interface AssistantMessageToolRequest { /** * Arguments to pass to the tool, format depends on the tool */ - arguments?: unknown; + arguments?: { + [k: string]: unknown | undefined; + }; /** * Resolved intention summary describing what this specific call does */ @@ -2677,8 +2679,6 @@ export interface AssistantUsageData { copilotUsage?: AssistantUsageCopilotUsage; /** * Model multiplier cost for billing purposes - * - * @experimental */ cost?: number; /** @@ -2716,10 +2716,10 @@ export interface AssistantUsageData { providerCallId?: string; /** * Per-quota resource usage snapshots, keyed by quota identifier - * - * @internal */ - quotaSnapshots?: unknown; + quotaSnapshots?: { + [k: string]: AssistantUsageQuotaSnapshot | undefined; + }; /** * Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") */ @@ -2767,6 +2767,43 @@ export interface AssistantUsageCopilotUsageTokenDetail { */ tokenType: string; } +/** + * Schema for the `AssistantUsageQuotaSnapshot` type. + */ +export interface AssistantUsageQuotaSnapshot { + /** + * Total requests allowed by the entitlement + */ + entitlementRequests: number; + /** + * Whether the user has an unlimited usage entitlement + */ + isUnlimitedEntitlement: boolean; + /** + * Number of requests over the entitlement limit + */ + overage: number; + /** + * Whether overage is allowed when quota is exhausted + */ + overageAllowedWithExhaustedQuota: boolean; + /** + * Percentage of quota remaining (0 to 100) + */ + remainingPercentage: number; + /** + * Date when the quota resets + */ + resetDate?: string; + /** + * Whether usage is still permitted after quota exhaustion + */ + usageAllowedWithExhaustedQuota: boolean; + /** + * Number of requests already consumed + */ + usedRequests: number; +} /** * Session event "model.call_failure". Failed LLM API call metadata for telemetry */ @@ -2904,7 +2941,9 @@ export interface ToolUserRequestedData { /** * Arguments for the tool invocation */ - arguments?: unknown; + arguments?: { + [k: string]: unknown | undefined; + }; /** * Unique identifier for this tool call */ @@ -2951,7 +2990,9 @@ export interface ToolExecutionStartData { /** * Arguments passed to the tool */ - arguments?: unknown; + arguments?: { + [k: string]: unknown | undefined; + }; /** * Name of the MCP server hosting this tool, when the tool is an MCP tool */ @@ -3707,7 +3748,9 @@ export interface HookStartData { /** * Input data passed to the hook */ - input?: unknown; + input?: { + [k: string]: unknown | undefined; + }; } /** * Session event "hook.end". Hook invocation completion details including output, success status, and error information @@ -3755,7 +3798,9 @@ export interface HookEndData { /** * Output data produced by the hook */ - output?: unknown; + output?: { + [k: string]: unknown | undefined; + }; /** * Whether the hook completed successfully */ @@ -4182,7 +4227,9 @@ export interface PermissionRequestMcp { /** * Arguments to pass to the MCP tool */ - args?: unknown; + args?: { + [k: string]: unknown | undefined; + }; /** * Permission kind discriminator */ @@ -4267,7 +4314,9 @@ export interface PermissionRequestCustomTool { /** * Arguments to pass to the custom tool */ - args?: unknown; + args?: { + [k: string]: unknown | undefined; + }; /** * Permission kind discriminator */ @@ -4300,7 +4349,9 @@ export interface PermissionRequestHook { /** * Arguments of the tool call being gated */ - toolArgs?: unknown; + toolArgs?: { + [k: string]: unknown | undefined; + }; /** * Tool call ID that triggered this permission request */ @@ -4443,9 +4494,6 @@ export interface PermissionPromptRequestRead { * MCP tool invocation permission prompt */ export interface PermissionPromptRequestMcp { - /** - * Arguments to pass to the MCP tool - */ args?: unknown; /** * Prompt kind discriminator @@ -4527,7 +4575,9 @@ export interface PermissionPromptRequestCustomTool { /** * Arguments to pass to the custom tool */ - args?: unknown; + args?: { + [k: string]: unknown | undefined; + }; /** * Prompt kind discriminator */ @@ -4578,7 +4628,9 @@ export interface PermissionPromptRequestHook { /** * Arguments of the tool call being gated */ - toolArgs?: unknown; + toolArgs?: { + [k: string]: unknown | undefined; + }; /** * Tool call ID that triggered this permission request */ @@ -5164,7 +5216,7 @@ export interface SamplingRequestedData { /** * The JSON-RPC request ID from the MCP protocol */ - mcpRequestId: unknown; + mcpRequestId: string | number; /** * Unique identifier for this sampling request; used to respond via session.respondToSampling() */ @@ -5410,7 +5462,9 @@ export interface ExternalToolRequestedData { /** * Arguments to pass to the external tool */ - arguments?: unknown; + arguments?: { + [k: string]: unknown | undefined; + }; /** * Unique identifier for this request; used to respond via session.respondToExternalTool() */ diff --git a/nodejs/src/session.ts b/nodejs/src/session.ts index 8653a14b7..343fb42ec 100644 --- a/nodejs/src/session.ts +++ b/nodejs/src/session.ts @@ -760,15 +760,10 @@ export class CopilotSession { private async _elicitation(params: ElicitationParams): Promise { this.assertElicitation(); - // The wire shape of `content` is `Record` (the runtime - // schema marks each field value as opaque JSON to allow MCP-style - // string|number|boolean|string[] values without a JSON-schema union). - // The SDK surface narrows it to `Record` - // because that's the only shape MCP-compatible hosts will produce. - return (await this.rpc.ui.elicitation({ + return this.rpc.ui.elicitation({ message: params.message, requestedSchema: params.requestedSchema, - })) as ElicitationResult; + }); } private async _confirm(message: string): Promise { diff --git a/nodejs/src/sessionFsProvider.ts b/nodejs/src/sessionFsProvider.ts index e941450f9..7e959849e 100644 --- a/nodejs/src/sessionFsProvider.ts +++ b/nodejs/src/sessionFsProvider.ts @@ -215,10 +215,7 @@ export function createSessionFsAdapter(provider: SessionFsProvider): SessionFsHa const result = await provider.sqlite.query( queryType, query, - // Wire shape is `Record` (each bind value is - // opaque JSON on the wire); the SDK provider contract narrows - // it to the primitives SQLite actually accepts. - normalizeSqliteParams(bindParams as Record | undefined) + normalizeSqliteParams(bindParams) ); return result ?? { rows: [], columns: [], rowsAffected: 0 }; }, diff --git a/nodejs/test/session-event-types.test.ts b/nodejs/test/session-event-types.test.ts index 5c5d0eccc..de21ba2ba 100644 --- a/nodejs/test/session-event-types.test.ts +++ b/nodejs/test/session-event-types.test.ts @@ -97,7 +97,7 @@ describe("Session event type exports (#1156)", () => { expect(data.toolName).toBe("shell"); expect(data.toolCallId).toBe("call-1"); - expect((data.arguments as { command?: string } | undefined)?.command).toBe("ls"); + expect(data.arguments?.command).toBe("ls"); expect(data.mcpServerName).toBe("filesystem"); expect(data.mcpToolName).toBe("list_dir"); expect(data.turnId).toBe("turn-1"); diff --git a/scripts/codegen/typescript.ts b/scripts/codegen/typescript.ts index e7ede9538..d02eda881 100644 --- a/scripts/codegen/typescript.ts +++ b/scripts/codegen/typescript.ts @@ -36,8 +36,6 @@ import { isNodeFullyDeprecated, isVoidSchema, isSchemaExperimental, - isOpaqueJson, - appendPropertyMarkerTagsToDescriptions, getEnumValueDescriptions, type ApiSchema, type DefinitionCollections, @@ -278,25 +276,18 @@ export function normalizeSchemaForTypeScript(schema: JSONSchema7): JSONSchema7 { return value; } - // Schemas marked `.asOpaqueJson()` carry `x-opaque-json: true`. Map them - // to `unknown` so consumers see a single flat type (`unknown`, or - // `Record` when this node is an `additionalProperties` - // schema, etc.) instead of json-schema-to-typescript walking into the - // shape and emitting a nested map. Preserve description so the generated - // JSDoc still surfaces. - if (isOpaqueJson(value as JSONSchema7)) { - const descriptionRaw = (value as Record).description; - const opaque: Record = { tsType: "unknown" }; - if (typeof descriptionRaw === "string") { - opaque.description = descriptionRaw; - } - return opaque; - } - const rewritten = Object.fromEntries( Object.entries(value as Record).map(([key, child]) => [key, rewrite(child)]) ) as Record; + // Strip the `x-opaque-json` marker so json-schema-to-typescript sees + // the original (typeless) schema and emits the same shape it did + // before the marker was introduced. C# codegen reads the marker from + // the un-normalized schema and emits `JsonElement` instead. + if ("x-opaque-json" in rewritten) { + delete rewritten["x-opaque-json"]; + } + const enumValueDescriptions = getEnumValueDescriptions(rewritten as JSONSchema7); if (enumValueDescriptions && Array.isArray(rewritten.enum) && rewritten.enum.every((entry) => typeof entry === "string")) { rewritten.tsType = (rewritten.enum as string[]) @@ -354,7 +345,6 @@ async function generateSessionEvents(schemaPath?: string): Promise { resolveSchema({ $ref: "#/$defs/SessionEvent" }, definitionCollections) ?? processed; const schemaForCompile = withSharedDefinitions(sessionEvent, definitionCollections); - appendPropertyMarkerTagsToDescriptions(schemaForCompile); const ts = await compile(normalizeSchemaForTypeScript(schemaForCompile), "SessionEvent", { bannerComment: `/** @@ -597,7 +587,6 @@ import type { MessageConnection } from "vscode-jsonrpc/node.js"; } const schemaForCompile = combinedSchema; - appendPropertyMarkerTagsToDescriptions(schemaForCompile); const compiled = await compile(normalizeSchemaForTypeScript(schemaForCompile), "_RpcSchemaRoot", { bannerComment: "", From c706604438111c4256996f9975ab55e2a61eaf40 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 18:05:48 +0100 Subject: [PATCH 16/20] Factor stripOpaqueJsonMarker into utils.ts Move the inline `delete rewritten["x-opaque-json"]` out of the TS codegen's rewrite loop and into a named helper next to isOpaqueJson, so the paired `read the marker` / `ignore the marker` operations live together and each language codegen calls the one it needs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- scripts/codegen/typescript.ts | 14 +++++++------- scripts/codegen/utils.ts | 11 +++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/scripts/codegen/typescript.ts b/scripts/codegen/typescript.ts index d02eda881..ee9936de3 100644 --- a/scripts/codegen/typescript.ts +++ b/scripts/codegen/typescript.ts @@ -37,6 +37,7 @@ import { isVoidSchema, isSchemaExperimental, getEnumValueDescriptions, + stripOpaqueJsonMarker, type ApiSchema, type DefinitionCollections, type RpcMethod, @@ -280,13 +281,12 @@ export function normalizeSchemaForTypeScript(schema: JSONSchema7): JSONSchema7 { Object.entries(value as Record).map(([key, child]) => [key, rewrite(child)]) ) as Record; - // Strip the `x-opaque-json` marker so json-schema-to-typescript sees - // the original (typeless) schema and emits the same shape it did - // before the marker was introduced. C# codegen reads the marker from - // the un-normalized schema and emits `JsonElement` instead. - if ("x-opaque-json" in rewritten) { - delete rewritten["x-opaque-json"]; - } + // The TypeScript codegen doesn't distinguish opaque JSON from any + // other unconstrained value, so drop the marker before feeding the + // schema to json-schema-to-typescript. C# codegen reads the marker + // from its own (un-normalized) view of the schema and emits + // `JsonElement` instead. + stripOpaqueJsonMarker(rewritten); const enumValueDescriptions = getEnumValueDescriptions(rewritten as JSONSchema7); if (enumValueDescriptions && Array.isArray(rewritten.enum) && rewritten.enum.every((entry) => typeof entry === "string")) { diff --git a/scripts/codegen/utils.ts b/scripts/codegen/utils.ts index 743f43d34..c2e3f7b7e 100644 --- a/scripts/codegen/utils.ts +++ b/scripts/codegen/utils.ts @@ -516,6 +516,17 @@ export function isOpaqueJson(schema: JSONSchema7 | null | undefined): boolean { return typeof schema === "object" && schema !== null && (schema as Record)["x-opaque-json"] === true; } +/** + * Removes the `x-opaque-json` marker from a schema node in place. Useful for + * codegens (e.g. TypeScript) that don't distinguish opaque JSON from any other + * unconstrained value and would otherwise have the marker confuse downstream + * tooling. Codegens that *do* care (e.g. C#, which maps opaque JSON to + * `JsonElement`) should call `isOpaqueJson` *before* this point. + */ +export function stripOpaqueJsonMarker(schema: Record): void { + delete schema["x-opaque-json"]; +} + /** * Append `@internal` and/or `@experimental` JSDoc-style tags to the `description` * of every property that carries `visibility: "internal"` or `stability: "experimental"` From 8baafad44c1ea5199c3cdb9128962e00acd70a7b Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 18:59:37 +0100 Subject: [PATCH 17/20] Regenerate SDK from latest runtime schemas Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/Rpc.cs | 155 ++- dotnet/src/Generated/SessionEvents.cs | 57 +- go/rpc/zrpc.go | 127 +- go/rpc/zrpc_encoding.go | 32 + go/rpc/zsession_events.go | 16 +- nodejs/src/generated/rpc.ts | 133 +- nodejs/src/generated/session-events.ts | 4 +- python/copilot/generated/rpc.py | 1379 +++++++++++--------- python/copilot/generated/session_events.py | 12 +- rust/src/generated/api_types.rs | 141 +- rust/src/generated/rpc.rs | 16 - rust/src/generated/session_events.rs | 22 +- 12 files changed, 1366 insertions(+), 728 deletions(-) diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index d1b61f929..513eda7cd 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -366,7 +366,6 @@ public sealed class McpConfigList } /// MCP server name and configuration to add to user configuration. -[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigAddRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). @@ -382,7 +381,6 @@ internal sealed class McpConfigAddRequest } /// MCP server name and replacement configuration to write to user configuration. -[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigUpdateRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). @@ -1333,8 +1331,9 @@ internal sealed class SendRequest public string SessionId { get; set; } = string.Empty; /// Optional provenance tag copied to the resulting user.message event. Supported values are `system`, `command-*`, and `schedule-*`. + [JsonInclude] [JsonPropertyName("source")] - public JsonElement? Source { get; set; } + internal JsonElement? Source { get; set; } /// W3C Trace Context traceparent header for distributed tracing of this agent turn. [JsonPropertyName("traceparent")] @@ -1539,8 +1538,115 @@ public sealed class CopilotUserResponseOrganizationListItem public string? Name { get; set; } } -/// RPC data type for CopilotUserResponseQuotaSnapshotsValue operations. -public sealed class CopilotUserResponseQuotaSnapshotsValue +/// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +[Experimental(Diagnostics.Experimental)] +public sealed class CopilotUserResponseQuotaSnapshotsChat +{ + /// Gets or sets the entitlement value. + [JsonPropertyName("entitlement")] + public double? Entitlement { get; set; } + + /// Gets or sets the has_quota value. + [JsonPropertyName("has_quota")] + public bool? HasQuota { get; set; } + + /// Gets or sets the overage_count value. + [JsonPropertyName("overage_count")] + public double? OverageCount { get; set; } + + /// Gets or sets the overage_permitted value. + [JsonPropertyName("overage_permitted")] + public bool? OveragePermitted { get; set; } + + /// Gets or sets the percent_remaining value. + [JsonPropertyName("percent_remaining")] + public double? PercentRemaining { get; set; } + + /// Gets or sets the quota_id value. + [JsonPropertyName("quota_id")] + public string? QuotaId { get; set; } + + /// Gets or sets the quota_remaining value. + [JsonPropertyName("quota_remaining")] + public double? QuotaRemaining { get; set; } + + /// Gets or sets the quota_reset_at value. + [JsonPropertyName("quota_reset_at")] + public double? QuotaResetAt { get; set; } + + /// Gets or sets the remaining value. + [JsonPropertyName("remaining")] + public double? Remaining { get; set; } + + /// Gets or sets the timestamp_utc value. + [JsonPropertyName("timestamp_utc")] + public string? TimestampUtc { get; set; } + + /// Gets or sets the token_based_billing value. + [JsonPropertyName("token_based_billing")] + public bool? TokenBasedBilling { get; set; } + + /// Gets or sets the unlimited value. + [JsonPropertyName("unlimited")] + public bool? Unlimited { get; set; } +} + +/// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. +[Experimental(Diagnostics.Experimental)] +public sealed class CopilotUserResponseQuotaSnapshotsCompletions +{ + /// Gets or sets the entitlement value. + [JsonPropertyName("entitlement")] + public double? Entitlement { get; set; } + + /// Gets or sets the has_quota value. + [JsonPropertyName("has_quota")] + public bool? HasQuota { get; set; } + + /// Gets or sets the overage_count value. + [JsonPropertyName("overage_count")] + public double? OverageCount { get; set; } + + /// Gets or sets the overage_permitted value. + [JsonPropertyName("overage_permitted")] + public bool? OveragePermitted { get; set; } + + /// Gets or sets the percent_remaining value. + [JsonPropertyName("percent_remaining")] + public double? PercentRemaining { get; set; } + + /// Gets or sets the quota_id value. + [JsonPropertyName("quota_id")] + public string? QuotaId { get; set; } + + /// Gets or sets the quota_remaining value. + [JsonPropertyName("quota_remaining")] + public double? QuotaRemaining { get; set; } + + /// Gets or sets the quota_reset_at value. + [JsonPropertyName("quota_reset_at")] + public double? QuotaResetAt { get; set; } + + /// Gets or sets the remaining value. + [JsonPropertyName("remaining")] + public double? Remaining { get; set; } + + /// Gets or sets the timestamp_utc value. + [JsonPropertyName("timestamp_utc")] + public string? TimestampUtc { get; set; } + + /// Gets or sets the token_based_billing value. + [JsonPropertyName("token_based_billing")] + public bool? TokenBasedBilling { get; set; } + + /// Gets or sets the unlimited value. + [JsonPropertyName("unlimited")] + public bool? Unlimited { get; set; } +} + +/// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. +[Experimental(Diagnostics.Experimental)] +public sealed class CopilotUserResponseQuotaSnapshotsPremiumInteractions { /// Gets or sets the entitlement value. [JsonPropertyName("entitlement")] @@ -1591,6 +1697,23 @@ public sealed class CopilotUserResponseQuotaSnapshotsValue public bool? Unlimited { get; set; } } +/// Schema for the `CopilotUserResponseQuotaSnapshots` type. +[Experimental(Diagnostics.Experimental)] +public sealed class CopilotUserResponseQuotaSnapshots +{ + /// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + [JsonPropertyName("chat")] + public CopilotUserResponseQuotaSnapshotsChat? Chat { get; set; } + + /// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + [JsonPropertyName("completions")] + public CopilotUserResponseQuotaSnapshotsCompletions? Completions { get; set; } + + /// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + [JsonPropertyName("premium_interactions")] + public CopilotUserResponseQuotaSnapshotsPremiumInteractions? PremiumInteractions { get; set; } +} + /// Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. [Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponse @@ -1675,9 +1798,9 @@ public sealed class CopilotUserResponse [JsonPropertyName("quota_reset_date_utc")] public string? QuotaResetDateUtc { get; set; } - /// Gets or sets the quota_snapshots value. + /// Schema for the `CopilotUserResponseQuotaSnapshots` type. [JsonPropertyName("quota_snapshots")] - public IDictionary? QuotaSnapshots { get; set; } + public CopilotUserResponseQuotaSnapshots? QuotaSnapshots { get; set; } /// Gets or sets the restricted_telemetry value. [JsonPropertyName("restricted_telemetry")] @@ -6383,9 +6506,9 @@ internal sealed class EventLogReadRequest [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - /// List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. + /// Either '*' to receive all event types, or a non-empty list of event types to receive. [JsonPropertyName("types")] - public IList? Types { get; set; } + public JsonElement? Types { get; set; } /// Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). [JsonConverter(typeof(MillisecondsTimeSpanConverter))] @@ -10188,7 +10311,6 @@ public async Task ListAsync(CancellationToken cancellationToken = /// Unique name for the MCP server. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - [Experimental(Diagnostics.Experimental)] public async Task AddAsync(string name, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); @@ -10202,7 +10324,6 @@ public async Task AddAsync(string name, object config, CancellationToken cancell /// Name of the MCP server to update. /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - [Experimental(Diagnostics.Experimental)] public async Task UpdateAsync(string name, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); @@ -12669,15 +12790,15 @@ internal EventLogApi(CopilotSession session) /// Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. /// Maximum number of events to return in this batch (1–1000, default 200). /// Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). - /// List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. + /// Either '*' to receive all event types, or a non-empty list of event types to receive. /// Agent-scope filter: 'primary' returns only main-agent events plus events whose type starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns events from all agents (matching wildcard-subscription behavior). Default is 'all' to preserve wildcard semantics for catch-up callers. /// The to monitor for cancellation requests. The default is . /// Batch of session events returned by a read, with cursor and continuation metadata. - public async Task ReadAsync(string? cursor = null, int? max = null, TimeSpan? waitMs = null, IList? types = null, EventsAgentScope? agentScope = null, CancellationToken cancellationToken = default) + public async Task ReadAsync(string? cursor = null, int? max = null, TimeSpan? waitMs = null, object? types = null, EventsAgentScope? agentScope = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new EventLogReadRequest { SessionId = _session.SessionId, Cursor = cursor, Max = max, Wait = waitMs, Types = types, AgentScope = agentScope }; + var request = new EventLogReadRequest { SessionId = _session.SessionId, Cursor = cursor, Max = max, Wait = waitMs, Types = CopilotClient.ToJsonElementForWire(types), AgentScope = agentScope }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.eventLog.read", [request], cancellationToken); } @@ -13017,6 +13138,7 @@ public static void RegisterClientSessionApiHandlers(JsonRpc rpc, FuncRaw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonInclude] [JsonPropertyName("anthropicAdvisorBlocks")] - internal JsonElement[]? AnthropicAdvisorBlocks { get; set; } + public JsonElement[]? AnthropicAdvisorBlocks { get; set; } /// Anthropic advisor model ID used for this response, for timeline display on replay. + [Experimental(Diagnostics.Experimental)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonInclude] [JsonPropertyName("anthropicAdvisorModel")] - internal string? AnthropicAdvisorModel { get; set; } + public string? AnthropicAdvisorModel { get; set; } /// The assistant's text response content. [JsonPropertyName("content")] @@ -2191,9 +2190,8 @@ public sealed partial class AssistantUsageData /// Per-quota resource usage snapshots, keyed by quota identifier. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonInclude] [JsonPropertyName("quotaSnapshots")] - internal JsonElement? QuotaSnapshots { get; set; } + public IDictionary? QuotaSnapshots { get; set; } /// Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max"). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -3606,6 +3604,52 @@ public sealed partial class AssistantUsageCopilotUsage public required double TotalNanoAiu { get; set; } } +/// Schema for the `AssistantUsageQuotaSnapshot` type. +/// Nested data type for AssistantUsageQuotaSnapshot. +public sealed partial class AssistantUsageQuotaSnapshot +{ + /// Total requests allowed by the entitlement. + [JsonInclude] + [JsonPropertyName("entitlementRequests")] + internal required long EntitlementRequests { get; set; } + + /// Whether the user has an unlimited usage entitlement. + [JsonInclude] + [JsonPropertyName("isUnlimitedEntitlement")] + internal required bool IsUnlimitedEntitlement { get; set; } + + /// Number of additional usage requests made this period. + [JsonInclude] + [JsonPropertyName("overage")] + internal required double Overage { get; set; } + + /// Whether additional usage is allowed when quota is exhausted. + [JsonInclude] + [JsonPropertyName("overageAllowedWithExhaustedQuota")] + internal required bool OverageAllowedWithExhaustedQuota { get; set; } + + /// Percentage of quota remaining (0 to 100). + [JsonInclude] + [JsonPropertyName("remainingPercentage")] + internal required double RemainingPercentage { get; set; } + + /// Date when the quota resets. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] + [JsonPropertyName("resetDate")] + internal DateTimeOffset? ResetDate { get; set; } + + /// Whether usage is still permitted after quota exhaustion. + [JsonInclude] + [JsonPropertyName("usageAllowedWithExhaustedQuota")] + internal required bool UsageAllowedWithExhaustedQuota { get; set; } + + /// Number of requests already consumed. + [JsonInclude] + [JsonPropertyName("usedRequests")] + internal required long UsedRequests { get; set; } +} + /// Error details when the tool execution failed. /// Nested data type for ToolExecutionCompleteError. public sealed partial class ToolExecutionCompleteError @@ -7090,6 +7134,7 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(AssistantUsageCopilotUsageTokenDetail))] [JsonSerializable(typeof(AssistantUsageData))] [JsonSerializable(typeof(AssistantUsageEvent))] +[JsonSerializable(typeof(AssistantUsageQuotaSnapshot))] [JsonSerializable(typeof(AutoModeSwitchCompletedData))] [JsonSerializable(typeof(AutoModeSwitchCompletedEvent))] [JsonSerializable(typeof(AutoModeSwitchRequestedData))] diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index d69def1da..24296589f 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -435,19 +435,20 @@ type CopilotUserResponse struct { CopilotignoreEnabled *bool `json:"copilotignore_enabled,omitempty"` CopilotPlan *string `json:"copilot_plan,omitempty"` // Schema for the `CopilotUserResponseEndpoints` type. - Endpoints *CopilotUserResponseEndpoints `json:"endpoints,omitempty"` - IsMcpEnabled *bool `json:"is_mcp_enabled,omitempty"` - LimitedUserQuotas map[string]float64 `json:"limited_user_quotas,omitempty"` - LimitedUserResetDate *string `json:"limited_user_reset_date,omitempty"` - Login *string `json:"login,omitempty"` - MonthlyQuotas map[string]float64 `json:"monthly_quotas,omitempty"` - OrganizationList []CopilotUserResponseOrganizationListItem `json:"organization_list,omitempty"` - OrganizationLoginList []string `json:"organization_login_list,omitempty"` - QuotaResetDate *string `json:"quota_reset_date,omitempty"` - QuotaResetDateUtc *string `json:"quota_reset_date_utc,omitempty"` - QuotaSnapshots map[string]*CopilotUserResponseQuotaSnapshotsValue `json:"quota_snapshots,omitempty"` - RestrictedTelemetry *bool `json:"restricted_telemetry,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + Endpoints *CopilotUserResponseEndpoints `json:"endpoints,omitempty"` + IsMcpEnabled *bool `json:"is_mcp_enabled,omitempty"` + LimitedUserQuotas map[string]float64 `json:"limited_user_quotas,omitempty"` + LimitedUserResetDate *string `json:"limited_user_reset_date,omitempty"` + Login *string `json:"login,omitempty"` + MonthlyQuotas map[string]float64 `json:"monthly_quotas,omitempty"` + OrganizationList []CopilotUserResponseOrganizationListItem `json:"organization_list,omitempty"` + OrganizationLoginList []string `json:"organization_login_list,omitempty"` + QuotaResetDate *string `json:"quota_reset_date,omitempty"` + QuotaResetDateUtc *string `json:"quota_reset_date_utc,omitempty"` + // Schema for the `CopilotUserResponseQuotaSnapshots` type. + QuotaSnapshots *CopilotUserResponseQuotaSnapshots `json:"quota_snapshots,omitempty"` + RestrictedTelemetry *bool `json:"restricted_telemetry,omitempty"` + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` } // Schema for the `CopilotUserResponseEndpoints` type. @@ -465,7 +466,58 @@ type CopilotUserResponseOrganizationListItem struct { Name *string `json:"name,omitempty"` } -type CopilotUserResponseQuotaSnapshotsValue struct { +// Schema for the `CopilotUserResponseQuotaSnapshots` type. +// Experimental: CopilotUserResponseQuotaSnapshots is part of an experimental API and may +// change or be removed. +type CopilotUserResponseQuotaSnapshots struct { + // Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + Chat *CopilotUserResponseQuotaSnapshotsChat `json:"chat,omitempty"` + // Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + Completions *CopilotUserResponseQuotaSnapshotsCompletions `json:"completions,omitempty"` + // Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + PremiumInteractions *CopilotUserResponseQuotaSnapshotsPremiumInteractions `json:"premium_interactions,omitempty"` +} + +// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +// Experimental: CopilotUserResponseQuotaSnapshotsChat is part of an experimental API and +// may change or be removed. +type CopilotUserResponseQuotaSnapshotsChat struct { + Entitlement *float64 `json:"entitlement,omitempty"` + HasQuota *bool `json:"has_quota,omitempty"` + OverageCount *float64 `json:"overage_count,omitempty"` + OveragePermitted *bool `json:"overage_permitted,omitempty"` + PercentRemaining *float64 `json:"percent_remaining,omitempty"` + QuotaID *string `json:"quota_id,omitempty"` + QuotaRemaining *float64 `json:"quota_remaining,omitempty"` + QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` + Remaining *float64 `json:"remaining,omitempty"` + TimestampUtc *string `json:"timestamp_utc,omitempty"` + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + Unlimited *bool `json:"unlimited,omitempty"` +} + +// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. +// Experimental: CopilotUserResponseQuotaSnapshotsCompletions is part of an experimental API +// and may change or be removed. +type CopilotUserResponseQuotaSnapshotsCompletions struct { + Entitlement *float64 `json:"entitlement,omitempty"` + HasQuota *bool `json:"has_quota,omitempty"` + OverageCount *float64 `json:"overage_count,omitempty"` + OveragePermitted *bool `json:"overage_permitted,omitempty"` + PercentRemaining *float64 `json:"percent_remaining,omitempty"` + QuotaID *string `json:"quota_id,omitempty"` + QuotaRemaining *float64 `json:"quota_remaining,omitempty"` + QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` + Remaining *float64 `json:"remaining,omitempty"` + TimestampUtc *string `json:"timestamp_utc,omitempty"` + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + Unlimited *bool `json:"unlimited,omitempty"` +} + +// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. +// Experimental: CopilotUserResponseQuotaSnapshotsPremiumInteractions is part of an +// experimental API and may change or be removed. +type CopilotUserResponseQuotaSnapshotsPremiumInteractions struct { Entitlement *float64 `json:"entitlement,omitempty"` HasQuota *bool `json:"has_quota,omitempty"` OverageCount *float64 `json:"overage_count,omitempty"` @@ -535,9 +587,8 @@ type EventLogReadRequest struct { Cursor *string `json:"cursor,omitempty"` // Maximum number of events to return in this batch (1–1000, default 200). Max *int32 `json:"max,omitempty"` - // List of event types to receive. Omit (or pass an empty/absent value) to receive all event - // types. - Types []string `json:"types,omitempty"` + // Either '*' to receive all event types, or a non-empty list of event types to receive + Types *EventLogTypes `json:"types,omitempty"` // Milliseconds to wait for new events when the cursor is at the tail of history. 0 // (default) returns immediately even if no events are available. Capped at 30000ms. // Ephemeral events that arrive during the wait are delivered in this batch but are NOT @@ -568,6 +619,13 @@ type EventLogTailResult struct { Cursor string `json:"cursor"` } +// Either '*' to receive all event types, or a non-empty list of event types to receive +// Experimental: EventLogTypes is part of an experimental API and may change or be removed. +type EventLogTypes struct { + String *EventLogTypesString + StringArray []string +} + // Batch of session events returned by a read, with cursor and continuation metadata. // Experimental: EventsReadResult is part of an experimental API and may change or be // removed. @@ -871,7 +929,6 @@ type ExternalToolTextResultForLlmContentResourceLinkIcon struct { // Content filtering mode to apply to all tools, or a map of tool name to content filtering // mode. -// Experimental: FilterMapping is part of an experimental API and may change or be removed. type FilterMapping interface { filterMapping() } @@ -1052,8 +1109,6 @@ type InstalledPlugin struct { // Source for direct repo installs (when marketplace is empty) // Experimental: InstalledPluginSource is part of an experimental API and may change or be // removed. -// Experimental: InstalledPluginSource is part of an experimental API and may change or be -// removed. type InstalledPluginSource struct { InstalledPluginSourceGithub *InstalledPluginSourceGithub InstalledPluginSourceLocal *InstalledPluginSourceLocal @@ -1187,10 +1242,6 @@ type McpCancelSamplingExecutionResult struct { } // MCP server name and configuration to add to user configuration. -// Experimental: McpConfigAddRequest is part of an experimental API and may change or be -// removed. -// Experimental: McpConfigAddRequest is part of an experimental API and may change or be -// removed. type McpConfigAddRequest struct { // MCP server configuration (stdio process or remote HTTP/SSE) Config McpServerConfig `json:"config"` @@ -1198,8 +1249,6 @@ type McpConfigAddRequest struct { Name string `json:"name"` } -// Experimental: McpConfigAddResult is part of an experimental API and may change or be -// removed. type McpConfigAddResult struct { } @@ -1240,10 +1289,6 @@ type McpConfigRemoveResult struct { } // MCP server name and replacement configuration to write to user configuration. -// Experimental: McpConfigUpdateRequest is part of an experimental API and may change or be -// removed. -// Experimental: McpConfigUpdateRequest is part of an experimental API and may change or be -// removed. type McpConfigUpdateRequest struct { // MCP server configuration (stdio process or remote HTTP/SSE) Config McpServerConfig `json:"config"` @@ -1251,8 +1296,6 @@ type McpConfigUpdateRequest struct { Name string `json:"name"` } -// Experimental: McpConfigUpdateResult is part of an experimental API and may change or be -// removed. type McpConfigUpdateResult struct { } @@ -1317,6 +1360,8 @@ type McpExecuteSamplingRequest struct { // construct/consume it per the MCP CreateMessageResult shape. // Experimental: McpExecuteSamplingResult is part of an experimental API and may change or // be removed. +// Experimental: McpExecuteSamplingResult is part of an experimental API and may change or +// be removed. type McpExecuteSamplingResult struct { } @@ -1397,7 +1442,6 @@ type McpServer struct { } // MCP server configuration (stdio process or remote HTTP/SSE) -// Experimental: McpServerConfig is part of an experimental API and may change or be removed. type McpServerConfig interface { mcpServerConfig() } @@ -2564,8 +2608,6 @@ type PermissionRulesSet struct { // Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. // Experimental: PermissionsConfigureAdditionalContentExclusionPolicy is part of an // experimental API and may change or be removed. -// Experimental: PermissionsConfigureAdditionalContentExclusionPolicy is part of an -// experimental API and may change or be removed. type PermissionsConfigureAdditionalContentExclusionPolicy struct { LastUpdatedAt any `json:"last_updated_at"` Rules []PermissionsConfigureAdditionalContentExclusionPolicyRule `json:"rules"` @@ -3352,6 +3394,8 @@ type SendRequest struct { RequiredTool *string `json:"requiredTool,omitempty"` // Optional provenance tag copied to the resulting user.message event. Supported values are // `system`, `command-*`, and `schedule-*`. + // Internal: Source is part of the SDK's internal API surface and is not intended for + // external use. Source any `json:"source,omitempty"` // W3C Trace Context traceparent header for distributed tracing of this agent turn Traceparent *string `json:"traceparent,omitempty"` @@ -3746,8 +3790,6 @@ type SessionInstalledPlugin struct { // Source descriptor for direct repo installs (when marketplace is empty) // Experimental: SessionInstalledPluginSource is part of an experimental API and may change // or be removed. -// Experimental: SessionInstalledPluginSource is part of an experimental API and may change -// or be removed. type SessionInstalledPluginSource struct { SessionInstalledPluginSourceGithub *SessionInstalledPluginSourceGithub SessionInstalledPluginSourceLocal *SessionInstalledPluginSourceLocal @@ -5903,6 +5945,12 @@ const ( DiscoveredMcpServerTypeStdio DiscoveredMcpServerType = "stdio" ) +type EventLogTypesString string + +const ( + EventLogTypesStringValue EventLogTypesString = "*" +) + // Agent-scope filter: 'primary' returns only main-agent events plus events whose type // starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns // events from all agents (matching wildcard-subscription behavior). Default is 'all' to @@ -6881,7 +6929,6 @@ type ServerMcpConfigApi serverApi // RPC method: mcp.config.add. // // Parameters: MCP server name and configuration to add to user configuration. -// Experimental: Add is an experimental API and may change or be removed in future versions. func (a *ServerMcpConfigApi) Add(ctx context.Context, params *McpConfigAddRequest) (*McpConfigAddResult, error) { raw, err := a.client.Request("mcp.config.add", params) if err != nil { @@ -6967,8 +7014,6 @@ func (a *ServerMcpConfigApi) Remove(ctx context.Context, params *McpConfigRemove // RPC method: mcp.config.update. // // Parameters: MCP server name and replacement configuration to write to user configuration. -// Experimental: Update is an experimental API and may change or be removed in future -// versions. func (a *ServerMcpConfigApi) Update(ctx context.Context, params *McpConfigUpdateRequest) (*McpConfigUpdateResult, error) { raw, err := a.client.Request("mcp.config.update", params) if err != nil { @@ -7915,7 +7960,7 @@ func (a *EventLogApi) Read(ctx context.Context, params *EventLogReadRequest) (*E req["max"] = *params.Max } if params.Types != nil { - req["types"] = params.Types + req["types"] = *params.Types } if params.WaitMs != nil { req["waitMs"] = *params.WaitMs diff --git a/go/rpc/zrpc_encoding.go b/go/rpc/zrpc_encoding.go index 4cc9da36f..f013a1fef 100644 --- a/go/rpc/zrpc_encoding.go +++ b/go/rpc/zrpc_encoding.go @@ -230,6 +230,38 @@ func (r *CommandsRespondToQueuedCommandRequest) UnmarshalJSON(data []byte) error return nil } +func (r EventLogTypes) MarshalJSON() ([]byte, error) { + if r.String != nil { + return json.Marshal(r.String) + } + if r.StringArray != nil { + return json.Marshal(r.StringArray) + } + return []byte("null"), nil +} + +func (r *EventLogTypes) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + *r = EventLogTypes{} + return nil + } + { + var value EventLogTypesString + if err := json.Unmarshal(data, &value); err == nil { + *r = EventLogTypes{String: &value} + return nil + } + } + { + var value []string + if err := json.Unmarshal(data, &value); err == nil { + *r = EventLogTypes{StringArray: value} + return nil + } + } + return errors.New("data did not match any union variant for EventLogTypes") +} + func unmarshalExternalToolTextResultForLlmContent(data []byte) (ExternalToolTextResultForLlmContent, error) { if string(data) == "null" { return nil, nil diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index 36a24ba3d..4eb2a4b22 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -170,10 +170,9 @@ func (*AssistantReasoningData) Type() SessionEventType { return SessionEventType // Assistant response containing text content, optional tool requests, and interaction metadata type AssistantMessageData struct { // Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping - // Internal: AnthropicAdvisorBlocks is part of the SDK's internal API surface and is not intended for external use. AnthropicAdvisorBlocks []any `json:"anthropicAdvisorBlocks,omitempty"` // Anthropic advisor model ID used for this response, for timeline display on replay - // Internal: AnthropicAdvisorModel is part of the SDK's internal API surface and is not intended for external use. + // Experimental: AnthropicAdvisorModel is part of an experimental API and may change or be removed. AnthropicAdvisorModel *string `json:"anthropicAdvisorModel,omitempty"` // The assistant's text response content Content string `json:"content"` @@ -556,7 +555,6 @@ type AssistantUsageData struct { // GitHub request tracing ID (x-github-request-id header) for server-side log correlation ProviderCallID *string `json:"providerCallId,omitempty"` // Per-quota resource usage snapshots, keyed by quota identifier - // Internal: QuotaSnapshots is part of the SDK's internal API surface and is not intended for external use. QuotaSnapshots map[string]AssistantUsageQuotaSnapshot `json:"quotaSnapshots,omitempty"` // Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") ReasoningEffort *string `json:"reasoningEffort,omitempty"` @@ -1490,20 +1488,28 @@ type AssistantUsageCopilotUsageTokenDetail struct { // Schema for the `AssistantUsageQuotaSnapshot` type. type AssistantUsageQuotaSnapshot struct { // Total requests allowed by the entitlement + // Internal: EntitlementRequests is part of the SDK's internal API surface and is not intended for external use. EntitlementRequests int64 `json:"entitlementRequests"` // Whether the user has an unlimited usage entitlement + // Internal: IsUnlimitedEntitlement is part of the SDK's internal API surface and is not intended for external use. IsUnlimitedEntitlement bool `json:"isUnlimitedEntitlement"` - // Number of requests over the entitlement limit + // Number of additional usage requests made this period + // Internal: Overage is part of the SDK's internal API surface and is not intended for external use. Overage float64 `json:"overage"` - // Whether overage is allowed when quota is exhausted + // Whether additional usage is allowed when quota is exhausted + // Internal: OverageAllowedWithExhaustedQuota is part of the SDK's internal API surface and is not intended for external use. OverageAllowedWithExhaustedQuota bool `json:"overageAllowedWithExhaustedQuota"` // Percentage of quota remaining (0 to 100) + // Internal: RemainingPercentage is part of the SDK's internal API surface and is not intended for external use. RemainingPercentage float64 `json:"remainingPercentage"` // Date when the quota resets + // Internal: ResetDate is part of the SDK's internal API surface and is not intended for external use. ResetDate *time.Time `json:"resetDate,omitempty"` // Whether usage is still permitted after quota exhaustion + // Internal: UsageAllowedWithExhaustedQuota is part of the SDK's internal API surface and is not intended for external use. UsageAllowedWithExhaustedQuota bool `json:"usageAllowedWithExhaustedQuota"` // Number of requests already consumed + // Internal: UsedRequests is part of the SDK's internal API surface and is not intended for external use. UsedRequests int64 `json:"usedRequests"` } diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index cd5d950ff..dd965d56f 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -134,6 +134,14 @@ export type DiscoveredMcpServerType = | "sse" /** Server is backed by an in-memory runtime implementation. */ | "memory"; +/** + * Either '*' to receive all event types, or a non-empty list of event types to receive + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "EventLogTypes". + */ +/** @experimental */ +export type EventLogTypes = "*" | [string, ...string[]]; /** * Agent-scope filter: 'primary' returns only main-agent events plus events whose type starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns events from all agents (matching wildcard-subscription behavior). Default is 'all' to preserve wildcard semantics for catch-up callers. * @@ -248,7 +256,6 @@ export type ExternalToolTextResultForLlmContentResourceDetails = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "FilterMapping". */ -/** @experimental */ export type FilterMapping = | { [k: string]: ContentFilterMode; @@ -324,7 +331,6 @@ export type SessionLogLevel = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfig". */ -/** @experimental */ export type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp; /** * Remote transport type. Defaults to "http" when omitted. @@ -1320,24 +1326,7 @@ export interface CopilotUserResponse { ) | null; quota_reset_date?: string; - quota_snapshots?: { - [k: string]: - | ({ - entitlement?: number; - overage_count?: number; - overage_permitted?: boolean; - percent_remaining?: number; - quota_id?: string; - quota_remaining?: number; - remaining?: number; - unlimited?: boolean; - timestamp_utc?: string; - has_quota?: boolean; - quota_reset_at?: number; - token_based_billing?: boolean; - } | null) - | undefined; - }; + quota_snapshots?: CopilotUserResponseQuotaSnapshots; restricted_telemetry?: boolean; token_based_billing?: boolean; quota_reset_date_utc?: string; @@ -1364,6 +1353,97 @@ export interface CopilotUserResponseEndpoints { proxy?: string; telemetry?: string; } +/** + * Schema for the `CopilotUserResponseQuotaSnapshots` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CopilotUserResponseQuotaSnapshots". + */ +/** @experimental */ +export interface CopilotUserResponseQuotaSnapshots { + chat?: CopilotUserResponseQuotaSnapshotsChat; + completions?: CopilotUserResponseQuotaSnapshotsCompletions; + premium_interactions?: CopilotUserResponseQuotaSnapshotsPremiumInteractions; + [k: string]: + | ({ + entitlement?: number; + overage_count?: number; + overage_permitted?: boolean; + percent_remaining?: number; + quota_id?: string; + quota_remaining?: number; + remaining?: number; + unlimited?: boolean; + timestamp_utc?: string; + has_quota?: boolean; + quota_reset_at?: number; + token_based_billing?: boolean; + } | null) + | undefined; +} +/** + * Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CopilotUserResponseQuotaSnapshotsChat". + */ +/** @experimental */ +export interface CopilotUserResponseQuotaSnapshotsChat { + entitlement?: number; + overage_count?: number; + overage_permitted?: boolean; + percent_remaining?: number; + quota_id?: string; + quota_remaining?: number; + remaining?: number; + unlimited?: boolean; + timestamp_utc?: string; + has_quota?: boolean; + quota_reset_at?: number; + token_based_billing?: boolean; +} +/** + * Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CopilotUserResponseQuotaSnapshotsCompletions". + */ +/** @experimental */ +export interface CopilotUserResponseQuotaSnapshotsCompletions { + entitlement?: number; + overage_count?: number; + overage_permitted?: boolean; + percent_remaining?: number; + quota_id?: string; + quota_remaining?: number; + remaining?: number; + unlimited?: boolean; + timestamp_utc?: string; + has_quota?: boolean; + quota_reset_at?: number; + token_based_billing?: boolean; +} +/** + * Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CopilotUserResponseQuotaSnapshotsPremiumInteractions". + */ +/** @experimental */ +export interface CopilotUserResponseQuotaSnapshotsPremiumInteractions { + entitlement?: number; + overage_count?: number; + overage_permitted?: boolean; + percent_remaining?: number; + quota_id?: string; + quota_remaining?: number; + remaining?: number; + unlimited?: boolean; + timestamp_utc?: string; + has_quota?: boolean; + quota_reset_at?: number; + token_based_billing?: boolean; +} /** * Schema for the `HMACAuthInfo` type. * @@ -1891,12 +1971,7 @@ export interface EventLogReadRequest { * Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). */ waitMs?: number; - /** - * List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. - * - * @minItems 1 - */ - types?: [string, ...string[]]; + types?: EventLogTypes; agentScope?: EventsAgentScope; } /** @@ -2723,7 +2798,6 @@ export interface McpCancelSamplingExecutionResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigAddRequest". */ -/** @experimental */ export interface McpConfigAddRequest { /** * Unique name for the MCP server @@ -2880,7 +2954,6 @@ export interface McpConfigRemoveRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigUpdateRequest". */ -/** @experimental */ export interface McpConfigUpdateRequest { /** * Name of the MCP server to update @@ -8699,8 +8772,6 @@ export function createServerRpc(connection: MessageConnection) { * Adds an MCP server to user configuration. * * @param params MCP server name and configuration to add to user configuration. - * - * @experimental */ add: async (params: McpConfigAddRequest): Promise => connection.sendRequest("mcp.config.add", params), @@ -8708,8 +8779,6 @@ export function createServerRpc(connection: MessageConnection) { * Updates an MCP server in user configuration. * * @param params MCP server name and replacement configuration to write to user configuration. - * - * @experimental */ update: async (params: McpConfigUpdateRequest): Promise => connection.sendRequest("mcp.config.update", params), diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index 3fc9d3c3b..e5fe8bd03 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -2780,11 +2780,11 @@ export interface AssistantUsageQuotaSnapshot { */ isUnlimitedEntitlement: boolean; /** - * Number of requests over the entitlement limit + * Number of additional usage requests made this period */ overage: number; /** - * Whether overage is allowed when quota is exhausted + * Whether additional usage is allowed when quota is exhausted */ overageAllowedWithExhaustedQuota: boolean; /** diff --git a/python/copilot/generated/rpc.py b/python/copilot/generated/rpc.py index 9c8b02bc6..327a41344 100644 --- a/python/copilot/generated/rpc.py +++ b/python/copilot/generated/rpc.py @@ -253,66 +253,6 @@ def to_dict(self) -> dict: result["telemetry"] = from_union([from_str, from_none], self.telemetry) return result -@dataclass -class QuotaSnapshot: - entitlement: float | None = None - has_quota: bool | None = None - overage_count: float | None = None - overage_permitted: bool | None = None - percent_remaining: float | None = None - quota_id: str | None = None - quota_remaining: float | None = None - quota_reset_at: float | None = None - remaining: float | None = None - timestamp_utc: str | None = None - token_based_billing: bool | None = None - unlimited: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> 'QuotaSnapshot': - assert isinstance(obj, dict) - entitlement = from_union([from_float, from_none], obj.get("entitlement")) - has_quota = from_union([from_bool, from_none], obj.get("has_quota")) - overage_count = from_union([from_float, from_none], obj.get("overage_count")) - overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) - percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) - quota_id = from_union([from_str, from_none], obj.get("quota_id")) - quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) - quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) - remaining = from_union([from_float, from_none], obj.get("remaining")) - timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - unlimited = from_union([from_bool, from_none], obj.get("unlimited")) - return QuotaSnapshot(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) - - def to_dict(self) -> dict: - result: dict = {} - if self.entitlement is not None: - result["entitlement"] = from_union([to_float, from_none], self.entitlement) - if self.has_quota is not None: - result["has_quota"] = from_union([from_bool, from_none], self.has_quota) - if self.overage_count is not None: - result["overage_count"] = from_union([to_float, from_none], self.overage_count) - if self.overage_permitted is not None: - result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) - if self.percent_remaining is not None: - result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) - if self.quota_id is not None: - result["quota_id"] = from_union([from_str, from_none], self.quota_id) - if self.quota_remaining is not None: - result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) - if self.quota_reset_at is not None: - result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) - if self.remaining is not None: - result["remaining"] = from_union([to_float, from_none], self.remaining) - if self.timestamp_utc is not None: - result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - if self.unlimited is not None: - result["unlimited"] = from_union([from_bool, from_none], self.unlimited) - return result - class APIKeyAuthInfoType(Enum): API_KEY = "api-key" @@ -584,6 +524,195 @@ class Host(Enum): class CopilotAPITokenAuthInfoType(Enum): COPILOT_API_TOKEN = "copilot-api-token" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotUserResponseQuotaSnapshotsChat: + """Schema for the `CopilotUserResponseQuotaSnapshotsChat` type.""" + + entitlement: float | None = None + has_quota: bool | None = None + overage_count: float | None = None + overage_permitted: bool | None = None + percent_remaining: float | None = None + quota_id: str | None = None + quota_remaining: float | None = None + quota_reset_at: float | None = None + remaining: float | None = None + timestamp_utc: str | None = None + token_based_billing: bool | None = None + unlimited: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsChat': + assert isinstance(obj, dict) + entitlement = from_union([from_float, from_none], obj.get("entitlement")) + has_quota = from_union([from_bool, from_none], obj.get("has_quota")) + overage_count = from_union([from_float, from_none], obj.get("overage_count")) + overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) + percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) + quota_id = from_union([from_str, from_none], obj.get("quota_id")) + quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) + quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) + remaining = from_union([from_float, from_none], obj.get("remaining")) + timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + unlimited = from_union([from_bool, from_none], obj.get("unlimited")) + return CopilotUserResponseQuotaSnapshotsChat(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + + def to_dict(self) -> dict: + result: dict = {} + if self.entitlement is not None: + result["entitlement"] = from_union([to_float, from_none], self.entitlement) + if self.has_quota is not None: + result["has_quota"] = from_union([from_bool, from_none], self.has_quota) + if self.overage_count is not None: + result["overage_count"] = from_union([to_float, from_none], self.overage_count) + if self.overage_permitted is not None: + result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) + if self.percent_remaining is not None: + result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) + if self.quota_id is not None: + result["quota_id"] = from_union([from_str, from_none], self.quota_id) + if self.quota_remaining is not None: + result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) + if self.quota_reset_at is not None: + result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) + if self.remaining is not None: + result["remaining"] = from_union([to_float, from_none], self.remaining) + if self.timestamp_utc is not None: + result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + if self.unlimited is not None: + result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotUserResponseQuotaSnapshotsCompletions: + """Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type.""" + + entitlement: float | None = None + has_quota: bool | None = None + overage_count: float | None = None + overage_permitted: bool | None = None + percent_remaining: float | None = None + quota_id: str | None = None + quota_remaining: float | None = None + quota_reset_at: float | None = None + remaining: float | None = None + timestamp_utc: str | None = None + token_based_billing: bool | None = None + unlimited: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsCompletions': + assert isinstance(obj, dict) + entitlement = from_union([from_float, from_none], obj.get("entitlement")) + has_quota = from_union([from_bool, from_none], obj.get("has_quota")) + overage_count = from_union([from_float, from_none], obj.get("overage_count")) + overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) + percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) + quota_id = from_union([from_str, from_none], obj.get("quota_id")) + quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) + quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) + remaining = from_union([from_float, from_none], obj.get("remaining")) + timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + unlimited = from_union([from_bool, from_none], obj.get("unlimited")) + return CopilotUserResponseQuotaSnapshotsCompletions(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + + def to_dict(self) -> dict: + result: dict = {} + if self.entitlement is not None: + result["entitlement"] = from_union([to_float, from_none], self.entitlement) + if self.has_quota is not None: + result["has_quota"] = from_union([from_bool, from_none], self.has_quota) + if self.overage_count is not None: + result["overage_count"] = from_union([to_float, from_none], self.overage_count) + if self.overage_permitted is not None: + result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) + if self.percent_remaining is not None: + result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) + if self.quota_id is not None: + result["quota_id"] = from_union([from_str, from_none], self.quota_id) + if self.quota_remaining is not None: + result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) + if self.quota_reset_at is not None: + result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) + if self.remaining is not None: + result["remaining"] = from_union([to_float, from_none], self.remaining) + if self.timestamp_utc is not None: + result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + if self.unlimited is not None: + result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotUserResponseQuotaSnapshotsPremiumInteractions: + """Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type.""" + + entitlement: float | None = None + has_quota: bool | None = None + overage_count: float | None = None + overage_permitted: bool | None = None + percent_remaining: float | None = None + quota_id: str | None = None + quota_remaining: float | None = None + quota_reset_at: float | None = None + remaining: float | None = None + timestamp_utc: str | None = None + token_based_billing: bool | None = None + unlimited: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsPremiumInteractions': + assert isinstance(obj, dict) + entitlement = from_union([from_float, from_none], obj.get("entitlement")) + has_quota = from_union([from_bool, from_none], obj.get("has_quota")) + overage_count = from_union([from_float, from_none], obj.get("overage_count")) + overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) + percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) + quota_id = from_union([from_str, from_none], obj.get("quota_id")) + quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) + quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) + remaining = from_union([from_float, from_none], obj.get("remaining")) + timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + unlimited = from_union([from_bool, from_none], obj.get("unlimited")) + return CopilotUserResponseQuotaSnapshotsPremiumInteractions(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + + def to_dict(self) -> dict: + result: dict = {} + if self.entitlement is not None: + result["entitlement"] = from_union([to_float, from_none], self.entitlement) + if self.has_quota is not None: + result["has_quota"] = from_union([from_bool, from_none], self.has_quota) + if self.overage_count is not None: + result["overage_count"] = from_union([to_float, from_none], self.overage_count) + if self.overage_permitted is not None: + result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) + if self.percent_remaining is not None: + result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) + if self.quota_id is not None: + result["quota_id"] = from_union([from_str, from_none], self.quota_id) + if self.quota_remaining is not None: + result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) + if self.quota_reset_at is not None: + result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) + if self.remaining is not None: + result["remaining"] = from_union([to_float, from_none], self.remaining) + if self.timestamp_utc is not None: + result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + if self.unlimited is not None: + result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CurrentModel: @@ -676,6 +805,10 @@ class EventsAgentScope(Enum): ALL = "all" PRIMARY = "primary" +# Experimental: this type is part of an experimental API and may change or be removed. +class EventLogTypes(Enum): + EMPTY = "*" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class EventLogReleaseInterestResult: @@ -6045,119 +6178,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CopilotUserResponse: - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - access_type_sku: str | None = None - analytics_tracking_id: str | None = None - assigned_date: Any = None - can_signup_for_limited: bool | None = None - chat_enabled: bool | None = None - cli_remote_control_enabled: bool | None = None - cloud_session_storage_enabled: bool | None = None - codex_agent_enabled: bool | None = None - copilot_plan: str | None = None - copilotignore_enabled: bool | None = None - endpoints: CopilotUserResponseEndpoints | None = None - """Schema for the `CopilotUserResponseEndpoints` type.""" - - is_mcp_enabled: Any = None - limited_user_quotas: dict[str, float] | None = None - limited_user_reset_date: str | None = None - login: str | None = None - monthly_quotas: dict[str, float] | None = None - organization_list: Any = None - organization_login_list: list[str] | None = None - quota_reset_date: str | None = None - quota_reset_date_utc: str | None = None - quota_snapshots: dict[str, QuotaSnapshot | None] | None = None - restricted_telemetry: bool | None = None - token_based_billing: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponse': - assert isinstance(obj, dict) - access_type_sku = from_union([from_str, from_none], obj.get("access_type_sku")) - analytics_tracking_id = from_union([from_str, from_none], obj.get("analytics_tracking_id")) - assigned_date = obj.get("assigned_date") - can_signup_for_limited = from_union([from_bool, from_none], obj.get("can_signup_for_limited")) - chat_enabled = from_union([from_bool, from_none], obj.get("chat_enabled")) - cli_remote_control_enabled = from_union([from_bool, from_none], obj.get("cli_remote_control_enabled")) - cloud_session_storage_enabled = from_union([from_bool, from_none], obj.get("cloud_session_storage_enabled")) - codex_agent_enabled = from_union([from_bool, from_none], obj.get("codex_agent_enabled")) - copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) - copilotignore_enabled = from_union([from_bool, from_none], obj.get("copilotignore_enabled")) - endpoints = from_union([CopilotUserResponseEndpoints.from_dict, from_none], obj.get("endpoints")) - is_mcp_enabled = obj.get("is_mcp_enabled") - limited_user_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("limited_user_quotas")) - limited_user_reset_date = from_union([from_str, from_none], obj.get("limited_user_reset_date")) - login = from_union([from_str, from_none], obj.get("login")) - monthly_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("monthly_quotas")) - organization_list = obj.get("organization_list") - organization_login_list = from_union([lambda x: from_list(from_str, x), from_none], obj.get("organization_login_list")) - quota_reset_date = from_union([from_str, from_none], obj.get("quota_reset_date")) - quota_reset_date_utc = from_union([from_str, from_none], obj.get("quota_reset_date_utc")) - quota_snapshots = from_union([lambda x: from_dict(lambda x: from_union([QuotaSnapshot.from_dict, from_none], x), x), from_none], obj.get("quota_snapshots")) - restricted_telemetry = from_union([from_bool, from_none], obj.get("restricted_telemetry")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - return CopilotUserResponse(access_type_sku, analytics_tracking_id, assigned_date, can_signup_for_limited, chat_enabled, cli_remote_control_enabled, cloud_session_storage_enabled, codex_agent_enabled, copilot_plan, copilotignore_enabled, endpoints, is_mcp_enabled, limited_user_quotas, limited_user_reset_date, login, monthly_quotas, organization_list, organization_login_list, quota_reset_date, quota_reset_date_utc, quota_snapshots, restricted_telemetry, token_based_billing) - - def to_dict(self) -> dict: - result: dict = {} - if self.access_type_sku is not None: - result["access_type_sku"] = from_union([from_str, from_none], self.access_type_sku) - if self.analytics_tracking_id is not None: - result["analytics_tracking_id"] = from_union([from_str, from_none], self.analytics_tracking_id) - if self.assigned_date is not None: - result["assigned_date"] = self.assigned_date - if self.can_signup_for_limited is not None: - result["can_signup_for_limited"] = from_union([from_bool, from_none], self.can_signup_for_limited) - if self.chat_enabled is not None: - result["chat_enabled"] = from_union([from_bool, from_none], self.chat_enabled) - if self.cli_remote_control_enabled is not None: - result["cli_remote_control_enabled"] = from_union([from_bool, from_none], self.cli_remote_control_enabled) - if self.cloud_session_storage_enabled is not None: - result["cloud_session_storage_enabled"] = from_union([from_bool, from_none], self.cloud_session_storage_enabled) - if self.codex_agent_enabled is not None: - result["codex_agent_enabled"] = from_union([from_bool, from_none], self.codex_agent_enabled) - if self.copilot_plan is not None: - result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) - if self.copilotignore_enabled is not None: - result["copilotignore_enabled"] = from_union([from_bool, from_none], self.copilotignore_enabled) - if self.endpoints is not None: - result["endpoints"] = from_union([lambda x: to_class(CopilotUserResponseEndpoints, x), from_none], self.endpoints) - if self.is_mcp_enabled is not None: - result["is_mcp_enabled"] = self.is_mcp_enabled - if self.limited_user_quotas is not None: - result["limited_user_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.limited_user_quotas) - if self.limited_user_reset_date is not None: - result["limited_user_reset_date"] = from_union([from_str, from_none], self.limited_user_reset_date) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - if self.monthly_quotas is not None: - result["monthly_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.monthly_quotas) - if self.organization_list is not None: - result["organization_list"] = self.organization_list - if self.organization_login_list is not None: - result["organization_login_list"] = from_union([lambda x: from_list(from_str, x), from_none], self.organization_login_list) - if self.quota_reset_date is not None: - result["quota_reset_date"] = from_union([from_str, from_none], self.quota_reset_date) - if self.quota_reset_date_utc is not None: - result["quota_reset_date_utc"] = from_union([from_str, from_none], self.quota_reset_date_utc) - if self.quota_snapshots is not None: - result["quota_snapshots"] = from_union([lambda x: from_dict(lambda x: from_union([lambda x: to_class(QuotaSnapshot, x), from_none], x), x), from_none], self.quota_snapshots) - if self.restricted_telemetry is not None: - result["restricted_telemetry"] = from_union([from_bool, from_none], self.restricted_telemetry) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionAuthStatus: - """Authentication status and account metadata for the session.""" +class SessionAuthStatus: + """Authentication status and account metadata for the session.""" is_authenticated: bool """Whether the session has resolved authentication""" @@ -6409,6 +6431,73 @@ def to_dict(self) -> dict: result["tools"] = from_union([lambda x: from_list(from_str, x), from_none], self.tools) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotUserResponseQuotaSnapshots: + """Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + + Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + + Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + """ + entitlement: float | None = None + has_quota: bool | None = None + overage_count: float | None = None + overage_permitted: bool | None = None + percent_remaining: float | None = None + quota_id: str | None = None + quota_remaining: float | None = None + quota_reset_at: float | None = None + remaining: float | None = None + timestamp_utc: str | None = None + token_based_billing: bool | None = None + unlimited: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshots': + assert isinstance(obj, dict) + entitlement = from_union([from_float, from_none], obj.get("entitlement")) + has_quota = from_union([from_bool, from_none], obj.get("has_quota")) + overage_count = from_union([from_float, from_none], obj.get("overage_count")) + overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) + percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) + quota_id = from_union([from_str, from_none], obj.get("quota_id")) + quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) + quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) + remaining = from_union([from_float, from_none], obj.get("remaining")) + timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + unlimited = from_union([from_bool, from_none], obj.get("unlimited")) + return CopilotUserResponseQuotaSnapshots(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + + def to_dict(self) -> dict: + result: dict = {} + if self.entitlement is not None: + result["entitlement"] = from_union([to_float, from_none], self.entitlement) + if self.has_quota is not None: + result["has_quota"] = from_union([from_bool, from_none], self.has_quota) + if self.overage_count is not None: + result["overage_count"] = from_union([to_float, from_none], self.overage_count) + if self.overage_permitted is not None: + result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) + if self.percent_remaining is not None: + result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) + if self.quota_id is not None: + result["quota_id"] = from_union([from_str, from_none], self.quota_id) + if self.quota_remaining is not None: + result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) + if self.quota_reset_at is not None: + result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) + if self.remaining is not None: + result["remaining"] = from_union([to_float, from_none], self.remaining) + if self.timestamp_utc is not None: + result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + if self.unlimited is not None: + result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + return result + @dataclass class DiscoveredMCPServer: """Schema for the `DiscoveredMcpServer` type.""" @@ -6461,10 +6550,9 @@ class EventLogReadRequest: max: int | None = None """Maximum number of events to return in this batch (1–1000, default 200).""" - types: list[str] | None = None - """List of event types to receive. Omit (or pass an empty/absent value) to receive all event - types. - """ + types: list[str] | EventLogTypes | None = None + """Either '*' to receive all event types, or a non-empty list of event types to receive""" + wait_ms: int | None = None """Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. @@ -6479,7 +6567,7 @@ def from_dict(obj: Any) -> 'EventLogReadRequest': agent_scope = from_union([EventsAgentScope, from_none], obj.get("agentScope")) cursor = from_union([from_str, from_none], obj.get("cursor")) max = from_union([from_int, from_none], obj.get("max")) - types = from_union([lambda x: from_list(from_str, x), from_none], obj.get("types")) + types = from_union([lambda x: from_list(from_str, x), EventLogTypes, from_none], obj.get("types")) wait_ms = from_union([from_int, from_none], obj.get("waitMs")) return EventLogReadRequest(agent_scope, cursor, max, types, wait_ms) @@ -6492,7 +6580,7 @@ def to_dict(self) -> dict: if self.max is not None: result["max"] = from_union([from_int, from_none], self.max) if self.types is not None: - result["types"] = from_union([lambda x: from_list(from_str, x), from_none], self.types) + result["types"] = from_union([lambda x: from_list(from_str, x), lambda x: to_enum(EventLogTypes, x), from_none], self.types) if self.wait_ms is not None: result["waitMs"] = from_union([from_int, from_none], self.wait_ms) return result @@ -7168,7 +7256,6 @@ def to_dict(self) -> dict: result["url"] = from_union([from_str, from_none], self.url) return result -# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerConfig: """MCP server configuration (stdio process or remote HTTP/SSE) @@ -10354,361 +10441,192 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class APIKeyAuthInfo: - """Schema for the `ApiKeyAuthInfo` type.""" - - api_key: str - """The API key. Treat as a secret.""" +class SlashCommandInfo: + """Schema for the `SlashCommandInfo` type.""" - host: str - """Authentication host.""" + allow_during_agent_execution: bool + """Whether the command may run while an agent turn is active""" - type: APIKeyAuthInfoType - """API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style).""" + description: str + """Human-readable command description""" - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + kind: SlashCommandKind + """Coarse command category for grouping and behavior: runtime built-in, skill-backed + command, or SDK/client-owned command """ + name: str + """Canonical command name without a leading slash""" + + aliases: list[str] | None = None + """Canonical aliases without leading slashes""" + + experimental: bool | None = None + """Whether the command is experimental""" + + input: SlashCommandInput | None = None + """Optional unstructured input hint""" @staticmethod - def from_dict(obj: Any) -> 'APIKeyAuthInfo': + def from_dict(obj: Any) -> 'SlashCommandInfo': assert isinstance(obj, dict) - api_key = from_str(obj.get("apiKey")) - host = from_str(obj.get("host")) - type = APIKeyAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return APIKeyAuthInfo(api_key, host, type, copilot_user) + allow_during_agent_execution = from_bool(obj.get("allowDuringAgentExecution")) + description = from_str(obj.get("description")) + kind = SlashCommandKind(obj.get("kind")) + name = from_str(obj.get("name")) + aliases = from_union([lambda x: from_list(from_str, x), from_none], obj.get("aliases")) + experimental = from_union([from_bool, from_none], obj.get("experimental")) + input = from_union([SlashCommandInput.from_dict, from_none], obj.get("input")) + return SlashCommandInfo(allow_during_agent_execution, description, kind, name, aliases, experimental, input) def to_dict(self) -> dict: result: dict = {} - result["apiKey"] = from_str(self.api_key) - result["host"] = from_str(self.host) - result["type"] = to_enum(APIKeyAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["allowDuringAgentExecution"] = from_bool(self.allow_during_agent_execution) + result["description"] = from_str(self.description) + result["kind"] = to_enum(SlashCommandKind, self.kind) + result["name"] = from_str(self.name) + if self.aliases is not None: + result["aliases"] = from_union([lambda x: from_list(from_str, x), from_none], self.aliases) + if self.experimental is not None: + result["experimental"] = from_union([from_bool, from_none], self.experimental) + if self.input is not None: + result["input"] = from_union([lambda x: to_class(SlashCommandInput, x), from_none], self.input) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CopilotAPITokenAuthInfo: - """Schema for the `CopilotApiTokenAuthInfo` type.""" +class RemoteSessionConnectionResult: + """Remote session connection result.""" - host: Host - """Authentication host (always the public GitHub host).""" + metadata: ConnectedRemoteSessionMetadata + """Metadata for a connected remote session.""" - type: CopilotAPITokenAuthInfoType - """Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` - environment-variable pair. The token itself is read from the environment by the runtime, - not carried in this struct. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ + session_id: str + """SDK session ID for the connected remote session.""" @staticmethod - def from_dict(obj: Any) -> 'CopilotAPITokenAuthInfo': + def from_dict(obj: Any) -> 'RemoteSessionConnectionResult': assert isinstance(obj, dict) - host = Host(obj.get("host")) - type = CopilotAPITokenAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return CopilotAPITokenAuthInfo(host, type, copilot_user) + metadata = ConnectedRemoteSessionMetadata.from_dict(obj.get("metadata")) + session_id = from_str(obj.get("sessionId")) + return RemoteSessionConnectionResult(metadata, session_id) def to_dict(self) -> dict: result: dict = {} - result["host"] = to_enum(Host, self.host) - result["type"] = to_enum(CopilotAPITokenAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["metadata"] = to_class(ConnectedRemoteSessionMetadata, self.metadata) + result["sessionId"] = from_str(self.session_id) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class EnvAuthInfo: - """Schema for the `EnvAuthInfo` type.""" - - env_var: str - """Name of the environment variable the token was sourced from.""" - - host: str - """Authentication host (e.g. https://github.com or a GHES host).""" - - token: str - """The token value itself. Treat as a secret.""" - - type: EnvAuthInfoType - """Personal access token (PAT) or server-to-server token sourced from an environment - variable. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - login: str | None = None - """User login associated with the token. Undefined for server-to-server tokens (those - starting with `ghs_`). - """ - - @staticmethod - def from_dict(obj: Any) -> 'EnvAuthInfo': - assert isinstance(obj, dict) - env_var = from_str(obj.get("envVar")) - host = from_str(obj.get("host")) - token = from_str(obj.get("token")) - type = EnvAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - login = from_union([from_str, from_none], obj.get("login")) - return EnvAuthInfo(env_var, host, token, type, copilot_user, login) - - def to_dict(self) -> dict: - result: dict = {} - result["envVar"] = from_str(self.env_var) - result["host"] = from_str(self.host) - result["token"] = from_str(self.token) - result["type"] = to_enum(EnvAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class GhCLIAuthInfo: - """Schema for the `GhCliAuthInfo` type.""" - - host: str - """Authentication host.""" - - login: str - """User login as reported by `gh auth status`.""" - - token: str - """The token returned by `gh auth token`. Treat as a secret.""" - - type: GhCLIAuthInfoType - """Authentication via the `gh` CLI's saved credentials.""" - - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - - @staticmethod - def from_dict(obj: Any) -> 'GhCLIAuthInfo': - assert isinstance(obj, dict) - host = from_str(obj.get("host")) - login = from_str(obj.get("login")) - token = from_str(obj.get("token")) - type = GhCLIAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return GhCLIAuthInfo(host, login, token, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["host"] = from_str(self.host) - result["login"] = from_str(self.login) - result["token"] = from_str(self.token) - result["type"] = to_enum(GhCLIAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HMACAuthInfo: - """Schema for the `HMACAuthInfo` type.""" - - hmac: str - """HMAC secret used to sign requests.""" - - host: Host - """Authentication host. HMAC auth always targets the public GitHub host.""" - - type: HMACAuthInfoType - """HMAC-based authentication used by GitHub-internal services.""" - - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - - @staticmethod - def from_dict(obj: Any) -> 'HMACAuthInfo': - assert isinstance(obj, dict) - hmac = from_str(obj.get("hmac")) - host = Host(obj.get("host")) - type = HMACAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return HMACAuthInfo(hmac, host, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["hmac"] = from_str(self.hmac) - result["host"] = to_enum(Host, self.host) - result["type"] = to_enum(HMACAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class TokenAuthInfo: - """Schema for the `TokenAuthInfo` type.""" - - host: str - """Authentication host.""" - - token: str - """The token value itself. Treat as a secret.""" - - type: TokenAuthInfoType - """SDK-side token authentication; the host configured the token directly via the SDK.""" - - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - - @staticmethod - def from_dict(obj: Any) -> 'TokenAuthInfo': - assert isinstance(obj, dict) - host = from_str(obj.get("host")) - token = from_str(obj.get("token")) - type = TokenAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return TokenAuthInfo(host, token, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["host"] = from_str(self.host) - result["token"] = from_str(self.token) - result["type"] = to_enum(TokenAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class UserAuthInfo: - """Schema for the `UserAuthInfo` type.""" - - host: str - """Authentication host.""" - - login: str - """OAuth user login.""" - - type: UserAuthInfoType - """OAuth user authentication. The token itself is held in the runtime's secret token store - (keyed by host+login) and is NOT carried in this struct. - """ - copilot_user: CopilotUserResponse | None = None +class CopilotUserResponse: """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. """ + access_type_sku: str | None = None + analytics_tracking_id: str | None = None + assigned_date: Any = None + can_signup_for_limited: bool | None = None + chat_enabled: bool | None = None + cli_remote_control_enabled: bool | None = None + cloud_session_storage_enabled: bool | None = None + codex_agent_enabled: bool | None = None + copilot_plan: str | None = None + copilotignore_enabled: bool | None = None + endpoints: CopilotUserResponseEndpoints | None = None + """Schema for the `CopilotUserResponseEndpoints` type.""" - @staticmethod - def from_dict(obj: Any) -> 'UserAuthInfo': - assert isinstance(obj, dict) - host = from_str(obj.get("host")) - login = from_str(obj.get("login")) - type = UserAuthInfoType(obj.get("type")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return UserAuthInfo(host, login, type, copilot_user) - - def to_dict(self) -> dict: - result: dict = {} - result["host"] = from_str(self.host) - result["login"] = from_str(self.login) - result["type"] = to_enum(UserAuthInfoType, self.type) - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SlashCommandInfo: - """Schema for the `SlashCommandInfo` type.""" - - allow_during_agent_execution: bool - """Whether the command may run while an agent turn is active""" - - description: str - """Human-readable command description""" - - kind: SlashCommandKind - """Coarse command category for grouping and behavior: runtime built-in, skill-backed - command, or SDK/client-owned command - """ - name: str - """Canonical command name without a leading slash""" - - aliases: list[str] | None = None - """Canonical aliases without leading slashes""" - - experimental: bool | None = None - """Whether the command is experimental""" - - input: SlashCommandInput | None = None - """Optional unstructured input hint""" - - @staticmethod - def from_dict(obj: Any) -> 'SlashCommandInfo': - assert isinstance(obj, dict) - allow_during_agent_execution = from_bool(obj.get("allowDuringAgentExecution")) - description = from_str(obj.get("description")) - kind = SlashCommandKind(obj.get("kind")) - name = from_str(obj.get("name")) - aliases = from_union([lambda x: from_list(from_str, x), from_none], obj.get("aliases")) - experimental = from_union([from_bool, from_none], obj.get("experimental")) - input = from_union([SlashCommandInput.from_dict, from_none], obj.get("input")) - return SlashCommandInfo(allow_during_agent_execution, description, kind, name, aliases, experimental, input) - - def to_dict(self) -> dict: - result: dict = {} - result["allowDuringAgentExecution"] = from_bool(self.allow_during_agent_execution) - result["description"] = from_str(self.description) - result["kind"] = to_enum(SlashCommandKind, self.kind) - result["name"] = from_str(self.name) - if self.aliases is not None: - result["aliases"] = from_union([lambda x: from_list(from_str, x), from_none], self.aliases) - if self.experimental is not None: - result["experimental"] = from_union([from_bool, from_none], self.experimental) - if self.input is not None: - result["input"] = from_union([lambda x: to_class(SlashCommandInput, x), from_none], self.input) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class RemoteSessionConnectionResult: - """Remote session connection result.""" - - metadata: ConnectedRemoteSessionMetadata - """Metadata for a connected remote session.""" + is_mcp_enabled: Any = None + limited_user_quotas: dict[str, float] | None = None + limited_user_reset_date: str | None = None + login: str | None = None + monthly_quotas: dict[str, float] | None = None + organization_list: Any = None + organization_login_list: list[str] | None = None + quota_reset_date: str | None = None + quota_reset_date_utc: str | None = None + quota_snapshots: dict[str, CopilotUserResponseQuotaSnapshots | None] | None = None + """Schema for the `CopilotUserResponseQuotaSnapshots` type.""" - session_id: str - """SDK session ID for the connected remote session.""" + restricted_telemetry: bool | None = None + token_based_billing: bool | None = None @staticmethod - def from_dict(obj: Any) -> 'RemoteSessionConnectionResult': + def from_dict(obj: Any) -> 'CopilotUserResponse': assert isinstance(obj, dict) - metadata = ConnectedRemoteSessionMetadata.from_dict(obj.get("metadata")) - session_id = from_str(obj.get("sessionId")) - return RemoteSessionConnectionResult(metadata, session_id) + access_type_sku = from_union([from_str, from_none], obj.get("access_type_sku")) + analytics_tracking_id = from_union([from_str, from_none], obj.get("analytics_tracking_id")) + assigned_date = obj.get("assigned_date") + can_signup_for_limited = from_union([from_bool, from_none], obj.get("can_signup_for_limited")) + chat_enabled = from_union([from_bool, from_none], obj.get("chat_enabled")) + cli_remote_control_enabled = from_union([from_bool, from_none], obj.get("cli_remote_control_enabled")) + cloud_session_storage_enabled = from_union([from_bool, from_none], obj.get("cloud_session_storage_enabled")) + codex_agent_enabled = from_union([from_bool, from_none], obj.get("codex_agent_enabled")) + copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) + copilotignore_enabled = from_union([from_bool, from_none], obj.get("copilotignore_enabled")) + endpoints = from_union([CopilotUserResponseEndpoints.from_dict, from_none], obj.get("endpoints")) + is_mcp_enabled = obj.get("is_mcp_enabled") + limited_user_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("limited_user_quotas")) + limited_user_reset_date = from_union([from_str, from_none], obj.get("limited_user_reset_date")) + login = from_union([from_str, from_none], obj.get("login")) + monthly_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("monthly_quotas")) + organization_list = obj.get("organization_list") + organization_login_list = from_union([lambda x: from_list(from_str, x), from_none], obj.get("organization_login_list")) + quota_reset_date = from_union([from_str, from_none], obj.get("quota_reset_date")) + quota_reset_date_utc = from_union([from_str, from_none], obj.get("quota_reset_date_utc")) + quota_snapshots = from_union([lambda x: from_dict(lambda x: from_union([CopilotUserResponseQuotaSnapshots.from_dict, from_none], x), x), from_none], obj.get("quota_snapshots")) + restricted_telemetry = from_union([from_bool, from_none], obj.get("restricted_telemetry")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + return CopilotUserResponse(access_type_sku, analytics_tracking_id, assigned_date, can_signup_for_limited, chat_enabled, cli_remote_control_enabled, cloud_session_storage_enabled, codex_agent_enabled, copilot_plan, copilotignore_enabled, endpoints, is_mcp_enabled, limited_user_quotas, limited_user_reset_date, login, monthly_quotas, organization_list, organization_login_list, quota_reset_date, quota_reset_date_utc, quota_snapshots, restricted_telemetry, token_based_billing) def to_dict(self) -> dict: result: dict = {} - result["metadata"] = to_class(ConnectedRemoteSessionMetadata, self.metadata) - result["sessionId"] = from_str(self.session_id) + if self.access_type_sku is not None: + result["access_type_sku"] = from_union([from_str, from_none], self.access_type_sku) + if self.analytics_tracking_id is not None: + result["analytics_tracking_id"] = from_union([from_str, from_none], self.analytics_tracking_id) + if self.assigned_date is not None: + result["assigned_date"] = self.assigned_date + if self.can_signup_for_limited is not None: + result["can_signup_for_limited"] = from_union([from_bool, from_none], self.can_signup_for_limited) + if self.chat_enabled is not None: + result["chat_enabled"] = from_union([from_bool, from_none], self.chat_enabled) + if self.cli_remote_control_enabled is not None: + result["cli_remote_control_enabled"] = from_union([from_bool, from_none], self.cli_remote_control_enabled) + if self.cloud_session_storage_enabled is not None: + result["cloud_session_storage_enabled"] = from_union([from_bool, from_none], self.cloud_session_storage_enabled) + if self.codex_agent_enabled is not None: + result["codex_agent_enabled"] = from_union([from_bool, from_none], self.codex_agent_enabled) + if self.copilot_plan is not None: + result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) + if self.copilotignore_enabled is not None: + result["copilotignore_enabled"] = from_union([from_bool, from_none], self.copilotignore_enabled) + if self.endpoints is not None: + result["endpoints"] = from_union([lambda x: to_class(CopilotUserResponseEndpoints, x), from_none], self.endpoints) + if self.is_mcp_enabled is not None: + result["is_mcp_enabled"] = self.is_mcp_enabled + if self.limited_user_quotas is not None: + result["limited_user_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.limited_user_quotas) + if self.limited_user_reset_date is not None: + result["limited_user_reset_date"] = from_union([from_str, from_none], self.limited_user_reset_date) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.monthly_quotas is not None: + result["monthly_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.monthly_quotas) + if self.organization_list is not None: + result["organization_list"] = self.organization_list + if self.organization_login_list is not None: + result["organization_login_list"] = from_union([lambda x: from_list(from_str, x), from_none], self.organization_login_list) + if self.quota_reset_date is not None: + result["quota_reset_date"] = from_union([from_str, from_none], self.quota_reset_date) + if self.quota_reset_date_utc is not None: + result["quota_reset_date_utc"] = from_union([from_str, from_none], self.quota_reset_date_utc) + if self.quota_snapshots is not None: + result["quota_snapshots"] = from_union([lambda x: from_dict(lambda x: from_union([lambda x: to_class(CopilotUserResponseQuotaSnapshots, x), from_none], x), x), from_none], self.quota_snapshots) + if self.restricted_telemetry is not None: + result["restricted_telemetry"] = from_union([from_bool, from_none], self.restricted_telemetry) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) return result @dataclass @@ -11147,7 +11065,6 @@ def to_dict(self) -> dict: result["sources"] = from_list(lambda x: to_class(InstructionsSources, x), self.sources) return result -# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigAddRequest: """MCP server name and configuration to add to user configuration.""" @@ -11189,7 +11106,6 @@ def to_dict(self) -> dict: result["servers"] = from_dict(lambda x: to_class(MCPServerConfig, x), self.servers) return result -# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigUpdateRequest: """MCP server name and replacement configuration to write to user configuration.""" @@ -12471,130 +12387,303 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class AuthInfo: - """The new auth credentials to install on the session. When omitted or `undefined`, the call - is a no-op and the session's existing credentials are preserved. The runtime stores the - value verbatim and uses it for outbound model/API requests; it does NOT re-validate or - re-fetch the associated Copilot user response. Several variants carry secret material; - treat this method's params as containing secrets at rest and in transit. +class CommandList: + """Slash commands available in the session, after applying any include/exclude filters.""" - Schema for the `HMACAuthInfo` type. + commands: list[SlashCommandInfo] + """Commands available in this session""" - Schema for the `EnvAuthInfo` type. + @staticmethod + def from_dict(obj: Any) -> 'CommandList': + assert isinstance(obj, dict) + commands = from_list(SlashCommandInfo.from_dict, obj.get("commands")) + return CommandList(commands) - Schema for the `TokenAuthInfo` type. + def to_dict(self) -> dict: + result: dict = {} + result["commands"] = from_list(lambda x: to_class(SlashCommandInfo, x), self.commands) + return result - Schema for the `CopilotApiTokenAuthInfo` type. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class APIKeyAuthInfo: + """Schema for the `ApiKeyAuthInfo` type.""" - Schema for the `UserAuthInfo` type. + api_key: str + """The API key. Treat as a secret.""" - Schema for the `GhCliAuthInfo` type. + host: str + """Authentication host.""" - Schema for the `ApiKeyAuthInfo` type. + type: APIKeyAuthInfoType + """API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style).""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. """ - host: str - """Authentication host. HMAC auth always targets the public GitHub host. - Authentication host (e.g. https://github.com or a GHES host). + @staticmethod + def from_dict(obj: Any) -> 'APIKeyAuthInfo': + assert isinstance(obj, dict) + api_key = from_str(obj.get("apiKey")) + host = from_str(obj.get("host")) + type = APIKeyAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return APIKeyAuthInfo(api_key, host, type, copilot_user) - Authentication host. + def to_dict(self) -> dict: + result: dict = {} + result["apiKey"] = from_str(self.api_key) + result["host"] = from_str(self.host) + result["type"] = to_enum(APIKeyAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result - Authentication host (always the public GitHub host). +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotAPITokenAuthInfo: + """Schema for the `CopilotApiTokenAuthInfo` type.""" + + host: Host + """Authentication host (always the public GitHub host).""" + + type: CopilotAPITokenAuthInfoType + """Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` + environment-variable pair. The token itself is read from the environment by the runtime, + not carried in this struct. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. """ - type: AuthInfoType - """HMAC-based authentication used by GitHub-internal services. - Personal access token (PAT) or server-to-server token sourced from an environment + @staticmethod + def from_dict(obj: Any) -> 'CopilotAPITokenAuthInfo': + assert isinstance(obj, dict) + host = Host(obj.get("host")) + type = CopilotAPITokenAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return CopilotAPITokenAuthInfo(host, type, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = to_enum(Host, self.host) + result["type"] = to_enum(CopilotAPITokenAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class EnvAuthInfo: + """Schema for the `EnvAuthInfo` type.""" + + env_var: str + """Name of the environment variable the token was sourced from.""" + + host: str + """Authentication host (e.g. https://github.com or a GHES host).""" + + token: str + """The token value itself. Treat as a secret.""" + + type: EnvAuthInfoType + """Personal access token (PAT) or server-to-server token sourced from an environment variable. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + login: str | None = None + """User login associated with the token. Undefined for server-to-server tokens (those + starting with `ghs_`). + """ + + @staticmethod + def from_dict(obj: Any) -> 'EnvAuthInfo': + assert isinstance(obj, dict) + env_var = from_str(obj.get("envVar")) + host = from_str(obj.get("host")) + token = from_str(obj.get("token")) + type = EnvAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + login = from_union([from_str, from_none], obj.get("login")) + return EnvAuthInfo(env_var, host, token, type, copilot_user, login) + + def to_dict(self) -> dict: + result: dict = {} + result["envVar"] = from_str(self.env_var) + result["host"] = from_str(self.host) + result["token"] = from_str(self.token) + result["type"] = to_enum(EnvAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class GhCLIAuthInfo: + """Schema for the `GhCliAuthInfo` type.""" + + host: str + """Authentication host.""" + + login: str + """User login as reported by `gh auth status`.""" + + token: str + """The token returned by `gh auth token`. Treat as a secret.""" + + type: GhCLIAuthInfoType + """Authentication via the `gh` CLI's saved credentials.""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'GhCLIAuthInfo': + assert isinstance(obj, dict) + host = from_str(obj.get("host")) + login = from_str(obj.get("login")) + token = from_str(obj.get("token")) + type = GhCLIAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return GhCLIAuthInfo(host, login, token, type, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = from_str(self.host) + result["login"] = from_str(self.login) + result["token"] = from_str(self.token) + result["type"] = to_enum(GhCLIAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result - SDK-side token authentication; the host configured the token directly via the SDK. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HMACAuthInfo: + """Schema for the `HMACAuthInfo` type.""" - Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` - environment-variable pair. The token itself is read from the environment by the runtime, - not carried in this struct. + hmac: str + """HMAC secret used to sign requests.""" - OAuth user authentication. The token itself is held in the runtime's secret token store - (keyed by host+login) and is NOT carried in this struct. + host: Host + """Authentication host. HMAC auth always targets the public GitHub host.""" - Authentication via the `gh` CLI's saved credentials. + type: HMACAuthInfoType + """HMAC-based authentication used by GitHub-internal services.""" - API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). - """ copilot_user: CopilotUserResponse | None = None """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. """ - hmac: str | None = None - """HMAC secret used to sign requests.""" - env_var: str | None = None - """Name of the environment variable the token was sourced from.""" + @staticmethod + def from_dict(obj: Any) -> 'HMACAuthInfo': + assert isinstance(obj, dict) + hmac = from_str(obj.get("hmac")) + host = Host(obj.get("host")) + type = HMACAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return HMACAuthInfo(hmac, host, type, copilot_user) - login: str | None = None - """User login associated with the token. Undefined for server-to-server tokens (those - starting with `ghs_`). + def to_dict(self) -> dict: + result: dict = {} + result["hmac"] = from_str(self.hmac) + result["host"] = to_enum(Host, self.host) + result["type"] = to_enum(HMACAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result - OAuth user login. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class TokenAuthInfo: + """Schema for the `TokenAuthInfo` type.""" - User login as reported by `gh auth status`. - """ - token: str | None = None - """The token value itself. Treat as a secret. + host: str + """Authentication host.""" - The token returned by `gh auth token`. Treat as a secret. + token: str + """The token value itself. Treat as a secret.""" + + type: TokenAuthInfoType + """SDK-side token authentication; the host configured the token directly via the SDK.""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. """ - api_key: str | None = None - """The API key. Treat as a secret.""" @staticmethod - def from_dict(obj: Any) -> 'AuthInfo': + def from_dict(obj: Any) -> 'TokenAuthInfo': assert isinstance(obj, dict) host = from_str(obj.get("host")) - type = AuthInfoType(obj.get("type")) + token = from_str(obj.get("token")) + type = TokenAuthInfoType(obj.get("type")) copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - hmac = from_union([from_str, from_none], obj.get("hmac")) - env_var = from_union([from_str, from_none], obj.get("envVar")) - login = from_union([from_str, from_none], obj.get("login")) - token = from_union([from_str, from_none], obj.get("token")) - api_key = from_union([from_str, from_none], obj.get("apiKey")) - return AuthInfo(host, type, copilot_user, hmac, env_var, login, token, api_key) + return TokenAuthInfo(host, token, type, copilot_user) def to_dict(self) -> dict: result: dict = {} result["host"] = from_str(self.host) - result["type"] = to_enum(AuthInfoType, self.type) + result["token"] = from_str(self.token) + result["type"] = to_enum(TokenAuthInfoType, self.type) if self.copilot_user is not None: result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - if self.hmac is not None: - result["hmac"] = from_union([from_str, from_none], self.hmac) - if self.env_var is not None: - result["envVar"] = from_union([from_str, from_none], self.env_var) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - if self.token is not None: - result["token"] = from_union([from_str, from_none], self.token) - if self.api_key is not None: - result["apiKey"] = from_union([from_str, from_none], self.api_key) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CommandList: - """Slash commands available in the session, after applying any include/exclude filters.""" +class UserAuthInfo: + """Schema for the `UserAuthInfo` type.""" - commands: list[SlashCommandInfo] - """Commands available in this session""" + host: str + """Authentication host.""" + + login: str + """OAuth user login.""" + + type: UserAuthInfoType + """OAuth user authentication. The token itself is held in the runtime's secret token store + (keyed by host+login) and is NOT carried in this struct. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ @staticmethod - def from_dict(obj: Any) -> 'CommandList': + def from_dict(obj: Any) -> 'UserAuthInfo': assert isinstance(obj, dict) - commands = from_list(SlashCommandInfo.from_dict, obj.get("commands")) - return CommandList(commands) + host = from_str(obj.get("host")) + login = from_str(obj.get("login")) + type = UserAuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return UserAuthInfo(host, login, type, copilot_user) def to_dict(self) -> dict: result: dict = {} - result["commands"] = from_list(lambda x: to_class(SlashCommandInfo, x), self.commands) + result["host"] = from_str(self.host) + result["login"] = from_str(self.login) + result["type"] = to_enum(UserAuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -13505,27 +13594,111 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionSetCredentialsParams: - """New auth credentials to install on the session. Omit to leave credentials unchanged.""" - - credentials: AuthInfo | None = None +class AuthInfo: """The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime stores the value verbatim and uses it for outbound model/API requests; it does NOT re-validate or re-fetch the associated Copilot user response. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. + + Schema for the `HMACAuthInfo` type. + + Schema for the `EnvAuthInfo` type. + + Schema for the `TokenAuthInfo` type. + + Schema for the `CopilotApiTokenAuthInfo` type. + + Schema for the `UserAuthInfo` type. + + Schema for the `GhCliAuthInfo` type. + + Schema for the `ApiKeyAuthInfo` type. + """ + host: str + """Authentication host. HMAC auth always targets the public GitHub host. + + Authentication host (e.g. https://github.com or a GHES host). + + Authentication host. + + Authentication host (always the public GitHub host). + """ + type: AuthInfoType + """HMAC-based authentication used by GitHub-internal services. + + Personal access token (PAT) or server-to-server token sourced from an environment + variable. + + SDK-side token authentication; the host configured the token directly via the SDK. + + Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` + environment-variable pair. The token itself is read from the environment by the runtime, + not carried in this struct. + + OAuth user authentication. The token itself is held in the runtime's secret token store + (keyed by host+login) and is NOT carried in this struct. + + Authentication via the `gh` CLI's saved credentials. + + API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + hmac: str | None = None + """HMAC secret used to sign requests.""" + + env_var: str | None = None + """Name of the environment variable the token was sourced from.""" + + login: str | None = None + """User login associated with the token. Undefined for server-to-server tokens (those + starting with `ghs_`). + + OAuth user login. + + User login as reported by `gh auth status`. + """ + token: str | None = None + """The token value itself. Treat as a secret. + + The token returned by `gh auth token`. Treat as a secret. """ + api_key: str | None = None + """The API key. Treat as a secret.""" @staticmethod - def from_dict(obj: Any) -> 'SessionSetCredentialsParams': + def from_dict(obj: Any) -> 'AuthInfo': assert isinstance(obj, dict) - credentials = from_union([AuthInfo.from_dict, from_none], obj.get("credentials")) - return SessionSetCredentialsParams(credentials) + host = from_str(obj.get("host")) + type = AuthInfoType(obj.get("type")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + hmac = from_union([from_str, from_none], obj.get("hmac")) + env_var = from_union([from_str, from_none], obj.get("envVar")) + login = from_union([from_str, from_none], obj.get("login")) + token = from_union([from_str, from_none], obj.get("token")) + api_key = from_union([from_str, from_none], obj.get("apiKey")) + return AuthInfo(host, type, copilot_user, hmac, env_var, login, token, api_key) def to_dict(self) -> dict: result: dict = {} - if self.credentials is not None: - result["credentials"] = from_union([lambda x: to_class(AuthInfo, x), from_none], self.credentials) + result["host"] = from_str(self.host) + result["type"] = to_enum(AuthInfoType, self.type) + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + if self.hmac is not None: + result["hmac"] = from_union([from_str, from_none], self.hmac) + if self.env_var is not None: + result["envVar"] = from_union([from_str, from_none], self.env_var) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.token is not None: + result["token"] = from_union([from_str, from_none], self.token) + if self.api_key is not None: + result["apiKey"] = from_union([from_str, from_none], self.api_key) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -13928,6 +14101,31 @@ def to_dict(self) -> dict: result["requestedSchema"] = to_class(UIElicitationSchema, self.requested_schema) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSetCredentialsParams: + """New auth credentials to install on the session. Omit to leave credentials unchanged.""" + + credentials: AuthInfo | None = None + """The new auth credentials to install on the session. When omitted or `undefined`, the call + is a no-op and the session's existing credentials are preserved. The runtime stores the + value verbatim and uses it for outbound model/API requests; it does NOT re-validate or + re-fetch the associated Copilot user response. Several variants carry secret material; + treat this method's params as containing secrets at rest and in transit. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SessionSetCredentialsParams': + assert isinstance(obj, dict) + credentials = from_union([AuthInfo.from_dict, from_none], obj.get("credentials")) + return SessionSetCredentialsParams(credentials) + + def to_dict(self) -> dict: + result: dict = {} + if self.credentials is not None: + result["credentials"] = from_union([lambda x: to_class(AuthInfo, x), from_none], self.credentials) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecision: @@ -14756,6 +14954,10 @@ class RPC: copilot_api_token_auth_info: CopilotAPITokenAuthInfo copilot_user_response: CopilotUserResponse copilot_user_response_endpoints: CopilotUserResponseEndpoints + copilot_user_response_quota_snapshots: dict[str, CopilotUserResponseQuotaSnapshots | None] + copilot_user_response_quota_snapshots_chat: CopilotUserResponseQuotaSnapshotsChat + copilot_user_response_quota_snapshots_completions: CopilotUserResponseQuotaSnapshotsCompletions + copilot_user_response_quota_snapshots_premium_interactions: CopilotUserResponseQuotaSnapshotsPremiumInteractions current_model: CurrentModel discovered_mcp_server: DiscoveredMCPServer discovered_mcp_server_type: DiscoveredMCPServerType @@ -14765,6 +14967,7 @@ class RPC: event_log_read_request: EventLogReadRequest event_log_release_interest_result: EventLogReleaseInterestResult event_log_tail_result: EventLogTailResult + event_log_types: list[str] | EventLogTypes events_agent_scope: EventsAgentScope events_cursor_status: EventsCursorStatus events_read_result: EventsReadResult @@ -15268,6 +15471,10 @@ def from_dict(obj: Any) -> 'RPC': copilot_api_token_auth_info = CopilotAPITokenAuthInfo.from_dict(obj.get("CopilotApiTokenAuthInfo")) copilot_user_response = CopilotUserResponse.from_dict(obj.get("CopilotUserResponse")) copilot_user_response_endpoints = CopilotUserResponseEndpoints.from_dict(obj.get("CopilotUserResponseEndpoints")) + copilot_user_response_quota_snapshots = from_dict(lambda x: from_union([CopilotUserResponseQuotaSnapshots.from_dict, from_none], x), obj.get("CopilotUserResponseQuotaSnapshots")) + copilot_user_response_quota_snapshots_chat = CopilotUserResponseQuotaSnapshotsChat.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsChat")) + copilot_user_response_quota_snapshots_completions = CopilotUserResponseQuotaSnapshotsCompletions.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsCompletions")) + copilot_user_response_quota_snapshots_premium_interactions = CopilotUserResponseQuotaSnapshotsPremiumInteractions.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsPremiumInteractions")) current_model = CurrentModel.from_dict(obj.get("CurrentModel")) discovered_mcp_server = DiscoveredMCPServer.from_dict(obj.get("DiscoveredMcpServer")) discovered_mcp_server_type = DiscoveredMCPServerType(obj.get("DiscoveredMcpServerType")) @@ -15277,6 +15484,7 @@ def from_dict(obj: Any) -> 'RPC': event_log_read_request = EventLogReadRequest.from_dict(obj.get("EventLogReadRequest")) event_log_release_interest_result = EventLogReleaseInterestResult.from_dict(obj.get("EventLogReleaseInterestResult")) event_log_tail_result = EventLogTailResult.from_dict(obj.get("EventLogTailResult")) + event_log_types = from_union([lambda x: from_list(from_str, x), EventLogTypes], obj.get("EventLogTypes")) events_agent_scope = EventsAgentScope(obj.get("EventsAgentScope")) events_cursor_status = EventsCursorStatus(obj.get("EventsCursorStatus")) events_read_result = EventsReadResult.from_dict(obj.get("EventsReadResult")) @@ -15744,7 +15952,7 @@ def from_dict(obj: Any) -> 'RPC': session_context_info = from_union([SessionContextInfo.from_dict, from_none], obj.get("SessionContextInfo")) task_progress = from_union([TaskProgress.from_dict, from_none], obj.get("TaskProgress")) workspace_summary = from_union([WorkspaceSummary.from_dict, from_none], obj.get("WorkspaceSummary")) - return RPC(abort_request, abort_result, account_get_quota_request, account_get_quota_result, account_quota_snapshot, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_reload_result, agent_select_request, agent_select_result, api_key_auth_info, auth_info, auth_info_type, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, current_model, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_source, installed_plugin_source_github, installed_plugin_source_local, installed_plugin_source_url, instructions_get_sources_result, instructions_sources, instructions_sources_location, instructions_sources_type, log_request, log_result, lsp_initialize_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_oauth_login_request, mcp_oauth_login_result, mcp_remove_git_hub_result, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_config, mcp_server_config_http, mcp_server_config_http_auth, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_list, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, options_update_env_value_mode, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_update_request, plugin, plugin_list, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_mode, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, send_agent_mode, send_attachment, send_attachment_blob, send_attachment_directory, send_attachment_file, send_attachment_file_line_range, send_attachment_github_reference, send_attachment_github_reference_type, send_attachment_selection, send_attachment_selection_details, send_attachment_selection_details_end, send_attachment_selection_details_start, send_mode, send_request, send_result, server_skill, server_skill_list, session_auth_status, session_bulk_delete_result, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_github, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_metadata, session_metadata_snapshot, session_mode, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_prune_old_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_exec_request, shell_exec_result, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_initialize_and_validate_result, tools_list_request, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_tool_session_approval_commands, user_tool_session_approval_custom_tool, user_tool_session_approval_extension_management, user_tool_session_approval_extension_permission_access, user_tool_session_approval_mcp, user_tool_session_approval_memory, user_tool_session_approval_read, user_tool_session_approval_write, workspaces_checkpoints, workspaces_create_file_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, task_progress, workspace_summary) + return RPC(abort_request, abort_result, account_get_quota_request, account_get_quota_result, account_quota_snapshot, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_reload_result, agent_select_request, agent_select_result, api_key_auth_info, auth_info, auth_info_type, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, event_log_types, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_source, installed_plugin_source_github, installed_plugin_source_local, installed_plugin_source_url, instructions_get_sources_result, instructions_sources, instructions_sources_location, instructions_sources_type, log_request, log_result, lsp_initialize_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_oauth_login_request, mcp_oauth_login_result, mcp_remove_git_hub_result, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_config, mcp_server_config_http, mcp_server_config_http_auth, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_list, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, options_update_env_value_mode, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_update_request, plugin, plugin_list, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_mode, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, send_agent_mode, send_attachment, send_attachment_blob, send_attachment_directory, send_attachment_file, send_attachment_file_line_range, send_attachment_github_reference, send_attachment_github_reference_type, send_attachment_selection, send_attachment_selection_details, send_attachment_selection_details_end, send_attachment_selection_details_start, send_mode, send_request, send_result, server_skill, server_skill_list, session_auth_status, session_bulk_delete_result, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_github, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_metadata, session_metadata_snapshot, session_mode, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_prune_old_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_exec_request, shell_exec_result, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_initialize_and_validate_result, tools_list_request, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_tool_session_approval_commands, user_tool_session_approval_custom_tool, user_tool_session_approval_extension_management, user_tool_session_approval_extension_permission_access, user_tool_session_approval_mcp, user_tool_session_approval_memory, user_tool_session_approval_read, user_tool_session_approval_write, workspaces_checkpoints, workspaces_create_file_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, task_progress, workspace_summary) def to_dict(self) -> dict: result: dict = {} @@ -15780,6 +15988,10 @@ def to_dict(self) -> dict: result["CopilotApiTokenAuthInfo"] = to_class(CopilotAPITokenAuthInfo, self.copilot_api_token_auth_info) result["CopilotUserResponse"] = to_class(CopilotUserResponse, self.copilot_user_response) result["CopilotUserResponseEndpoints"] = to_class(CopilotUserResponseEndpoints, self.copilot_user_response_endpoints) + result["CopilotUserResponseQuotaSnapshots"] = from_dict(lambda x: from_union([lambda x: to_class(CopilotUserResponseQuotaSnapshots, x), from_none], x), self.copilot_user_response_quota_snapshots) + result["CopilotUserResponseQuotaSnapshotsChat"] = to_class(CopilotUserResponseQuotaSnapshotsChat, self.copilot_user_response_quota_snapshots_chat) + result["CopilotUserResponseQuotaSnapshotsCompletions"] = to_class(CopilotUserResponseQuotaSnapshotsCompletions, self.copilot_user_response_quota_snapshots_completions) + result["CopilotUserResponseQuotaSnapshotsPremiumInteractions"] = to_class(CopilotUserResponseQuotaSnapshotsPremiumInteractions, self.copilot_user_response_quota_snapshots_premium_interactions) result["CurrentModel"] = to_class(CurrentModel, self.current_model) result["DiscoveredMcpServer"] = to_class(DiscoveredMCPServer, self.discovered_mcp_server) result["DiscoveredMcpServerType"] = to_enum(DiscoveredMCPServerType, self.discovered_mcp_server_type) @@ -15789,6 +16001,7 @@ def to_dict(self) -> dict: result["EventLogReadRequest"] = to_class(EventLogReadRequest, self.event_log_read_request) result["EventLogReleaseInterestResult"] = to_class(EventLogReleaseInterestResult, self.event_log_release_interest_result) result["EventLogTailResult"] = to_class(EventLogTailResult, self.event_log_tail_result) + result["EventLogTypes"] = from_union([lambda x: from_list(from_str, x), lambda x: to_enum(EventLogTypes, x)], self.event_log_types) result["EventsAgentScope"] = to_enum(EventsAgentScope, self.events_agent_scope) result["EventsCursorStatus"] = to_enum(EventsCursorStatus, self.events_cursor_status) result["EventsReadResult"] = to_class(EventsReadResult, self.events_read_result) @@ -16344,12 +16557,12 @@ async def list(self, *, timeout: float | None = None) -> MCPConfigList: return MCPConfigList.from_dict(await self._client.request("mcp.config.list", {}, **_timeout_kwargs(timeout))) async def add(self, params: MCPConfigAddRequest, *, timeout: float | None = None) -> None: - "Adds an MCP server to user configuration.\n\nArgs:\n params: MCP server name and configuration to add to user configuration.\n\n.. warning:: This API is experimental and may change or be removed in future versions." + "Adds an MCP server to user configuration.\n\nArgs:\n params: MCP server name and configuration to add to user configuration." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} await self._client.request("mcp.config.add", params_dict, **_timeout_kwargs(timeout)) async def update(self, params: MCPConfigUpdateRequest, *, timeout: float | None = None) -> None: - "Updates an MCP server in user configuration.\n\nArgs:\n params: MCP server name and replacement configuration to write to user configuration.\n\n.. warning:: This API is experimental and may change or be removed in future versions." + "Updates an MCP server in user configuration.\n\nArgs:\n params: MCP server name and replacement configuration to write to user configuration." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} await self._client.request("mcp.config.update", params_dict, **_timeout_kwargs(timeout)) diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index c655a2370..05b89a125 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -320,9 +320,8 @@ class AssistantMessageData: "Assistant response containing text content, optional tool requests, and interaction metadata" content: str message_id: str - # Internal: this field is an internal SDK API and is not part of the public surface. anthropic_advisor_blocks: list[Any] | None = None - # Internal: this field is an internal SDK API and is not part of the public surface. + # Experimental: this field is part of an experimental API and may change or be removed. anthropic_advisor_model: str | None = None encrypted_content: str | None = None interaction_id: str | None = None @@ -693,7 +692,6 @@ class AssistantUsageData: # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None provider_call_id: str | None = None - # Internal: this field is an internal SDK API and is not part of the public surface. quota_snapshots: dict[str, AssistantUsageQuotaSnapshot] | None = None reasoning_effort: str | None = None reasoning_tokens: int | None = None @@ -784,13 +782,21 @@ def to_dict(self) -> dict: @dataclass class AssistantUsageQuotaSnapshot: "Schema for the `AssistantUsageQuotaSnapshot` type." + # Internal: this field is an internal SDK API and is not part of the public surface. entitlement_requests: int + # Internal: this field is an internal SDK API and is not part of the public surface. is_unlimited_entitlement: bool + # Internal: this field is an internal SDK API and is not part of the public surface. overage: float + # Internal: this field is an internal SDK API and is not part of the public surface. overage_allowed_with_exhausted_quota: bool + # Internal: this field is an internal SDK API and is not part of the public surface. remaining_percentage: float + # Internal: this field is an internal SDK API and is not part of the public surface. usage_allowed_with_exhausted_quota: bool + # Internal: this field is an internal SDK API and is not part of the public surface. used_requests: int + # Internal: this field is an internal SDK API and is not part of the public surface. reset_date: datetime | None = None @staticmethod diff --git a/rust/src/generated/api_types.rs b/rust/src/generated/api_types.rs index 74fe3718f..b0ef34ff6 100644 --- a/rust/src/generated/api_types.rs +++ b/rust/src/generated/api_types.rs @@ -598,9 +598,57 @@ pub struct CopilotUserResponseEndpoints { pub telemetry: Option, } +/// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CopilotUserResponseQuotaSnapshotsChat { + #[serde(skip_serializing_if = "Option::is_none")] + pub entitlement: Option, + #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] + pub has_quota: Option, + #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] + pub overage_count: Option, + #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] + pub overage_permitted: Option, + #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] + pub percent_remaining: Option, + #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] + pub quota_id: Option, + #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] + pub quota_remaining: Option, + #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] + pub quota_reset_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub remaining: Option, + #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] + pub timestamp_utc: Option, + #[serde( + rename = "token_based_billing", + skip_serializing_if = "Option::is_none" + )] + pub token_based_billing: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub unlimited: Option, +} + +/// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CopilotUserResponseQuotaSnapshotsValue { +pub struct CopilotUserResponseQuotaSnapshotsCompletions { #[serde(skip_serializing_if = "Option::is_none")] pub entitlement: Option, #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] @@ -630,6 +678,71 @@ pub struct CopilotUserResponseQuotaSnapshotsValue { pub unlimited: Option, } +/// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CopilotUserResponseQuotaSnapshotsPremiumInteractions { + #[serde(skip_serializing_if = "Option::is_none")] + pub entitlement: Option, + #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] + pub has_quota: Option, + #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] + pub overage_count: Option, + #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] + pub overage_permitted: Option, + #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] + pub percent_remaining: Option, + #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] + pub quota_id: Option, + #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] + pub quota_remaining: Option, + #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] + pub quota_reset_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub remaining: Option, + #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] + pub timestamp_utc: Option, + #[serde( + rename = "token_based_billing", + skip_serializing_if = "Option::is_none" + )] + pub token_based_billing: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub unlimited: Option, +} + +/// Schema for the `CopilotUserResponseQuotaSnapshots` type. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CopilotUserResponseQuotaSnapshots { + /// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + #[serde(skip_serializing_if = "Option::is_none")] + pub chat: Option, + /// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + #[serde(skip_serializing_if = "Option::is_none")] + pub completions: Option, + /// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + #[serde( + rename = "premium_interactions", + skip_serializing_if = "Option::is_none" + )] + pub premium_interactions: Option, +} + /// Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. /// ///
@@ -706,8 +819,9 @@ pub struct CopilotUserResponse { skip_serializing_if = "Option::is_none" )] pub quota_reset_date_utc: Option, - #[serde(rename = "quota_snapshots", default)] - pub quota_snapshots: HashMap>, + /// Schema for the `CopilotUserResponseQuotaSnapshots` type. + #[serde(rename = "quota_snapshots", skip_serializing_if = "Option::is_none")] + pub quota_snapshots: Option, #[serde( rename = "restricted_telemetry", skip_serializing_if = "Option::is_none" @@ -1143,9 +1257,9 @@ pub struct EventLogReadRequest { /// Maximum number of events to return in this batch (1–1000, default 200). #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, - /// List of event types to receive. Omit (or pass an empty/absent value) to receive all event types. - #[serde(default)] - pub types: Vec, + /// Either '*' to receive all event types, or a non-empty list of event types to receive + #[serde(skip_serializing_if = "Option::is_none")] + pub types: Option, /// Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). #[serde(skip_serializing_if = "Option::is_none")] pub wait_ms: Option, @@ -2048,13 +2162,6 @@ pub struct McpCancelSamplingExecutionResult { } /// MCP server name and configuration to add to user configuration. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigAddRequest { @@ -2097,13 +2204,6 @@ pub struct McpConfigRemoveRequest { } /// MCP server name and replacement configuration to write to user configuration. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigUpdateRequest { @@ -5050,6 +5150,7 @@ pub struct SendRequest { #[serde(skip_serializing_if = "Option::is_none")] pub required_tool: Option, /// Optional provenance tag copied to the resulting user.message event. Supported values are `system`, `command-*`, and `schedule-*`. + #[doc(hidden)] #[serde(skip_serializing_if = "Option::is_none")] pub source: Option, /// W3C Trace Context traceparent header for distributed tracing of this agent turn diff --git a/rust/src/generated/rpc.rs b/rust/src/generated/rpc.rs index 4c09d647c..f73d1bc00 100644 --- a/rust/src/generated/rpc.rs +++ b/rust/src/generated/rpc.rs @@ -222,14 +222,6 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name and configuration to add to user configuration. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
pub async fn add(&self, params: McpConfigAddRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -246,14 +238,6 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name and replacement configuration to write to user configuration. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
pub async fn update(&self, params: McpConfigUpdateRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index d9efe0290..c12b14898 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -1137,11 +1137,16 @@ pub struct AssistantMessageToolRequest { #[serde(rename_all = "camelCase")] pub struct AssistantMessageData { /// Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping - #[doc(hidden)] #[serde(default)] pub anthropic_advisor_blocks: Vec, /// Anthropic advisor model ID used for this response, for timeline display on replay - #[doc(hidden)] + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(skip_serializing_if = "Option::is_none")] pub anthropic_advisor_model: Option, /// The assistant's text response content @@ -1248,21 +1253,29 @@ pub struct AssistantUsageCopilotUsage { #[serde(rename_all = "camelCase")] pub struct AssistantUsageQuotaSnapshot { /// Total requests allowed by the entitlement + #[doc(hidden)] pub entitlement_requests: i64, /// Whether the user has an unlimited usage entitlement + #[doc(hidden)] pub is_unlimited_entitlement: bool, - /// Number of requests over the entitlement limit + /// Number of additional usage requests made this period + #[doc(hidden)] pub overage: f64, - /// Whether overage is allowed when quota is exhausted + /// Whether additional usage is allowed when quota is exhausted + #[doc(hidden)] pub overage_allowed_with_exhausted_quota: bool, /// Percentage of quota remaining (0 to 100) + #[doc(hidden)] pub remaining_percentage: f64, /// Date when the quota resets + #[doc(hidden)] #[serde(skip_serializing_if = "Option::is_none")] pub reset_date: Option, /// Whether usage is still permitted after quota exhaustion + #[doc(hidden)] pub usage_allowed_with_exhausted_quota: bool, /// Number of requests already consumed + #[doc(hidden)] pub used_requests: i64, } @@ -1321,7 +1334,6 @@ pub struct AssistantUsageData { #[serde(skip_serializing_if = "Option::is_none")] pub provider_call_id: Option, /// Per-quota resource usage snapshots, keyed by quota identifier - #[doc(hidden)] #[serde(default)] pub quota_snapshots: HashMap, /// Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") From bb0e481d9cbf070411dc36b54e7c6fe8b2ae8509 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 19:07:02 +0100 Subject: [PATCH 18/20] Regenerate SDK: MarketplaceSource is experimental Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- go/rpc/zrpc.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index 24296589f..97ab8d760 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -1109,6 +1109,8 @@ type InstalledPlugin struct { // Source for direct repo installs (when marketplace is empty) // Experimental: InstalledPluginSource is part of an experimental API and may change or be // removed. +// Experimental: InstalledPluginSource is part of an experimental API and may change or be +// removed. type InstalledPluginSource struct { InstalledPluginSourceGithub *InstalledPluginSourceGithub InstalledPluginSourceLocal *InstalledPluginSourceLocal @@ -3790,6 +3792,8 @@ type SessionInstalledPlugin struct { // Source descriptor for direct repo installs (when marketplace is empty) // Experimental: SessionInstalledPluginSource is part of an experimental API and may change // or be removed. +// Experimental: SessionInstalledPluginSource is part of an experimental API and may change +// or be removed. type SessionInstalledPluginSource struct { SessionInstalledPluginSourceGithub *SessionInstalledPluginSourceGithub SessionInstalledPluginSourceLocal *SessionInstalledPluginSourceLocal From de221da771dccbb1c68bf9799a6bb9cdd1460a65 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 19:16:01 +0100 Subject: [PATCH 19/20] Regenerate SDK: anthropicAdvisorBlocks is experimental Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/SessionEvents.cs | 1 + go/rpc/zsession_events.go | 1 + python/copilot/generated/session_events.py | 1 + rust/src/generated/session_events.rs | 7 +++++++ 4 files changed, 10 insertions(+) diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index f7299d910..0a9c22a68 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -1995,6 +1995,7 @@ public sealed partial class AssistantStreamingDeltaData public sealed partial class AssistantMessageData { /// Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping. + [Experimental(Diagnostics.Experimental)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("anthropicAdvisorBlocks")] public JsonElement[]? AnthropicAdvisorBlocks { get; set; } diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index 4eb2a4b22..d944e9158 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -170,6 +170,7 @@ func (*AssistantReasoningData) Type() SessionEventType { return SessionEventType // Assistant response containing text content, optional tool requests, and interaction metadata type AssistantMessageData struct { // Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping + // Experimental: AnthropicAdvisorBlocks is part of an experimental API and may change or be removed. AnthropicAdvisorBlocks []any `json:"anthropicAdvisorBlocks,omitempty"` // Anthropic advisor model ID used for this response, for timeline display on replay // Experimental: AnthropicAdvisorModel is part of an experimental API and may change or be removed. diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index 05b89a125..497b76b2d 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -320,6 +320,7 @@ class AssistantMessageData: "Assistant response containing text content, optional tool requests, and interaction metadata" content: str message_id: str + # Experimental: this field is part of an experimental API and may change or be removed. anthropic_advisor_blocks: list[Any] | None = None # Experimental: this field is part of an experimental API and may change or be removed. anthropic_advisor_model: str | None = None diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index c12b14898..815593e48 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -1137,6 +1137,13 @@ pub struct AssistantMessageToolRequest { #[serde(rename_all = "camelCase")] pub struct AssistantMessageData { /// Raw Anthropic content array with advisor blocks (server_tool_use, advisor_tool_result) for verbatim round-tripping + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
#[serde(default)] pub anthropic_advisor_blocks: Vec, /// Anthropic advisor model ID used for this response, for timeline display on replay From 55eec83ff21f0bafd7d7f893e03fcd4f3744daae Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Thu, 21 May 2026 20:14:52 +0100 Subject: [PATCH 20/20] Regenerate SDK: optional internal/experimental metrics fields quotaSnapshots and totalPremiumRequests are now optional+internal; ShutdownModelMetricRequests.count and .cost are now optional+experimental. C# fields become nullable and gain [JsonInclude]/[Experimental] attributes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dotnet/src/Generated/SessionEvents.cs | 15 ++++++++---- go/rpc/zsession_events.go | 10 +++++--- nodejs/src/generated/session-events.ts | 6 ++--- python/copilot/generated/session_events.py | 27 ++++++++++++++-------- rust/src/generated/session_events.rs | 25 +++++++++++++++++--- 5 files changed, 60 insertions(+), 23 deletions(-) diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index 0a9c22a68..35e78a923 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -1681,8 +1681,10 @@ public sealed partial class SessionShutdownData public double? TotalNanoAiu { get; set; } /// Total number of premium API requests used during the session. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] [JsonPropertyName("totalPremiumRequests")] - public required double TotalPremiumRequests { get; set; } + internal double? TotalPremiumRequests { get; set; } } /// Working directory and git context at session start. @@ -2191,8 +2193,9 @@ public sealed partial class AssistantUsageData /// Per-quota resource usage snapshots, keyed by quota identifier. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] [JsonPropertyName("quotaSnapshots")] - public IDictionary? QuotaSnapshots { get; set; } + internal IDictionary? QuotaSnapshots { get; set; } /// Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max"). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -3189,12 +3192,16 @@ public sealed partial class ShutdownCodeChanges public sealed partial class ShutdownModelMetricRequests { /// Cumulative cost multiplier for requests to this model. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("cost")] - public required double Cost { get; set; } + public double? Cost { get; set; } /// Total number of API requests made to this model. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("count")] - public required long Count { get; set; } + public long? Count { get; set; } } /// Schema for the `ShutdownModelMetricTokenDetail` type. diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index d944e9158..0ab4e074d 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -556,6 +556,7 @@ type AssistantUsageData struct { // GitHub request tracing ID (x-github-request-id header) for server-side log correlation ProviderCallID *string `json:"providerCallId,omitempty"` // Per-quota resource usage snapshots, keyed by quota identifier + // Internal: QuotaSnapshots is part of the SDK's internal API surface and is not intended for external use. QuotaSnapshots map[string]AssistantUsageQuotaSnapshot `json:"quotaSnapshots,omitempty"` // Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") ReasoningEffort *string `json:"reasoningEffort,omitempty"` @@ -1058,7 +1059,8 @@ type SessionShutdownData struct { // Experimental: TotalNanoAiu is part of an experimental API and may change or be removed. TotalNanoAiu *float64 `json:"totalNanoAiu,omitempty"` // Total number of premium API requests used during the session - TotalPremiumRequests float64 `json:"totalPremiumRequests"` + // Internal: TotalPremiumRequests is part of the SDK's internal API surface and is not intended for external use. + TotalPremiumRequests *float64 `json:"totalPremiumRequests,omitempty"` } func (*SessionShutdownData) sessionEventData() {} @@ -2248,9 +2250,11 @@ type ShutdownModelMetric struct { // Request count and cost metrics type ShutdownModelMetricRequests struct { // Cumulative cost multiplier for requests to this model - Cost float64 `json:"cost"` + // Experimental: Cost is part of an experimental API and may change or be removed. + Cost *float64 `json:"cost,omitempty"` // Total number of API requests made to this model - Count int64 `json:"count"` + // Experimental: Count is part of an experimental API and may change or be removed. + Count *int64 `json:"count,omitempty"` } // Schema for the `ShutdownModelMetricTokenDetail` type. diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index e5fe8bd03..e466d1337 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -1469,7 +1469,7 @@ export interface ShutdownData { /** * Total number of premium API requests used during the session */ - totalPremiumRequests: number; + totalPremiumRequests?: number; } /** * Aggregate code change metrics for the session @@ -1512,11 +1512,11 @@ export interface ShutdownModelMetricRequests { /** * Cumulative cost multiplier for requests to this model */ - cost: number; + cost?: number; /** * Total number of API requests made to this model */ - count: number; + count?: number; } /** * Schema for the `ShutdownModelMetricTokenDetail` type. diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index 497b76b2d..706ec8086 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -693,6 +693,7 @@ class AssistantUsageData: # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None provider_call_id: str | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. quota_snapshots: dict[str, AssistantUsageQuotaSnapshot] | None = None reasoning_effort: str | None = None reasoning_tokens: int | None = None @@ -3103,7 +3104,6 @@ class SessionShutdownData: session_start_time: int shutdown_type: ShutdownType total_api_duration: timedelta - total_premium_requests: float conversation_tokens: int | None = None current_model: str | None = None current_tokens: int | None = None @@ -3113,6 +3113,8 @@ class SessionShutdownData: tool_definitions_tokens: int | None = None # Experimental: this field is part of an experimental API and may change or be removed. total_nano_aiu: float | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. + total_premium_requests: float | None = None @staticmethod def from_dict(obj: Any) -> "SessionShutdownData": @@ -3122,7 +3124,6 @@ def from_dict(obj: Any) -> "SessionShutdownData": session_start_time = from_int(obj.get("sessionStartTime")) shutdown_type = parse_enum(ShutdownType, obj.get("shutdownType")) total_api_duration = from_timedelta(obj.get("totalApiDurationMs")) - total_premium_requests = from_float(obj.get("totalPremiumRequests")) conversation_tokens = from_union([from_none, from_int], obj.get("conversationTokens")) current_model = from_union([from_none, from_str], obj.get("currentModel")) current_tokens = from_union([from_none, from_int], obj.get("currentTokens")) @@ -3131,13 +3132,13 @@ def from_dict(obj: Any) -> "SessionShutdownData": token_details = from_union([from_none, lambda x: from_dict(ShutdownTokenDetail.from_dict, x)], obj.get("tokenDetails")) tool_definitions_tokens = from_union([from_none, from_int], obj.get("toolDefinitionsTokens")) total_nano_aiu = from_union([from_none, from_float], obj.get("totalNanoAiu")) + total_premium_requests = from_union([from_none, from_float], obj.get("totalPremiumRequests")) return SessionShutdownData( code_changes=code_changes, model_metrics=model_metrics, session_start_time=session_start_time, shutdown_type=shutdown_type, total_api_duration=total_api_duration, - total_premium_requests=total_premium_requests, conversation_tokens=conversation_tokens, current_model=current_model, current_tokens=current_tokens, @@ -3146,6 +3147,7 @@ def from_dict(obj: Any) -> "SessionShutdownData": token_details=token_details, tool_definitions_tokens=tool_definitions_tokens, total_nano_aiu=total_nano_aiu, + total_premium_requests=total_premium_requests, ) def to_dict(self) -> dict: @@ -3155,7 +3157,6 @@ def to_dict(self) -> dict: result["sessionStartTime"] = to_int(self.session_start_time) result["shutdownType"] = to_enum(ShutdownType, self.shutdown_type) result["totalApiDurationMs"] = to_timedelta_int(self.total_api_duration) - result["totalPremiumRequests"] = to_float(self.total_premium_requests) if self.conversation_tokens is not None: result["conversationTokens"] = from_union([from_none, to_int], self.conversation_tokens) if self.current_model is not None: @@ -3172,6 +3173,8 @@ def to_dict(self) -> dict: result["toolDefinitionsTokens"] = from_union([from_none, to_int], self.tool_definitions_tokens) if self.total_nano_aiu is not None: result["totalNanoAiu"] = from_union([from_none, to_float], self.total_nano_aiu) + if self.total_premium_requests is not None: + result["totalPremiumRequests"] = from_union([from_none, to_float], self.total_premium_requests) return result @@ -3559,14 +3562,16 @@ def to_dict(self) -> dict: @dataclass class ShutdownModelMetricRequests: "Request count and cost metrics" - cost: float - count: int + # Experimental: this field is part of an experimental API and may change or be removed. + cost: float | None = None + # Experimental: this field is part of an experimental API and may change or be removed. + count: int | None = None @staticmethod def from_dict(obj: Any) -> "ShutdownModelMetricRequests": assert isinstance(obj, dict) - cost = from_float(obj.get("cost")) - count = from_int(obj.get("count")) + cost = from_union([from_none, from_float], obj.get("cost")) + count = from_union([from_none, from_int], obj.get("count")) return ShutdownModelMetricRequests( cost=cost, count=count, @@ -3574,8 +3579,10 @@ def from_dict(obj: Any) -> "ShutdownModelMetricRequests": def to_dict(self) -> dict: result: dict = {} - result["cost"] = to_float(self.cost) - result["count"] = to_int(self.count) + if self.cost is not None: + result["cost"] = from_union([from_none, to_float], self.cost) + if self.count is not None: + result["count"] = from_union([from_none, to_int], self.count) return result diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index 815593e48..8b16291c4 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -723,9 +723,25 @@ pub struct ShutdownCodeChanges { #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetricRequests { /// Cumulative cost multiplier for requests to this model - pub cost: f64, + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub cost: Option, /// Total number of API requests made to this model - pub count: i64, + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub count: Option, } /// Schema for the `ShutdownModelMetricTokenDetail` type. @@ -830,7 +846,9 @@ pub struct SessionShutdownData { #[serde(skip_serializing_if = "Option::is_none")] pub total_nano_aiu: Option, /// Total number of premium API requests used during the session - pub total_premium_requests: f64, + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub total_premium_requests: Option, } /// Session event "session.context_changed". Updated working directory and git context after the change @@ -1341,6 +1359,7 @@ pub struct AssistantUsageData { #[serde(skip_serializing_if = "Option::is_none")] pub provider_call_id: Option, /// Per-quota resource usage snapshots, keyed by quota identifier + #[doc(hidden)] #[serde(default)] pub quota_snapshots: HashMap, /// Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max")